From bd2d0db405d87a310cc25e2a00c48457de08a0b6 Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Thu, 12 Nov 2026 19:48:34 +0000 Subject: Add genotype sample order proposal helpers Add `proposed_order`, which keeps an existing population order and appends missing samples alphabetically (or sorts alphabetically without an existing order), and `population_sample_order`, which reads a population's order from `StrainXRef.OrderId`. Co-authored-by: pi coding agent --- uploader/genotypes/ordering.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 uploader/genotypes/ordering.py 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()) -- cgit 1.4.1