blob: 795eb631ad6a39a770208ec968977a618b7f2cc5 (
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
|
"""Normalise genotype files to a single (untransposed) form."""
from pathlib import Path
from typing import Any, Mapping
from uploader.csvprocessing import (is_blank_line, make_comment_line_checker,
read_text_file)
class NormalisationError(Exception):
"""Raised when a genotype file cannot be normalised."""
def work_filepath(original: Path) -> Path:
"""Return the canonical working-file path for ``original``."""
return original.with_name(f"{original.stem}__work{original.suffix}")
def normalise_file(original: Path, config: Mapping[str, Any]) -> Path:
"""Write a canonical untransposed data matrix for ``original``.
Comments and ``@`` directives are dropped (Stage 01 already captured them).
The original file is left untouched; the canonical file is written next to
it as ``<stem>__work<suffix>``.
"""
_is_comment = make_comment_line_checker(config["comment.char"])
def __is_skippable__(line: str) -> bool:
return (is_blank_line(line) or _is_comment(line)
or line.startswith("@"))
rows = tuple(
tuple(field.strip() for field in line.split(config["separator"]))
for line in read_text_file(original)
if not __is_skippable__(line.strip()))
if not rows:
raise NormalisationError(
"The genotype file has no data matrix rows to normalise.")
if len({len(row) for row in rows}) != 1:
raise NormalisationError(
"The genotype data matrix has ragged rows: all rows must have the "
"same number of fields.")
output_rows = tuple(zip(*rows)) if config["transposed"] else rows
outpath = work_filepath(original)
with outpath.open("w", encoding="utf8") as outfile:
for row in output_rows:
outfile.write(config["separator"].join(row) + "\n")
return outpath
|