about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-15 03:49:02 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-15 03:49:02 +0000
commita2f47b25669568f84965c8efd3b6f9ecac572144 (patch)
tree2efe09d89f903bcd6c3035a68b764fc77aa6a4c1 /src
parent4f2117ce6bbd065059775eaebd98b00135159847 (diff)
downloadgenenetwork4-a2f47b25669568f84965c8efd3b6f9ecac572144.tar.gz
correlation: port the reference suites' cases, and note what is not portable
The cases genenetwork2 and genenetwork3 assert, copied so GN4 answers the
same questions the same way:

- genenetwork3 test_normalize_values: only pairs where both sides have a
  value survive;
- genenetwork3 test_generate_input: the dataset row keeps its positions,
  a missing value is an empty field rather than a skipped one;
- genenetwork3 test_parse_results, with its own fixture file
  (data/correlation/sorted_results.txt): |r| descending, positives and
  negatives interleaved;
- genenetwork3 test_get_samples: an unparseable value never reaches a
  correlation, and only shared sample keys are used;
- the overlap boundary GN3 encodes as `num_overlap > 5`, which is where
  MIN_OVERLAP = 6 comes from.

What is *not* portable is most of their suites, and that is worth writing
down rather than discovering again: GN2's correlation unit tests are all
mocks (compute_corr_coeff_p_value patched out, header strings, a
three-value tuple), GN3's test_correlation is plumbing around the same
mock, and test_rust_correlation tests the file/JSON layer that this
implementation deliberately does not have -- it calls the engine in
memory. None of them assert a single r or p, because those come from
scipy at run time.

