blob: ab8ccfcca92fd4e2e879bac2c82e6ade5ad0ea9a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
"""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 is_valid_order(
order: Iterable[str],
samples: Iterable[str]
) -> bool:
"""Check that ``order`` is a permutation of ``samples``."""
return sorted(order) == sorted(samples)
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())
|