diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-10 21:09:21 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-10 21:09:21 +0000 |
| commit | 0d3874f12587a771b774712bfa182926bfe37592 (patch) | |
| tree | e1a89e9fd29eb2383223c365a77be75c6c20bc2b /scripts/example-matrix.py | |
| parent | 65a56cb93e905e5901ae61eca750991042721be5 (diff) | |
| download | genenetwork4-0d3874f12587a771b774712bfa182926bfe37592.tar.gz | |
matrices: upload new traits and covariates as one named table
The other half of changing data: bringing new columns in. A matrix is a
delimited table -- a header row, then one row per individual, the first
column naming them -- stored in the uploader's own SQLite file and checked
against an existing genotype version's panel before it is accepted.
* POST /matrices {name, genotype_version, contents, kinds?}: parse the
table (tab, comma or semicolon, guessed from the header), then check
it against that version's individuals. The count must match and every
name must be in the panel; 92 of 93, or a name the panel does not
have, is a 422 that says which. A mapping that silently drops
individuals is worse than an error.
* kinds marks columns that are covariates; everything else is a trait.
* Each column becomes a basket named <matrix>.<column> -- a dot, not a
slash, because a basket name has to survive a URL path segment -- so
a column maps on any engine with {"basket": "my-traits.bw"} and
inherits the revision history and digest without a line of new
mapping code.
* GET /matrices lists them, GET /matrices/{name} their columns and
basket names, GET /matrices/{name}/values the table back (parsed
values, null where missing), DELETE removes the matrix and its
columns.
Two bugs this found in the basket store, both real:
* SQLite has foreign keys OFF by default, so the ON DELETE CASCADE
never fired: deleting a basket left its rows behind, rowids were
reused, and the next create hit "UNIQUE constraint failed:
basket_version.basket_id, revision". The pragma is now set, and
deletion removes the dependants explicitly, because files written
before it have orphans.
* The first attempt named a column's basket "<matrix>/<column>", which
the basket-name rule (rightly) refuses. The dot keeps both rules.
scripts/example-matrix.py writes a table from a genotype file's own header
with deterministic values, so the fixture passes the panel check by
construction -- tests/matrices.rs builds its own for the same reason and
walks the loop: upload, read back, map a column with R/qtl2, delete, plus
the three refusals (too few individuals, a name not in the panel, an
unknown version).
Diffstat (limited to 'scripts/example-matrix.py')
| -rwxr-xr-x | scripts/example-matrix.py | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/scripts/example-matrix.py b/scripts/example-matrix.py new file mode 100755 index 0000000..d970d81 --- /dev/null +++ b/scripts/example-matrix.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Write an example traits/covariates matrix for a genotype file. + +The table GN4's POST /matrices accepts: a header row, then one row per +individual. The individuals are read from the genotype file's own header, so +the matrix passes the panel check by construction -- which is the point: this +is the fixture to try an upload with, not a random CSV. + + scripts/example-matrix.py --genotype \\ + /home/wrk/tmp/ai-root/factory/gn4-data/genotype-files/genotype/BXD.4.geno \\ + --out /tmp/example-matrix.csv + +Values are deterministic (a hash of the individual and the column, not +`random`), so the same command gives the same table and a test can rely on it. +""" + +import argparse +import hashlib +import sys + + +def pseudo(individual: str, column: str, low: float, spread: float) -> float: + """A reproducible number in [low, low + spread) for this pair.""" + digest = hashlib.sha256(f"{individual}:{column}".encode()).digest() + unit = int.from_bytes(digest[:8], "big") / 2**64 + return round(low + unit * spread, 3) + + +def individuals_of(genotype_path: str) -> list[str]: + """The genotype file's individual columns, in file order.""" + with open(genotype_path, errors="replace") as handle: + for line in handle: + if line.startswith(("#", "@")) or not line.strip(): + continue + columns = line.rstrip("\n").split("\t") + start = 4 if len(columns) > 3 and columns[3] == "Mb" else 3 + return [name.strip() for name in columns[start:] if name.strip()] + raise SystemExit(f"{genotype_path}: no header line") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--genotype", required=True, help="a .geno file") + parser.add_argument("--out", required=True, help="where to write the CSV") + parser.add_argument("--traits", type=int, default=2, help="how many trait columns") + parser.add_argument("--covariates", type=int, default=1, help="how many covariate columns") + parser.add_argument("--separator", default=",", help="field separator (default ',')") + arguments = parser.parse_args() + + individuals = individuals_of(arguments.genotype) + if not individuals: + raise SystemExit(f"{arguments.genotype}: no individuals in the header") + traits = [f"trait_{index + 1}" for index in range(arguments.traits)] + covariates = [f"covariate_{index + 1}" for index in range(arguments.covariates)] + + separator = arguments.separator + with open(arguments.out, "w") as handle: + handle.write(separator.join(["id", *traits, *covariates]) + "\n") + for individual in individuals: + row = [individual] + row += [f"{pseudo(individual, trait, 1.0, 9.0):.3f}" for trait in traits] + # A covariate is a small integer class, like a batch -- and one + # cell is left empty, so the upload's missing-value path is + # exercised by the example itself. + for index, covariate in enumerate(covariates): + if index == 0 and individual == individuals[-1]: + row.append("") + else: + row.append(str(1 + int(hashlib.sha256((individual + covariate).encode()).hexdigest(), 16) % 3)) + handle.write(separator.join(row) + "\n") + print(f"{arguments.out}: {len(individuals)} individuals, {len(traits)} trait(s), " + f"{len(covariates)} covariate(s)", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) |
