"""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 ``__work``. """ _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