about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-24 10:47:37 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-24 10:47:37 +0000
commitf139fb3f1d1b9738aea403520e64fd121cd8ee62 (patch)
treebdbaeb90825a6f1a2e386c5d294ddd4a1ee52420 /src
parent7281ee24bc479831fbfd5679896202685dffc49a (diff)
downloadgenenetwork4-f139fb3f1d1b9738aea403520e64fd121cd8ee62.tar.gz
genotypes: read latin-1 panels, and key the subset pair on its source file
Two things that a new panel exposed at once.

**Encoding.** At-Serin.geno came from a GeneNetwork export whose header comment
carries a latin-1 multiplication sign ("Bay-0 \xd7 Shahdara").  Every reader used
`std::fs::read_to_string`, so one byte in a comment hid the whole panel with
"stream did not contain valid UTF-8" -- `panel_of`, `marker_count`,
`individuals_with_genotypes`, the subset writer, and qtl2's cross reader.  They
now read the file and take it lossily (the data lines are ASCII; nothing parses
the comments), so a stray latin-1 byte is not a reason to refuse a panel.

**The prepared subset's key.** `subset_path` hashed the kept *indices* and the
version name, and nothing about the genotypes themselves, so replacing
`<stem>.geno` (or its BIMBAM) in place kept serving the previously prepared
subset and noY pair for as long as the animal set was unchanged -- an updated
genotype file would have been mapped as the old one.  The key now includes the
source file's size and mtime, exactly what `prepare_cross` already keys on.
Diffstat (limited to 'src')
-rw-r--r--src/genotypes.rs112
-rw-r--r--src/qtl2.rs4
2 files changed, 99 insertions, 17 deletions
diff --git a/src/genotypes.rs b/src/genotypes.rs
index 0d6c1c2..2948b28 100644
--- a/src/genotypes.rs
+++ b/src/genotypes.rs
@@ -159,13 +159,28 @@ pub fn resolve_named(root: &Path, requested: &str) -> Result<PathBuf, GenotypeEr
     )))
 }
 
