about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--uploader/genotypes/ordering.py40
1 files changed, 40 insertions, 0 deletions
diff --git a/uploader/genotypes/ordering.py b/uploader/genotypes/ordering.py
new file mode 100644
index 0000000..816025a
--- /dev/null
+++ b/uploader/genotypes/ordering.py
@@ -0,0 +1,40 @@
+"""Sample-ordering helpers for genotype uploads."""
+from typing import Iterable
+
+import MySQLdb as mdb
+from MySQLdb.cursors import DictCursor
+
+
+def proposed_order(
+        samples: Iterable[str],
+        existing_order: Iterable[str] = ()
+) -> tuple[str, ...]:
+    """Propose a sample order from the file's samples and existing order.
+
+    If an existing population order is available, keep the samples it contains
+    in that order and append any remaining samples alphabetically. Without an
+    existing order, sort all the samples alphabetically.
+    """
+    sample_set = set(samples)
+    retained = tuple(
+        sample for sample in existing_order if sample in sample_set)
+    return retained + tuple(sorted(sample_set.difference(retained)))
+
+
+def population_sample_order(
+        conn: mdb.Connection,
+        population_id: int
+) -> tuple[str, ...]:
+    """Return the population's existing sample order.
+
+    Samples are ordered by ``StrainXRef.OrderId``; any without an order value
+    follow, sorted by name.
+    """
+    with conn.cursor(cursorclass=DictCursor) as cursor:
+        cursor.execute(
+            "SELECT strn.Name FROM StrainXRef AS sxr "
+            "INNER JOIN Strain AS strn ON sxr.StrainId=strn.Id "
+            "WHERE sxr.InbredSetId=%s "
+            "ORDER BY sxr.OrderId IS NULL, sxr.OrderId ASC, strn.Name ASC",
+            (population_id,))
+        return tuple(row["Name"] for row in cursor.fetchall())