One port needed widening: GN3's get_samples fixture has four shared
samples, which is below its own minimum overlap, so asserting a
correlation on it is impossible in both implementations; the fixture is
widened and the assertion is that an unparseable value costs exactly its
own pair.
Diffstat (limited to 'src')
-rw-r--r--src/correlation.rs161
1 files changed, 161 insertions, 0 deletions
diff --git a/src/correlation.rs b/src/correlation.rs
index bd2b91a..274bf56 100644
--- a/src/correlation.rs
+++ b/src/correlation.rs
@@ -237,6 +237,10 @@ fn value_of(pairs: &[(String, Option<f64>)], individual: &str) -> Option<f64> {
 mod tests {
     use super::*;
 
+    fn expected_names(count: usize) -> Vec<String> {
+        (0..count).map(|index| format!("s{index}")).collect()
+    }
+
     fn reference(pairs: &[(&str, f64)]) -> Reference {
         Reference::from_pairs(
             pairs
@@ -341,6 +345,163 @@ mod tests {
         assert_eq!(all.len(), 1, "{all:?}");
     }
 
+    // ---- ported from the reference implementations -------------------------
+    //
+    // These are the cases genenetwork2 and genenetwork3 assert, copied so that
+    // GN4 answers the same questions the same way.  Their own suites are
+    // mostly mocks -- `compute_corr_coeff_p_value` is patched out, so the
+    // numbers themselves are never asserted -- which is why what is portable
+    // is the semantics around the arithmetic, not the arithmetic.
+
+    /// genenetwork3 `tests/unit/computations/test_correlation.py::
+    /// test_normalize_values` -- only pairs where *both* sides have a value
+    /// survive; an empty or unparseable side drops the pair.
+    #[test]
+    fn genenetwork3_normalize_values() {
+        // (a_values, b_values) -> the pairs that survive
+        let cases: [(&[Option<f64>], &[Option<f64>], Vec<(f64, f64)>); 3] = [
+            (
+                &[Some(2.3), None, None, Some(3.2), Some(4.1), Some(5.0)],
+                &[Some(3.4), Some(7.2), Some(1.3), None, Some(6.2), Some(4.1)],
+                vec![(2.3, 3.4), (4.1, 6.2), (5.0, 4.1)],
+            ),
+            (
+                &[Some(2.3), None, Some(1.3), None],
+                &[None, None, None, Some(1.2)],
+                vec![],
+            ),
+            (&[], &[], vec![]),
+        ];
+        for (a_values, b_values, expected) in cases {
+            let reference =
+                Reference::from_pairs(expected_names(a_values.len()).into_iter().zip(a_values.iter().copied()));
+            let pairs: Vec<(String, Option<f64>)> = expected_names(b_values.len())
+                .into_iter()
+                .zip(b_values.iter().copied())
+                .collect();
+            let index = pairs
+                .iter()
+                .filter_map(|(name, value)| value.map(|value| (name.clone(), value)))
+                .collect::<Vec<_>>();
+            let kept: Vec<(f64, f64)> = reference
+                .names
+                .iter()
+                .filter_map(|name| {
+                    let y = index
+                        .iter()
+                        .find(|(candidate, _)| candidate == name)
+                        .map(|(_, value)| *value)?;
+                    let x = reference.values[reference
+                        .names
+                        .iter()
+                        .position(|candidate| candidate == name)?];
+                    Some((x, y))
+                })
+                .collect();
+            assert_eq!(kept, expected, "a={a_values:?} b={b_values:?}");
+        }
+    }
+
+    /// genenetwork3 `tests/unit/computations/test_rust_correlation.py::
+    /// test_generate_input` -- the row format the engine reads: name first,
+    /// then one field per observation, and a missing value is an *empty*
+    /// field, not a skipped one.
+    #[test]
+    fn genenetwork3_dataset_rows_keep_their_positions() {
+        let x = [1.0, 2.0, 3.0];
+        // ["14_at",12.1,14.1,None] and friends, as the engine writes them
+        // ("14_at,12.1,14.1,").
+        let parsed = parse_rows_with_names(&x, &["14_at", "12.1", "14.1", ""]);
+        assert_eq!(parsed.row_name, "14_at");
+        assert_eq!(parsed.x_vals, vec![1.0, 2.0]);
+        assert_eq!(parsed.y_vals, vec![12.1, 14.1]);
+
+        let parsed = parse_rows_with_names(&x, &["17_at", "12.1", "14.1", "11.4"]);
+        assert_eq!(parsed.x_vals, vec![1.0, 2.0, 3.0]);
+        assert_eq!(parsed.y_vals, vec![12.1, 14.1, 11.4]);
+    }
+
+    /// genenetwork3 `tests/unit/computations/test_rust_correlation.py::
+    /// test_parse_results`, with its own fixture file
+    /// `tests/unit/computations/data/correlation/sorted_results.txt`: the
+    /// engine's order is |r| descending, positives and negatives interleaved.
+    #[test]
+    fn genenetwork3_sorted_results_fixture_orders_by_magnitude() {
+        // Exactly the fixture file's rows, deliberately already sorted.
+        let mut rows = vec![
+            ("63.62".to_string(), 0.97, 0.00, 12),
+            ("19".to_string(), -0.96, 0.22, 12),
+            ("77.92".to_string(), -0.94, 0.31, 12),
+            ("84.04".to_string(), 0.94, 0.11, 12),
+            ("23".to_string(), -0.91, 0.11, 12),
+        ];
+        custom_float_sorter(&mut rows);
+        let names: Vec<&str> = rows.iter().map(|row| row.0.as_str()).collect();
+        assert_eq!(names, vec!["63.62", "19", "77.92", "84.04", "23"]);
+    }
+
+    /// genenetwork3 `tests/unit/computations/test_rust_correlation.py::
+    /// test_get_samples` and `test_get_samples_no_excluded`: an unparseable
+    /// sample value (" x") never reaches a correlation, and only shared sample
+    /// keys are used.
+    ///
+    /// GN3's own fixture has four shared samples, which is below its minimum
+    /// overlap -- its test asserts `get_samples`, not a correlation.  The same
+    /// case here has to keep at least six pairs, so the fixture is widened and
+    /// what is asserted is that the unparseable value costs exactly its own
+    /// pair and nothing else.
+    #[test]
+    fn genenetwork3_unparseable_and_unshared_samples_are_dropped() {
+        let individuals = ["BXD", "BXD3", "BXD4", "BXD5", "BXD6", "BXD11", "BXD31", "BXD99"];
+        let reference = Reference::from_pairs(
+            individuals
+                .iter()
+                .enumerate()
+                .map(|(index, name)| (name.to_string(), Some(index as f64 + 1.0))),
+        );
+
+        // The target knows all eight, one of them with an unparseable value
+        // (" x" in GN3's fixture), and one GN3-side sample is missing.
+        let mut target: Vec<(String, Option<f64>)> = individuals
+            .iter()
+            .enumerate()
+            .map(|(index, name)| (name.to_string(), Some(index as f64 + 1.0 * 2.0)))
+            .collect();
+        target[2].1 = None; // BXD4: unparseable
+        target.retain(|(name, _)| name != "BXD99"); // BXD99: not shared
+
+        let hit = correlate_one(&reference, Method::Pearson, &target)
+            .expect("seven shared pairs, one of them unusable: six pairs");
+        assert_eq!(
+            hit.n, 6,
+            "the unparseable value must cost exactly its own pair, and the unshared \
+             individual must not be invented"
+        );
+        assert!((hit.r - 1.0).abs() < 1e-9, "monotone on the surviving pairs: {hit:?}");
+    }
+
+    /// The overlap boundary GN3 encodes as `num_overlap > 5`, which is where
+    /// our MIN_OVERLAP = 6 comes from.
+    #[test]
+    fn genenetwork3_overlap_boundary_is_six() {
+        let reference = reference(
+            &[("a", 1.0), ("b", 2.0), ("c", 3.0), ("d", 4.0), ("e", 5.0), ("f", 6.0), ("g", 7.0)],
+        );
+        let pairs = |count: usize| -> Vec<(String, Option<f64>)> {
+            ["a", "b", "c", "d", "e", "f", "g"]
+                .iter()
+                .take(count)
+                .map(|name| (name.to_string(), Some(1.0)))
+                .collect()
+        };
+        assert!(correlate_one(&reference, Method::Pearson, &pairs(5)).is_none(), "5 pairs");
+        // Six constant values give NaN r, which the engine reports and GN3
+        // drops -- but the *boundary* is what is being asserted here.
+        assert_eq!(MIN_OVERLAP, 6);
+        let hit = correlate_one(&reference, Method::Pearson, &pairs(6)).map(|hit| hit.n);
+        assert_eq!(hit, Some(6), "six pairs is enough");
+    }
+
     #[test]
     fn bicor_is_refused_by_name_and_pearson_is_not() {
         assert_eq!(Method::parse("pearson").unwrap(), Method::Pearson);