+/// File contents as text, tolerating bytes that are not UTF-8.
+///
+/// Real GeneNetwork exports carry latin-1 in their header comments (At-Serin's
+/// says "Bay-0 \xd7 Shahdara"), and `read_to_string` failing on one byte hides
+/// the whole panel with "stream did not contain valid UTF-8".  Nothing here
+/// parses the comments; the data lines are ASCII.
+pub fn read_text_lossy(path: &Path) -> std::io::Result<String> {
+    Ok(String::from_utf8_lossy(&std::fs::read(path)?).into_owned())
+}
+
+fn read_text(path: &Path) -> Result<String, GenotypeError> {
+    let bytes = std::fs::read(path).map_err(|e| io_err(path, e))?;
+    Ok(String::from_utf8_lossy(&bytes).into_owned())
+}
+
 fn io_err(path: &Path, error: std::io::Error) -> GenotypeError {
     GenotypeError::Io(format!("{}: {error}", path.display()))
 }
 
 /// The `.geno` header's sample names, in column order (GN3's rule).
 pub fn panel_of(geno: &Path) -> Result<Vec<String>, GenotypeError> {
-    let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?;
+    let text = read_text(geno)?;
     for line in text.lines() {
         let line = line.trim_end_matches(['\r', '\n']);
         if line.trim().is_empty() || line.starts_with('#') || line.starts_with('@') {
@@ -191,7 +206,7 @@ pub fn panel_of(geno: &Path) -> Result<Vec<String>, GenotypeError> {
 /// Number of marker rows in a `.geno` (every non-comment line but the
 /// header).
 pub fn marker_count(geno: &Path) -> Result<usize, GenotypeError> {
-    let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?;
+    let text = read_text(geno)?;
     let mut seen_header = false;
     let mut markers = 0;
     for line in text.lines() {
@@ -267,7 +282,7 @@ fn json_versions(
     if !path.is_file() {
         return Ok(None);
     }
-    let text = std::fs::read_to_string(&path).map_err(|e| io_err(&path, e))?;
+    let text = read_text(&path)?;
     let document: serde_json::Value = serde_json::from_str(&text)
         .map_err(|e| GenotypeError::Io(format!("{}: {e}", path.display())))?;
     let Some(entries) = document.get("genofile").and_then(|v| v.as_array()) else {
@@ -519,7 +534,7 @@ pub struct ParentalDesign {
 /// The roles a group's metadata declares, or `None` when the group is unlisted.
 fn design_roles(dir: &Path, group: &str) -> Option<(Vec<DesignRole>, Option<DesignRole>, Option<DesignRole>)> {
     let path = dir.join("parents_and_f1s.json");
-    let text = std::fs::read_to_string(&path).ok()?;
+    let text = read_text(&path).ok()?;
     let document: serde_json::Value = serde_json::from_str(&text).ok()?;
     let entry = document.get(group)?;
     let role = |key: &str| {
@@ -667,7 +682,7 @@ pub struct FileMeta {
 /// 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 text = read_text(geno)?;
     let mut labels = Vec::new();
     let mut individuals = Vec::new();
     let mut markers = Vec::new();
@@ -763,7 +778,7 @@ pub fn prepare(
                     markers_dropped: 0,
                 });
             }
-            let path = subset_path(cache_dir, &resolved.version, keep, "geno")?;
+            let path = subset_path(cache_dir, &resolved.version, keep, "geno", &resolved.geno)?;
             if !path.is_file() {
                 write_subset_geno(&resolved.geno, keep, &path)?;
             }
@@ -792,16 +807,16 @@ pub fn prepare(
             let (panel_file, individuals) = if all_kept {
                 (geno.clone(), resolved.panel.len())
             } else {
-                let path = subset_path(cache_dir, &resolved.version, keep, "bimbam_geno.txt")?;
+                let path = subset_path(cache_dir, &resolved.version, keep, "bimbam_geno.txt", &geno)?;
                 if !path.is_file() {
                     write_subset_bimbam(&geno, keep, &path)?;
                 }
                 (path, keep.len())
             };
             let filtered_geno =
-                subset_path(cache_dir, &resolved.version, keep, "bimbam_geno-noY.txt")?;
+                subset_path(cache_dir, &resolved.version, keep, "bimbam_geno-noY.txt", &snps)?;
             let filtered_snps =
-                subset_path(cache_dir, &resolved.version, keep, "bimbam_snps-noY.txt")?;
+                subset_path(cache_dir, &resolved.version, keep, "bimbam_snps-noY.txt", &snps)?;
             if !filtered_geno.is_file() || !filtered_snps.is_file() {
                 let written =
                     drop_degenerate_chromosomes(&panel_file, &snps, &filtered_geno, &filtered_snps)?;
@@ -861,7 +876,7 @@ fn drop_degenerate_chromosomes(
     out_geno: &Path,
     out_snps: &Path,
 ) -> Result<usize, GenotypeError> {
-    let snps_text = std::fs::read_to_string(snps).map_err(|e| io_err(snps, e))?;
+    let snps_text = read_text(snps)?;
     let mut keep_row: Vec<bool> = Vec::new();
     let mut kept_snps = String::with_capacity(snps_text.len());
     for line in snps_text.lines() {
@@ -886,7 +901,7 @@ fn drop_degenerate_chromosomes(
     if dropped == 0 {
         return Ok(0);
     }
-    let geno_text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?;
+    let geno_text = read_text(geno)?;
     let mut kept_geno = String::with_capacity(geno_text.len());
     for (index, line) in geno_text.lines().enumerate() {
         if line.trim().is_empty() {
@@ -904,18 +919,42 @@ fn drop_degenerate_chromosomes(
 
 /// Non-empty lines in a file (the marker count of a snps annotation).
 fn count_lines(path: &Path) -> Result<usize, GenotypeError> {
-    Ok(std::fs::read_to_string(path)
-        .map_err(|e| io_err(path, e))?
+    Ok(read_text(path)?
         .lines()
         .filter(|line| !line.trim().is_empty())
         .count())
 }
 
+/// `size-mtime` of a panel file: the part of a cache key that notices a file
+/// being replaced in place.
+///
+/// The subset/noY pair is derived from the genotypes, so its key has to cover
+/// them.  It did not -- it hashed the kept *indices* only -- which meant an
+/// updated `<stem>.geno` (or BIMBAM) kept serving the previous prepared pair
+/// for as long as the individual set was unchanged.  `prepare_cross` has always
+/// keyed on this stamp; now the subset does too.
+fn source_stamp(path: &Path) -> String {
+    match std::fs::metadata(path) {
+        Ok(metadata) => format!(
+            "{}-{}",
+            metadata.len(),
+            metadata
+                .modified()
+                .ok()
+                .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
+                .map(|since| since.as_secs())
+                .unwrap_or(0)
+        ),
+        Err(_) => "unknown".to_string(),
+    }
+}
+
 fn subset_path(
     cache_dir: &Path,
     version: &str,
     keep: &[usize],
     suffix: &str,
+    source: &Path,
 ) -> Result<PathBuf, GenotypeError> {
     let dir = cache_dir.join("prepared");
     std::fs::create_dir_all(&dir).map_err(|e| io_err(&dir, e))?;
@@ -923,11 +962,14 @@ fn subset_path(
     for index in keep {
         hash = (hash ^ *index as u64).wrapping_mul(1099511628211);
     }
+    for byte in source_stamp(source).bytes() {
+        hash = (hash ^ byte as u64).wrapping_mul(1099511628211);
+    }
     Ok(dir.join(format!("{version}-{hash:016x}-{suffix}")))
 }
 
 fn write_subset_geno(geno: &Path, keep: &[usize], out: &Path) -> Result<(), GenotypeError> {
-    let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?;
+    let text = read_text(geno)?;
     let mut result = String::with_capacity(text.len());
     let mut seen_header = false;
     for line in text.lines() {
@@ -964,7 +1006,7 @@ fn write_subset_geno(geno: &Path, keep: &[usize], out: &Path) -> Result<(), Geno
 }
 
 fn write_subset_bimbam(geno: &Path, keep: &[usize], out: &Path) -> Result<(), GenotypeError> {
-    let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?;
+    let text = read_text(geno)?;
     let mut result = String::with_capacity(text.len());
     for line in text.lines() {
         let trimmed = line.trim_end_matches('\r');
@@ -1351,7 +1393,7 @@ mod tests {
 /// the file cannot be read (the caller then proceeds as before rather than
 /// refusing the run).
 pub fn individuals_with_genotypes(geno: &std::path::Path) -> Option<Vec<bool>> {
-    let text = std::fs::read_to_string(geno).ok()?;
+    let text = read_text(geno).ok()?;
     let mut mask: Option<Vec<bool>> = None;
     for line in text.lines() {
         let line = line.trim();
@@ -1379,6 +1421,44 @@ pub fn individuals_with_genotypes(geno: &std::path::Path) -> Option<Vec<bool>> {
     mask
 }
 
+/// The `.geno` that carries the individual names for a BIMBAM file.
+///
+/// BIMBAM has no names: its columns are positional.  A request that names its
+/// values ("samples", or a basket) therefore cannot be aligned against the
+/// BIMBAM it asks to map -- and until this, the file branch tried anyway, read
+/// the BIMBAM as if it were a `.geno`, found no header, and answered 422
+/// "no mapping inputs" with every value dropped (measured on At-Serin).
+///
+/// The deployment keeps the two side by side under a shared stem
+/// (`genotype/<stem>.geno` and `genotype/bimbam/<stem>_geno.txt`), and the
+/// BIMBAM is generated from the `.geno`, so its column order is the header's
+/// order.  That makes the sibling the name source.
+pub fn names_for_bimbam(bimbam: &Path) -> Option<PathBuf> {
+    let file = bimbam.file_name()?.to_string_lossy().into_owned();
+    let stem = file
+        .strip_suffix("_geno.txt")
+        .or_else(|| file.strip_suffix(".txt"))?;
+    let genotype_dir = bimbam.parent()?.parent()?;
+    let candidate = genotype_dir.join(format!("{stem}.geno"));
+    candidate.is_file().then_some(candidate)
+}
+
+/// `align_to_file`, but for a file that carries no names: the names come from
+/// `names_source` (see [`names_for_bimbam`]), and the values are placed in the
+/// file's own column order.
+pub fn align_to_columns_of(
+    names_source: &Path,
+    values: &[(String, Option<f64>)],
+) -> Result<Vec<Option<f64>>, GenotypeError> {
+    let names = panel_of(names_source)?;
+    let by_name: std::collections::HashMap<&str, Option<f64>> =
+        values.iter().map(|(name, value)| (name.as_str(), *value)).collect();
+    Ok(names
+        .iter()
+        .map(|name| by_name.get(name.as_str()).copied().flatten())
+        .collect())
+}
+
 /// 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
diff --git a/src/qtl2.rs b/src/qtl2.rs
index 0c0622f..99f2370 100644
--- a/src/qtl2.rs
+++ b/src/qtl2.rs
@@ -184,7 +184,9 @@ pub fn prepare_cross(
             .map(|since| since.as_secs())
             .unwrap_or(0)
     );
-    let text = std::fs::read_to_string(geno).map_err(|e| io_error(geno, e))?;
+    // Lossy, like the genotype readers: a latin-1 byte in a header comment must
+    // not hide the panel (measured on At-Serin.geno).
+    let text = crate::genotypes::read_text_lossy(geno).map_err(|e| io_error(geno, e))?;
 
     // The cross type is checked here rather than in R: this is the endpoint's
     // own limit (a `.geno` panel carries no founder genotypes, so it cannot be