From 8e8cf057f4f054d887e831884b5bfea3e3bd697b Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Wed, 11 Nov 2026 12:57:26 +0000 Subject: [PATCH 1/6] feat(results): build structured results from qsidd output --- src/sist/results/__init__.py | 0 src/sist/results/builder.py | 192 ++++++++ src/sist/results/diagnostics.py | 299 ++++++++++++ src/sist/results/model.py | 433 ++++++++++++++++++ src/sist/results/provenance.py | 103 +++++ src/sist/results/qsidd_output.py | 109 +++++ src/sist/results/reader.py | 226 +++++++++ src/sist/results/sequence.py | 90 ++++ src/sist/results/writer.py | 82 ++++ .../qsidd/competition-no-inverted-repeats.txt | 154 +++++++ tests/unit/data/qsidd/competition.txt | 154 +++++++ tests/unit/data/qsidd/cruciform.txt | 127 +++++ tests/unit/data/qsidd/fragment.fa | 3 + tests/unit/data/qsidd/fragment.ir | 1 + tests/unit/data/qsidd/melting.txt | 127 +++++ tests/unit/data/qsidd/underflow.txt | 32 ++ tests/unit/data/qsidd/z-dna.txt | 126 +++++ tests/unit/results/conftest.py | 18 + tests/unit/results/results_helpers.py | 66 +++ tests/unit/results/test_builder.py | 131 ++++++ tests/unit/results/test_diagnostics.py | 104 +++++ tests/unit/results/test_model.py | 61 +++ tests/unit/results/test_provenance.py | 40 ++ tests/unit/results/test_qsidd_output.py | 52 +++ tests/unit/results/test_reader.py | 117 +++++ tests/unit/results/test_sequence.py | 71 +++ tests/unit/results/test_writer.py | 59 +++ 27 files changed, 2977 insertions(+) create mode 100644 src/sist/results/__init__.py create mode 100644 src/sist/results/builder.py create mode 100644 src/sist/results/diagnostics.py create mode 100644 src/sist/results/model.py create mode 100644 src/sist/results/provenance.py create mode 100644 src/sist/results/qsidd_output.py create mode 100644 src/sist/results/reader.py create mode 100644 src/sist/results/sequence.py create mode 100644 src/sist/results/writer.py create mode 100644 tests/unit/data/qsidd/competition-no-inverted-repeats.txt create mode 100644 tests/unit/data/qsidd/competition.txt create mode 100644 tests/unit/data/qsidd/cruciform.txt create mode 100644 tests/unit/data/qsidd/fragment.fa create mode 100644 tests/unit/data/qsidd/fragment.ir create mode 100644 tests/unit/data/qsidd/melting.txt create mode 100644 tests/unit/data/qsidd/underflow.txt create mode 100644 tests/unit/data/qsidd/z-dna.txt create mode 100644 tests/unit/results/conftest.py create mode 100644 tests/unit/results/results_helpers.py create mode 100644 tests/unit/results/test_builder.py create mode 100644 tests/unit/results/test_diagnostics.py create mode 100644 tests/unit/results/test_model.py create mode 100644 tests/unit/results/test_provenance.py create mode 100644 tests/unit/results/test_qsidd_output.py create mode 100644 tests/unit/results/test_reader.py create mode 100644 tests/unit/results/test_sequence.py create mode 100644 tests/unit/results/test_writer.py diff --git a/src/sist/results/__init__.py b/src/sist/results/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/sist/results/builder.py b/src/sist/results/builder.py new file mode 100644 index 0000000..b8df121 --- /dev/null +++ b/src/sist/results/builder.py @@ -0,0 +1,192 @@ +"""Put the parts of a result together for a successful or failed run.""" + +from __future__ import annotations + +from pathlib import Path + +from sist.results.diagnostics import ( + ErrorCode, + ResultError, + ResultWarning, + WarningCode, + check_sequence, + check_settings, + qsidd_warnings, +) +from sist.results.model import ( + DerivedParameters, + InputDescription, + InvertedRepeat, + Result, + RunSettings, +) +from sist.results.provenance import ProvenanceRecorder +from sist.results.qsidd_output import QsiddOutput +from sist.results.reader import QsiddReader +from sist.results.sequence import SequenceInput + + +class ResultBuilder: + """Build the result of one run. + + Create one builder when the run starts, so its start time is recorded, + then call :meth:`read_sequence` and either :meth:`success` or + :meth:`failure`. + + Attributes: + settings: The run's settings. + warnings: Warnings raised so far, in the order they were raised. + """ + + def __init__(self, settings: RunSettings, *, command: list[str] | None = None): + """Start recording a run. + + Args: + settings: The run's settings. + command: The command line as given, or None when run from Python. + """ + self.settings = settings + self.warnings: list[ResultWarning] = [] + + self._provenance = ProvenanceRecorder( + engine=settings.algorithm.engine, command=command + ) + self._reader = QsiddReader(settings.algorithm) + + def read_sequence(self) -> SequenceInput: + """Read the input sequence and raise the warnings it and the settings call for. + + Returns: + The sequence that qsidd will analyse. + + Raises: + ResultError: If the sequence cannot be analysed. + """ + sequence = SequenceInput.read(Path(self.settings.file)) + + self.warnings.extend(check_sequence(sequence)) + self.warnings.extend( + check_settings( + self.settings.algorithm, + nearest_neighbor=self.settings.nearest_neighbor, + salt=self.settings.salt, + ) + ) + + return sequence + + def success( + self, + output: QsiddOutput, + sequence: SequenceInput, + *, + ir_string: str | None = None, + irf_version: str | None = None, + ) -> Result: + """Build the result of a run that finished. + + qsidd's warnings are recorded before checking for underflow, so a run + that fails that check still keeps them. + + Args: + output: The parsed qsidd output. + sequence: The sequence that was analysed. + ir_string: The scored inverted repeats passed to qsidd, if used. + irf_version: The IRF version, if inverted repeats were scored. + + Returns: + The result. + + Raises: + ResultError: If the partition function underflowed, so qsidd's + values are meaningless even though it exited normally. + """ + self.warnings.extend(qsidd_warnings(output.warnings)) + + if self._reader.underflowed(output): + raise ResultError( + ErrorCode.PARTITION_FUNCTION_UNDERFLOW, + "The partition function underflowed to zero, so qsidd could not " + "work out any probabilities. Try a lower superhelical density or " + "a shorter sequence.", + exit_code=0, + details={"min_energy_kcal_per_mol": output.number("MinE")}, + ) + + inverted_repeats = None + + if self.settings.algorithm.needs_inverted_repeats: + inverted_repeats = InvertedRepeat.parse_all(ir_string or "") + + if not inverted_repeats: + self.warnings.append( + ResultWarning( + WarningCode.NO_INVERTED_REPEATS_FOUND, + "IRF found no candidate inverted repeats, so no cruciforms " + "can form.", + ) + ) + + return Result( + provenance=self._provenance.finish(irf_version=irf_version), + algorithm=self.settings.algorithm, + input=InputDescription.describe(self.settings, sequence), + parameters=self.settings.parameters(), + warnings=self.warnings, + derived_parameters=self._reader.derived_parameters(output), + summary=self._reader.summary(output), + transitions=self._reader.transitions(output), + inverted_repeats=inverted_repeats, + diagnostics=self._reader.diagnostics(output), + ) + + def failure( + self, + error: ResultError, + *, + sequence: SequenceInput | None = None, + output: QsiddOutput | None = None, + irf_version: str | None = None, + ) -> Result: + """Build the result of a run that failed. + + Everything known before the failure is kept, so a partition function + underflow still records the derived parameters qsidd printed. + + Args: + error: Why the run failed. + sequence: The sequence, if it was read before the failure. + output: The parsed qsidd output, if qsidd ran. + irf_version: The IRF version, if IRF ran. + + Returns: + The failed result. + """ + return Result( + provenance=self._provenance.finish(irf_version=irf_version), + algorithm=self.settings.algorithm, + input=InputDescription.describe(self.settings, sequence), + parameters=self.settings.parameters(), + warnings=self.warnings, + derived_parameters=self._known_derived_parameters(output), + error=error, + ) + + def _known_derived_parameters( + self, output: QsiddOutput | None + ) -> DerivedParameters | None: + """Read the derived parameters for a failed run, if they can be read. + + Args: + output: The parsed qsidd output, or None if qsidd did not run. + + Returns: + The derived parameters, or None if they are not known. + """ + if output is None: + return None + + try: + return self._reader.derived_parameters(output) + except (KeyError, ValueError): + return None diff --git a/src/sist/results/diagnostics.py b/src/sist/results/diagnostics.py new file mode 100644 index 0000000..d9e892d --- /dev/null +++ b/src/sist/results/diagnostics.py @@ -0,0 +1,299 @@ +"""Warning and error codes, and the checks that raise warnings. + +Every code a result can hold is listed here once, along with the part of SIST +that raises it, so codes cannot drift between the code, the tests and the docs. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import StrEnum +from typing import TYPE_CHECKING, Any + +from sist.ir_finder import IRFinder + +if TYPE_CHECKING: + from sist.results.sequence import SequenceInput + from sist.transitions import Algorithm + + +class WarningCode(StrEnum): + """Every warning a result can hold.""" + + THRESHOLD_TOO_LOW = "threshold_too_low" + THRESHOLD_TOO_HIGH = "threshold_too_high" + SUPERHELICAL_DENSITY_OUT_OF_RANGE = "superhelical_density_out_of_range" + TEMPERATURE_OUT_OF_RANGE = "temperature_out_of_range" + SALT_CONCENTRATION_OUT_OF_RANGE = "salt_concentration_out_of_range" + SEQUENCE_TOO_SHORT = "sequence_too_short" + SEQUENCE_TOO_LONG = "sequence_too_long" + AMBIGUOUS_BASES_REPLACED = "ambiguous_bases_replaced" + UNRECOGNISED_CHARACTERS_IGNORED = "unrecognised_characters_ignored" + NEAREST_NEIGHBOR_IGNORED = "nearest_neighbor_ignored" + CRUCIFORM_SALT_FIXED = "cruciform_salt_fixed" + NO_INVERTED_REPEATS_FOUND = "no_inverted_repeats_found" + + @property + def source(self) -> str: + """Part of SIST that raises this warning.""" + return WARNING_SOURCES.get(self, "sist") + + +class ErrorCode(StrEnum): + """Every reason a run can fail.""" + + INPUT_NOT_FOUND = "input_not_found" + EMPTY_SEQUENCE = "empty_sequence" + MULTIPLE_SEQUENCES = "multiple_sequences" + IRF_NOT_FOUND = "irf_not_found" + QSIDD_NOT_FOUND = "qsidd_not_found" + QSIDD_FAILED = "qsidd_failed" + PARTITION_FUNCTION_UNDERFLOW = "partition_function_underflow" + INTERNAL_ERROR = "internal_error" + + @property + def stage(self) -> str: + """Step of the run that fails with this code.""" + return ERROR_STAGES[self] + + +WARNING_SOURCES: dict[WarningCode, str] = { + WarningCode.THRESHOLD_TOO_LOW: "qsidd", + WarningCode.THRESHOLD_TOO_HIGH: "qsidd", + WarningCode.SUPERHELICAL_DENSITY_OUT_OF_RANGE: "qsidd", + WarningCode.TEMPERATURE_OUT_OF_RANGE: "qsidd", + WarningCode.SALT_CONCENTRATION_OUT_OF_RANGE: "qsidd", + WarningCode.NO_INVERTED_REPEATS_FOUND: "ir_finder", +} + +ERROR_STAGES: dict[ErrorCode, str] = { + ErrorCode.INPUT_NOT_FOUND: "input", + ErrorCode.EMPTY_SEQUENCE: "input", + ErrorCode.MULTIPLE_SEQUENCES: "input", + ErrorCode.IRF_NOT_FOUND: "ir_finder", + ErrorCode.QSIDD_NOT_FOUND: "qsidd", + ErrorCode.QSIDD_FAILED: "qsidd", + ErrorCode.PARTITION_FUNCTION_UNDERFLOW: "qsidd", + ErrorCode.INTERNAL_ERROR: "internal", +} + +QSIDD_WARNINGS: dict[str, WarningCode] = { + "threshold is too small, results may be inaccurate": WarningCode.THRESHOLD_TOO_LOW, + "threshold is too high, execution time may be very long": ( + WarningCode.THRESHOLD_TOO_HIGH + ), + "superhelical density is outside of physiological range": ( + WarningCode.SUPERHELICAL_DENSITY_OUT_OF_RANGE + ), + "temperature is outside of physiological range": ( + WarningCode.TEMPERATURE_OUT_OF_RANGE + ), + "salt concentration is outside of physiological range": ( + WarningCode.SALT_CONCENTRATION_OUT_OF_RANGE + ), +} +"""qsidd's warning text and its code. qsidd's two sequence length warnings are +left out, because it checks the size of the file rather than the number of base +pairs, so :func:`check_sequence` raises those instead.""" + +MIN_SEQUENCE_LENGTH = 1500 +"""Shortest recommended sequence, in base pairs.""" + +MAX_SEQUENCE_LENGTH = 10000 +"""Longest recommended sequence, in base pairs.""" + + +@dataclass(frozen=True) +class ResultWarning: + """A warning recorded in a result. + + Attributes: + code: What kind of warning it is. + message: What it means, written for people. + details: Extra values about the warning. + """ + + code: WarningCode + message: str + details: dict[str, Any] | None = None + + def to_dict(self) -> dict[str, Any]: + """Write the warning in the shape the result schema expects. + + Returns: + One entry of a result's ``warnings`` list. + """ + warning: dict[str, Any] = { + "code": str(self.code), + "message": self.message, + "source": self.code.source, + } + + if self.details: + warning["details"] = self.details + + return warning + + +class ResultError(Exception): + """A run that could not produce a result, and why. + + Attributes: + code: Why the run failed. + message: What went wrong, written for people. + exit_code: Exit code of the failing external program, if any. + stderr: Standard error of the failing external program, if any. + details: Extra values about the error. + """ + + def __init__( + self, + code: ErrorCode, + message: str, + *, + exit_code: int | None = None, + stderr: str | None = None, + details: dict[str, Any] | None = None, + ) -> None: + """Record why the run failed. + + Args: + code: Why the run failed. + message: What went wrong. + exit_code: Exit code of the failing external program, if any. + stderr: Standard error of the failing external program, if any. + details: Extra values about the error. + """ + super().__init__(message) + + self.code = code + self.message = message + self.exit_code = exit_code + self.stderr = stderr + self.details = details + + def to_dict(self) -> dict[str, Any]: + """Write the error in the shape the result schema expects. + + Returns: + The ``error`` section of a failed result. + """ + error: dict[str, Any] = { + "code": str(self.code), + "message": self.message, + "stage": self.code.stage, + "exit_code": self.exit_code, + "stderr": self.stderr, + } + + if self.details: + error["details"] = self.details + + return error + + +def check_sequence(sequence: SequenceInput) -> list[ResultWarning]: + """Raise the warnings the input sequence calls for. + + Args: + sequence: The sequence qsidd will analyse. + + Returns: + Warnings about ambiguous bases, dropped characters and the length. + """ + warnings = [] + length = len(sequence.analysed) + n_positions = sequence.n_positions + + if n_positions: + warnings.append( + ResultWarning( + WarningCode.AMBIGUOUS_BASES_REPLACED, + f"{len(n_positions)} N base(s) in the sequence were analysed as G.", + {"count": len(n_positions), "positions": n_positions}, + ) + ) + + if sequence.dropped: + warnings.append( + ResultWarning( + WarningCode.UNRECOGNISED_CHARACTERS_IGNORED, + f"{sequence.dropped} character(s) other than A, C, G, T and N were " + "dropped, so later positions are shifted.", + {"count": sequence.dropped}, + ) + ) + + if length < MIN_SEQUENCE_LENGTH: + warnings.append( + ResultWarning( + WarningCode.SEQUENCE_TOO_SHORT, + f"The sequence is {length} bp, shorter than the recommended " + f"{MIN_SEQUENCE_LENGTH} bp.", + {"sequence_length_bp": length}, + ) + ) + + if length > MAX_SEQUENCE_LENGTH: + warnings.append( + ResultWarning( + WarningCode.SEQUENCE_TOO_LONG, + f"The sequence is {length} bp, longer than the recommended " + f"{MAX_SEQUENCE_LENGTH} bp.", + {"sequence_length_bp": length}, + ) + ) + + return warnings + + +def check_settings( + algorithm: Algorithm, *, nearest_neighbor: bool, salt: float +) -> list[ResultWarning]: + """Raise the warnings for settings the algorithm cannot use as given. + + Args: + algorithm: The algorithm being run. + nearest_neighbor: Whether nearest-neighbor energetics were asked for. + salt: Salt concentration in mol/L. + + Returns: + Warnings about ignored energetics and the fixed cruciform salt. + """ + warnings = [] + + if nearest_neighbor and not algorithm.supports_nearest_neighbor: + warnings.append( + ResultWarning( + WarningCode.NEAREST_NEIGHBOR_IGNORED, + "Nearest-neighbor energetics only apply to melting, so they were " + "ignored.", + ) + ) + + if algorithm.needs_inverted_repeats and salt != IRFinder.CRUCIFORM_SALT: + warnings.append( + ResultWarning( + WarningCode.CRUCIFORM_SALT_FIXED, + f"Inverted repeats are always scored at {IRFinder.CRUCIFORM_SALT} M " + f"salt, not the {salt} M used by qsidd.", + ) + ) + + return warnings + + +def qsidd_warnings(messages: list[str]) -> list[ResultWarning]: + """Turn qsidd's warning lines into coded warnings. + + Args: + messages: The text of each ``WARNING:`` line qsidd printed. + + Returns: + A warning for each line with a known code, in the same order. + """ + return [ + ResultWarning(QSIDD_WARNINGS[message], f"{message[0].upper()}{message[1:]}.") + for message in messages + if message in QSIDD_WARNINGS + ] diff --git a/src/sist/results/model.py b/src/sist/results/model.py new file mode 100644 index 0000000..766c3d5 --- /dev/null +++ b/src/sist/results/model.py @@ -0,0 +1,433 @@ +"""The typed SIST result. + +Each section of a result is a small dataclass with a ``to_dict`` method. This +is the one place that knows the shape of ``sist-result-v1.schema.json``, so the +rest of the code works with typed values instead of nested dictionaries. +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +from typing import Any + +from sist.ir_finder import IRFinder +from sist.results.diagnostics import ResultError, ResultWarning +from sist.results.sequence import SequenceInput +from sist.transitions import Algorithm + +SCHEMA_VERSION = "1.0.0" +"""Version of the result model this package writes.""" + +PairMatrices = dict[str, dict[str, dict[str, float | None]]] +"""Pairwise probabilities, read as ``matrices[name][first][second]``.""" + + +@dataclass(frozen=True) +class RunSettings: + """The settings for one SIST calculation. + + Attributes: + file: Path to the input sequence file, as given. + algorithm: The algorithm being run. + temperature: Temperature in kelvin. + superhelical_density: Superhelical density, as given. + salt: Salt concentration in mol/L. + energy_threshold: Energy threshold in kcal/mol. + circular: Whether the molecule is circular. + nearest_neighbor: Whether nearest-neighbor energetics were asked for. + """ + + file: str + algorithm: Algorithm + temperature: float + superhelical_density: float + salt: float + energy_threshold: float + circular: bool + nearest_neighbor: bool + + @property + def molecule_type(self) -> str: + """``"circular"`` or ``"linear"``.""" + return "circular" if self.circular else "linear" + + def parameters(self) -> dict[str, Any]: + """Write the settings as the calculation used them. + + qsidd always uses negative supercoiling, and the IR finder always scores + inverted repeats at a fixed salt, so those are recorded as used. + + Returns: + The ``parameters`` section. + """ + melting_energetics = None + + if "melting" in self.algorithm.transition_names: + melting_energetics = ( + "nearest_neighbor" if self.nearest_neighbor else "copolymeric" + ) + + parameters: dict[str, Any] = { + "temperature_k": self.temperature, + "superhelical_density": -abs(self.superhelical_density), + "salt_concentration_m": self.salt, + "energy_threshold_kcal_per_mol": self.energy_threshold, + "melting_energetics": melting_energetics, + } + + if self.algorithm.needs_inverted_repeats: + parameters["cruciform_salt_concentration_m"] = IRFinder.CRUCIFORM_SALT + + return parameters + + +@dataclass(frozen=True) +class Provenance: + """How, where and when a result was made. + + Attributes: + version: SIST version. + git_sha: Git commit of the SIST source, if known. + engine: qsidd binary used. + irf_version: IRF version, for runs that score inverted repeats. + python: Python version. + platform: Operating system and architecture. + command: The command line as given, or None when run from Python. + started_at: When the run started. + finished_at: When the run finished. + wall_time_s: Elapsed time in seconds. + """ + + version: str + git_sha: str | None + engine: str + irf_version: str | None + python: str + platform: str + command: list[str] | None + started_at: str + finished_at: str + wall_time_s: float + + def to_dict(self) -> dict[str, Any]: + """Write the ``provenance`` section.""" + return { + "software": { + "name": "SIST", + "version": self.version, + "git_sha": self.git_sha, + "engine": self.engine, + "irf_version": self.irf_version, + }, + "environment": {"python": self.python, "platform": self.platform}, + "command": self.command, + "started_at": self.started_at, + "finished_at": self.finished_at, + "wall_time_s": self.wall_time_s, + } + + +@dataclass(frozen=True) +class InputDescription: + """The input sequence, as analysed. + + Attributes: + sequence_file: Path to the sequence file, as given. + sequence_name: FASTA header, or None. + sequence_length_bp: Base pairs analysed, or None if never read. + analysed_sequence: The bases qsidd reports, or None if never read. + sequence_sha256: SHA-256 of the analysed bases, or None if never read. + molecule_type: ``"linear"`` or ``"circular"``. + """ + + sequence_file: str | None + sequence_name: str | None + sequence_length_bp: int | None + analysed_sequence: str | None + sequence_sha256: str | None + molecule_type: str + + @classmethod + def describe( + cls, settings: RunSettings, sequence: SequenceInput | None + ) -> InputDescription: + """Describe the input, as far as it was read. + + Args: + settings: The run's settings. + sequence: The sequence, or None if it was never read. + + Returns: + The input description. + """ + if sequence is None: + return cls(settings.file, None, None, None, None, settings.molecule_type) + + return cls( + sequence_file=settings.file, + sequence_name=sequence.name, + sequence_length_bp=len(sequence.analysed), + analysed_sequence=sequence.bases, + sequence_sha256=sequence.sha256, + molecule_type=settings.molecule_type, + ) + + def to_dict(self) -> dict[str, Any]: + """Write the ``input`` section, leaving out a sequence that was never read.""" + section = asdict(self) + + if self.analysed_sequence is None: + del section["analysed_sequence"] + + return section + + +@dataclass(frozen=True) +class DerivedParameters: + """Model values qsidd works out from the settings. + + Attributes: + linking_difference_turns: Imposed linking difference, in turns. + torsional_stiffness_kcal_bp_per_rad2: Torsional stiffness. + bat_kcal_per_mol: Copolymeric A-T melting energy, if printed. + bgc_kcal_per_mol: Copolymeric G-C melting energy, if printed. + """ + + linking_difference_turns: float | None + torsional_stiffness_kcal_bp_per_rad2: float | None + bat_kcal_per_mol: float | None + bgc_kcal_per_mol: float | None + + def to_dict(self) -> dict[str, Any]: + """Write the ``derived_parameters`` section.""" + return asdict(self) + + +@dataclass(frozen=True) +class Summary: + """Whole-molecule results. + + Attributes: + ln_partition_function: Natural log of the partition function. + partition_function: The partition function, or None if too small to + store. + average_number_of_runs: Expected total number of runs. + states_by_number_of_runs: Entry k counts states with k + 1 runs. + total_states: All states counted. + pairwise: Pairwise probabilities, for competition runs. + """ + + ln_partition_function: float | None + partition_function: float | None + average_number_of_runs: float | None + states_by_number_of_runs: list[int] + total_states: int + pairwise: PairMatrices | None = None + + def to_dict(self) -> dict[str, Any]: + """Write the ``summary`` section.""" + summary: dict[str, Any] = { + "ln_partition_function": self.ln_partition_function, + "partition_function": self.partition_function, + "average_number_of_runs": self.average_number_of_runs, + "state_counts": { + "by_number_of_runs": self.states_by_number_of_runs, + "total": self.total_states, + }, + } + + if self.pairwise is not None: + summary["pairwise"] = self.pairwise + + return summary + + +@dataclass(frozen=True) +class TransitionResult: + """Everything SIST reports about one transition. + + Attributes: + nucleation_energy_kcal_per_mol: Nucleation energy. + probability: Probability of at least one run. + expected_runs: Expected number of runs. + expected_transformed_bp: Expected number of base pairs in the transition. + profile_probability: Probability at each position. + free_energy_kcal_per_mol: G(x) at each position, where qsidd reports it. + """ + + nucleation_energy_kcal_per_mol: float | None + probability: float | None + expected_runs: float | None + expected_transformed_bp: float | None + profile_probability: list[float] + free_energy_kcal_per_mol: list[float | None] | None = None + + def to_dict(self) -> dict[str, Any]: + """Write one entry of the ``transitions`` section.""" + profile: dict[str, Any] = {"probability": self.profile_probability} + + if self.free_energy_kcal_per_mol is not None: + profile["free_energy_kcal_per_mol"] = self.free_energy_kcal_per_mol + + return { + "nucleation_energy_kcal_per_mol": self.nucleation_energy_kcal_per_mol, + "probability": self.probability, + "expected_runs": self.expected_runs, + "expected_transformed_bp": self.expected_transformed_bp, + "profile": profile, + } + + +@dataclass(frozen=True) +class InvertedRepeat: + """One candidate cruciform scored by the IR finder. + + Attributes: + start: 1-based first position of the region. + length_bp: Length of the region, arms and loop. + energy_kcal_per_mol: Free energy to extrude the cruciform. + """ + + start: int + length_bp: int + energy_kcal_per_mol: float + + @classmethod + def parse_all(cls, ir_string: str) -> list[InvertedRepeat]: + """Read the scored inverted repeats from the string passed to qsidd. + + The string is ``start,length,energy,|`` repeated, and starts with a + placeholder entry of length 0, which is left out. + + Args: + ir_string: The string the IR finder built for ``qsidd -X``. + + Returns: + The scored inverted repeats. + """ + inverted_repeats = [] + + for entry in ir_string.split("|"): + parts = entry.split(",") + + if len(parts) >= 3 and int(parts[1]) > 0: + inverted_repeats.append( + cls(int(parts[0]), int(parts[1]), float(parts[2])) + ) + + return inverted_repeats + + def to_dict(self) -> dict[str, Any]: + """Write one entry of the ``inverted_repeats`` section.""" + return asdict(self) + + +@dataclass(frozen=True) +class Diagnostics: + """Values for checking a run. + + Attributes: + scaling_factor: Offset qsidd adds to every Boltzmann exponent. + min_energy_kcal_per_mol: Lowest state energy found. + max_energy_kcal_per_mol: Highest state energy counted. + """ + + scaling_factor: float | None + min_energy_kcal_per_mol: float | None + max_energy_kcal_per_mol: float | None + + def to_dict(self) -> dict[str, Any]: + """Write the ``diagnostics`` section.""" + return { + "scaling_factor": self.scaling_factor, + "energy_window": { + "min_energy_kcal_per_mol": self.min_energy_kcal_per_mol, + "max_energy_kcal_per_mol": self.max_energy_kcal_per_mol, + }, + } + + +@dataclass(frozen=True) +class Result: + """A complete SIST result, successful or failed. + + Attributes: + provenance: How, where and when it was made. + algorithm: The algorithm that was run. + input: The input sequence. + parameters: The settings as used, from :meth:`RunSettings.parameters`. + warnings: Warnings raised during the run. + derived_parameters: Model values, if known. + summary: Whole-molecule results, for a successful run. + transitions: Results for each transition, for a successful run. + inverted_repeats: Scored inverted repeats, for runs that use them. + diagnostics: Values for checking a successful run. + error: Why the run failed, for a failed run. + """ + + provenance: Provenance + algorithm: Algorithm + input: InputDescription + parameters: dict[str, Any] + warnings: list[ResultWarning] + derived_parameters: DerivedParameters | None = None + summary: Summary | None = None + transitions: dict[str, TransitionResult] | None = None + inverted_repeats: list[InvertedRepeat] | None = None + diagnostics: Diagnostics | None = None + error: ResultError | None = None + + @property + def status(self) -> str: + """``"failed"`` if there is an error, otherwise ``"success"``.""" + return "failed" if self.error is not None else "success" + + def to_dict(self) -> dict[str, Any]: + """Write the result in the shape of ``sist-result-v1.schema.json``. + + Returns: + The result, with its sections in the documented order. + """ + result: dict[str, Any] = { + "schema_version": SCHEMA_VERSION, + "status": self.status, + "provenance": self.provenance.to_dict(), + "calculation": { + "algorithm": self.algorithm.flag, + "transitions": list(self.algorithm.transition_names), + }, + "input": self.input.to_dict(), + "parameters": self.parameters, + "derived_parameters": _to_dict_or_none(self.derived_parameters), + "summary": _to_dict_or_none(self.summary), + "transitions": ( + {name: result.to_dict() for name, result in self.transitions.items()} + if self.transitions is not None + else None + ), + } + + if self.inverted_repeats is not None: + result["inverted_repeats"] = [ + inverted_repeat.to_dict() for inverted_repeat in self.inverted_repeats + ] + + if self.diagnostics is not None: + result["diagnostics"] = self.diagnostics.to_dict() + + result["warnings"] = [warning.to_dict() for warning in self.warnings] + result["error"] = _to_dict_or_none(self.error) + + return result + + +def _to_dict_or_none(section: Any) -> dict[str, Any] | None: + """Write a section with its own ``to_dict``, or None if it is missing. + + Args: + section: A section object with a ``to_dict`` method, or None. + + Returns: + The section as a dictionary, or None. + """ + return section.to_dict() if section is not None else None diff --git a/src/sist/results/provenance.py b/src/sist/results/provenance.py new file mode 100644 index 0000000..7431a41 --- /dev/null +++ b/src/sist/results/provenance.py @@ -0,0 +1,103 @@ +"""Record how, where and when a result was made.""" + +from __future__ import annotations + +import os +import platform +import re +import subprocess +import time +from datetime import UTC, datetime +from pathlib import Path + +import sist +from sist.results.model import Provenance + + +class ProvenanceRecorder: + """Record a run's provenance, starting the clock when it is created. + + Attributes: + GIT_SHA_ENV_VAR: Environment variable that sets the git commit, for + builds made outside a git checkout. + engine: qsidd binary the run uses. + command: The command line as given, or None when run from Python. + started_at: When the run started. + """ + + GIT_SHA_ENV_VAR = "SIST_GIT_SHA" + + def __init__(self, *, engine: str, command: list[str] | None) -> None: + """Start the clock for a run. + + Args: + engine: qsidd binary the run uses. + command: The command line as given, or None when run from Python. + """ + self.engine = engine + self.command = command + self.started_at = self.timestamp() + + self._start = time.perf_counter() + + def finish(self, *, irf_version: str | None) -> Provenance: + """Stop the clock and record the provenance. + + Args: + irf_version: The IRF version, for runs that score inverted repeats. + + Returns: + The provenance. + """ + return Provenance( + version=sist.__version__, + git_sha=self.git_sha(), + engine=self.engine, + irf_version=irf_version, + python=platform.python_version(), + platform=platform.platform(), + command=self.command, + started_at=self.started_at, + finished_at=self.timestamp(), + wall_time_s=round(time.perf_counter() - self._start, 3), + ) + + @staticmethod + def timestamp() -> str: + """The current UTC time in RFC 3339 format.""" + return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") + + @classmethod + def git_sha(cls) -> str | None: + """Find the git commit SIST is running from. + + The environment variable wins if it is set. Otherwise the commit is read + with git, but only when SIST is running from a source checkout, so an + installed copy never reports an unrelated repository. + + Returns: + The commit hash, or None if it cannot be found. + """ + override = os.environ.get(cls.GIT_SHA_ENV_VAR) + + if override: + return override + + repository_root = Path(__file__).resolve().parents[3] + + if not (repository_root / ".git").exists(): + return None + + try: + completed = subprocess.run( + ["git", "-C", str(repository_root), "rev-parse", "HEAD"], + capture_output=True, + text=True, + check=False, + ) + except OSError: + return None + + sha = completed.stdout.strip() + + return sha if re.fullmatch(r"[0-9a-f]{7,40}", sha) else None diff --git a/src/sist/results/qsidd_output.py b/src/sist/results/qsidd_output.py new file mode 100644 index 0000000..fd376f1 --- /dev/null +++ b/src/sist/results/qsidd_output.py @@ -0,0 +1,109 @@ +"""Split qsidd's text output into its parts.""" + +from __future__ import annotations + +import math +from dataclasses import dataclass, field + + +@dataclass(frozen=True) +class QsiddOutput: + """The text output of one qsidd run, split into its parts. + + This knows only qsidd's text format, not what the values mean or where they + go in a result. + + Attributes: + values: Every ``key = value`` line, with the value kept as text. + warnings: The text of each ``WARNING:`` line, in order. + columns: Headings of the per-position table. + rows: The per-position table, one list of values per position. + """ + + values: dict[str, str] = field(default_factory=dict) + warnings: list[str] = field(default_factory=list) + columns: list[str] = field(default_factory=list) + rows: list[list[str]] = field(default_factory=list) + + @classmethod + def parse(cls, text: str) -> QsiddOutput: + """Split qsidd's text output into values, warnings and the table. + + Most values are printed as ``key = value``, sometimes two to a line + separated by ``;``. The scaling factor is the one value printed without + an ``=``. + + Args: + text: Standard output of a qsidd run. + + Returns: + The parsed output. + """ + output = cls() + + for line in text.splitlines(): + if output.columns: + if line.strip(): + output.rows.append(line.rstrip("\t").split("\t")) + continue + + if line.startswith("WARNING: "): + output.warnings.append(line.removeprefix("WARNING: ")) + elif line.startswith("Position"): + output.columns.extend(line.split("\t")) + elif line.startswith("Scaling factor"): + output.values["Scaling factor"] = line.split()[-1] + else: + for part in line.split(";"): + if "=" in part: + key, value = part.split("=", 1) + output.values[key.strip()] = value.strip() + + return output + + def number(self, key: str) -> float | None: + """Read a printed value as a number. + + Values such as ``-25.4 turns`` keep only the number. qsidd prints + ``nan`` and ``inf`` when a calculation breaks down, and those come back + as None, because JSON cannot hold them. + + Args: + key: Name of the value, as printed before the ``=``. + + Returns: + The number, or None if it is not a finite number. + + Raises: + KeyError: If qsidd did not print the value. + """ + value = float(self.values[key].split()[0]) + + return value if math.isfinite(value) else None + + def count(self, key: str) -> int: + """Read a printed state count as an exact integer. + + Args: + key: Name of the count, as printed before the ``=``. + + Returns: + The count. + + Raises: + KeyError: If qsidd did not print the count. + """ + return int(float(self.values[key])) + + def column(self, name: str) -> list[str]: + """Read one column of the per-position table. + + Args: + name: Column heading, such as ``"P(x)"``. + + Returns: + The column's values as text, one per position. + """ + index = self.columns.index(name) + + return [row[index] for row in self.rows] diff --git a/src/sist/results/reader.py b/src/sist/results/reader.py new file mode 100644 index 0000000..3ff59c4 --- /dev/null +++ b/src/sist/results/reader.py @@ -0,0 +1,226 @@ +"""Turn qsidd's output into result values, for any algorithm. + +qsidd prints the same values under different names depending on whether it ran +one transition or a competition. The names come from :mod:`sist.transitions`, +so one reader handles every algorithm without checking algorithm letters. +""" + +from __future__ import annotations + +from sist.results.model import ( + DerivedParameters, + Diagnostics, + PairMatrices, + Summary, + TransitionResult, +) +from sist.results.qsidd_output import QsiddOutput +from sist.transitions import Algorithm, Transition + + +class QsiddReader: + """Read result values from the full-precision output of one qsidd run. + + Attributes: + FREE_ENERGY_COLUMN: Heading of qsidd's G(x) column, which it prints for + a single melting transition. + algorithm: The algorithm qsidd ran. + """ + + FREE_ENERGY_COLUMN = "G(x)" + + def __init__(self, algorithm: Algorithm) -> None: + """Set up a reader for one algorithm's output. + + Args: + algorithm: The algorithm qsidd ran. + """ + self.algorithm = algorithm + + def underflowed(self, output: QsiddOutput) -> bool: + """Check whether the partition function underflowed to zero. + + qsidd still exits normally when this happens, but every probability it + prints is meaningless, and its log of the partition function is not a + finite number. + + Args: + output: The parsed qsidd output. + + Returns: + True if the run's values cannot be used. + """ + return output.number("ln Partition Function") is None + + def derived_parameters(self, output: QsiddOutput) -> DerivedParameters: + """Read the model values qsidd works out from the settings. + + Args: + output: The parsed qsidd output. + + Returns: + The derived parameters. + + Raises: + KeyError: If qsidd did not print them. + """ + stiffness_key = "K" if "K" in output.values else "C" + + return DerivedParameters( + linking_difference_turns=output.number("linking difference"), + torsional_stiffness_kcal_bp_per_rad2=output.number(stiffness_key), + bat_kcal_per_mol=self._optional_number(output, "BAT"), + bgc_kcal_per_mol=self._optional_number(output, "BGC"), + ) + + def summary(self, output: QsiddOutput) -> Summary: + """Read the whole-molecule results. + + Args: + output: The parsed qsidd output. + + Returns: + The summary. + """ + return Summary( + ln_partition_function=output.number("ln Partition Function"), + partition_function=output.number("Total Partition Function") or None, + average_number_of_runs=output.number("Average number of runs"), + states_by_number_of_runs=[ + output.count(f"Number of {runs}-run states") + for runs in ("one", "two", "three", "four") + ], + total_states=output.count("Total number of states"), + pairwise=self._pairwise(output) if self.algorithm.competition else None, + ) + + def transitions(self, output: QsiddOutput) -> dict[str, TransitionResult]: + """Read the results for each transition. + + Args: + output: The parsed qsidd output. + + Returns: + The results, keyed by transition name. + """ + return { + transition.name: self._transition(output, transition) + for transition in self.algorithm.transitions + } + + def diagnostics(self, output: QsiddOutput) -> Diagnostics: + """Read the values for checking a run. + + Args: + output: The parsed qsidd output. + + Returns: + The diagnostics. + """ + return Diagnostics( + scaling_factor=output.number("Scaling factor"), + min_energy_kcal_per_mol=output.number("MinE"), + max_energy_kcal_per_mol=output.number("Max_E"), + ) + + def _transition( + self, output: QsiddOutput, transition: Transition + ) -> TransitionResult: + """Read the results for one transition. + + G(x) is included when qsidd printed it, and is null where the + transition's probability is 0, because G(x) is undefined there. + + Args: + output: The parsed qsidd output. + transition: The transition to read. + + Returns: + The transition's results. + """ + names = transition.names(competition=self.algorithm.competition) + probability = [float(value) for value in output.column(names.profile_column)] + free_energy = None + + if self.FREE_ENERGY_COLUMN in output.columns: + free_energy = [ + None if position_probability == 0 else float(value) + for position_probability, value in zip( + probability, output.column(self.FREE_ENERGY_COLUMN), strict=True + ) + ] + + return TransitionResult( + nucleation_energy_kcal_per_mol=output.number(names.nucleation_energy), + probability=output.number(names.probability), + expected_runs=output.number(names.expected_runs), + expected_transformed_bp=output.number(names.expected_transformed_bp), + profile_probability=probability, + free_energy_kcal_per_mol=free_energy, + ) + + def _pairwise(self, output: QsiddOutput) -> PairMatrices: + """Read the probabilities for pairs of transitions. + + qsidd writes 0 for P(a given not b) when b is certain, which is + undefined rather than 0, so that case is written as null. Values qsidd + prints as ``nan``, such as P(a given b) when b never happens, are also + null. + + Args: + output: The parsed qsidd output. + + Returns: + The joint and conditional probabilities. + """ + competition_names = { + transition.name: transition.names(competition=True) + for transition in self.algorithm.transitions + } + certain = { + name: (output.number(names.probability) or 0.0) >= 1.0 + for name, names in competition_names.items() + } + matrices: PairMatrices = { + "joint_probability": {}, + "conditional_probability": {}, + "conditional_probability_given_absent": {}, + } + + for first in self.algorithm.transitions: + for second in self.algorithm.transitions: + if first is second: + continue + + pair = f"{first.letter} {second.letter}" + given = f"{first.letter} given {second.letter}" + given_not = f"{first.letter} given not {second.letter}" + + matrices["joint_probability"].setdefault(first.name, {})[ + second.name + ] = output.number(f"Joint probability {pair}") + matrices["conditional_probability"].setdefault(first.name, {})[ + second.name + ] = output.number(f"Conditional probability {given}") + matrices["conditional_probability_given_absent"].setdefault( + first.name, {} + )[second.name] = ( + None + if certain[second.name] + else output.number(f"Conditional probability {given_not}") + ) + + return matrices + + @staticmethod + def _optional_number(output: QsiddOutput, key: str) -> float | None: + """Read a value qsidd only prints for some algorithms. + + Args: + output: The parsed qsidd output. + key: Name of the value. + + Returns: + The value, or None if qsidd did not print it. + """ + return output.number(key) if key in output.values else None diff --git a/src/sist/results/sequence.py b/src/sist/results/sequence.py new file mode 100644 index 0000000..bafbe9f --- /dev/null +++ b/src/sist/results/sequence.py @@ -0,0 +1,90 @@ +"""Read the input sequence the way qsidd does.""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from pathlib import Path + +from sist.results.diagnostics import ErrorCode, ResultError + + +@dataclass(frozen=True) +class SequenceInput: + """The sequence read from the input file, as qsidd will analyse it. + + qsidd skips header lines, keeps A, C, G, T and N (in any case) and drops + every other character. This mirrors that, so the result can record what + was actually analysed. + + Attributes: + name: The FASTA header without the leading ``>``, or None if the file + has no header. + analysed: The bases qsidd analyses, in upper case. + dropped: Number of characters qsidd drops because they are not A, C, + G, T or N. + """ + + name: str | None + analysed: str + dropped: int + + @classmethod + def read(cls, path: Path) -> SequenceInput: + """Read a sequence file the way qsidd does. + + Args: + path: Path to the sequence file. + + Returns: + The sequence that qsidd will analyse. + + Raises: + ResultError: If the file does not exist, holds more than one FASTA + record, or has no bases to analyse. + """ + if not path.is_file(): + raise ResultError( + ErrorCode.INPUT_NOT_FOUND, f"The sequence file {path} does not exist." + ) + + lines = path.read_text(encoding="utf-8").splitlines() + headers = [line for line in lines if line.startswith(">")] + + if len(headers) > 1: + raise ResultError( + ErrorCode.MULTIPLE_SEQUENCES, + f"The sequence file has {len(headers)} FASTA records. SIST analyses " + "one sequence per run.", + details={"records": len(headers)}, + ) + + letters = "".join( + "".join(line.split()) for line in lines if not line.startswith(">") + ).upper() + analysed = "".join(base for base in letters if base in "ACGTN") + + if not analysed: + raise ResultError( + ErrorCode.EMPTY_SEQUENCE, + f"The sequence file {path} has no bases to analyse.", + ) + + name = headers[0][1:].strip() if headers else None + + return cls(name=name, analysed=analysed, dropped=len(letters) - len(analysed)) + + @property + def bases(self) -> str: + """The analysed sequence with N replaced by G, as qsidd reports it.""" + return self.analysed.replace("N", "G") + + @property + def sha256(self) -> str: + """SHA-256 of the bases qsidd reports, for comparing results.""" + return hashlib.sha256(self.bases.encode("ascii")).hexdigest() + + @property + def n_positions(self) -> list[int]: + """1-based positions of every N in the analysed sequence.""" + return [index + 1 for index, base in enumerate(self.analysed) if base == "N"] diff --git a/src/sist/results/writer.py b/src/sist/results/writer.py new file mode 100644 index 0000000..bf8c8b8 --- /dev/null +++ b/src/sist/results/writer.py @@ -0,0 +1,82 @@ +"""Check a result against the schema and write it as JSON.""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Any + +from sist.results.model import Result +from sist.schema import ResultValidator + + +class ResultWriter: + """Check results against the schema before writing them. + + Attributes: + validator: Validator every result must pass. + """ + + def __init__(self, validator: ResultValidator | None = None) -> None: + """Set up the writer. + + Args: + validator: Validator to use, or None for a new one. + """ + self.validator = validator or ResultValidator() + + def check(self, result: Result) -> dict[str, Any]: + """Turn a result into its schema shape and make sure it is valid. + + Args: + result: The result to check. + + Returns: + The result as a dictionary. + + Raises: + ResultValidationError: If the result is not valid. + """ + data = result.to_dict() + self.validator.check(data) + + return data + + def write(self, result: Result, path: Path) -> None: + """Check a result and write it as JSON. + + Args: + result: The result to write. + path: File to write it to. + + Raises: + ResultValidationError: If the result is not valid. + """ + path.write_text(self.to_json(self.check(result)), encoding="utf-8") + + @staticmethod + def to_json(data: dict[str, Any]) -> str: + """Write a result dictionary as JSON. + + Objects are indented, but arrays of plain values stay on one line, so a + per-position array is one line rather than one line per base pair. + + Args: + data: The result as a dictionary. + + Returns: + The JSON text, ending with a newline. + + Raises: + ValueError: If the result holds NaN or Infinity. + """ + text = json.dumps(data, indent=2, allow_nan=False, ensure_ascii=False) + value = r'(?:-?[0-9][0-9.eE+-]*|null|true|false|"[^"\n]*")' + flat_array = re.compile(rf"\[\n(\s+{value}(?:,\n\s+{value})*)\n\s*\]") + + def join(match: re.Match[str]) -> str: + items = [item.strip() for item in match.group(1).split(",\n")] + return "[" + ", ".join(items) + "]" + + return flat_array.sub(join, text) + "\n" diff --git a/tests/unit/data/qsidd/competition-no-inverted-repeats.txt b/tests/unit/data/qsidd/competition-no-inverted-repeats.txt new file mode 100644 index 0000000..a29fa95 --- /dev/null +++ b/tests/unit/data/qsidd/competition-no-inverted-repeats.txt @@ -0,0 +1,154 @@ +DNA sequence file: fragment.fa +WARNING: sequence length is too short +Sequence Length = 100 +Copolymeric melting energetics +Molecule type: linear DNA +Stress Level = -0.059999999999999998 +linking difference = -0.86538461538461531 turns +Threshold = 12 kcal/mol +Temperature = 310 K +Salt Concentration = 0.01 M +K = 3.6000000000000001 kcal-bp/rad^2 +Melting nucleation energy = 10.84 kcal/mol +Z-DNA nucleation energy = 10 kcal/mol +Cruciform nucleation energy = 12.150009109596439 kcal/mol +BAT = 0.25811566340021741 kcal/mol; BGC = 1.3048755414539936 kcal/mol +MinE = 3.4139199408284022 kcal/mol; Max_E = 15.413919940828402 kcal/mol +Number of one-run states = 734 +Number of two-run states = 0 +Number of three-run states = 0 +Number of four-run states = 0 +Total number of states = 734 +Total Partition Function = 0.0039196304026189437 +Scaling factor 300 +ln Partition Function = -5.5417579146710523 +Number of M_runs = 3.2025644480199974e-05 +Number of Z_runs = 0 +Number of C_runs = 0 +Average number of runs = 3.2025644480199974e-05 +Prob_M = 3.2025644480199974e-05 +Prob_Z = 0 +Prob_C = 0 +Joint probability M Z = 0 +Conditional probability M given Z = -nan +Conditional probability M given not Z = 3.2025644480199974e-05 +Joint probability M C = 0 +Conditional probability M given C = -nan +Conditional probability M given not C = 3.2025644480199974e-05 +Joint probability Z M = 0 +Conditional probability Z given M = 0 +Conditional probability Z given not M = 0 +Joint probability Z C = 0 +Conditional probability Z given C = -nan +Conditional probability Z given not C = 0 +Joint probability C M = 0 +Conditional probability C given M = 0 +Conditional probability C given not M = 0 +Joint probability C Z = 0 +Conditional probability C given Z = -nan +Conditional probability C given not Z = 0 +N_Melting = 0.00010879893004904143 +N_Z = 0 +N_Cruciform = 0 +Run time = 0 sec +Position Base P_melt P_Z P_cruciform +1 T 4.0793423753589667e-07 0 0 +2 T 4.6914030971625862e-07 0 0 +3 C 2.9182935314984666e-07 0 0 +4 T 4.2018992254908285e-07 0 0 +5 C 3.4610442850793684e-07 0 0 +6 A 6.9251306731949819e-07 0 0 +7 T 7.8946862192955229e-07 0 0 +8 G 6.2448139425428095e-07 0 0 +9 T 1.0593660732128728e-06 0 0 +10 T 1.1647284332383163e-06 0 0 +11 T 9.523205739885378e-07 0 0 +12 G 4.2404254498165718e-07 0 0 +13 A 4.0429861176683124e-07 0 0 +14 C 1.8857493407235279e-07 0 0 +15 A 2.4819980172218085e-07 0 0 +16 G 1.3797034223318018e-07 0 0 +17 C 2.9331162987555774e-07 0 0 +18 T 1.1165181930123367e-06 0 0 +19 T 1.587234171115155e-06 0 0 +20 A 1.6857093879700097e-06 0 0 +21 T 1.3988348489018199e-06 0 0 +22 C 7.2547105739161977e-07 0 0 +23 A 8.0858047845003177e-07 0 0 +24 T 6.4375647755173711e-07 0 0 +25 C 2.4986901078106603e-07 0 0 +26 G 3.2317653502844521e-07 0 0 +27 A 1.0581303380334267e-06 0 0 +28 T 1.4375928818987398e-06 0 0 +29 A 1.4571485839238291e-06 0 0 +30 A 1.1183171063534956e-06 0 0 +31 G 4.2345610575473713e-07 0 0 +32 C 5.2193676313987064e-07 0 0 +33 T 1.8173381555616419e-06 0 0 +34 T 2.7423748518765695e-06 0 0 +35 T 3.2151365673371688e-06 0 0 +36 A 3.1854909206977992e-06 0 0 +37 A 2.6575586548377811e-06 0 0 +38 T 1.683101351344876e-06 0 0 +39 G 3.463449547792037e-07 0 0 +40 C 7.1997383202316657e-08 0 0 +41 G 3.6382534827987523e-08 0 0 +42 G 1.4341987880425654e-07 0 0 +43 T 6.0774782473787239e-07 0 0 +44 A 8.6029778057583612e-07 0 0 +45 G 8.7297851751519428e-07 0 0 +46 T 1.8961267822509131e-06 0 0 +47 T 2.5179027242233128e-06 0 0 +48 T 2.6978952410212593e-06 0 0 +49 A 2.4261110260970521e-06 0 0 +50 T 1.7243386006184001e-06 0 0 +51 C 6.4076369383616412e-07 0 0 +52 A 5.583354452456917e-07 0 0 +53 C 3.0415151130535692e-07 0 0 +54 A 6.1191333578782006e-07 0 0 +55 G 7.6173240715902808e-07 0 0 +56 T 2.3014841076537773e-06 0 0 +57 T 3.5097942216022031e-06 0 0 +58 A 4.2759919571447433e-06 0 0 +59 A 4.5150093335851082e-06 0 0 +60 A 4.1951856786740917e-06 0 0 +61 T 3.3575617419947795e-06 0 0 +62 T 2.0989149306141172e-06 0 0 +63 G 5.3033249958333282e-07 0 0 +64 C 3.4150433203696613e-07 0 0 +65 T 7.3199359271558464e-07 0 0 +66 A 8.2860431736227873e-07 0 0 +67 A 6.4248018313138444e-07 0 0 +68 C 1.6591252367629922e-07 0 0 +69 G 5.3841835553960749e-08 0 0 +70 C 6.2658104598805347e-08 0 0 +71 A 1.9110438721605213e-07 0 0 +72 G 1.4937760670745735e-07 0 0 +73 T 2.4110116378703278e-07 0 0 +74 C 1.4937760670745735e-07 0 0 +75 A 1.9110438721605213e-07 0 0 +76 G 6.2658104598805347e-08 0 0 +77 G 3.406687501535414e-08 0 0 +78 C 5.3330299827052268e-08 0 0 +79 A 1.3066045487821799e-07 0 0 +80 C 5.3330299827052262e-08 0 0 +81 C 3.406687501535414e-08 0 0 +82 G 8.3195204979939733e-08 0 0 +83 T 3.2967240647713059e-07 0 0 +84 G 4.0107073114679307e-07 0 0 +85 T 1.0105453417380568e-06 0 0 +86 A 1.3277886858022369e-06 0 0 +87 T 1.343863670542425e-06 0 0 +88 G 1.0355801928332564e-06 0 0 +89 A 1.7701895522843551e-06 0 0 +90 A 2.1413624757858118e-06 0 0 +91 A 2.1458404298177064e-06 0 0 +92 T 1.7856529259718588e-06 0 0 +93 C 1.0661213145139547e-06 0 0 +94 T 1.4728854496082566e-06 0 0 +95 A 1.567262389978091e-06 0 0 +96 A 1.3589414185356195e-06 0 0 +97 C 8.4227407125499549e-07 0 0 +98 A 1.1404676043498826e-06 0 0 +99 A 1.1173518897285279e-06 0 0 +100 T 7.9774492162681328e-07 0 0 diff --git a/tests/unit/data/qsidd/competition.txt b/tests/unit/data/qsidd/competition.txt new file mode 100644 index 0000000..1a64769 --- /dev/null +++ b/tests/unit/data/qsidd/competition.txt @@ -0,0 +1,154 @@ +DNA sequence file: fragment.fa +WARNING: sequence length is too short +Sequence Length = 100 +Copolymeric melting energetics +Molecule type: linear DNA +Stress Level = -0.059999999999999998 +linking difference = -0.86538461538461531 turns +Threshold = 12 kcal/mol +Temperature = 310 K +Salt Concentration = 0.01 M +K = 3.6000000000000001 kcal-bp/rad^2 +Melting nucleation energy = 10.84 kcal/mol +Z-DNA nucleation energy = 10 kcal/mol +Cruciform nucleation energy = 12.150009109596439 kcal/mol +BAT = 0.25811566340021741 kcal/mol; BGC = 1.3048755414539936 kcal/mol +MinE = 2.8793244378698226 kcal/mol; Max_E = 14.879324437869823 kcal/mol +Number of one-run states = 588 +Number of two-run states = 84 +Number of three-run states = 0 +Number of four-run states = 0 +Total number of states = 672 +Total Partition Function = 0.01325462922107587 +Scaling factor 300 +ln Partition Function = -4.3234084123916432 +Number of M_runs = 9.694790048799928e-06 +Number of Z_runs = 0 +Number of C_runs = 0.70428238770367024 +Average number of runs = 0.70429208249371678 +Prob_M = 9.6947900487998822e-06 +Prob_Z = 0 +Prob_C = 0.70428238770366802 +Joint probability M Z = 0 +Conditional probability M given Z = -nan +Conditional probability M given not Z = 9.6947900487998822e-06 +Joint probability M C = 4.5792657045468985e-07 +Conditional probability M given C = 6.5020306974844557e-07 +Conditional probability M given not C = 3.1235418839677156e-05 +Joint probability Z M = 0 +Conditional probability Z given M = 0 +Conditional probability Z given not M = 0 +Joint probability Z C = 0 +Conditional probability Z given C = 0 +Conditional probability Z given not C = 0 +Joint probability C M = 4.5792657045468985e-07 +Conditional probability C given M = 0.047234294724244862 +Conditional probability C given not M = 0.70428875770873722 +Joint probability C Z = 0 +Conditional probability C given Z = -nan +Conditional probability C given not Z = 0.70428238770366802 +N_Melting = 3.1581038383173296e-05 +N_Z = 0 +N_Cruciform = 8.4513907782201976 +Run time = 0 sec +Position Base P_melt P_Z P_cruciform +1 T 1.2837202054154014e-07 0 0 +2 T 1.4854536477113216e-07 0 0 +3 C 8.4225531306322499e-08 0 0 +4 T 1.272482268662588e-07 0 0 +5 C 9.8351265964941495e-08 0 0 +6 A 2.1075192806767564e-07 0 0 +7 T 2.3942341583348001e-07 0 0 +8 G 1.8082154533395449e-07 0 0 +9 T 3.1923690876448779e-07 0 0 +10 T 3.5321808365076585e-07 0 0 +11 T 2.8758164431121559e-07 0 0 +12 G 1.2139895788886951e-07 0 0 +13 A 1.2254888267181411e-07 0 0 +14 C 5.1617740504977282e-08 0 0 +15 A 7.6238436118224707e-08 0 0 +16 G 3.3304922904038372e-08 0 0 +17 C 7.9391356564540425e-08 0 0 +18 T 3.3406419412213954e-07 0 0 +19 T 4.7816057037304521e-07 0 0 +20 A 5.0728144938451044e-07 0 1.6352124245557493e-07 +21 T 4.1962388389122197e-07 0 1.6352124245557493e-07 +22 C 2.1068599098392705e-07 0 1.6352124245557493e-07 +23 A 2.4315075915945523e-07 0 1.6352124245557493e-07 +24 T 1.9233574424371436e-07 0 1.6352124245557493e-07 +25 C 6.462022510478155e-08 0 1.6352124245557493e-07 +26 G 8.8222941986971968e-08 0 1.6352124245557493e-07 +27 A 3.1547365249520576e-07 0 1.6352124245557493e-07 +28 T 4.2933617509661332e-07 0 1.6352124245557493e-07 +29 A 4.3187056053842029e-07 0 1.6352124245557493e-07 +30 A 3.2352620006628755e-07 0 1.6352124245557493e-07 +31 G 1.0488306208739792e-07 0 1.6352124245557493e-07 +32 C 1.3208117624367593e-07 0 1.6352124245557493e-07 +33 T 5.2639045160384718e-07 0 1.6352124245557493e-07 +34 T 8.04837572031912e-07 0 1.6352124245557493e-07 +35 T 9.4656602191033707e-07 0 1.6352124245557493e-07 +36 A 9.4104785978106246e-07 0 1.6352124245557493e-07 +37 A 7.8817745193148602e-07 0 1.6352124245557493e-07 +38 T 4.9836436063918277e-07 0 1.6352124245557493e-07 +39 G 9.5223499856579924e-08 0 1.6352124245557493e-07 +40 C 1.4743880352934081e-08 0 1.6352124245557493e-07 +41 G 6.1363078235899114e-09 0 1.6352124245557493e-07 +42 G 3.5815096288767313e-08 0 1.6352124245557493e-07 +43 T 1.8288766858936738e-07 0 1.6352124245557493e-07 +44 A 2.563962292992348e-07 0 1.6352124245557493e-07 +45 G 2.4840957287944071e-07 0 0 +46 T 5.5753639213101772e-07 0 0 +47 T 7.4230590539223428e-07 0 0 +48 T 7.9553290475358391e-07 0 0 +49 A 7.1516146214280564e-07 0 0 +50 T 5.0673556109254924e-07 0 0 +51 C 1.7574151529457612e-07 0 0 +52 A 1.583545693574363e-07 0 0 +53 C 7.4125669340366904e-08 0 0 +54 A 1.7612288145818846e-07 0 0 +55 G 2.1536287006445211e-07 0 0 +56 T 6.8125653468855385e-07 0 0 +57 T 1.0353268142324145e-06 0 0 +58 A 1.2488443706337435e-06 0 0 +59 A 1.3162774897104355e-06 0 0 +60 A 1.2216999273843151e-06 0 0.70428222418242781 +61 T 9.7724816571980061e-07 0 0.70428222418242781 +62 T 6.0429443631701142e-07 0 0.70428222418242781 +63 G 1.370884818536368e-07 0 0.70428222418242781 +64 C 8.2572833805809545e-08 0 0.70428222418242781 +65 T 2.046441981979341e-07 0 0.70428222418242781 +66 A 2.3853591463062928e-07 0 0.70428222418242781 +67 A 1.846706548043514e-07 0 0.70428222418242781 +68 C 4.5715157418713542e-08 0 0.70428222418242781 +69 G 9.2257182236592619e-09 0 0.70428222418242781 +70 C 1.3107366617368327e-08 0 0.70428222418242781 +71 A 5.2365744940158256e-08 0 0.70428222418242781 +72 G 4.0026391288165247e-08 0 0 +73 T 6.92243004171074e-08 0 0 +74 C 4.0026391288165247e-08 0 0 +75 A 5.9354303124711378e-08 0 0 +76 G 1.3107366617368327e-08 0 0 +77 G 3.3779094886955779e-09 0 0 +78 C 1.0348968282473994e-08 0 0 +79 A 3.9406337247692869e-08 0 0 +80 C 1.0348968282473994e-08 0 0 +81 C 3.3779094886955779e-09 0 0 +82 G 1.9180553704905545e-08 0 0 +83 T 9.7082754665520805e-08 0 0 +84 G 1.1003298702463103e-07 0 0 +85 T 3.0082711445099522e-07 0 0 +86 A 3.9421669290508595e-07 0 0 +87 T 3.928981233975114e-07 0 0 +88 G 2.8867240986205715e-07 0 0 +89 A 5.1439749927636994e-07 0 0 +90 A 6.2373501679666162e-07 0 0 +91 A 6.2373501679666162e-07 0 0 +92 T 5.1439749927636994e-07 0 0 +93 C 2.9120679530386406e-07 0 0 +94 T 4.2263062299559628e-07 0 0 +95 A 4.5661179788187439e-07 0 0 +96 A 3.9543250883931831e-07 0 0 +97 C 2.3415676181422991e-07 0 0 +98 A 3.3539869866221617e-07 0 0 +99 A 3.3463519869515267e-07 0 0 +100 T 2.3847303802889526e-07 0 0 diff --git a/tests/unit/data/qsidd/cruciform.txt b/tests/unit/data/qsidd/cruciform.txt new file mode 100644 index 0000000..5f2125e --- /dev/null +++ b/tests/unit/data/qsidd/cruciform.txt @@ -0,0 +1,127 @@ +DNA sequence file: fragment.fa +WARNING: sequence length is too short +Sequence Length = 100 +Transition: Cruciform +Molecule type: linear DNA +Stress Level = -0.059999999999999998 +linking difference = -0.86538461538461531 TURNS +Threshold = 12 kcal/mol +Temperature = 310 K +Salt Concentration = 0.01 M +C = 3.6000000000000001 kcal-bp/rad^2 +Nucleation energy = 12.150009109596439 kcal/mol +BAT = 0.25811566340021741 kcal/mol; BGC = 1.3048755414539936 kcal/mol +MinE = 2.8793244378698226 kcal/mol; Max_E = 14.879324437869823 kcal/mol +Number of one-run states = 2 +Number of two-run states = 0 +Number of three-run states = 0 +Number of four-run states = 0 +Total number of states = 2 +Total Partition Function = 0.013254500720228397 +Scaling factor 300 +ln Partition Function = -4.3234181072286901 +Average number of runs = 0.70428875770873733 +Transition Probability = 0.70428875770873733 +Number of cruciform bases = 8.4514672183016089 +Run time = 0 sec +Position Base P(x) +1 T 0 +2 T 0 +3 C 0 +4 T 0 +5 C 0 +6 A 0 +7 T 0 +8 G 0 +9 T 0 +10 T 0 +11 T 0 +12 G 0 +13 A 0 +14 C 0 +15 A 0 +16 G 0 +17 C 0 +18 T 0 +19 T 0 +20 A 1.635228277750584e-07 +21 T 1.635228277750584e-07 +22 C 1.635228277750584e-07 +23 A 1.635228277750584e-07 +24 T 1.635228277750584e-07 +25 C 1.635228277750584e-07 +26 G 1.635228277750584e-07 +27 A 1.635228277750584e-07 +28 T 1.635228277750584e-07 +29 A 1.635228277750584e-07 +30 A 1.635228277750584e-07 +31 G 1.635228277750584e-07 +32 C 1.635228277750584e-07 +33 T 1.635228277750584e-07 +34 T 1.635228277750584e-07 +35 T 1.635228277750584e-07 +36 A 1.635228277750584e-07 +37 A 1.635228277750584e-07 +38 T 1.635228277750584e-07 +39 G 1.635228277750584e-07 +40 C 1.635228277750584e-07 +41 G 1.635228277750584e-07 +42 G 1.635228277750584e-07 +43 T 1.635228277750584e-07 +44 A 1.635228277750584e-07 +45 G 0 +46 T 0 +47 T 0 +48 T 0 +49 A 0 +50 T 0 +51 C 0 +52 A 0 +53 C 0 +54 A 0 +55 G 0 +56 T 0 +57 T 0 +58 A 0 +59 A 0 +60 A 0.7042885941859095 +61 T 0.7042885941859095 +62 T 0.7042885941859095 +63 G 0.7042885941859095 +64 C 0.7042885941859095 +65 T 0.7042885941859095 +66 A 0.7042885941859095 +67 A 0.7042885941859095 +68 C 0.7042885941859095 +69 G 0.7042885941859095 +70 C 0.7042885941859095 +71 A 0.7042885941859095 +72 G 0 +73 T 0 +74 C 0 +75 A 0 +76 G 0 +77 G 0 +78 C 0 +79 A 0 +80 C 0 +81 C 0 +82 G 0 +83 T 0 +84 G 0 +85 T 0 +86 A 0 +87 T 0 +88 G 0 +89 A 0 +90 A 0 +91 A 0 +92 T 0 +93 C 0 +94 T 0 +95 A 0 +96 A 0 +97 C 0 +98 A 0 +99 A 0 +100 T 0 diff --git a/tests/unit/data/qsidd/fragment.fa b/tests/unit/data/qsidd/fragment.fa new file mode 100644 index 0000000..7f389ea --- /dev/null +++ b/tests/unit/data/qsidd/fragment.fa @@ -0,0 +1,3 @@ +>pbr322 fragment +TTCTCATGTTTGACAGCTTATCATCGATAAGCTTTAATGCGGTAGTTTATCACAGTTAAATTGCTAACGC +AGTCAGGCACCGTGTATGAAATCTAACAAT diff --git a/tests/unit/data/qsidd/fragment.ir b/tests/unit/data/qsidd/fragment.ir new file mode 100644 index 0000000..f5022bc --- /dev/null +++ b/tests/unit/data/qsidd/fragment.ir @@ -0,0 +1 @@ +1,0,10000,|20,25,1.5,|60,12,2.5,| diff --git a/tests/unit/data/qsidd/melting.txt b/tests/unit/data/qsidd/melting.txt new file mode 100644 index 0000000..cc907d0 --- /dev/null +++ b/tests/unit/data/qsidd/melting.txt @@ -0,0 +1,127 @@ +DNA sequence file: fragment.fa +WARNING: sequence length is too short +Sequence Length = 100 +Transition: Melting - copolymeric energetics +Molecule type: linear DNA +Stress Level = -0.059999999999999998 +linking difference = -0.86538461538461531 TURNS +Threshold = 12 kcal/mol +Temperature = 310 K +Salt Concentration = 0.01 M +C = 3.6000000000000001 kcal-bp/rad^2 +Nucleation energy = 10.84 kcal/mol +BAT = 0.25811566340021741 kcal/mol; BGC = 1.3048755414539936 kcal/mol +MinE = 3.4139199408284022 kcal/mol; Max_E = 15.413919940828402 kcal/mol +Number of one-run states = 734 +Number of two-run states = 0 +Number of three-run states = 0 +Number of four-run states = 0 +Total number of states = 734 +Total Partition Function = 0.0039196304026189437 +Scaling factor 300 +ln Partition Function = -5.5417579146710523 +Average number of runs = 3.2025644480199974e-05 +Transition Probability = 3.2025644480259002e-05 +Number of melted bases = 0.00010879893004904143 +Run time = 0 sec +Position Base P(x) G(x) +1 T 4.0793423753589667e-07 10.829988838005404 +2 T 4.6914030971625862e-07 10.886524619775502 +3 C 2.9182935314984666e-07 11.332463047615308 +4 T 4.2018992254908285e-07 11.193997029771323 +5 C 3.4610442850793684e-07 11.415312335271333 +6 A 6.9251306731949819e-07 10.944138843401165 +7 T 7.8946862192955229e-07 10.908309719496579 +8 G 6.2448139425428095e-07 11.086441625272657 +9 T 1.0593660732128728e-06 10.689379232670358 +10 T 1.1647284332383163e-06 10.626750125445867 +11 T 9.523205739885378e-07 10.681369219117816 +12 G 4.2404254498165718e-07 11.222084326764325 +13 A 4.0429861176683124e-07 11.147939789436982 +14 C 1.8857493407235279e-07 11.524173255298866 +15 A 2.4819980172218085e-07 11.314874506363109 +16 G 1.3797034223318018e-07 11.768472697970326 +17 C 2.9331162987555774e-07 11.298284921656004 +18 T 1.1165181930123367e-06 10.415089715135053 +19 T 1.587234171115155e-06 10.351560545675291 +20 A 1.6857093879700097e-06 10.36965870877183 +21 T 1.3988348489018199e-06 10.469808299984702 +22 C 7.2547105739161977e-07 10.959217643180791 +23 A 8.0858047845003177e-07 10.866978522660322 +24 T 6.4375647755173711e-07 10.943376611462876 +25 C 2.4986901078106603e-07 11.671361513874004 +26 G 3.2317653502844521e-07 11.345421995130977 +27 A 1.0581303380334267e-06 10.437860739097919 +28 T 1.4375928818987398e-06 10.35917509989603 +29 A 1.4571485839238291e-06 10.381857838405748 +30 A 1.1183171063534956e-06 10.523479933752448 +31 G 4.2345610575473713e-07 11.496603892571166 +32 C 5.2193676313987064e-07 11.361701259613346 +33 T 1.8173381555616419e-06 10.258249982146163 +34 T 2.7423748518765695e-06 10.095405746258701 +35 T 3.2151365673371688e-06 10.036635685943036 +36 A 3.1854909206977992e-06 10.018691995926771 +37 A 2.6575586548377811e-06 10.036419515620516 +38 T 1.683101351344876e-06 10.12500342423591 +39 G 3.463449547792037e-07 11.077761721361174 +40 C 7.1997383202316657e-08 11.912747248509717 +41 G 3.6382534827987523e-08 11.956517554162023 +42 G 1.4341987880425654e-07 11.55410130144986 +43 T 6.0774782473787239e-07 10.845844015524989 +44 A 8.6029778057583612e-07 10.84345531433406 +45 G 8.7297851751519428e-07 10.962484289049055 +46 T 1.8961267822509131e-06 10.386290289472299 +47 T 2.5179027242233128e-06 10.264410630374183 +48 T 2.6978952410212593e-06 10.233570874466929 +49 A 2.4261110260970521e-06 10.255160623640405 +50 T 1.7243386006184001e-06 10.370166335865951 +51 C 6.4076369383616412e-07 11.092089094609035 +52 A 5.583354452456917e-07 11.167768735717683 +53 C 3.0415151130535692e-07 11.683012107339657 +54 A 6.1191333578782006e-07 11.153280922622718 +55 G 7.6173240715902808e-07 11.050516290849741 +56 T 2.3014841076537773e-06 10.225686349465452 +57 T 3.5097942216022031e-06 10.068503538040204 +58 A 4.2759919571447433e-06 10.00611005718895 +59 A 4.5150093335851082e-06 9.9868828923796666 +60 A 4.1951856786740917e-06 10.000761718947983 +61 T 3.3575617419947795e-06 10.055500424358751 +62 T 2.0989149306141172e-06 10.208299071552112 +63 G 5.3033249958333282e-07 11.312502506113645 +64 C 3.4150433203696613e-07 11.594020713994853 +65 T 7.3199359271558464e-07 10.715376347886576 +66 A 8.2860431736227873e-07 10.567004091269396 +67 A 6.4248018313138444e-07 10.549018808439898 +68 C 1.6591252367629922e-07 11.247165442622808 +69 G 5.3841835553960749e-08 11.931044742095978 +70 C 6.2658104598805347e-08 11.683571639359963 +71 A 1.9110438721605213e-07 11.159501010675305 +72 G 1.4937760670745735e-07 11.447326701230489 +73 T 2.4110116378703278e-07 11.158846860058718 +74 C 1.4937760670745735e-07 11.447326701230489 +75 A 1.9110438721605213e-07 11.159501010675305 +76 G 6.2658104598805347e-08 11.683571639359965 +77 G 3.406687501535414e-08 12 +78 C 5.3330299827052268e-08 11.65461321813059 +79 A 1.3066045487821799e-07 11.111149346636928 +80 C 5.3330299827052262e-08 11.654613218130592 +81 C 3.406687501535414e-08 12 +82 G 8.3195204979939733e-08 11.709807328183267 +83 T 3.2967240647713059e-07 11.102756470307469 +84 G 4.0107073114679307e-07 11.201783315220112 +85 T 1.0105453417380568e-06 10.679790691858482 +86 A 1.3277886858022369e-06 10.645920329010925 +87 T 1.343863670542425e-06 10.716527129385954 +88 G 1.0355801928332564e-06 10.997094654659163 +89 A 1.7701895522843551e-06 10.580382708382173 +90 A 2.1413624757858118e-06 10.48854717996136 +91 A 2.1458404298177064e-06 10.492329839800288 +92 T 1.7856529259718588e-06 10.594445487480652 +93 C 1.0661213145139547e-06 11.028427761890528 +94 T 1.4728854496082566e-06 10.749377999951282 +95 A 1.567262389978091e-06 10.688879819451783 +96 A 1.3589414185356195e-06 10.73048486851479 +97 C 8.4227407125499549e-07 11.033593544709449 +98 A 1.1404676043498826e-06 10.686335003845432 +99 A 1.1173518897285279e-06 10.589463734876958 +100 T 7.9774492162681328e-07 10.590602066443518 diff --git a/tests/unit/data/qsidd/underflow.txt b/tests/unit/data/qsidd/underflow.txt new file mode 100644 index 0000000..c861719 --- /dev/null +++ b/tests/unit/data/qsidd/underflow.txt @@ -0,0 +1,32 @@ +DNA sequence file: pbr322.toy.fa +WARNING: superhelical density is outside of physiological range +Sequence Length = 4361 +Transition: Melting - copolymeric energetics +Molecule type: linear DNA +Stress Level = -0.29999999999999999 +linking difference = -127.24038461538461 TURNS +Threshold = 12 kcal/mol +Temperature = 310 K +Salt Concentration = 0.01 M +C = 3.6000000000000001 kcal-bp/rad^2 +Nucleation energy = 10.84 kcal/mol +BAT = 0.25811566340021741 kcal/mol; BGC = 1.3048755414539936 kcal/mol +MinE = 1239.0152081215717 kcal/mol; Max_E = 1251.0152081215717 kcal/mol +Number of one-run states = 611 +Number of two-run states = 2609265 +Number of three-run states = 0 +Number of four-run states = 0 +Total number of states = 2609876 +Total Partition Function = 0 +Scaling factor 300 +ln Partition Function = -inf +Average number of runs = -nan +Transition Probability = -nan +Number of melted bases = 4411 +Run time = 0 sec +Position Base P(x) G(x) +1 T 1 12 +2 T 1 12 +3 C 1 12 +4 T 1 12 +5 C 1 12 diff --git a/tests/unit/data/qsidd/z-dna.txt b/tests/unit/data/qsidd/z-dna.txt new file mode 100644 index 0000000..841c6d8 --- /dev/null +++ b/tests/unit/data/qsidd/z-dna.txt @@ -0,0 +1,126 @@ +DNA sequence file: fragment.fa +WARNING: sequence length is too short +Sequence Length = 100 +Transition: Z-DNA +Molecule type: linear DNA +Stress Level = -0.059999999999999998 +linking difference = -0.86538461538461531 TURNS +Threshold = 12 kcal/mol +Temperature = 310 K +Salt Concentration = 0.01 M +C = 3.6000000000000001 kcal-bp/rad^2 +Nucleation energy = 10 kcal/mol +MinE = 3.4139199408284022 kcal/mol; Max_E = 15.413919940828402 kcal/mol +Number of one-run states = 0 +Number of two-run states = 0 +Number of three-run states = 0 +Number of four-run states = 0 +Total number of states = 0 +Total Partition Function = 0.0039195048739291754 +Scaling factor 300 +ln Partition Function = -5.5417899408283802 +Average number of runs = 0 +Transition Probability = 0 +Number of Z-DNA bases = 0 +Run time = 0 sec +Position Base P(x) +1 T 0 +2 T 0 +3 C 0 +4 T 0 +5 C 0 +6 A 0 +7 T 0 +8 G 0 +9 T 0 +10 T 0 +11 T 0 +12 G 0 +13 A 0 +14 C 0 +15 A 0 +16 G 0 +17 C 0 +18 T 0 +19 T 0 +20 A 0 +21 T 0 +22 C 0 +23 A 0 +24 T 0 +25 C 0 +26 G 0 +27 A 0 +28 T 0 +29 A 0 +30 A 0 +31 G 0 +32 C 0 +33 T 0 +34 T 0 +35 T 0 +36 A 0 +37 A 0 +38 T 0 +39 G 0 +40 C 0 +41 G 0 +42 G 0 +43 T 0 +44 A 0 +45 G 0 +46 T 0 +47 T 0 +48 T 0 +49 A 0 +50 T 0 +51 C 0 +52 A 0 +53 C 0 +54 A 0 +55 G 0 +56 T 0 +57 T 0 +58 A 0 +59 A 0 +60 A 0 +61 T 0 +62 T 0 +63 G 0 +64 C 0 +65 T 0 +66 A 0 +67 A 0 +68 C 0 +69 G 0 +70 C 0 +71 A 0 +72 G 0 +73 T 0 +74 C 0 +75 A 0 +76 G 0 +77 G 0 +78 C 0 +79 A 0 +80 C 0 +81 C 0 +82 G 0 +83 T 0 +84 G 0 +85 T 0 +86 A 0 +87 T 0 +88 G 0 +89 A 0 +90 A 0 +91 A 0 +92 T 0 +93 C 0 +94 T 0 +95 A 0 +96 A 0 +97 C 0 +98 A 0 +99 A 0 +100 T 0 diff --git a/tests/unit/results/conftest.py b/tests/unit/results/conftest.py new file mode 100644 index 0000000..5490fe4 --- /dev/null +++ b/tests/unit/results/conftest.py @@ -0,0 +1,18 @@ +"""Fixtures for the sist.results tests.""" + +from __future__ import annotations + +import pytest +from results_helpers import read_output + +from sist.results.qsidd_output import QsiddOutput + + +@pytest.fixture +def melting_output() -> QsiddOutput: + return read_output("melting.txt") + + +@pytest.fixture +def competition_output() -> QsiddOutput: + return read_output("competition.txt") diff --git a/tests/unit/results/results_helpers.py b/tests/unit/results/results_helpers.py new file mode 100644 index 0000000..cf21dab --- /dev/null +++ b/tests/unit/results/results_helpers.py @@ -0,0 +1,66 @@ +"""Saved qsidd outputs and settings shared by the sist.results tests. + +The saved qsidd outputs in ``tests/unit/data/qsidd`` were made with ``-b -p -r +-P`` on ``fragment.fa``, the first 100 bp of the regression sequence. The +underflow output was made on the full regression sequence at a superhelical +density of 0.3, with its table cut to 5 rows. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from sist.results.model import RunSettings +from sist.results.qsidd_output import QsiddOutput +from sist.transitions import ALGORITHMS + +REPOSITORY_ROOT = Path(__file__).resolve().parents[3] +QSIDD_PATH = REPOSITORY_ROOT / "tests" / "unit" / "data" / "qsidd" +FRAGMENT_PATH = QSIDD_PATH / "fragment.fa" +TOY_PATH = REPOSITORY_ROOT / "tests" / "regression" / "data" / "pbr322.toy.fa" +FRAGMENT_IR_STRING = (QSIDD_PATH / "fragment.ir").read_text(encoding="utf-8").strip() + +OUTPUTS = { + "M": "melting.txt", + "Z": "z-dna.txt", + "C": "cruciform.txt", + "A": "competition.txt", +} + + +def read_output(name: str) -> QsiddOutput: + """Parse one of the saved qsidd outputs. + + Args: + name: File name of the saved output, for example ``"melting.txt"``. + + Returns: + The parsed output. + """ + return QsiddOutput.parse((QSIDD_PATH / name).read_text(encoding="utf-8")) + + +def make_settings(flag: str, **overrides: Any) -> RunSettings: + """Make settings for the 100 bp fragment the saved outputs were run on. + + Args: + flag: Algorithm flag, such as ``"M"``. + **overrides: Settings to change from the defaults. + + Returns: + The settings the saved outputs were made with. + """ + settings: dict[str, Any] = { + "file": str(FRAGMENT_PATH), + "algorithm": ALGORITHMS[flag], + "temperature": 310.0, + "superhelical_density": 0.06, + "salt": 0.01, + "energy_threshold": 12.0, + "circular": False, + "nearest_neighbor": False, + } + settings.update(overrides) + + return RunSettings(**settings) diff --git a/tests/unit/results/test_builder.py b/tests/unit/results/test_builder.py new file mode 100644 index 0000000..0800dd3 --- /dev/null +++ b/tests/unit/results/test_builder.py @@ -0,0 +1,131 @@ +"""Unit tests for sist.results.builder.""" + +from __future__ import annotations + +import pytest +from results_helpers import ( + FRAGMENT_IR_STRING, + OUTPUTS, + TOY_PATH, + make_settings, + read_output, +) + +from sist.results.builder import ResultBuilder +from sist.results.diagnostics import ErrorCode, ResultError, WarningCode +from sist.results.qsidd_output import QsiddOutput +from sist.schema import ResultValidator + + +@pytest.fixture(scope="module") +def validator() -> ResultValidator: + return ResultValidator() + + +@pytest.mark.parametrize(("flag", "output_name"), list(OUTPUTS.items())) +def test_success_builds_a_valid_result( + validator: ResultValidator, flag: str, output_name: str +) -> None: + builder = ResultBuilder(make_settings(flag), command=["sist", "-a", flag]) + sequence = builder.read_sequence() + + result = builder.success( + read_output(output_name), + sequence, + ir_string=FRAGMENT_IR_STRING, + irf_version="3.09", + ) + + assert validator.validate(result.to_dict()) == [] + assert result.status == "success" + + +def test_success_records_inverted_repeats_only_when_used() -> None: + builder = ResultBuilder(make_settings("C")) + sequence = builder.read_sequence() + + result = builder.success( + read_output("cruciform.txt"), sequence, ir_string=FRAGMENT_IR_STRING + ) + + assert result.inverted_repeats is not None + assert [repeat.start for repeat in result.inverted_repeats] == [20, 60] + + +def test_success_warns_when_there_are_no_inverted_repeats() -> None: + builder = ResultBuilder(make_settings("A")) + sequence = builder.read_sequence() + + result = builder.success( + read_output("competition-no-inverted-repeats.txt"), + sequence, + ir_string="1,0,10000,|", + ) + + assert WarningCode.NO_INVERTED_REPEATS_FOUND in [w.code for w in result.warnings] + + +def test_success_replaces_the_qsidd_length_warning_with_its_own() -> None: + """qsidd checks the size of the file, so SIST checks the base pairs instead.""" + builder = ResultBuilder(make_settings("M")) + sequence = builder.read_sequence() + + result = builder.success(read_output("melting.txt"), sequence) + + assert [w.code for w in result.warnings] == [WarningCode.SEQUENCE_TOO_SHORT] + + +def test_success_raises_when_the_partition_function_underflows() -> None: + builder = ResultBuilder( + make_settings("M", file=str(TOY_PATH), superhelical_density=0.3) + ) + sequence = builder.read_sequence() + + with pytest.raises(ResultError) as raised: + builder.success(read_output("underflow.txt"), sequence) + + assert raised.value.code == ErrorCode.PARTITION_FUNCTION_UNDERFLOW + assert raised.value.exit_code == 0 + + +def test_failure_after_underflow_keeps_what_qsidd_printed( + validator: ResultValidator, +) -> None: + builder = ResultBuilder( + make_settings("M", file=str(TOY_PATH), superhelical_density=0.3) + ) + sequence = builder.read_sequence() + output = read_output("underflow.txt") + + with pytest.raises(ResultError) as raised: + builder.success(output, sequence) + + result = builder.failure(raised.value, sequence=sequence, output=output) + + assert validator.validate(result.to_dict()) == [] + assert result.derived_parameters is not None + assert [w.code for w in result.warnings] == [ + WarningCode.SUPERHELICAL_DENSITY_OUT_OF_RANGE + ] + + +def test_failure_before_the_sequence_is_read_is_valid( + validator: ResultValidator, +) -> None: + builder = ResultBuilder(make_settings("A", file="missing.fa")) + error = ResultError(ErrorCode.INPUT_NOT_FOUND, "Missing.") + + result = builder.failure(error) + + assert validator.validate(result.to_dict()) == [] + assert result.status == "failed" + assert result.input.sequence_length_bp is None + + +def test_failure_leaves_out_derived_parameters_it_cannot_read() -> None: + builder = ResultBuilder(make_settings("M")) + error = ResultError(ErrorCode.INTERNAL_ERROR, "Unreadable.") + + result = builder.failure(error, output=QsiddOutput()) + + assert result.derived_parameters is None diff --git a/tests/unit/results/test_diagnostics.py b/tests/unit/results/test_diagnostics.py new file mode 100644 index 0000000..bee8ffe --- /dev/null +++ b/tests/unit/results/test_diagnostics.py @@ -0,0 +1,104 @@ +"""Unit tests for sist.results.diagnostics.""" + +from __future__ import annotations + +import pytest + +from sist.results.diagnostics import ( + ErrorCode, + ResultError, + ResultWarning, + WarningCode, + check_sequence, + check_settings, + qsidd_warnings, +) +from sist.results.sequence import SequenceInput +from sist.transitions import ALGORITHMS + + +def test_every_error_code_has_a_stage() -> None: + stages = {code.stage for code in ErrorCode} + + assert stages <= {"validation", "input", "ir_finder", "qsidd", "output", "internal"} + + +def test_warning_sources() -> None: + assert WarningCode.THRESHOLD_TOO_LOW.source == "qsidd" + assert WarningCode.NO_INVERTED_REPEATS_FOUND.source == "ir_finder" + assert WarningCode.AMBIGUOUS_BASES_REPLACED.source == "sist" + + +def test_warning_to_dict_includes_the_source_and_details() -> None: + warning = ResultWarning(WarningCode.SEQUENCE_TOO_SHORT, "Short.", {"bp": 100}) + + assert warning.to_dict() == { + "code": "sequence_too_short", + "message": "Short.", + "source": "sist", + "details": {"bp": 100}, + } + + +def test_error_to_dict_takes_the_stage_from_the_code() -> None: + error = ResultError(ErrorCode.QSIDD_FAILED, "Broken.", exit_code=3) + + assert error.to_dict() == { + "code": "qsidd_failed", + "message": "Broken.", + "stage": "qsidd", + "exit_code": 3, + "stderr": None, + } + + +def test_check_sequence_warns_about_n_bases_dropped_characters_and_length() -> None: + sequence = SequenceInput(name=None, analysed="ACNTN", dropped=2) + + warnings = check_sequence(sequence) + + assert [warning.code for warning in warnings] == [ + WarningCode.AMBIGUOUS_BASES_REPLACED, + WarningCode.UNRECOGNISED_CHARACTERS_IGNORED, + WarningCode.SEQUENCE_TOO_SHORT, + ] + assert warnings[0].details == {"count": 2, "positions": [3, 5]} + + +def test_check_sequence_warns_about_a_long_sequence() -> None: + sequence = SequenceInput(name=None, analysed="A" * 10001, dropped=0) + + warnings = check_sequence(sequence) + + assert [warning.code for warning in warnings] == [WarningCode.SEQUENCE_TOO_LONG] + + +@pytest.mark.parametrize( + ("flag", "nearest_neighbor", "salt", "codes"), + [ + ("M", True, 0.01, []), + ("Z", True, 0.01, [WarningCode.NEAREST_NEIGHBOR_IGNORED]), + ("C", False, 0.1, [WarningCode.CRUCIFORM_SALT_FIXED]), + ("M", False, 0.1, []), + ], +) +def test_check_settings( + flag: str, nearest_neighbor: bool, salt: float, codes: list[WarningCode] +) -> None: + warnings = check_settings( + ALGORITHMS[flag], nearest_neighbor=nearest_neighbor, salt=salt + ) + + assert [warning.code for warning in warnings] == codes + + +def test_qsidd_warnings_skips_the_file_size_length_warning() -> None: + messages = [ + "threshold is too small, results may be inaccurate", + "sequence length is too short", + ] + + warnings = qsidd_warnings(messages) + + assert [warning.code for warning in warnings] == [WarningCode.THRESHOLD_TOO_LOW] + assert warnings[0].message == "Threshold is too small, results may be inaccurate." diff --git a/tests/unit/results/test_model.py b/tests/unit/results/test_model.py new file mode 100644 index 0000000..5974712 --- /dev/null +++ b/tests/unit/results/test_model.py @@ -0,0 +1,61 @@ +"""Unit tests for sist.results.model.""" + +from __future__ import annotations + +from results_helpers import make_settings + +from sist.results.model import InputDescription, InvertedRepeat +from sist.results.sequence import SequenceInput + + +def test_parameters_record_the_superhelical_density_as_used() -> None: + parameters = make_settings("M").parameters() + + assert parameters["superhelical_density"] == -0.06 + assert parameters["melting_energetics"] == "copolymeric" + assert "cruciform_salt_concentration_m" not in parameters + + +def test_parameters_record_the_fixed_cruciform_salt() -> None: + parameters = make_settings("C", salt=0.1).parameters() + + assert parameters["salt_concentration_m"] == 0.1 + assert parameters["cruciform_salt_concentration_m"] == 0.01 + assert parameters["melting_energetics"] is None + + +def test_parameters_record_nearest_neighbor_energetics() -> None: + parameters = make_settings("A", nearest_neighbor=True).parameters() + + assert parameters["melting_energetics"] == "nearest_neighbor" + + +def test_input_description_of_an_unread_sequence_leaves_out_the_bases() -> None: + description = InputDescription.describe(make_settings("M"), None) + + section = description.to_dict() + + assert section["sequence_length_bp"] is None + assert "analysed_sequence" not in section + + +def test_input_description_reports_the_analysed_bases() -> None: + sequence = SequenceInput(name="example", analysed="ACNT", dropped=0) + + section = InputDescription.describe(make_settings("M"), sequence).to_dict() + + assert section["analysed_sequence"] == "ACGT" + assert section["sequence_length_bp"] == 4 + + +def test_parse_all_skips_the_placeholder_entry() -> None: + inverted_repeats = InvertedRepeat.parse_all("1,0,10000,|20,25,1.5,|60,12,2.5,|") + + assert inverted_repeats == [ + InvertedRepeat(20, 25, 1.5), + InvertedRepeat(60, 12, 2.5), + ] + + +def test_parse_all_of_an_empty_string() -> None: + assert InvertedRepeat.parse_all("") == [] diff --git a/tests/unit/results/test_provenance.py b/tests/unit/results/test_provenance.py new file mode 100644 index 0000000..31abdad --- /dev/null +++ b/tests/unit/results/test_provenance.py @@ -0,0 +1,40 @@ +"""Unit tests for sist.results.provenance.""" + +from __future__ import annotations + +from datetime import datetime + +import pytest + +from sist.results.provenance import ProvenanceRecorder + + +def test_finish_records_the_run(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("SIST_GIT_SHA", "0123456") + recorder = ProvenanceRecorder(engine="trans_three", command=["sist", "-a", "M"]) + + provenance = recorder.finish(irf_version=None) + + assert provenance.engine == "trans_three" + assert provenance.command == ["sist", "-a", "M"] + assert provenance.git_sha == "0123456" + assert provenance.wall_time_s >= 0 + + +def test_timestamp_is_an_rfc_3339_date_time() -> None: + timestamp = ProvenanceRecorder.timestamp() + + assert timestamp.endswith("Z") + assert datetime.fromisoformat(timestamp) + + +def test_to_dict_has_the_schema_shape() -> None: + provenance = ProvenanceRecorder(engine="trans_compete", command=None).finish( + irf_version="3.09" + ) + + section = provenance.to_dict() + + assert section["software"]["name"] == "SIST" + assert section["software"]["irf_version"] == "3.09" + assert set(section["environment"]) == {"python", "platform"} diff --git a/tests/unit/results/test_qsidd_output.py b/tests/unit/results/test_qsidd_output.py new file mode 100644 index 0000000..52e94f8 --- /dev/null +++ b/tests/unit/results/test_qsidd_output.py @@ -0,0 +1,52 @@ +"""Unit tests for sist.results.qsidd_output.""" + +from __future__ import annotations + +from results_helpers import read_output + +from sist.results.qsidd_output import QsiddOutput + + +def test_parse_reads_values_that_share_a_line(melting_output: QsiddOutput) -> None: + assert "BAT" in melting_output.values + assert "BGC" in melting_output.values + + +def test_parse_reads_the_scaling_factor(melting_output: QsiddOutput) -> None: + assert melting_output.number("Scaling factor") == 300.0 + + +def test_parse_reads_warnings(melting_output: QsiddOutput) -> None: + assert melting_output.warnings == ["sequence length is too short"] + + +def test_parse_reads_the_profile_table(competition_output: QsiddOutput) -> None: + assert competition_output.columns == [ + "Position", + "Base", + "P_melt", + "P_Z", + "P_cruciform", + ] + assert len(competition_output.rows) == 100 + + +def test_number_drops_the_unit(melting_output: QsiddOutput) -> None: + assert melting_output.number("Nucleation energy") == 10.84 + + +def test_number_returns_none_for_nan_and_infinity() -> None: + output = read_output("underflow.txt") + + assert output.number("Transition Probability") is None + assert output.number("ln Partition Function") is None + + +def test_count_reads_an_exact_integer(melting_output: QsiddOutput) -> None: + assert melting_output.count("Total number of states") == 734 + + +def test_column_reads_one_column(melting_output: QsiddOutput) -> None: + bases = melting_output.column("Base") + + assert "".join(bases[:5]) == "TTCTC" diff --git a/tests/unit/results/test_reader.py b/tests/unit/results/test_reader.py new file mode 100644 index 0000000..4c40fc0 --- /dev/null +++ b/tests/unit/results/test_reader.py @@ -0,0 +1,117 @@ +"""Unit tests for sist.results.reader.""" + +from __future__ import annotations + +from results_helpers import OUTPUTS, QSIDD_PATH, read_output + +from sist.results.qsidd_output import QsiddOutput +from sist.results.reader import QsiddReader +from sist.transitions import ALGORITHMS + + +def test_transitions_follow_the_algorithm() -> None: + for flag, output_name in OUTPUTS.items(): + reader = QsiddReader(ALGORITHMS[flag]) + + transitions = reader.transitions(read_output(output_name)) + + assert tuple(transitions) == ALGORITHMS[flag].transition_names + + +def test_transitions_read_the_single_layout(melting_output: QsiddOutput) -> None: + reader = QsiddReader(ALGORITHMS["M"]) + + melting = reader.transitions(melting_output)["melting"] + + assert melting.nucleation_energy_kcal_per_mol == 10.84 + assert melting.probability == melting_output.number("Transition Probability") + assert len(melting.profile_probability) == 100 + + +def test_transitions_read_the_competition_layout( + competition_output: QsiddOutput, +) -> None: + reader = QsiddReader(ALGORITHMS["A"]) + + cruciform = reader.transitions(competition_output)["cruciform"] + + assert cruciform.probability == competition_output.number("Prob_C") + assert cruciform.nucleation_energy_kcal_per_mol == competition_output.number( + "Cruciform nucleation energy" + ) + + +def test_free_energy_is_null_where_probability_is_zero( + melting_output: QsiddOutput, +) -> None: + reader = QsiddReader(ALGORITHMS["M"]) + + melting = reader.transitions(melting_output)["melting"] + + assert melting.free_energy_kcal_per_mol is not None + assert [value is None for value in melting.free_energy_kcal_per_mol] == [ + value == 0 for value in melting.profile_probability + ] + + +def test_free_energy_is_left_out_where_qsidd_does_not_print_it( + competition_output: QsiddOutput, +) -> None: + reader = QsiddReader(ALGORITHMS["A"]) + + transitions = reader.transitions(competition_output) + + assert all(t.free_energy_kcal_per_mol is None for t in transitions.values()) + + +def test_summary_reads_exact_state_counts(melting_output: QsiddOutput) -> None: + reader = QsiddReader(ALGORITHMS["M"]) + + summary = reader.summary(melting_output) + + assert summary.states_by_number_of_runs == [734, 0, 0, 0] + assert summary.total_states == 734 + assert summary.pairwise is None + + +def test_pairwise_is_null_where_undefined() -> None: + """P(a given b) is undefined when b never happens, so it is null.""" + reader = QsiddReader(ALGORITHMS["A"]) + + summary = reader.summary(read_output("competition-no-inverted-repeats.txt")) + + assert summary.pairwise is not None + assert summary.pairwise["conditional_probability"]["melting"]["cruciform"] is None + + +def test_given_absent_is_null_when_the_other_transition_is_certain() -> None: + """qsidd writes 0 for P(a given not b) when b is certain, which is undefined.""" + text = (QSIDD_PATH / "competition.txt").read_text(encoding="utf-8") + certain = "\n".join( + "Prob_C = 1" if line.startswith("Prob_C =") else line + for line in text.splitlines() + ) + reader = QsiddReader(ALGORITHMS["A"]) + + summary = reader.summary(QsiddOutput.parse(certain)) + + assert summary.pairwise is not None + given_absent = summary.pairwise["conditional_probability_given_absent"] + assert given_absent["melting"]["cruciform"] is None + assert given_absent["melting"]["z_dna"] is not None + + +def test_derived_parameters_are_null_where_not_printed() -> None: + reader = QsiddReader(ALGORITHMS["Z"]) + + derived = reader.derived_parameters(read_output("z-dna.txt")) + + assert derived.bat_kcal_per_mol is None + assert derived.torsional_stiffness_kcal_bp_per_rad2 == 3.6 + + +def test_underflowed() -> None: + reader = QsiddReader(ALGORITHMS["M"]) + + assert reader.underflowed(read_output("underflow.txt")) + assert not reader.underflowed(read_output("melting.txt")) diff --git a/tests/unit/results/test_sequence.py b/tests/unit/results/test_sequence.py new file mode 100644 index 0000000..7182cb3 --- /dev/null +++ b/tests/unit/results/test_sequence.py @@ -0,0 +1,71 @@ +"""Unit tests for sist.results.sequence.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from sist.results.diagnostics import ErrorCode, ResultError +from sist.results.sequence import SequenceInput + + +def test_read_skips_the_header_and_uses_upper_case(tmp_path: Path) -> None: + path = tmp_path / "sequence.fa" + path.write_text(">example\nacgt\nTTGG\n", encoding="utf-8") + + sequence = SequenceInput.read(path) + + assert sequence.name == "example" + assert sequence.analysed == "ACGTTTGG" + + +def test_read_counts_dropped_characters(tmp_path: Path) -> None: + path = tmp_path / "sequence.fa" + path.write_text("ACGRYT\n", encoding="utf-8") + + sequence = SequenceInput.read(path) + + assert sequence.analysed == "ACGT" + assert sequence.dropped == 2 + + +def test_bases_reports_n_as_g_and_finds_its_positions(tmp_path: Path) -> None: + path = tmp_path / "sequence.fa" + path.write_text("ACNTN\n", encoding="utf-8") + + sequence = SequenceInput.read(path) + + assert sequence.n_positions == [3, 5] + assert sequence.bases == "ACGTG" + + +def test_sha256_matches_the_reported_bases() -> None: + sequence = SequenceInput(name=None, analysed="TTCTC", dropped=0) + + assert sequence.sha256 == ( + "2f02431f1d80b9dd4c4da090b4aae94406b6129aa7f78d95f6e4f19b3a30c3e2" + ) + + +@pytest.mark.parametrize( + ("text", "code"), + [ + (None, ErrorCode.INPUT_NOT_FOUND), + (">first\nACGT\n>second\nACGT\n", ErrorCode.MULTIPLE_SEQUENCES), + (">empty\n", ErrorCode.EMPTY_SEQUENCE), + ], +) +def test_read_rejects_input_that_cannot_be_analysed( + tmp_path: Path, text: str | None, code: ErrorCode +) -> None: + path = tmp_path / "sequence.fa" + + if text is not None: + path.write_text(text, encoding="utf-8") + + with pytest.raises(ResultError) as raised: + SequenceInput.read(path) + + assert raised.value.code == code + assert raised.value.code.stage == "input" diff --git a/tests/unit/results/test_writer.py b/tests/unit/results/test_writer.py new file mode 100644 index 0000000..27ec8cc --- /dev/null +++ b/tests/unit/results/test_writer.py @@ -0,0 +1,59 @@ +"""Unit tests for sist.results.writer.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from results_helpers import make_settings, read_output + +from sist.results.builder import ResultBuilder +from sist.results.model import Result +from sist.results.writer import ResultWriter +from sist.schema import ResultValidationError + + +def _melting_result() -> Result: + """Build a successful melting result from the saved output. + + Returns: + The result. + """ + builder = ResultBuilder(make_settings("M")) + sequence = builder.read_sequence() + + return builder.success(read_output("melting.txt"), sequence) + + +def test_to_json_keeps_arrays_of_values_on_one_line() -> None: + data = _melting_result().to_dict() + + text = ResultWriter.to_json(data) + + assert sum('"probability": [' in line for line in text.splitlines()) == 1 + assert json.loads(text) == data + + +def test_to_json_rejects_nan() -> None: + with pytest.raises(ValueError): + ResultWriter.to_json({"value": float("nan")}) + + +def test_write_writes_a_checked_result(tmp_path: Path) -> None: + path = tmp_path / "result.json" + + ResultWriter().write(_melting_result(), path) + + assert json.loads(path.read_text(encoding="utf-8"))["status"] == "success" + + +def test_write_refuses_an_invalid_result(tmp_path: Path) -> None: + result = _melting_result() + transitions = result.transitions or {} + transitions["melting"].profile_probability.append(0.5) + + with pytest.raises(ResultValidationError): + ResultWriter().write(result, tmp_path / "result.json") + + assert not (tmp_path / "result.json").exists() From a4c07ec6873d28ddf41e5133525968d6675897a9 Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Wed, 11 Nov 2026 13:29:41 +0000 Subject: [PATCH 2/6] test(results): remove overlap and shrink the qsidd fixtures --- .../qsidd/competition-no-inverted-repeats.txt | 146 ++++----------- tests/unit/data/qsidd/competition.txt | 166 +++++------------- tests/unit/data/qsidd/cruciform.txt | 126 +++---------- tests/unit/data/qsidd/fragment.fa | 3 +- tests/unit/data/qsidd/fragment.ir | 2 +- tests/unit/data/qsidd/melting.txt | 140 ++++----------- tests/unit/data/qsidd/z-dna.txt | 90 +--------- tests/unit/results/results_helpers.py | 4 +- tests/unit/results/test_builder.py | 18 +- tests/unit/results/test_diagnostics.py | 19 +- tests/unit/results/test_qsidd_output.py | 4 +- tests/unit/results/test_reader.py | 29 ++- 12 files changed, 167 insertions(+), 580 deletions(-) diff --git a/tests/unit/data/qsidd/competition-no-inverted-repeats.txt b/tests/unit/data/qsidd/competition-no-inverted-repeats.txt index a29fa95..fd15666 100644 --- a/tests/unit/data/qsidd/competition-no-inverted-repeats.txt +++ b/tests/unit/data/qsidd/competition-no-inverted-repeats.txt @@ -1,10 +1,10 @@ DNA sequence file: fragment.fa WARNING: sequence length is too short -Sequence Length = 100 +Sequence Length = 20 Copolymeric melting energetics Molecule type: linear DNA Stress Level = -0.059999999999999998 -linking difference = -0.86538461538461531 turns +linking difference = -0.40384615384615385 turns Threshold = 12 kcal/mol Temperature = 310 K Salt Concentration = 0.01 M @@ -13,28 +13,28 @@ Melting nucleation energy = 10.84 kcal/mol Z-DNA nucleation energy = 10 kcal/mol Cruciform nucleation energy = 12.150009109596439 kcal/mol BAT = 0.25811566340021741 kcal/mol; BGC = 1.3048755414539936 kcal/mol -MinE = 3.4139199408284022 kcal/mol; Max_E = 15.413919940828402 kcal/mol -Number of one-run states = 734 +MinE = 1.5931626390532545 kcal/mol; Max_E = 13.593162639053254 kcal/mol +Number of one-run states = 117 Number of two-run states = 0 Number of three-run states = 0 Number of four-run states = 0 -Total number of states = 734 -Total Partition Function = 0.0039196304026189437 +Total number of states = 117 +Total Partition Function = 0.075308195391646654 Scaling factor 300 -ln Partition Function = -5.5417579146710523 -Number of M_runs = 3.2025644480199974e-05 +ln Partition Function = -2.5861663135560775 +Number of M_runs = 2.3254944476833412e-06 Number of Z_runs = 0 Number of C_runs = 0 -Average number of runs = 3.2025644480199974e-05 -Prob_M = 3.2025644480199974e-05 +Average number of runs = 2.3254944476833412e-06 +Prob_M = 2.3254944476833412e-06 Prob_Z = 0 Prob_C = 0 Joint probability M Z = 0 Conditional probability M given Z = -nan -Conditional probability M given not Z = 3.2025644480199974e-05 +Conditional probability M given not Z = 2.3254944476833412e-06 Joint probability M C = 0 Conditional probability M given C = -nan -Conditional probability M given not C = 3.2025644480199974e-05 +Conditional probability M given not C = 2.3254944476833412e-06 Joint probability Z M = 0 Conditional probability Z given M = 0 Conditional probability Z given not M = 0 @@ -47,108 +47,28 @@ Conditional probability C given not M = 0 Joint probability C Z = 0 Conditional probability C given Z = -nan Conditional probability C given not Z = 0 -N_Melting = 0.00010879893004904143 +N_Melting = 3.973309811615764e-06 N_Z = 0 N_Cruciform = 0 Run time = 0 sec Position Base P_melt P_Z P_cruciform -1 T 4.0793423753589667e-07 0 0 -2 T 4.6914030971625862e-07 0 0 -3 C 2.9182935314984666e-07 0 0 -4 T 4.2018992254908285e-07 0 0 -5 C 3.4610442850793684e-07 0 0 -6 A 6.9251306731949819e-07 0 0 -7 T 7.8946862192955229e-07 0 0 -8 G 6.2448139425428095e-07 0 0 -9 T 1.0593660732128728e-06 0 0 -10 T 1.1647284332383163e-06 0 0 -11 T 9.523205739885378e-07 0 0 -12 G 4.2404254498165718e-07 0 0 -13 A 4.0429861176683124e-07 0 0 -14 C 1.8857493407235279e-07 0 0 -15 A 2.4819980172218085e-07 0 0 -16 G 1.3797034223318018e-07 0 0 -17 C 2.9331162987555774e-07 0 0 -18 T 1.1165181930123367e-06 0 0 -19 T 1.587234171115155e-06 0 0 -20 A 1.6857093879700097e-06 0 0 -21 T 1.3988348489018199e-06 0 0 -22 C 7.2547105739161977e-07 0 0 -23 A 8.0858047845003177e-07 0 0 -24 T 6.4375647755173711e-07 0 0 -25 C 2.4986901078106603e-07 0 0 -26 G 3.2317653502844521e-07 0 0 -27 A 1.0581303380334267e-06 0 0 -28 T 1.4375928818987398e-06 0 0 -29 A 1.4571485839238291e-06 0 0 -30 A 1.1183171063534956e-06 0 0 -31 G 4.2345610575473713e-07 0 0 -32 C 5.2193676313987064e-07 0 0 -33 T 1.8173381555616419e-06 0 0 -34 T 2.7423748518765695e-06 0 0 -35 T 3.2151365673371688e-06 0 0 -36 A 3.1854909206977992e-06 0 0 -37 A 2.6575586548377811e-06 0 0 -38 T 1.683101351344876e-06 0 0 -39 G 3.463449547792037e-07 0 0 -40 C 7.1997383202316657e-08 0 0 -41 G 3.6382534827987523e-08 0 0 -42 G 1.4341987880425654e-07 0 0 -43 T 6.0774782473787239e-07 0 0 -44 A 8.6029778057583612e-07 0 0 -45 G 8.7297851751519428e-07 0 0 -46 T 1.8961267822509131e-06 0 0 -47 T 2.5179027242233128e-06 0 0 -48 T 2.6978952410212593e-06 0 0 -49 A 2.4261110260970521e-06 0 0 -50 T 1.7243386006184001e-06 0 0 -51 C 6.4076369383616412e-07 0 0 -52 A 5.583354452456917e-07 0 0 -53 C 3.0415151130535692e-07 0 0 -54 A 6.1191333578782006e-07 0 0 -55 G 7.6173240715902808e-07 0 0 -56 T 2.3014841076537773e-06 0 0 -57 T 3.5097942216022031e-06 0 0 -58 A 4.2759919571447433e-06 0 0 -59 A 4.5150093335851082e-06 0 0 -60 A 4.1951856786740917e-06 0 0 -61 T 3.3575617419947795e-06 0 0 -62 T 2.0989149306141172e-06 0 0 -63 G 5.3033249958333282e-07 0 0 -64 C 3.4150433203696613e-07 0 0 -65 T 7.3199359271558464e-07 0 0 -66 A 8.2860431736227873e-07 0 0 -67 A 6.4248018313138444e-07 0 0 -68 C 1.6591252367629922e-07 0 0 -69 G 5.3841835553960749e-08 0 0 -70 C 6.2658104598805347e-08 0 0 -71 A 1.9110438721605213e-07 0 0 -72 G 1.4937760670745735e-07 0 0 -73 T 2.4110116378703278e-07 0 0 -74 C 1.4937760670745735e-07 0 0 -75 A 1.9110438721605213e-07 0 0 -76 G 6.2658104598805347e-08 0 0 -77 G 3.406687501535414e-08 0 0 -78 C 5.3330299827052268e-08 0 0 -79 A 1.3066045487821799e-07 0 0 -80 C 5.3330299827052262e-08 0 0 -81 C 3.406687501535414e-08 0 0 -82 G 8.3195204979939733e-08 0 0 -83 T 3.2967240647713059e-07 0 0 -84 G 4.0107073114679307e-07 0 0 -85 T 1.0105453417380568e-06 0 0 -86 A 1.3277886858022369e-06 0 0 -87 T 1.343863670542425e-06 0 0 -88 G 1.0355801928332564e-06 0 0 -89 A 1.7701895522843551e-06 0 0 -90 A 2.1413624757858118e-06 0 0 -91 A 2.1458404298177064e-06 0 0 -92 T 1.7856529259718588e-06 0 0 -93 C 1.0661213145139547e-06 0 0 -94 T 1.4728854496082566e-06 0 0 -95 A 1.567262389978091e-06 0 0 -96 A 1.3589414185356195e-06 0 0 -97 C 8.4227407125499549e-07 0 0 -98 A 1.1404676043498826e-06 0 0 -99 A 1.1173518897285279e-06 0 0 -100 T 7.9774492162681328e-07 0 0 +1 T 1.7943769227335756e-07 0 0 +2 T 1.9299982650029421e-07 0 0 +3 C 7.4619322404720301e-08 0 0 +4 T 1.2841391991155851e-07 0 0 +5 C 7.4619322404720301e-08 0 0 +6 A 2.0976271300214558e-07 0 0 +7 T 2.2652559950399694e-07 0 0 +8 G 1.2170722963535973e-07 0 0 +9 T 3.0390518981523601e-07 0 0 +10 T 3.6524782921337266e-07 0 0 +11 T 2.8714230331338467e-07 0 0 +12 G 9.1382208906571691e-08 0 0 +13 A 1.2453907234073486e-07 0 0 +14 C 5.0738321141446112e-08 0 0 +15 A 9.4214051611946813e-08 0 0 +16 G 2.3451634817975627e-08 0 0 +17 C 4.733263608124981e-08 0 0 +18 T 2.5037326311908279e-07 0 0 +19 T 3.2527803674415601e-07 0 0 +20 A 2.5037326311908279e-07 0 0 diff --git a/tests/unit/data/qsidd/competition.txt b/tests/unit/data/qsidd/competition.txt index 1a64769..ff817d0 100644 --- a/tests/unit/data/qsidd/competition.txt +++ b/tests/unit/data/qsidd/competition.txt @@ -1,10 +1,10 @@ DNA sequence file: fragment.fa WARNING: sequence length is too short -Sequence Length = 100 +Sequence Length = 20 Copolymeric melting energetics Molecule type: linear DNA Stress Level = -0.059999999999999998 -linking difference = -0.86538461538461531 turns +linking difference = -0.40384615384615385 turns Threshold = 12 kcal/mol Temperature = 310 K Salt Concentration = 0.01 M @@ -13,142 +13,62 @@ Melting nucleation energy = 10.84 kcal/mol Z-DNA nucleation energy = 10 kcal/mol Cruciform nucleation energy = 12.150009109596439 kcal/mol BAT = 0.25811566340021741 kcal/mol; BGC = 1.3048755414539936 kcal/mol -MinE = 2.8793244378698226 kcal/mol; Max_E = 14.879324437869823 kcal/mol -Number of one-run states = 588 -Number of two-run states = 84 +MinE = 1.5931626390532545 kcal/mol; Max_E = 13.593162639053254 kcal/mol +Number of one-run states = 119 +Number of two-run states = 0 Number of three-run states = 0 Number of four-run states = 0 -Total number of states = 672 -Total Partition Function = 0.01325462922107587 +Total number of states = 119 +Total Partition Function = 0.09660048857821156 Scaling factor 300 -ln Partition Function = -4.3234084123916432 -Number of M_runs = 9.694790048799928e-06 +ln Partition Function = -2.3371714800309746 +Number of M_runs = 1.8129182660037511e-06 Number of Z_runs = 0 -Number of C_runs = 0.70428238770367024 -Average number of runs = 0.70429208249371678 -Prob_M = 9.6947900487998822e-06 +Number of C_runs = 0.22041599892453786 +Average number of runs = 0.22041781184280387 +Prob_M = 1.8129182660037511e-06 Prob_Z = 0 -Prob_C = 0.70428238770366802 +Prob_C = 0.22041599892453786 Joint probability M Z = 0 Conditional probability M given Z = -nan -Conditional probability M given not Z = 9.6947900487998822e-06 -Joint probability M C = 4.5792657045468985e-07 -Conditional probability M given C = 6.5020306974844557e-07 -Conditional probability M given not C = 3.1235418839677156e-05 +Conditional probability M given not Z = 1.8129182660037511e-06 +Joint probability M C = 0 +Conditional probability M given C = 0 +Conditional probability M given not C = 2.3254944476833412e-06 Joint probability Z M = 0 Conditional probability Z given M = 0 Conditional probability Z given not M = 0 Joint probability Z C = 0 Conditional probability Z given C = 0 Conditional probability Z given not C = 0 -Joint probability C M = 4.5792657045468985e-07 -Conditional probability C given M = 0.047234294724244862 -Conditional probability C given not M = 0.70428875770873722 +Joint probability C M = 0 +Conditional probability C given M = 0 +Conditional probability C given not M = 0.22041639852145287 Joint probability C Z = 0 Conditional probability C given Z = -nan -Conditional probability C given not Z = 0.70428238770366802 -N_Melting = 3.1581038383173296e-05 +Conditional probability C given not Z = 0.22041599892453786 +N_Melting = 3.09752876045181e-06 N_Z = 0 -N_Cruciform = 8.4513907782201976 +N_Cruciform = 1.5408490099006309 Run time = 0 sec Position Base P_melt P_Z P_cruciform -1 T 1.2837202054154014e-07 0 0 -2 T 1.4854536477113216e-07 0 0 -3 C 8.4225531306322499e-08 0 0 -4 T 1.272482268662588e-07 0 0 -5 C 9.8351265964941495e-08 0 0 -6 A 2.1075192806767564e-07 0 0 -7 T 2.3942341583348001e-07 0 0 -8 G 1.8082154533395449e-07 0 0 -9 T 3.1923690876448779e-07 0 0 -10 T 3.5321808365076585e-07 0 0 -11 T 2.8758164431121559e-07 0 0 -12 G 1.2139895788886951e-07 0 0 -13 A 1.2254888267181411e-07 0 0 -14 C 5.1617740504977282e-08 0 0 -15 A 7.6238436118224707e-08 0 0 -16 G 3.3304922904038372e-08 0 0 -17 C 7.9391356564540425e-08 0 0 -18 T 3.3406419412213954e-07 0 0 -19 T 4.7816057037304521e-07 0 0 -20 A 5.0728144938451044e-07 0 1.6352124245557493e-07 -21 T 4.1962388389122197e-07 0 1.6352124245557493e-07 -22 C 2.1068599098392705e-07 0 1.6352124245557493e-07 -23 A 2.4315075915945523e-07 0 1.6352124245557493e-07 -24 T 1.9233574424371436e-07 0 1.6352124245557493e-07 -25 C 6.462022510478155e-08 0 1.6352124245557493e-07 -26 G 8.8222941986971968e-08 0 1.6352124245557493e-07 -27 A 3.1547365249520576e-07 0 1.6352124245557493e-07 -28 T 4.2933617509661332e-07 0 1.6352124245557493e-07 -29 A 4.3187056053842029e-07 0 1.6352124245557493e-07 -30 A 3.2352620006628755e-07 0 1.6352124245557493e-07 -31 G 1.0488306208739792e-07 0 1.6352124245557493e-07 -32 C 1.3208117624367593e-07 0 1.6352124245557493e-07 -33 T 5.2639045160384718e-07 0 1.6352124245557493e-07 -34 T 8.04837572031912e-07 0 1.6352124245557493e-07 -35 T 9.4656602191033707e-07 0 1.6352124245557493e-07 -36 A 9.4104785978106246e-07 0 1.6352124245557493e-07 -37 A 7.8817745193148602e-07 0 1.6352124245557493e-07 -38 T 4.9836436063918277e-07 0 1.6352124245557493e-07 -39 G 9.5223499856579924e-08 0 1.6352124245557493e-07 -40 C 1.4743880352934081e-08 0 1.6352124245557493e-07 -41 G 6.1363078235899114e-09 0 1.6352124245557493e-07 -42 G 3.5815096288767313e-08 0 1.6352124245557493e-07 -43 T 1.8288766858936738e-07 0 1.6352124245557493e-07 -44 A 2.563962292992348e-07 0 1.6352124245557493e-07 -45 G 2.4840957287944071e-07 0 0 -46 T 5.5753639213101772e-07 0 0 -47 T 7.4230590539223428e-07 0 0 -48 T 7.9553290475358391e-07 0 0 -49 A 7.1516146214280564e-07 0 0 -50 T 5.0673556109254924e-07 0 0 -51 C 1.7574151529457612e-07 0 0 -52 A 1.583545693574363e-07 0 0 -53 C 7.4125669340366904e-08 0 0 -54 A 1.7612288145818846e-07 0 0 -55 G 2.1536287006445211e-07 0 0 -56 T 6.8125653468855385e-07 0 0 -57 T 1.0353268142324145e-06 0 0 -58 A 1.2488443706337435e-06 0 0 -59 A 1.3162774897104355e-06 0 0 -60 A 1.2216999273843151e-06 0 0.70428222418242781 -61 T 9.7724816571980061e-07 0 0.70428222418242781 -62 T 6.0429443631701142e-07 0 0.70428222418242781 -63 G 1.370884818536368e-07 0 0.70428222418242781 -64 C 8.2572833805809545e-08 0 0.70428222418242781 -65 T 2.046441981979341e-07 0 0.70428222418242781 -66 A 2.3853591463062928e-07 0 0.70428222418242781 -67 A 1.846706548043514e-07 0 0.70428222418242781 -68 C 4.5715157418713542e-08 0 0.70428222418242781 -69 G 9.2257182236592619e-09 0 0.70428222418242781 -70 C 1.3107366617368327e-08 0 0.70428222418242781 -71 A 5.2365744940158256e-08 0 0.70428222418242781 -72 G 4.0026391288165247e-08 0 0 -73 T 6.92243004171074e-08 0 0 -74 C 4.0026391288165247e-08 0 0 -75 A 5.9354303124711378e-08 0 0 -76 G 1.3107366617368327e-08 0 0 -77 G 3.3779094886955779e-09 0 0 -78 C 1.0348968282473994e-08 0 0 -79 A 3.9406337247692869e-08 0 0 -80 C 1.0348968282473994e-08 0 0 -81 C 3.3779094886955779e-09 0 0 -82 G 1.9180553704905545e-08 0 0 -83 T 9.7082754665520805e-08 0 0 -84 G 1.1003298702463103e-07 0 0 -85 T 3.0082711445099522e-07 0 0 -86 A 3.9421669290508595e-07 0 0 -87 T 3.928981233975114e-07 0 0 -88 G 2.8867240986205715e-07 0 0 -89 A 5.1439749927636994e-07 0 0 -90 A 6.2373501679666162e-07 0 0 -91 A 6.2373501679666162e-07 0 0 -92 T 5.1439749927636994e-07 0 0 -93 C 2.9120679530386406e-07 0 0 -94 T 4.2263062299559628e-07 0 0 -95 A 4.5661179788187439e-07 0 0 -96 A 3.9543250883931831e-07 0 0 -97 C 2.3415676181422991e-07 0 0 -98 A 3.3539869866221617e-07 0 0 -99 A 3.3463519869515267e-07 0 0 -100 T 2.3847303802889526e-07 0 0 +1 T 1.3988675408621162e-07 0 0 +2 T 1.5045957694996938e-07 0 0 +3 C 5.8172029917811721e-08 0 0.10917650817670201 +4 T 1.0010943747843674e-07 0 0.10917650817670201 +5 C 5.8172029917811721e-08 0 0.10917650817670201 +6 A 1.6352765507865651e-07 0 0.10917650817670201 +7 T 1.7659573320734365e-07 0 0.10917650817670201 +8 G 9.488100903894379e-08 0 0.10917650817670201 +9 T 2.3691962382375946e-07 0 0.10917650817670201 +10 T 2.847413640822881e-07 0 0.10917650817670201 +11 T 2.2385154569507235e-07 0 0 +12 G 7.1240108046498882e-08 0 0.11123949074783585 +13 A 9.7088668305616505e-08 0 0.11123949074783585 +14 C 3.9554783403300265e-08 0 0.11123949074783585 +15 A 7.3447767313171598e-08 0 0.11123949074783585 +16 G 1.8282519303158056e-08 0 0.11123949074783585 +17 C 3.6899765817669505e-08 0 0.11123949074783585 +18 T 1.9518699022469397e-07 0 0 +19 T 2.5358155334698032e-07 0 0 +20 A 1.9518699022469397e-07 0 0 diff --git a/tests/unit/data/qsidd/cruciform.txt b/tests/unit/data/qsidd/cruciform.txt index 5f2125e..42a40fd 100644 --- a/tests/unit/data/qsidd/cruciform.txt +++ b/tests/unit/data/qsidd/cruciform.txt @@ -1,127 +1,47 @@ DNA sequence file: fragment.fa WARNING: sequence length is too short -Sequence Length = 100 +Sequence Length = 20 Transition: Cruciform Molecule type: linear DNA Stress Level = -0.059999999999999998 -linking difference = -0.86538461538461531 TURNS +linking difference = -0.40384615384615385 TURNS Threshold = 12 kcal/mol Temperature = 310 K Salt Concentration = 0.01 M C = 3.6000000000000001 kcal-bp/rad^2 Nucleation energy = 12.150009109596439 kcal/mol BAT = 0.25811566340021741 kcal/mol; BGC = 1.3048755414539936 kcal/mol -MinE = 2.8793244378698226 kcal/mol; Max_E = 14.879324437869823 kcal/mol +MinE = 1.5931626390532545 kcal/mol; Max_E = 13.593162639053254 kcal/mol Number of one-run states = 2 Number of two-run states = 0 Number of three-run states = 0 Number of four-run states = 0 Total number of states = 2 -Total Partition Function = 0.013254500720228397 +Total Partition Function = 0.096600313449421313 Scaling factor 300 -ln Partition Function = -4.3234181072286901 -Average number of runs = 0.70428875770873733 -Transition Probability = 0.70428875770873733 -Number of cruciform bases = 8.4514672183016089 +ln Partition Function = -2.3371732929509221 +Average number of runs = 0.22041639852145287 +Transition Probability = 0.22041639852145287 +Number of cruciform bases = 1.5408518033390106 Run time = 0 sec Position Base P(x) 1 T 0 2 T 0 -3 C 0 -4 T 0 -5 C 0 -6 A 0 -7 T 0 -8 G 0 -9 T 0 -10 T 0 +3 C 0.10917670610514672 +4 T 0.10917670610514672 +5 C 0.10917670610514672 +6 A 0.10917670610514672 +7 T 0.10917670610514672 +8 G 0.10917670610514672 +9 T 0.10917670610514672 +10 T 0.10917670610514672 11 T 0 -12 G 0 -13 A 0 -14 C 0 -15 A 0 -16 G 0 -17 C 0 +12 G 0.11123969241630613 +13 A 0.11123969241630613 +14 C 0.11123969241630613 +15 A 0.11123969241630613 +16 G 0.11123969241630613 +17 C 0.11123969241630613 18 T 0 19 T 0 -20 A 1.635228277750584e-07 -21 T 1.635228277750584e-07 -22 C 1.635228277750584e-07 -23 A 1.635228277750584e-07 -24 T 1.635228277750584e-07 -25 C 1.635228277750584e-07 -26 G 1.635228277750584e-07 -27 A 1.635228277750584e-07 -28 T 1.635228277750584e-07 -29 A 1.635228277750584e-07 -30 A 1.635228277750584e-07 -31 G 1.635228277750584e-07 -32 C 1.635228277750584e-07 -33 T 1.635228277750584e-07 -34 T 1.635228277750584e-07 -35 T 1.635228277750584e-07 -36 A 1.635228277750584e-07 -37 A 1.635228277750584e-07 -38 T 1.635228277750584e-07 -39 G 1.635228277750584e-07 -40 C 1.635228277750584e-07 -41 G 1.635228277750584e-07 -42 G 1.635228277750584e-07 -43 T 1.635228277750584e-07 -44 A 1.635228277750584e-07 -45 G 0 -46 T 0 -47 T 0 -48 T 0 -49 A 0 -50 T 0 -51 C 0 -52 A 0 -53 C 0 -54 A 0 -55 G 0 -56 T 0 -57 T 0 -58 A 0 -59 A 0 -60 A 0.7042885941859095 -61 T 0.7042885941859095 -62 T 0.7042885941859095 -63 G 0.7042885941859095 -64 C 0.7042885941859095 -65 T 0.7042885941859095 -66 A 0.7042885941859095 -67 A 0.7042885941859095 -68 C 0.7042885941859095 -69 G 0.7042885941859095 -70 C 0.7042885941859095 -71 A 0.7042885941859095 -72 G 0 -73 T 0 -74 C 0 -75 A 0 -76 G 0 -77 G 0 -78 C 0 -79 A 0 -80 C 0 -81 C 0 -82 G 0 -83 T 0 -84 G 0 -85 T 0 -86 A 0 -87 T 0 -88 G 0 -89 A 0 -90 A 0 -91 A 0 -92 T 0 -93 C 0 -94 T 0 -95 A 0 -96 A 0 -97 C 0 -98 A 0 -99 A 0 -100 T 0 +20 A 0 diff --git a/tests/unit/data/qsidd/fragment.fa b/tests/unit/data/qsidd/fragment.fa index 7f389ea..5f976cd 100644 --- a/tests/unit/data/qsidd/fragment.fa +++ b/tests/unit/data/qsidd/fragment.fa @@ -1,3 +1,2 @@ >pbr322 fragment -TTCTCATGTTTGACAGCTTATCATCGATAAGCTTTAATGCGGTAGTTTATCACAGTTAAATTGCTAACGC -AGTCAGGCACCGTGTATGAAATCTAACAAT +TTCTCATGTTTGACAGCTTA diff --git a/tests/unit/data/qsidd/fragment.ir b/tests/unit/data/qsidd/fragment.ir index f5022bc..bacf503 100644 --- a/tests/unit/data/qsidd/fragment.ir +++ b/tests/unit/data/qsidd/fragment.ir @@ -1 +1 @@ -1,0,10000,|20,25,1.5,|60,12,2.5,| +1,0,10000,|3,8,1.5,|12,6,2.5,| diff --git a/tests/unit/data/qsidd/melting.txt b/tests/unit/data/qsidd/melting.txt index cc907d0..a0947b3 100644 --- a/tests/unit/data/qsidd/melting.txt +++ b/tests/unit/data/qsidd/melting.txt @@ -1,127 +1,47 @@ DNA sequence file: fragment.fa WARNING: sequence length is too short -Sequence Length = 100 +Sequence Length = 20 Transition: Melting - copolymeric energetics Molecule type: linear DNA Stress Level = -0.059999999999999998 -linking difference = -0.86538461538461531 TURNS +linking difference = -0.40384615384615385 TURNS Threshold = 12 kcal/mol Temperature = 310 K Salt Concentration = 0.01 M C = 3.6000000000000001 kcal-bp/rad^2 Nucleation energy = 10.84 kcal/mol BAT = 0.25811566340021741 kcal/mol; BGC = 1.3048755414539936 kcal/mol -MinE = 3.4139199408284022 kcal/mol; Max_E = 15.413919940828402 kcal/mol -Number of one-run states = 734 +MinE = 1.5931626390532545 kcal/mol; Max_E = 13.593162639053254 kcal/mol +Number of one-run states = 117 Number of two-run states = 0 Number of three-run states = 0 Number of four-run states = 0 -Total number of states = 734 -Total Partition Function = 0.0039196304026189437 +Total number of states = 117 +Total Partition Function = 0.075308195391646654 Scaling factor 300 -ln Partition Function = -5.5417579146710523 -Average number of runs = 3.2025644480199974e-05 -Transition Probability = 3.2025644480259002e-05 -Number of melted bases = 0.00010879893004904143 +ln Partition Function = -2.5861663135560775 +Average number of runs = 2.3254944476833412e-06 +Transition Probability = 2.3254944476803689e-06 +Number of melted bases = 3.973309811615764e-06 Run time = 0 sec Position Base P(x) G(x) -1 T 4.0793423753589667e-07 10.829988838005404 -2 T 4.6914030971625862e-07 10.886524619775502 -3 C 2.9182935314984666e-07 11.332463047615308 -4 T 4.2018992254908285e-07 11.193997029771323 -5 C 3.4610442850793684e-07 11.415312335271333 -6 A 6.9251306731949819e-07 10.944138843401165 -7 T 7.8946862192955229e-07 10.908309719496579 -8 G 6.2448139425428095e-07 11.086441625272657 -9 T 1.0593660732128728e-06 10.689379232670358 -10 T 1.1647284332383163e-06 10.626750125445867 -11 T 9.523205739885378e-07 10.681369219117816 -12 G 4.2404254498165718e-07 11.222084326764325 -13 A 4.0429861176683124e-07 11.147939789436982 -14 C 1.8857493407235279e-07 11.524173255298866 -15 A 2.4819980172218085e-07 11.314874506363109 -16 G 1.3797034223318018e-07 11.768472697970326 -17 C 2.9331162987555774e-07 11.298284921656004 -18 T 1.1165181930123367e-06 10.415089715135053 -19 T 1.587234171115155e-06 10.351560545675291 -20 A 1.6857093879700097e-06 10.36965870877183 -21 T 1.3988348489018199e-06 10.469808299984702 -22 C 7.2547105739161977e-07 10.959217643180791 -23 A 8.0858047845003177e-07 10.866978522660322 -24 T 6.4375647755173711e-07 10.943376611462876 -25 C 2.4986901078106603e-07 11.671361513874004 -26 G 3.2317653502844521e-07 11.345421995130977 -27 A 1.0581303380334267e-06 10.437860739097919 -28 T 1.4375928818987398e-06 10.35917509989603 -29 A 1.4571485839238291e-06 10.381857838405748 -30 A 1.1183171063534956e-06 10.523479933752448 -31 G 4.2345610575473713e-07 11.496603892571166 -32 C 5.2193676313987064e-07 11.361701259613346 -33 T 1.8173381555616419e-06 10.258249982146163 -34 T 2.7423748518765695e-06 10.095405746258701 -35 T 3.2151365673371688e-06 10.036635685943036 -36 A 3.1854909206977992e-06 10.018691995926771 -37 A 2.6575586548377811e-06 10.036419515620516 -38 T 1.683101351344876e-06 10.12500342423591 -39 G 3.463449547792037e-07 11.077761721361174 -40 C 7.1997383202316657e-08 11.912747248509717 -41 G 3.6382534827987523e-08 11.956517554162023 -42 G 1.4341987880425654e-07 11.55410130144986 -43 T 6.0774782473787239e-07 10.845844015524989 -44 A 8.6029778057583612e-07 10.84345531433406 -45 G 8.7297851751519428e-07 10.962484289049055 -46 T 1.8961267822509131e-06 10.386290289472299 -47 T 2.5179027242233128e-06 10.264410630374183 -48 T 2.6978952410212593e-06 10.233570874466929 -49 A 2.4261110260970521e-06 10.255160623640405 -50 T 1.7243386006184001e-06 10.370166335865951 -51 C 6.4076369383616412e-07 11.092089094609035 -52 A 5.583354452456917e-07 11.167768735717683 -53 C 3.0415151130535692e-07 11.683012107339657 -54 A 6.1191333578782006e-07 11.153280922622718 -55 G 7.6173240715902808e-07 11.050516290849741 -56 T 2.3014841076537773e-06 10.225686349465452 -57 T 3.5097942216022031e-06 10.068503538040204 -58 A 4.2759919571447433e-06 10.00611005718895 -59 A 4.5150093335851082e-06 9.9868828923796666 -60 A 4.1951856786740917e-06 10.000761718947983 -61 T 3.3575617419947795e-06 10.055500424358751 -62 T 2.0989149306141172e-06 10.208299071552112 -63 G 5.3033249958333282e-07 11.312502506113645 -64 C 3.4150433203696613e-07 11.594020713994853 -65 T 7.3199359271558464e-07 10.715376347886576 -66 A 8.2860431736227873e-07 10.567004091269396 -67 A 6.4248018313138444e-07 10.549018808439898 -68 C 1.6591252367629922e-07 11.247165442622808 -69 G 5.3841835553960749e-08 11.931044742095978 -70 C 6.2658104598805347e-08 11.683571639359963 -71 A 1.9110438721605213e-07 11.159501010675305 -72 G 1.4937760670745735e-07 11.447326701230489 -73 T 2.4110116378703278e-07 11.158846860058718 -74 C 1.4937760670745735e-07 11.447326701230489 -75 A 1.9110438721605213e-07 11.159501010675305 -76 G 6.2658104598805347e-08 11.683571639359965 -77 G 3.406687501535414e-08 12 -78 C 5.3330299827052268e-08 11.65461321813059 -79 A 1.3066045487821799e-07 11.111149346636928 -80 C 5.3330299827052262e-08 11.654613218130592 -81 C 3.406687501535414e-08 12 -82 G 8.3195204979939733e-08 11.709807328183267 -83 T 3.2967240647713059e-07 11.102756470307469 -84 G 4.0107073114679307e-07 11.201783315220112 -85 T 1.0105453417380568e-06 10.679790691858482 -86 A 1.3277886858022369e-06 10.645920329010925 -87 T 1.343863670542425e-06 10.716527129385954 -88 G 1.0355801928332564e-06 10.997094654659163 -89 A 1.7701895522843551e-06 10.580382708382173 -90 A 2.1413624757858118e-06 10.48854717996136 -91 A 2.1458404298177064e-06 10.492329839800288 -92 T 1.7856529259718588e-06 10.594445487480652 -93 C 1.0661213145139547e-06 11.028427761890528 -94 T 1.4728854496082566e-06 10.749377999951282 -95 A 1.567262389978091e-06 10.688879819451783 -96 A 1.3589414185356195e-06 10.73048486851479 -97 C 8.4227407125499549e-07 11.033593544709449 -98 A 1.1404676043498826e-06 10.686335003845432 -99 A 1.1173518897285279e-06 10.589463734876958 -100 T 7.9774492162681328e-07 10.590602066443518 +1 T 1.7943769227335756e-07 11.113741431995159 +2 T 1.9299982650029421e-07 11.161631231059431 +3 C 7.4619322404720301e-08 11.842526298039925 +4 T 1.2841391991155851e-07 11.471890736938324 +5 C 7.4619322404720301e-08 11.842526298039925 +6 A 2.0976271300214558e-07 11.234631002135689 +7 T 2.2652559950399694e-07 11.296826812159495 +8 G 1.2170722963535973e-07 11.901327828238045 +9 T 3.0390518981523601e-07 11.183672297758406 +10 T 3.6524782921337266e-07 11.070019753307626 +11 T 2.8714230331338467e-07 11.131631348174853 +12 G 9.1382208906571691e-08 11.885191750633801 +13 A 1.2453907234073486e-07 11.471598984846818 +14 C 5.0738321141446112e-08 11.830536041215822 +15 A 9.4214051611946813e-08 11.317629526470171 +16 G 2.3451634817975627e-08 11.875883236726121 +17 C 4.733263608124981e-08 11.871906454337086 +18 T 2.5037326311908279e-07 11.00363854591475 +19 T 3.2527803674415601e-07 10.94297768238534 +20 A 2.5037326311908279e-07 11.00363854591475 diff --git a/tests/unit/data/qsidd/z-dna.txt b/tests/unit/data/qsidd/z-dna.txt index 841c6d8..a3ac749 100644 --- a/tests/unit/data/qsidd/z-dna.txt +++ b/tests/unit/data/qsidd/z-dna.txt @@ -1,24 +1,24 @@ DNA sequence file: fragment.fa WARNING: sequence length is too short -Sequence Length = 100 +Sequence Length = 20 Transition: Z-DNA Molecule type: linear DNA Stress Level = -0.059999999999999998 -linking difference = -0.86538461538461531 TURNS +linking difference = -0.40384615384615385 TURNS Threshold = 12 kcal/mol Temperature = 310 K Salt Concentration = 0.01 M C = 3.6000000000000001 kcal-bp/rad^2 Nucleation energy = 10 kcal/mol -MinE = 3.4139199408284022 kcal/mol; Max_E = 15.413919940828402 kcal/mol +MinE = 1.5931626390532545 kcal/mol; Max_E = 13.593162639053254 kcal/mol Number of one-run states = 0 Number of two-run states = 0 Number of three-run states = 0 Number of four-run states = 0 Total number of states = 0 -Total Partition Function = 0.0039195048739291754 +Total Partition Function = 0.075308020262856407 Scaling factor 300 -ln Partition Function = -5.5417899408283802 +ln Partition Function = -2.5861686390532554 Average number of runs = 0 Transition Probability = 0 Number of Z-DNA bases = 0 @@ -44,83 +44,3 @@ Position Base P(x) 18 T 0 19 T 0 20 A 0 -21 T 0 -22 C 0 -23 A 0 -24 T 0 -25 C 0 -26 G 0 -27 A 0 -28 T 0 -29 A 0 -30 A 0 -31 G 0 -32 C 0 -33 T 0 -34 T 0 -35 T 0 -36 A 0 -37 A 0 -38 T 0 -39 G 0 -40 C 0 -41 G 0 -42 G 0 -43 T 0 -44 A 0 -45 G 0 -46 T 0 -47 T 0 -48 T 0 -49 A 0 -50 T 0 -51 C 0 -52 A 0 -53 C 0 -54 A 0 -55 G 0 -56 T 0 -57 T 0 -58 A 0 -59 A 0 -60 A 0 -61 T 0 -62 T 0 -63 G 0 -64 C 0 -65 T 0 -66 A 0 -67 A 0 -68 C 0 -69 G 0 -70 C 0 -71 A 0 -72 G 0 -73 T 0 -74 C 0 -75 A 0 -76 G 0 -77 G 0 -78 C 0 -79 A 0 -80 C 0 -81 C 0 -82 G 0 -83 T 0 -84 G 0 -85 T 0 -86 A 0 -87 T 0 -88 G 0 -89 A 0 -90 A 0 -91 A 0 -92 T 0 -93 C 0 -94 T 0 -95 A 0 -96 A 0 -97 C 0 -98 A 0 -99 A 0 -100 T 0 diff --git a/tests/unit/results/results_helpers.py b/tests/unit/results/results_helpers.py index cf21dab..f746a56 100644 --- a/tests/unit/results/results_helpers.py +++ b/tests/unit/results/results_helpers.py @@ -1,7 +1,7 @@ """Saved qsidd outputs and settings shared by the sist.results tests. The saved qsidd outputs in ``tests/unit/data/qsidd`` were made with ``-b -p -r --P`` on ``fragment.fa``, the first 100 bp of the regression sequence. The +-P`` on ``fragment.fa``, the first 20 bp of the regression sequence. The underflow output was made on the full regression sequence at a superhelical density of 0.3, with its table cut to 5 rows. """ @@ -42,7 +42,7 @@ def read_output(name: str) -> QsiddOutput: def make_settings(flag: str, **overrides: Any) -> RunSettings: - """Make settings for the 100 bp fragment the saved outputs were run on. + """Make settings for the 20 bp fragment the saved outputs were run on. Args: flag: Algorithm flag, such as ``"M"``. diff --git a/tests/unit/results/test_builder.py b/tests/unit/results/test_builder.py index 0800dd3..e54ce42 100644 --- a/tests/unit/results/test_builder.py +++ b/tests/unit/results/test_builder.py @@ -49,7 +49,7 @@ def test_success_records_inverted_repeats_only_when_used() -> None: ) assert result.inverted_repeats is not None - assert [repeat.start for repeat in result.inverted_repeats] == [20, 60] + assert [repeat.start for repeat in result.inverted_repeats] == [3, 12] def test_success_warns_when_there_are_no_inverted_repeats() -> None: @@ -75,20 +75,7 @@ def test_success_replaces_the_qsidd_length_warning_with_its_own() -> None: assert [w.code for w in result.warnings] == [WarningCode.SEQUENCE_TOO_SHORT] -def test_success_raises_when_the_partition_function_underflows() -> None: - builder = ResultBuilder( - make_settings("M", file=str(TOY_PATH), superhelical_density=0.3) - ) - sequence = builder.read_sequence() - - with pytest.raises(ResultError) as raised: - builder.success(read_output("underflow.txt"), sequence) - - assert raised.value.code == ErrorCode.PARTITION_FUNCTION_UNDERFLOW - assert raised.value.exit_code == 0 - - -def test_failure_after_underflow_keeps_what_qsidd_printed( +def test_underflow_becomes_a_failed_result_that_keeps_what_qsidd_printed( validator: ResultValidator, ) -> None: builder = ResultBuilder( @@ -102,6 +89,7 @@ def test_failure_after_underflow_keeps_what_qsidd_printed( result = builder.failure(raised.value, sequence=sequence, output=output) + assert raised.value.code == ErrorCode.PARTITION_FUNCTION_UNDERFLOW assert validator.validate(result.to_dict()) == [] assert result.derived_parameters is not None assert [w.code for w in result.warnings] == [ diff --git a/tests/unit/results/test_diagnostics.py b/tests/unit/results/test_diagnostics.py index bee8ffe..def95c1 100644 --- a/tests/unit/results/test_diagnostics.py +++ b/tests/unit/results/test_diagnostics.py @@ -14,19 +14,24 @@ qsidd_warnings, ) from sist.results.sequence import SequenceInput +from sist.schema import ResultValidator from sist.transitions import ALGORITHMS -def test_every_error_code_has_a_stage() -> None: - stages = {code.stage for code in ErrorCode} +def test_error_stages_are_ones_the_schema_allows() -> None: + schema = ResultValidator.load_schema() - assert stages <= {"validation", "input", "ir_finder", "qsidd", "output", "internal"} + allowed = schema["$defs"]["error"]["properties"]["stage"]["enum"] + assert {code.stage for code in ErrorCode} <= set(allowed) -def test_warning_sources() -> None: - assert WarningCode.THRESHOLD_TOO_LOW.source == "qsidd" - assert WarningCode.NO_INVERTED_REPEATS_FOUND.source == "ir_finder" - assert WarningCode.AMBIGUOUS_BASES_REPLACED.source == "sist" + +def test_warning_sources_are_ones_the_schema_allows() -> None: + schema = ResultValidator.load_schema() + + allowed = schema["$defs"]["warning"]["properties"]["source"]["enum"] + + assert {code.source for code in WarningCode} == set(allowed) def test_warning_to_dict_includes_the_source_and_details() -> None: diff --git a/tests/unit/results/test_qsidd_output.py b/tests/unit/results/test_qsidd_output.py index 52e94f8..10214a1 100644 --- a/tests/unit/results/test_qsidd_output.py +++ b/tests/unit/results/test_qsidd_output.py @@ -28,7 +28,7 @@ def test_parse_reads_the_profile_table(competition_output: QsiddOutput) -> None: "P_Z", "P_cruciform", ] - assert len(competition_output.rows) == 100 + assert len(competition_output.rows) == 20 def test_number_drops_the_unit(melting_output: QsiddOutput) -> None: @@ -43,7 +43,7 @@ def test_number_returns_none_for_nan_and_infinity() -> None: def test_count_reads_an_exact_integer(melting_output: QsiddOutput) -> None: - assert melting_output.count("Total number of states") == 734 + assert melting_output.count("Total number of states") == 117 def test_column_reads_one_column(melting_output: QsiddOutput) -> None: diff --git a/tests/unit/results/test_reader.py b/tests/unit/results/test_reader.py index 4c40fc0..560b4bb 100644 --- a/tests/unit/results/test_reader.py +++ b/tests/unit/results/test_reader.py @@ -25,7 +25,7 @@ def test_transitions_read_the_single_layout(melting_output: QsiddOutput) -> None assert melting.nucleation_energy_kcal_per_mol == 10.84 assert melting.probability == melting_output.number("Transition Probability") - assert len(melting.profile_probability) == 100 + assert len(melting.profile_probability) == 20 def test_transitions_read_the_competition_layout( @@ -41,17 +41,19 @@ def test_transitions_read_the_competition_layout( ) -def test_free_energy_is_null_where_probability_is_zero( - melting_output: QsiddOutput, -) -> None: +def test_free_energy_is_null_where_probability_is_zero() -> None: + """G(x) is undefined where no counted state includes the position.""" + lines = (QSIDD_PATH / "melting.txt").read_text(encoding="utf-8").splitlines() + table_start = next(n for n, line in enumerate(lines) if line.startswith("Position")) + position, base, _, free_energy = lines[table_start + 3].split("\t") + lines[table_start + 3] = "\t".join([position, base, "0", free_energy]) reader = QsiddReader(ALGORITHMS["M"]) - melting = reader.transitions(melting_output)["melting"] + melting = reader.transitions(QsiddOutput.parse("\n".join(lines)))["melting"] assert melting.free_energy_kcal_per_mol is not None - assert [value is None for value in melting.free_energy_kcal_per_mol] == [ - value == 0 for value in melting.profile_probability - ] + assert melting.free_energy_kcal_per_mol[2] is None + assert melting.free_energy_kcal_per_mol[0] is not None def test_free_energy_is_left_out_where_qsidd_does_not_print_it( @@ -69,8 +71,8 @@ def test_summary_reads_exact_state_counts(melting_output: QsiddOutput) -> None: summary = reader.summary(melting_output) - assert summary.states_by_number_of_runs == [734, 0, 0, 0] - assert summary.total_states == 734 + assert summary.states_by_number_of_runs == [117, 0, 0, 0] + assert summary.total_states == 117 assert summary.pairwise is None @@ -108,10 +110,3 @@ def test_derived_parameters_are_null_where_not_printed() -> None: assert derived.bat_kcal_per_mol is None assert derived.torsional_stiffness_kcal_bp_per_rad2 == 3.6 - - -def test_underflowed() -> None: - reader = QsiddReader(ALGORITHMS["M"]) - - assert reader.underflowed(read_output("underflow.txt")) - assert not reader.underflowed(read_output("melting.txt")) From 57d512524e8e60d9a973b9ba98acdd96738bec32 Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Wed, 11 Nov 2026 14:25:03 +0000 Subject: [PATCH 3/6] test(results): cover the provenance fallbacks --- tests/unit/results/test_provenance.py | 52 +++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/tests/unit/results/test_provenance.py b/tests/unit/results/test_provenance.py index 31abdad..a748f4f 100644 --- a/tests/unit/results/test_provenance.py +++ b/tests/unit/results/test_provenance.py @@ -2,10 +2,13 @@ from __future__ import annotations +import subprocess from datetime import datetime +from pathlib import Path import pytest +from sist.results import provenance from sist.results.provenance import ProvenanceRecorder @@ -38,3 +41,52 @@ def test_to_dict_has_the_schema_shape() -> None: assert section["software"]["name"] == "SIST" assert section["software"]["irf_version"] == "3.09" assert set(section["environment"]) == {"python", "platform"} + + +def test_git_sha_is_read_from_a_source_checkout( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("SIST_GIT_SHA", raising=False) + module_path = tmp_path / "src" / "sist" / "results" / "provenance.py" + (tmp_path / ".git").mkdir() + monkeypatch.setattr(provenance, "__file__", str(module_path)) + monkeypatch.setattr( + provenance.subprocess, + "run", + lambda command, **_: subprocess.CompletedProcess(command, 0, "0123abc\n"), + ) + + assert ProvenanceRecorder.git_sha() == "0123abc" + + +def test_git_sha_is_none_for_an_installed_copy( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("SIST_GIT_SHA", raising=False) + module_path = tmp_path / "site-packages" / "sist" / "results" / "provenance.py" + monkeypatch.setattr(provenance, "__file__", str(module_path)) + + assert ProvenanceRecorder.git_sha() is None + + +def test_git_sha_is_none_when_git_cannot_run( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def missing_git(command: list[str], **_: object) -> None: + """Behave as if git is not installed. + + Args: + command: The command that would have run. + + Raises: + OSError: Always. + """ + raise OSError("git") + + monkeypatch.delenv("SIST_GIT_SHA", raising=False) + (tmp_path / ".git").mkdir() + module_path = tmp_path / "src" / "sist" / "results" / "provenance.py" + monkeypatch.setattr(provenance, "__file__", str(module_path)) + monkeypatch.setattr(provenance.subprocess, "run", missing_git) + + assert ProvenanceRecorder.git_sha() is None From 115fd8c1d0d758ffa827f4e40ebc94a12f86e455 Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Wed, 11 Nov 2026 14:48:10 +0000 Subject: [PATCH 4/6] docs(results): describe what each part of the results package does --- src/sist/results/builder.py | 12 +++++------- src/sist/results/diagnostics.py | 7 +++---- src/sist/results/model.py | 11 +++++------ src/sist/results/provenance.py | 6 +++--- src/sist/results/qsidd_output.py | 8 ++------ src/sist/results/reader.py | 23 ++++++++++------------- src/sist/results/sequence.py | 8 +++----- src/sist/results/writer.py | 4 ++-- tests/unit/results/test_builder.py | 2 +- tests/unit/results/test_reader.py | 6 +++--- 10 files changed, 37 insertions(+), 50 deletions(-) diff --git a/src/sist/results/builder.py b/src/sist/results/builder.py index b8df121..82b3613 100644 --- a/src/sist/results/builder.py +++ b/src/sist/results/builder.py @@ -29,7 +29,7 @@ class ResultBuilder: """Build the result of one run. - Create one builder when the run starts, so its start time is recorded, + Create one builder when the run starts, which records its start time, then call :meth:`read_sequence` and either :meth:`success` or :meth:`failure`. @@ -85,8 +85,7 @@ def success( ) -> Result: """Build the result of a run that finished. - qsidd's warnings are recorded before checking for underflow, so a run - that fails that check still keeps them. + Records qsidd's warnings, then checks for underflow. Args: output: The parsed qsidd output. @@ -98,8 +97,7 @@ def success( The result. Raises: - ResultError: If the partition function underflowed, so qsidd's - values are meaningless even though it exited normally. + ResultError: If the partition function underflowed to zero. """ self.warnings.extend(qsidd_warnings(output.warnings)) @@ -150,8 +148,8 @@ def failure( ) -> Result: """Build the result of a run that failed. - Everything known before the failure is kept, so a partition function - underflow still records the derived parameters qsidd printed. + Keeps everything known before the failure, including any derived + parameters qsidd printed. Args: error: Why the run failed. diff --git a/src/sist/results/diagnostics.py b/src/sist/results/diagnostics.py index d9e892d..2787137 100644 --- a/src/sist/results/diagnostics.py +++ b/src/sist/results/diagnostics.py @@ -1,7 +1,7 @@ """Warning and error codes, and the checks that raise warnings. -Every code a result can hold is listed here once, along with the part of SIST -that raises it, so codes cannot drift between the code, the tests and the docs. +Each warning code records the part of SIST that raises it, and each error code +the stage of the run that fails. """ from __future__ import annotations @@ -93,8 +93,7 @@ def stage(self) -> str: ), } """qsidd's warning text and its code. qsidd's two sequence length warnings are -left out, because it checks the size of the file rather than the number of base -pairs, so :func:`check_sequence` raises those instead.""" +not included. :func:`check_sequence` raises the sequence length warnings.""" MIN_SEQUENCE_LENGTH = 1500 """Shortest recommended sequence, in base pairs.""" diff --git a/src/sist/results/model.py b/src/sist/results/model.py index 766c3d5..e3a8459 100644 --- a/src/sist/results/model.py +++ b/src/sist/results/model.py @@ -1,8 +1,7 @@ """The typed SIST result. -Each section of a result is a small dataclass with a ``to_dict`` method. This -is the one place that knows the shape of ``sist-result-v1.schema.json``, so the -rest of the code works with typed values instead of nested dictionaries. +Each section of a result is a small dataclass with a ``to_dict`` method that +writes it in the shape of ``sist-result-v1.schema.json``. """ from __future__ import annotations @@ -54,8 +53,8 @@ def molecule_type(self) -> str: def parameters(self) -> dict[str, Any]: """Write the settings as the calculation used them. - qsidd always uses negative supercoiling, and the IR finder always scores - inverted repeats at a fixed salt, so those are recorded as used. + The superhelical density is written as negative, as qsidd uses it. + Runs that score inverted repeats also record the IR finder's fixed salt. Returns: The ``parameters`` section. @@ -297,7 +296,7 @@ def parse_all(cls, ir_string: str) -> list[InvertedRepeat]: """Read the scored inverted repeats from the string passed to qsidd. The string is ``start,length,energy,|`` repeated, and starts with a - placeholder entry of length 0, which is left out. + placeholder entry of length 0, which is skipped. Args: ir_string: The string the IR finder built for ``qsidd -X``. diff --git a/src/sist/results/provenance.py b/src/sist/results/provenance.py index 7431a41..88945b1 100644 --- a/src/sist/results/provenance.py +++ b/src/sist/results/provenance.py @@ -71,9 +71,9 @@ def timestamp() -> str: def git_sha(cls) -> str | None: """Find the git commit SIST is running from. - The environment variable wins if it is set. Otherwise the commit is read - with git, but only when SIST is running from a source checkout, so an - installed copy never reports an unrelated repository. + Uses the environment variable if it is set. Otherwise reads the commit + with git when SIST is running from a source checkout, and returns None + for an installed copy. Returns: The commit hash, or None if it cannot be found. diff --git a/src/sist/results/qsidd_output.py b/src/sist/results/qsidd_output.py index fd376f1..dfb65b9 100644 --- a/src/sist/results/qsidd_output.py +++ b/src/sist/results/qsidd_output.py @@ -10,9 +10,6 @@ class QsiddOutput: """The text output of one qsidd run, split into its parts. - This knows only qsidd's text format, not what the values mean or where they - go in a result. - Attributes: values: Every ``key = value`` line, with the value kept as text. warnings: The text of each ``WARNING:`` line, in order. @@ -64,9 +61,8 @@ def parse(cls, text: str) -> QsiddOutput: def number(self, key: str) -> float | None: """Read a printed value as a number. - Values such as ``-25.4 turns`` keep only the number. qsidd prints - ``nan`` and ``inf`` when a calculation breaks down, and those come back - as None, because JSON cannot hold them. + Values such as ``-25.4 turns`` keep only the number. ``nan`` and + ``inf`` are returned as None. Args: key: Name of the value, as printed before the ``=``. diff --git a/src/sist/results/reader.py b/src/sist/results/reader.py index 3ff59c4..f4c64ca 100644 --- a/src/sist/results/reader.py +++ b/src/sist/results/reader.py @@ -1,8 +1,8 @@ """Turn qsidd's output into result values, for any algorithm. -qsidd prints the same values under different names depending on whether it ran -one transition or a competition. The names come from :mod:`sist.transitions`, -so one reader handles every algorithm without checking algorithm letters. +qsidd prints each value under one name for a single transition and another for +a competition. The reader looks the names up in :mod:`sist.transitions` for the +algorithm it was given. """ from __future__ import annotations @@ -40,15 +40,14 @@ def __init__(self, algorithm: Algorithm) -> None: def underflowed(self, output: QsiddOutput) -> bool: """Check whether the partition function underflowed to zero. - qsidd still exits normally when this happens, but every probability it - prints is meaningless, and its log of the partition function is not a - finite number. + qsidd reports this by printing a log of the partition function that is + not a finite number. Args: output: The parsed qsidd output. Returns: - True if the run's values cannot be used. + True if the partition function underflowed. """ return output.number("ln Partition Function") is None @@ -128,8 +127,8 @@ def _transition( ) -> TransitionResult: """Read the results for one transition. - G(x) is included when qsidd printed it, and is null where the - transition's probability is 0, because G(x) is undefined there. + G(x) is included when qsidd printed it, with null where the + transition's probability is 0. Args: output: The parsed qsidd output. @@ -162,10 +161,8 @@ def _transition( def _pairwise(self, output: QsiddOutput) -> PairMatrices: """Read the probabilities for pairs of transitions. - qsidd writes 0 for P(a given not b) when b is certain, which is - undefined rather than 0, so that case is written as null. Values qsidd - prints as ``nan``, such as P(a given b) when b never happens, are also - null. + P(a given not b) is null when b is certain. Any value qsidd prints as + ``nan`` is null. Args: output: The parsed qsidd output. diff --git a/src/sist/results/sequence.py b/src/sist/results/sequence.py index bafbe9f..ec91b22 100644 --- a/src/sist/results/sequence.py +++ b/src/sist/results/sequence.py @@ -13,16 +13,14 @@ class SequenceInput: """The sequence read from the input file, as qsidd will analyse it. - qsidd skips header lines, keeps A, C, G, T and N (in any case) and drops - every other character. This mirrors that, so the result can record what - was actually analysed. + Header lines are skipped, A, C, G, T and N are kept in any case, and every + other character is dropped, as qsidd does. Attributes: name: The FASTA header without the leading ``>``, or None if the file has no header. analysed: The bases qsidd analyses, in upper case. - dropped: Number of characters qsidd drops because they are not A, C, - G, T or N. + dropped: Number of characters dropped that are not A, C, G, T or N. """ name: str | None diff --git a/src/sist/results/writer.py b/src/sist/results/writer.py index bf8c8b8..985006c 100644 --- a/src/sist/results/writer.py +++ b/src/sist/results/writer.py @@ -59,8 +59,8 @@ def write(self, result: Result, path: Path) -> None: def to_json(data: dict[str, Any]) -> str: """Write a result dictionary as JSON. - Objects are indented, but arrays of plain values stay on one line, so a - per-position array is one line rather than one line per base pair. + Objects are indented, and arrays of plain values are written on one + line. Args: data: The result as a dictionary. diff --git a/tests/unit/results/test_builder.py b/tests/unit/results/test_builder.py index e54ce42..70ae771 100644 --- a/tests/unit/results/test_builder.py +++ b/tests/unit/results/test_builder.py @@ -66,7 +66,7 @@ def test_success_warns_when_there_are_no_inverted_repeats() -> None: def test_success_replaces_the_qsidd_length_warning_with_its_own() -> None: - """qsidd checks the size of the file, so SIST checks the base pairs instead.""" + """Only SIST's base pair length warning is recorded, not qsidd's.""" builder = ResultBuilder(make_settings("M")) sequence = builder.read_sequence() diff --git a/tests/unit/results/test_reader.py b/tests/unit/results/test_reader.py index 560b4bb..1448140 100644 --- a/tests/unit/results/test_reader.py +++ b/tests/unit/results/test_reader.py @@ -42,7 +42,7 @@ def test_transitions_read_the_competition_layout( def test_free_energy_is_null_where_probability_is_zero() -> None: - """G(x) is undefined where no counted state includes the position.""" + """G(x) is null at a position whose probability is 0.""" lines = (QSIDD_PATH / "melting.txt").read_text(encoding="utf-8").splitlines() table_start = next(n for n, line in enumerate(lines) if line.startswith("Position")) position, base, _, free_energy = lines[table_start + 3].split("\t") @@ -77,7 +77,7 @@ def test_summary_reads_exact_state_counts(melting_output: QsiddOutput) -> None: def test_pairwise_is_null_where_undefined() -> None: - """P(a given b) is undefined when b never happens, so it is null.""" + """P(a given b) is null when b never happens.""" reader = QsiddReader(ALGORITHMS["A"]) summary = reader.summary(read_output("competition-no-inverted-repeats.txt")) @@ -87,7 +87,7 @@ def test_pairwise_is_null_where_undefined() -> None: def test_given_absent_is_null_when_the_other_transition_is_certain() -> None: - """qsidd writes 0 for P(a given not b) when b is certain, which is undefined.""" + """P(a given not b) is null when b is certain.""" text = (QSIDD_PATH / "competition.txt").read_text(encoding="utf-8") certain = "\n".join( "Prob_C = 1" if line.startswith("Prob_C =") else line From 74212b87faf00fc64df837dcc28a8b62e185da13 Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Mon, 16 Nov 2026 12:09:25 +0000 Subject: [PATCH 5/6] docs: expand the transitions and schema docstrings --- src/sist/schema.py | 126 ++++++++++++++++++++++++++++++---------- src/sist/transitions.py | 74 +++++++++++++++++------ 2 files changed, 151 insertions(+), 49 deletions(-) diff --git a/src/sist/schema.py b/src/sist/schema.py index acd5e58..05a2940 100644 --- a/src/sist/schema.py +++ b/src/sist/schema.py @@ -1,9 +1,22 @@ """Validate structured SIST results. -A result is checked in two passes. The JSON schema checks its shape: types, -ranges, required keys and allowed names. The cross-checks then compare one part -of the result with another, such as each per-position array against the -sequence length. +A result is checked in two passes: + +1. The JSON schema, ``sist-result-v1.schema.json``, checks its shape: types, + ranges, required keys and allowed names. +2. The cross-checks compare one part of the result with another: the + transitions against the algorithm, each per-position array against the + sequence length, the state counts against their total, and the partition + function against its log. + +Each problem is reported as a :class:`ValidationIssue`, which prints as its +path and message:: + + for issue in ResultValidator().validate(result): + print(issue) + +For a melting profile one entry too long, this prints a line starting +``transitions/melting/profile/probability:``. """ from __future__ import annotations @@ -27,22 +40,30 @@ class ValidationIssue: """A single problem found in a SIST result. Attributes: - path: Where the problem is, written as keys joined by ``/``, for example - ``"profile/probability/melting"``. Empty for the top level. - message: What is wrong. + path: Where the problem is, written as keys and list indexes joined by + ``/``, for example ``"transitions/melting/profile/probability/2"``. + Empty for the top level. + message: What is wrong, such as ``"1.5 is greater than the maximum of + 1"``. """ path: str message: str def __str__(self) -> str: - """Format the issue as ``path: message``.""" + """Format the issue as ``path: message``, or ``(top level): message``.""" return f"{self.path or '(top level)'}: {self.message}" class ResultValidationError(ValueError): """Error for a SIST result that fails validation. + The message lists every problem, one per line:: + + 2 problem(s) in SIST result: + schema_version: '2.0.0' does not match ... + input/analysed_sequence: has 6 letters, expected 5 + Attributes: issues: Every problem found in the result. """ @@ -62,6 +83,10 @@ def __init__(self, issues: Sequence[ValidationIssue]) -> None: class ResultValidator: """Check SIST results against the result schema and the cross-checks. + :meth:`validate` returns every problem found, and :meth:`check` raises + :class:`ResultValidationError` if there are any. One validator can check + any number of results. + Attributes: SCHEMA_FILE: File name of the schema inside ``sist/schemas``. LN_PARTITION_FUNCTION_RTOL: Relative tolerance when comparing @@ -83,6 +108,9 @@ def __init__(self) -> None: def load_schema(cls) -> dict[str, Any]: """Load the result schema that ships with the package. + The schema is read from ``sist/schemas/sist-result-v1.schema.json`` + inside the installed package. + Returns: The schema as a dictionary. """ @@ -98,14 +126,16 @@ def load_schema(cls) -> dict[str, Any]: def validate(self, result: dict[str, Any]) -> list[ValidationIssue]: """Find every problem in a result. - The cross-checks run only when the schema passes. A result that fails - the schema reports only the schema problems. + The result is checked against the schema first. If the schema passes, + the cross-checks run as well. A result that fails the schema reports + only the schema problems. Args: - result: A parsed SIST result. + result: A parsed SIST result, such as the output of ``json.load``. Returns: - Every problem found. An empty list means the result is valid. + Every problem found, schema problems first. An empty list means the + result is valid. """ issues = [ self._schema_issue(error) for error in self._validator.iter_errors(result) @@ -119,11 +149,14 @@ def validate(self, result: dict[str, Any]) -> list[ValidationIssue]: def check(self, result: dict[str, Any]) -> None: """Raise an error listing every problem in a result. + Runs :meth:`validate`, and does nothing if it finds no problems. + Args: result: A parsed SIST result. Raises: - ResultValidationError: If the result has any problems. + ResultValidationError: If the result has any problems. Its + ``issues`` attribute holds them all. """ issues = self.validate(result) @@ -135,8 +168,10 @@ def _schema_issue(error: ValidationError) -> ValidationIssue: """Turn a schema error into an issue for its deepest underlying error. For a section with more than one allowed shape, such as ``transitions`` - (results or null), this follows the error down to the deepest point in - the result. + (results or null), the schema error holds one inner error per shape. + This follows the inner errors down to the one with the longest path in + the result, so a bad probability inside ``transitions`` is reported at + ``transitions/melting/profile/probability/2``. Args: error: An error from the JSON Schema validator. @@ -154,14 +189,15 @@ def _schema_issue(error: ValidationError) -> ValidationIssue: def _cross_check(self, result: dict[str, Any]) -> list[ValidationIssue]: """Run the checks that compare one part of a result with another. - A failed run gets the timestamp and transition checks. A successful run - gets every check. + Every result gets the timestamp and transition checks. A successful + result also gets the pairwise, length, state count and partition + function checks, which read its ``summary`` and ``transitions``. Args: result: A result that has passed the schema. Returns: - Every problem found. + Every problem found, in the order the checks run. """ issues = [] @@ -180,11 +216,16 @@ def _cross_check(self, result: dict[str, Any]) -> list[ValidationIssue]: def _check_timestamps(result: dict[str, Any]) -> list[ValidationIssue]: """Check that the start and finish times are RFC 3339 date-times. + Reads ``provenance.started_at`` and ``provenance.finished_at``, and + parses each with :meth:`datetime.fromisoformat`. A null time is + accepted. + Args: result: A result that has passed the schema. Returns: - A problem for each time that is not an RFC 3339 date-time. + An issue at ``provenance/started_at`` or ``provenance/finished_at`` + for each time that does not parse. """ issues = [] provenance = result["provenance"] @@ -211,15 +252,20 @@ def _check_timestamps(result: dict[str, Any]) -> list[ValidationIssue]: def _check_transitions(result: dict[str, Any]) -> list[ValidationIssue]: """Check the transitions against the algorithm and the results. - ``calculation.transitions`` is compared with what the algorithm - calculates, and ``transitions`` with ``calculation.transitions``. + Two comparisons are made: + + * ``calculation.transitions`` against the transitions the algorithm in + ``calculation.algorithm`` calculates, from :data:`ALGORITHMS`. + * The keys of ``transitions`` against ``calculation.transitions``. This + is skipped for a failed run, where ``transitions`` is null. Args: result: A result that has passed the schema. Returns: - A problem if the transitions do not match the algorithm, and one if - the results have extra or missing transitions. + An issue at ``calculation/transitions`` if they do not match the + algorithm, and issues at ``transitions`` naming any extra or + missing transitions. """ issues = [] calculation = result["calculation"] @@ -262,13 +308,18 @@ def _check_transitions(result: dict[str, Any]) -> list[ValidationIssue]: def _check_pairwise(result: dict[str, Any]) -> list[ValidationIssue]: """Check that pairwise probabilities only pair different, known transitions. + Reads ``summary.pairwise``, if present. Each of its three matrices is + read as ``matrix[first][second]``, and every pair is checked against + ``calculation.transitions``. + Args: result: A successful result that has passed the schema. Returns: - A problem if the calculation has only one transition, and one for - each pair that repeats a transition or uses one not in the - calculation. + One issue at ``summary/pairwise`` if the calculation has only one + transition. Otherwise an issue at + ``summary/pairwise///`` for each pair that + repeats a transition or names one not in the calculation. """ pairwise = result["summary"].get("pairwise") @@ -307,12 +358,17 @@ def _check_pairwise(result: dict[str, Any]) -> list[ValidationIssue]: def _check_lengths(result: dict[str, Any]) -> list[ValidationIssue]: """Check that every per-position value has one entry per base pair. + Compares ``input.sequence_length_bp`` with the length of + ``input.analysed_sequence`` and of every array in each transition's + ``profile``. + Args: result: A successful result that has passed the schema. Returns: - A problem for each array, or the analysed sequence, of the wrong - length, or a single problem if the sequence length is missing. + One issue at ``input/sequence_length_bp`` if the length is null. + Otherwise an issue for each value of the wrong length, giving its + length and the expected one. """ length = result["input"]["sequence_length_bp"] @@ -350,11 +406,15 @@ def _check_lengths(result: dict[str, Any]) -> list[ValidationIssue]: def _check_state_counts(result: dict[str, Any]) -> list[ValidationIssue]: """Check that the state counts add up to the total. + Sums ``summary.state_counts.by_number_of_runs`` and compares the sum + with ``summary.state_counts.total``. + Args: result: A successful result that has passed the schema. Returns: - A problem if the counts do not add up to the total. + An issue at ``summary/state_counts`` giving both numbers if they + differ, otherwise an empty list. """ state_counts = result["summary"]["state_counts"] counted = sum(state_counts["by_number_of_runs"]) @@ -374,12 +434,16 @@ def _check_state_counts(result: dict[str, Any]) -> list[ValidationIssue]: def _check_partition_function(cls, result: dict[str, Any]) -> list[ValidationIssue]: """Check that the partition function is above 0 and matches its natural log. + A null ``summary.partition_function`` is accepted. Otherwise its log is + compared with ``summary.ln_partition_function``, to within + :attr:`LN_PARTITION_FUNCTION_RTOL`. + Args: result: A successful result that has passed the schema. Returns: - A problem if the partition function is not above 0, or does not - match ``ln_partition_function``. + An issue at ``summary/partition_function`` if it is 0 or below, or + at ``summary/ln_partition_function`` if the two do not match. """ summary = result["summary"] partition_function = summary["partition_function"] diff --git a/src/sist/transitions.py b/src/sist/transitions.py index 90488ec..6c88309 100644 --- a/src/sist/transitions.py +++ b/src/sist/transitions.py @@ -1,7 +1,22 @@ """The structural transitions and algorithms SIST can calculate. -Each transition records what qsidd calls its values. Each algorithm records the -transitions it calculates, and the qsidd binary and flags that run it. +There are three transitions (melting, Z-DNA and cruciform) and four algorithms, +one for each ``-a`` flag: + +>>> ALGORITHMS["Z"].transition_names +('z_dna',) +>>> ALGORITHMS["A"].transition_names +('melting', 'z_dna', 'cruciform') +>>> ALGORITHMS["A"].engine +'trans_compete' + +Each transition also records the names qsidd prints its values under, which +differ between qsidd's two output layouts: + +>>> MELTING.names(competition=False).probability +'Transition Probability' +>>> MELTING.names(competition=True).probability +'Prob_M' """ from __future__ import annotations @@ -14,15 +29,22 @@ class QsiddNames: """What qsidd calls one transition's values in one of its output layouts. qsidd has two layouts: one for a single transition (``trans_three``) and - one for competition between transitions (``trans_compete``). + one for competition between transitions (``trans_compete``). Each name is + the text qsidd prints before the ``=``, or the column heading in its + per-position table. For melting in the competition layout, qsidd prints + ``Prob_M = 0.703`` and a ``P_melt`` column. Attributes: - probability: Name of the probability of at least one run. - expected_runs: Name of the expected number of runs. + probability: Name of the probability of at least one run, such as + ``"Prob_M"``. + expected_runs: Name of the expected number of runs, such as + ``"Number of M_runs"``. expected_transformed_bp: Name of the expected number of base pairs in - the transition. - nucleation_energy: Name of the nucleation energy. - profile_column: Heading of the per-position probability column. + the transition, such as ``"N_Melting"``. + nucleation_energy: Name of the nucleation energy, such as + ``"Melting nucleation energy"``. + profile_column: Heading of the per-position probability column, such + as ``"P_melt"``. """ probability: str @@ -37,10 +59,12 @@ class Transition: """A structural transition SIST can calculate. Attributes: - name: Name used in results, such as ``"z_dna"``. - letter: Letter qsidd uses for the transition in competition output. + name: Name used as the key in results, such as ``"z_dna"`` in + ``result["transitions"]["z_dna"]``. + letter: Letter qsidd uses for the transition in competition output, + such as ``"Z"`` in ``Prob_Z`` and ``Joint probability M Z``. needs_inverted_repeats: Whether the IR finder must score candidate - inverted repeats before qsidd runs. + inverted repeats before qsidd runs. Only cruciform needs them. single: What qsidd calls the values when this is the only transition. competition: What qsidd calls the values in competition output. """ @@ -55,10 +79,11 @@ def names(self, *, competition: bool) -> QsiddNames: """Choose the names for one of qsidd's output layouts. Args: - competition: Whether qsidd ran in competition mode. + competition: Whether qsidd ran in competition mode, which is + :attr:`Algorithm.competition` for the algorithm being read. Returns: - What qsidd calls this transition's values in that layout. + :attr:`competition` if True, otherwise :attr:`single`. """ return self.competition if competition else self.single @@ -73,8 +98,11 @@ class Algorithm: reports them. engine: qsidd binary that runs it, ``"trans_three"`` or ``"trans_compete"``. - qsidd_flags: Extra flags that pick the transition in the engine. - supports_nearest_neighbor: Whether ``-n`` is passed on to qsidd. + qsidd_flags: Extra flags that pick the transition in the engine: + ``("-Z",)`` for Z-DNA, ``("-C",)`` for cruciform, and none for + melting and competition. + supports_nearest_neighbor: Whether ``-n`` is passed on to qsidd. True + for the algorithms that include melting. """ flag: str @@ -85,17 +113,27 @@ class Algorithm: @property def transition_names(self) -> tuple[str, ...]: - """Names of the transitions the algorithm calculates.""" + """Names of the transitions the algorithm calculates, such as ``("melting",)``. + + These are the values written to ``calculation.transitions`` in a result. + """ return tuple(transition.name for transition in self.transitions) @property def competition(self) -> bool: - """Whether qsidd runs in competition mode, with its competition layout.""" + """Whether the algorithm calculates more than one transition. + + When True, qsidd prints its competition layout, with ``Prob_M``-style + names and pairwise probabilities. + """ return len(self.transitions) > 1 @property def needs_inverted_repeats(self) -> bool: - """Whether the IR finder must run before qsidd.""" + """Whether any of its transitions need the IR finder to run before qsidd. + + When True, qsidd is given the scored inverted repeats with ``-X``. + """ return any(transition.needs_inverted_repeats for transition in self.transitions) From df9c9595df3888e57d8769c818a4aa29e8fb345b Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Mon, 16 Nov 2026 12:10:00 +0000 Subject: [PATCH 6/6] docs(results): expand the result builder docstrings --- src/sist/results/builder.py | 66 +++++++++++++++++------ src/sist/results/diagnostics.py | 89 ++++++++++++++++++++++++++------ src/sist/results/model.py | 82 ++++++++++++++++++++++++----- src/sist/results/provenance.py | 37 ++++++++++--- src/sist/results/qsidd_output.py | 53 +++++++++++++++---- src/sist/results/reader.py | 56 +++++++++++++++----- src/sist/results/sequence.py | 37 ++++++++++--- src/sist/results/writer.py | 34 ++++++++---- 8 files changed, 361 insertions(+), 93 deletions(-) diff --git a/src/sist/results/builder.py b/src/sist/results/builder.py index 82b3613..dbb040f 100644 --- a/src/sist/results/builder.py +++ b/src/sist/results/builder.py @@ -1,4 +1,15 @@ -"""Put the parts of a result together for a successful or failed run.""" +"""Put the parts of a result together for a successful or failed run. + +:class:`ResultBuilder` brings together the other parts of :mod:`sist.results`: + +- :class:`SequenceInput` reads the input sequence. +- :mod:`sist.results.diagnostics` checks the sequence, the settings and + qsidd's output, and raises warnings. +- :class:`QsiddReader` reads the values out of the parsed qsidd output. +- :class:`ProvenanceRecorder` records how, where and when the run was made. + +The result it returns is a :class:`Result`, ready for :class:`ResultWriter`. +""" from __future__ import annotations @@ -27,11 +38,17 @@ class ResultBuilder: - """Build the result of one run. + """Build the result of one run, successful or failed. + + A run uses one builder from start to finish:: - Create one builder when the run starts, which records its start time, - then call :meth:`read_sequence` and either :meth:`success` or - :meth:`failure`. + builder = ResultBuilder(settings, command=argv) + sequence = builder.read_sequence() + result = builder.success(output, sequence, ir_string=ir_string) + + ``read_sequence`` and ``success`` add warnings to ``warnings`` as they go. + If any step raises a ``ResultError``, ``failure`` builds the failed result + instead, keeping the warnings and anything already read. Attributes: settings: The run's settings. @@ -39,11 +56,14 @@ class ResultBuilder: """ def __init__(self, settings: RunSettings, *, command: list[str] | None = None): - """Start recording a run. + """Start recording a run, and its start time. Args: - settings: The run's settings. - command: The command line as given, or None when run from Python. + settings: The run's settings, which also pick the qsidd binary + and how its output is read. + command: The command line as given, such as + ``["sist", "-a", "M", "-f", "seq.fa", "--json", "out.json"]``, + or None when run from Python. """ self.settings = settings self.warnings: list[ResultWarning] = [] @@ -56,6 +76,10 @@ def __init__(self, settings: RunSettings, *, command: list[str] | None = None): def read_sequence(self) -> SequenceInput: """Read the input sequence and raise the warnings it and the settings call for. + The sequence warnings come first, such as characters dropped or ``N`` + read as ``G``, then the settings warnings, such as ``-n`` given for an + algorithm that ignores it. + Returns: The sequence that qsidd will analyse. @@ -85,16 +109,21 @@ def success( ) -> Result: """Build the result of a run that finished. - Records qsidd's warnings, then checks for underflow. + Adds qsidd's own warnings, such as an energy threshold that is too + low, then checks the partition function did not underflow. For + algorithms with cruciforms, the inverted repeats are parsed from + ``ir_string``, and a warning is added if there are none. Args: - output: The parsed qsidd output. + output: The parsed qsidd output, from a run with ``-b -p -r -P``. sequence: The sequence that was analysed. - ir_string: The scored inverted repeats passed to qsidd, if used. - irf_version: The IRF version, if inverted repeats were scored. + ir_string: The scored inverted repeats passed to qsidd with + ``-X``, if used. + irf_version: The IRF version, such as ``"3.09"``, if inverted + repeats were scored. Returns: - The result. + The successful result, with every section filled in. Raises: ResultError: If the partition function underflowed to zero. @@ -148,11 +177,13 @@ def failure( ) -> Result: """Build the result of a run that failed. - Keeps everything known before the failure, including any derived - parameters qsidd printed. + Keeps everything known before the failure: the settings, the + warnings so far, the input if it was read, and any derived parameters + qsidd printed. The summary, transitions and diagnostics are left out, + and the error is recorded in their place. Args: - error: Why the run failed. + error: Why the run failed, with its code, stage and message. sequence: The sequence, if it was read before the failure. output: The parsed qsidd output, if qsidd ran. irf_version: The IRF version, if IRF ran. @@ -175,6 +206,9 @@ def _known_derived_parameters( ) -> DerivedParameters | None: """Read the derived parameters for a failed run, if they can be read. + qsidd may have stopped before printing them, or printed only some, in + which case None is returned. + Args: output: The parsed qsidd output, or None if qsidd did not run. diff --git a/src/sist/results/diagnostics.py b/src/sist/results/diagnostics.py index 2787137..84ceeab 100644 --- a/src/sist/results/diagnostics.py +++ b/src/sist/results/diagnostics.py @@ -1,7 +1,17 @@ """Warning and error codes, and the checks that raise warnings. -Each warning code records the part of SIST that raises it, and each error code -the stage of the run that fails. +:class:`WarningCode` and :class:`ErrorCode` list every code a result can hold. +Each warning code knows which part of SIST raises it, and each error code which +stage of the run fails: + +>>> WarningCode.THRESHOLD_TOO_LOW.source +'qsidd' +>>> ErrorCode.IRF_NOT_FOUND.stage +'ir_finder' + +The ``check_*`` functions and :func:`qsidd_warnings` return the warnings for the +input sequence, the run's settings and qsidd's own ``WARNING:`` lines. A run +that cannot produce a result raises :class:`ResultError`. """ from __future__ import annotations @@ -18,7 +28,11 @@ class WarningCode(StrEnum): - """Every warning a result can hold.""" + """Every warning a result can hold. + + Each member's value is the code written to the result, such as + ``"threshold_too_low"``. + """ THRESHOLD_TOO_LOW = "threshold_too_low" THRESHOLD_TOO_HIGH = "threshold_too_high" @@ -35,12 +49,19 @@ class WarningCode(StrEnum): @property def source(self) -> str: - """Part of SIST that raises this warning.""" + """Part of SIST that raises this warning. + + One of ``"sist"``, ``"qsidd"`` or ``"ir_finder"``. + """ return WARNING_SOURCES.get(self, "sist") class ErrorCode(StrEnum): - """Every reason a run can fail.""" + """Every reason a run can fail. + + Each member's value is the code written to the result, such as + ``"irf_not_found"``. + """ INPUT_NOT_FOUND = "input_not_found" EMPTY_SEQUENCE = "empty_sequence" @@ -53,7 +74,10 @@ class ErrorCode(StrEnum): @property def stage(self) -> str: - """Step of the run that fails with this code.""" + """Step of the run that fails with this code. + + Such as ``"input"``, ``"ir_finder"`` or ``"qsidd"``. + """ return ERROR_STAGES[self] @@ -92,8 +116,10 @@ def stage(self) -> str: WarningCode.SALT_CONCENTRATION_OUT_OF_RANGE ), } -"""qsidd's warning text and its code. qsidd's two sequence length warnings are -not included. :func:`check_sequence` raises the sequence length warnings.""" +"""qsidd's warning text, after ``WARNING:``, and its code. + +qsidd's two sequence length warnings are not included. :func:`check_sequence` +raises the sequence length warnings.""" MIN_SEQUENCE_LENGTH = 1500 """Shortest recommended sequence, in base pairs.""" @@ -108,8 +134,10 @@ class ResultWarning: Attributes: code: What kind of warning it is. - message: What it means, written for people. - details: Extra values about the warning. + message: What it means, written for people, such as ``"1 N base(s) in + the sequence were analysed as G."``. + details: Extra values about the warning, such as + ``{"count": 1, "positions": [601]}``. """ code: WarningCode @@ -120,7 +148,8 @@ def to_dict(self) -> dict[str, Any]: """Write the warning in the shape the result schema expects. Returns: - One entry of a result's ``warnings`` list. + One entry of a result's ``warnings`` list, with ``code``, + ``message`` and ``source``, plus ``details`` when there are any. """ warning: dict[str, Any] = { "code": str(self.code), @@ -137,12 +166,16 @@ def to_dict(self) -> dict[str, Any]: class ResultError(Exception): """A run that could not produce a result, and why. + Raised by the steps of a run, and caught by the runner, which turns it into + a failed result with :meth:`to_dict` as its ``error`` section. + Attributes: - code: Why the run failed. + code: Why the run failed. Its :attr:`ErrorCode.stage` gives the step. message: What went wrong, written for people. exit_code: Exit code of the failing external program, if any. stderr: Standard error of the failing external program, if any. - details: Extra values about the error. + details: Extra values about the error, such as + ``{"records": 2}`` for a file with two FASTA records. """ def __init__( @@ -175,7 +208,9 @@ def to_dict(self) -> dict[str, Any]: """Write the error in the shape the result schema expects. Returns: - The ``error`` section of a failed result. + The ``error`` section of a failed result, with ``code``, + ``message``, ``stage``, ``exit_code`` and ``stderr``, plus + ``details`` when there are any. """ error: dict[str, Any] = { "code": str(self.code), @@ -194,11 +229,19 @@ def to_dict(self) -> dict[str, Any]: def check_sequence(sequence: SequenceInput) -> list[ResultWarning]: """Raise the warnings the input sequence calls for. + Checks, in order: + + * ``N`` bases, which qsidd analyses as ``G``. The warning lists their + 1-based positions. + * Characters other than A, C, G, T and N, which qsidd drops. + * A length below :data:`MIN_SEQUENCE_LENGTH` or above + :data:`MAX_SEQUENCE_LENGTH` base pairs. + Args: sequence: The sequence qsidd will analyse. Returns: - Warnings about ambiguous bases, dropped characters and the length. + A warning for each check that applies, in that order. """ warnings = [] length = len(sequence.analysed) @@ -251,13 +294,20 @@ def check_settings( ) -> list[ResultWarning]: """Raise the warnings for settings the algorithm cannot use as given. + Checks, in order: + + * Nearest-neighbor energetics asked for with an algorithm that does not + include melting. + * A salt other than the IR finder's fixed 0.01 M, for an algorithm that + scores inverted repeats. + Args: algorithm: The algorithm being run. nearest_neighbor: Whether nearest-neighbor energetics were asked for. salt: Salt concentration in mol/L. Returns: - Warnings about ignored energetics and the fixed cruciform salt. + A warning for each check that applies, in that order. """ warnings = [] @@ -285,8 +335,13 @@ def check_settings( def qsidd_warnings(messages: list[str]) -> list[ResultWarning]: """Turn qsidd's warning lines into coded warnings. + Each line in :data:`QSIDD_WARNINGS` becomes a warning with its code, and its + text as the message, capitalised and ending with a full stop. Other lines + are skipped. + Args: - messages: The text of each ``WARNING:`` line qsidd printed. + messages: The text of each ``WARNING:`` line qsidd printed, without + the ``WARNING:``, as in :attr:`QsiddOutput.warnings`. Returns: A warning for each line with a known code, in the same order. diff --git a/src/sist/results/model.py b/src/sist/results/model.py index e3a8459..9fa2281 100644 --- a/src/sist/results/model.py +++ b/src/sist/results/model.py @@ -1,7 +1,17 @@ """The typed SIST result. Each section of a result is a small dataclass with a ``to_dict`` method that -writes it in the shape of ``sist-result-v1.schema.json``. +writes it in the shape of ``sist-result-v1.schema.json``. :class:`Result` holds +the sections, and its ``to_dict`` writes the whole result: + +* :class:`Provenance` writes ``provenance``. +* :class:`InputDescription` writes ``input``. +* :class:`RunSettings` writes ``parameters``, with :meth:`RunSettings.parameters`. +* :class:`DerivedParameters` writes ``derived_parameters``. +* :class:`Summary` writes ``summary``. +* :class:`TransitionResult` writes one entry of ``transitions``. +* :class:`InvertedRepeat` writes one entry of ``inverted_repeats``. +* :class:`Diagnostics` writes ``diagnostics``. """ from __future__ import annotations @@ -18,13 +28,21 @@ """Version of the result model this package writes.""" PairMatrices = dict[str, dict[str, dict[str, float | None]]] -"""Pairwise probabilities, read as ``matrices[name][first][second]``.""" +"""Pairwise probabilities, read as ``matrices[name][first][second]``. + +``name`` is ``"joint_probability"``, ``"conditional_probability"`` or +``"conditional_probability_given_absent"``, and ``first`` and ``second`` are +transition names, such as ``matrices["conditional_probability"]["melting"] +["z_dna"]`` for P(melting given Z-DNA).""" @dataclass(frozen=True) class RunSettings: """The settings for one SIST calculation. + Built by the runner from the command-line options, and used by the builder + for the ``parameters`` and ``input`` sections. + Attributes: file: Path to the input sequence file, as given. algorithm: The algorithm being run. @@ -53,8 +71,11 @@ def molecule_type(self) -> str: def parameters(self) -> dict[str, Any]: """Write the settings as the calculation used them. - The superhelical density is written as negative, as qsidd uses it. - Runs that score inverted repeats also record the IR finder's fixed salt. + The superhelical density is written as negative, as qsidd uses it, so + ``-s 0.06`` is written as ``-0.06``. ``melting_energetics`` is + ``"copolymeric"`` or ``"nearest_neighbor"`` when the algorithm includes + melting, and None otherwise. Runs that score inverted repeats also + record the IR finder's fixed salt as ``cruciform_salt_concentration_m``. Returns: The ``parameters`` section. @@ -109,7 +130,12 @@ class Provenance: wall_time_s: float def to_dict(self) -> dict[str, Any]: - """Write the ``provenance`` section.""" + """Write the ``provenance`` section. + + The SIST version, git commit, engine and IRF version are grouped under + ``software``, and the Python version and platform under + ``environment``. + """ return { "software": { "name": "SIST", @@ -153,11 +179,13 @@ def describe( """Describe the input, as far as it was read. Args: - settings: The run's settings. - sequence: The sequence, or None if it was never read. + settings: The run's settings, for the file path and molecule type. + sequence: The sequence, or None if the run failed before reading + it. Returns: - The input description. + The input description. Its name, length, analysed sequence and + SHA-256 are None when ``sequence`` is None. """ if sequence is None: return cls(settings.file, None, None, None, None, settings.molecule_type) @@ -172,7 +200,10 @@ def describe( ) def to_dict(self) -> dict[str, Any]: - """Write the ``input`` section, leaving out a sequence that was never read.""" + """Write the ``input`` section. + + ``analysed_sequence`` is left out when the sequence was never read. + """ section = asdict(self) if self.analysed_sequence is None: @@ -224,7 +255,12 @@ class Summary: pairwise: PairMatrices | None = None def to_dict(self) -> dict[str, Any]: - """Write the ``summary`` section.""" + """Write the ``summary`` section. + + The state counts are grouped under ``state_counts`` as + ``by_number_of_runs`` and ``total``, and ``pairwise`` is only written + when there are pairwise probabilities. + """ summary: dict[str, Any] = { "ln_partition_function": self.ln_partition_function, "partition_function": self.partition_function, @@ -262,7 +298,11 @@ class TransitionResult: free_energy_kcal_per_mol: list[float | None] | None = None def to_dict(self) -> dict[str, Any]: - """Write one entry of the ``transitions`` section.""" + """Write one entry of the ``transitions`` section. + + The per-position values are grouped under ``profile``, with + ``free_energy_kcal_per_mol`` only written when there is G(x). + """ profile: dict[str, Any] = {"probability": self.profile_probability} if self.free_energy_kcal_per_mol is not None: @@ -296,7 +336,10 @@ def parse_all(cls, ir_string: str) -> list[InvertedRepeat]: """Read the scored inverted repeats from the string passed to qsidd. The string is ``start,length,energy,|`` repeated, and starts with a - placeholder entry of length 0, which is skipped. + placeholder entry of length 0, which is skipped: + + >>> InvertedRepeat.parse_all("1,0,10000,|2982,25,17.27,|") + [InvertedRepeat(start=2982, length_bp=25, energy_kcal_per_mol=17.27)] Args: ir_string: The string the IR finder built for ``qsidd -X``. @@ -336,7 +379,11 @@ class Diagnostics: max_energy_kcal_per_mol: float | None def to_dict(self) -> dict[str, Any]: - """Write the ``diagnostics`` section.""" + """Write the ``diagnostics`` section. + + The lowest and highest state energies are grouped under + ``energy_window``. + """ return { "scaling_factor": self.scaling_factor, "energy_window": { @@ -350,6 +397,10 @@ def to_dict(self) -> dict[str, Any]: class Result: """A complete SIST result, successful or failed. + A successful result has ``summary``, ``transitions`` and ``diagnostics`` + and no ``error``. A failed result has an ``error``, and keeps whatever was + known before the failure, such as ``input`` and ``derived_parameters``. + Attributes: provenance: How, where and when it was made. algorithm: The algorithm that was run. @@ -384,6 +435,11 @@ def status(self) -> str: def to_dict(self) -> dict[str, Any]: """Write the result in the shape of ``sist-result-v1.schema.json``. + ``schema_version`` and ``status`` come first and ``warnings`` and + ``error`` last. ``inverted_repeats`` and ``diagnostics`` are only + written when they are set. Missing required sections are written as + null. + Returns: The result, with its sections in the documented order. """ diff --git a/src/sist/results/provenance.py b/src/sist/results/provenance.py index 88945b1..2948584 100644 --- a/src/sist/results/provenance.py +++ b/src/sist/results/provenance.py @@ -1,4 +1,13 @@ -"""Record how, where and when a result was made.""" +"""Record how, where and when a result was made. + +A :class:`ProvenanceRecorder` is created when a run starts and finished when its +result is built:: + + recorder = ProvenanceRecorder(engine="trans_three", command=["sist", "-a", "M"]) + provenance = recorder.finish(irf_version=None) + +``provenance.wall_time_s`` is then the number of seconds between the two. +""" from __future__ import annotations @@ -17,9 +26,12 @@ class ProvenanceRecorder: """Record a run's provenance, starting the clock when it is created. + The SIST version, git commit, Python version and platform are read when + :meth:`finish` is called. + Attributes: GIT_SHA_ENV_VAR: Environment variable that sets the git commit, for - builds made outside a git checkout. + builds made outside a git checkout, such as a conda package. engine: qsidd binary the run uses. command: The command line as given, or None when run from Python. started_at: When the run started. @@ -28,11 +40,14 @@ class ProvenanceRecorder: GIT_SHA_ENV_VAR = "SIST_GIT_SHA" def __init__(self, *, engine: str, command: list[str] | None) -> None: - """Start the clock for a run. + """Start the clock for a run, and record its start time. Args: - engine: qsidd binary the run uses. - command: The command line as given, or None when run from Python. + engine: qsidd binary the run uses, ``"trans_three"`` or + ``"trans_compete"``. + command: The command line as given, such as + ``["sist", "-a", "M", "-f", "seq.fa"]``, or None when run from + Python. """ self.engine = engine self.command = command @@ -44,10 +59,12 @@ def finish(self, *, irf_version: str | None) -> Provenance: """Stop the clock and record the provenance. Args: - irf_version: The IRF version, for runs that score inverted repeats. + irf_version: The IRF version, such as ``"3.09"``, for runs that + score inverted repeats, otherwise None. Returns: - The provenance. + The provenance, with the finish time and the elapsed seconds, + rounded to milliseconds. """ return Provenance( version=sist.__version__, @@ -64,7 +81,11 @@ def finish(self, *, irf_version: str | None) -> Provenance: @staticmethod def timestamp() -> str: - """The current UTC time in RFC 3339 format.""" + """The current UTC time in RFC 3339 format. + + Returns: + The time to the second, such as ``"2026-11-06T10:00:02Z"``. + """ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") @classmethod diff --git a/src/sist/results/qsidd_output.py b/src/sist/results/qsidd_output.py index dfb65b9..07d605f 100644 --- a/src/sist/results/qsidd_output.py +++ b/src/sist/results/qsidd_output.py @@ -1,4 +1,9 @@ -"""Split qsidd's text output into its parts.""" +"""Split qsidd's text output into its parts. + +:meth:`QsiddOutput.parse` reads the text qsidd prints with ``-b -p -r`` (and +``-P`` for full precision) into named values, warnings and the per-position +table. It does not interpret the values; :mod:`sist.results.reader` does that. +""" from __future__ import annotations @@ -10,11 +15,21 @@ class QsiddOutput: """The text output of one qsidd run, split into its parts. + >>> output = QsiddOutput.parse("Temperature = 310 K\\nPosition\\tP(x)\\n1\\t0.5") + >>> output.number("Temperature") + 310.0 + >>> output.column("P(x)") + ['0.5'] + Attributes: - values: Every ``key = value`` line, with the value kept as text. - warnings: The text of each ``WARNING:`` line, in order. - columns: Headings of the per-position table. - rows: The per-position table, one list of values per position. + values: Every ``key = value`` line, keyed by the text before the ``=`` + and with the value kept as text, such as ``{"Temperature": "310 K"}``. + warnings: The text of each ``WARNING:`` line, after ``WARNING:``, in + order. + columns: Headings of the per-position table, such as + ``["Position", "Base", "P(x)", "G(x)"]``. + rows: The per-position table, one list of values per position, in the + same order as ``columns``. """ values: dict[str, str] = field(default_factory=dict) @@ -26,9 +41,16 @@ class QsiddOutput: def parse(cls, text: str) -> QsiddOutput: """Split qsidd's text output into values, warnings and the table. - Most values are printed as ``key = value``, sometimes two to a line - separated by ``;``. The scaling factor is the one value printed without - an ``=``. + Each line is read as one of: + + * ``WARNING: threshold is too small, ...``, added to ``warnings``. + * ``BAT = 0.258 kcal/mol; BGC = 1.305 kcal/mol``, added to ``values`` + as two entries. Most lines hold one ``key = value``. + * ``Scaling factor 300``, added to ``values`` without an ``=``. + * ``Position Base P(x) G(x)``, which starts the per-position table. + Every non-blank line after it is one row. + + Other lines, such as ``Molecule type: linear DNA``, are skipped. Args: text: Standard output of a qsidd run. @@ -80,8 +102,13 @@ def number(self, key: str) -> float | None: def count(self, key: str) -> int: """Read a printed state count as an exact integer. + With ``-P`` qsidd prints counts in full, such as ``1301378``. Without + it, large counts are printed rounded, such as ``1.30138e+06``, and this + returns the rounded number. + Args: - key: Name of the count, as printed before the ``=``. + key: Name of the count, as printed before the ``=``, such as + ``"Number of three-run states"``. Returns: The count. @@ -95,10 +122,14 @@ def column(self, name: str) -> list[str]: """Read one column of the per-position table. Args: - name: Column heading, such as ``"P(x)"``. + name: Column heading, such as ``"P(x)"`` or ``"Base"``. Returns: - The column's values as text, one per position. + The column's values as text, one per position, starting at + position 1. + + Raises: + ValueError: If the table has no column with that heading. """ index = self.columns.index(name) diff --git a/src/sist/results/reader.py b/src/sist/results/reader.py index f4c64ca..2846d24 100644 --- a/src/sist/results/reader.py +++ b/src/sist/results/reader.py @@ -1,8 +1,14 @@ """Turn qsidd's output into result values, for any algorithm. qsidd prints each value under one name for a single transition and another for -a competition. The reader looks the names up in :mod:`sist.transitions` for the -algorithm it was given. +a competition, such as ``Transition Probability`` or ``Prob_M``. +:class:`QsiddReader` looks the names up in :mod:`sist.transitions` for the +algorithm it was given, and returns the typed sections from +:mod:`sist.results.model`:: + + reader = QsiddReader(ALGORITHMS["A"]) + summary = reader.summary(output) + transitions = reader.transitions(output) """ from __future__ import annotations @@ -21,6 +27,9 @@ class QsiddReader: """Read result values from the full-precision output of one qsidd run. + Each method reads one section of a result from a :class:`QsiddOutput` + parsed from qsidd run with ``-b -p -r -P``. + Attributes: FREE_ENERGY_COLUMN: Heading of qsidd's G(x) column, which it prints for a single melting transition. @@ -40,8 +49,8 @@ def __init__(self, algorithm: Algorithm) -> None: def underflowed(self, output: QsiddOutput) -> bool: """Check whether the partition function underflowed to zero. - qsidd reports this by printing a log of the partition function that is - not a finite number. + qsidd reports this by printing ``ln Partition Function = -inf``, or + another value that is not a finite number. Args: output: The parsed qsidd output. @@ -54,11 +63,16 @@ def underflowed(self, output: QsiddOutput) -> bool: def derived_parameters(self, output: QsiddOutput) -> DerivedParameters: """Read the model values qsidd works out from the settings. + Reads ``linking difference``, the torsional stiffness (printed as ``K`` + in competition output and ``C`` otherwise), and ``BAT`` and ``BGC`` + where qsidd prints them. + Args: output: The parsed qsidd output. Returns: - The derived parameters. + The derived parameters, with ``bat_kcal_per_mol`` and + ``bgc_kcal_per_mol`` None for Z-DNA runs. Raises: KeyError: If qsidd did not print them. @@ -75,11 +89,16 @@ def derived_parameters(self, output: QsiddOutput) -> DerivedParameters: def summary(self, output: QsiddOutput) -> Summary: """Read the whole-molecule results. + Reads the partition function and its log, the average number of runs, + and the state counts for one to four runs and their total. For a + competition, also reads the pairwise probabilities. + Args: output: The parsed qsidd output. Returns: - The summary. + The summary, with ``partition_function`` None if qsidd printed it + as 0. """ return Summary( ln_partition_function=output.number("ln Partition Function"), @@ -94,13 +113,14 @@ def summary(self, output: QsiddOutput) -> Summary: ) def transitions(self, output: QsiddOutput) -> dict[str, TransitionResult]: - """Read the results for each transition. + """Read the results for each transition the algorithm calculates. Args: output: The parsed qsidd output. Returns: - The results, keyed by transition name. + The results, keyed by transition name, such as ``"melting"``, in + the algorithm's order. """ return { transition.name: self._transition(output, transition) @@ -110,6 +130,8 @@ def transitions(self, output: QsiddOutput) -> dict[str, TransitionResult]: def diagnostics(self, output: QsiddOutput) -> Diagnostics: """Read the values for checking a run. + Reads ``Scaling factor``, ``MinE`` and ``Max_E``. + Args: output: The parsed qsidd output. @@ -127,8 +149,10 @@ def _transition( ) -> TransitionResult: """Read the results for one transition. - G(x) is included when qsidd printed it, with null where the - transition's probability is 0. + Reads the transition's probability, expected runs, expected base pairs + and nucleation energy, and its per-position probability column. G(x) is + read from the ``G(x)`` column when qsidd printed one, with null where + the transition's probability is 0. Args: output: The parsed qsidd output. @@ -161,6 +185,13 @@ def _transition( def _pairwise(self, output: QsiddOutput) -> PairMatrices: """Read the probabilities for pairs of transitions. + For each pair of different transitions, reads the three lines ``-P`` + adds to competition output, such as:: + + Joint probability M Z = 0.69 + Conditional probability M given Z = 0.70 + Conditional probability M given not Z = 0.99 + P(a given not b) is null when b is certain. Any value qsidd prints as ``nan`` is null. @@ -168,7 +199,8 @@ def _pairwise(self, output: QsiddOutput) -> PairMatrices: output: The parsed qsidd output. Returns: - The joint and conditional probabilities. + The joint and conditional probabilities, read as + ``matrices[name][first][second]``. """ competition_names = { transition.name: transition.names(competition=True) @@ -215,7 +247,7 @@ def _optional_number(output: QsiddOutput, key: str) -> float | None: Args: output: The parsed qsidd output. - key: Name of the value. + key: Name of the value, such as ``"BAT"``. Returns: The value, or None if qsidd did not print it. diff --git a/src/sist/results/sequence.py b/src/sist/results/sequence.py index ec91b22..918f122 100644 --- a/src/sist/results/sequence.py +++ b/src/sist/results/sequence.py @@ -1,4 +1,8 @@ -"""Read the input sequence the way qsidd does.""" +"""Read the input sequence the way qsidd does. + +:meth:`SequenceInput.read` turns a FASTA file into the bases qsidd will analyse, +and raises a :class:`ResultError` for input that cannot be analysed. +""" from __future__ import annotations @@ -14,12 +18,19 @@ class SequenceInput: """The sequence read from the input file, as qsidd will analyse it. Header lines are skipped, A, C, G, T and N are kept in any case, and every - other character is dropped, as qsidd does. + other character is dropped, as qsidd does. For a file holding + ``">example"`` then ``"acgRNt"``: + + >>> sequence = SequenceInput(name="example", analysed="ACGNT", dropped=1) + >>> sequence.bases + 'ACGGT' + >>> sequence.n_positions + [4] Attributes: name: The FASTA header without the leading ``>``, or None if the file has no header. - analysed: The bases qsidd analyses, in upper case. + analysed: The bases qsidd analyses, in upper case, with any ``N`` kept. dropped: Number of characters dropped that are not A, C, G, T or N. """ @@ -31,6 +42,9 @@ class SequenceInput: def read(cls, path: Path) -> SequenceInput: """Read a sequence file the way qsidd does. + Line breaks and other whitespace are ignored, so a sequence split over + many lines is read as one. + Args: path: Path to the sequence file. @@ -38,8 +52,9 @@ def read(cls, path: Path) -> SequenceInput: The sequence that qsidd will analyse. Raises: - ResultError: If the file does not exist, holds more than one FASTA - record, or has no bases to analyse. + ResultError: With ``input_not_found`` if the file does not exist, + ``multiple_sequences`` if it holds more than one FASTA record, + or ``empty_sequence`` if it has no bases to analyse. """ if not path.is_file(): raise ResultError( @@ -74,12 +89,20 @@ def read(cls, path: Path) -> SequenceInput: @property def bases(self) -> str: - """The analysed sequence with N replaced by G, as qsidd reports it.""" + """The analysed sequence with N replaced by G, as qsidd reports it. + + This is what qsidd prints in its ``Base`` column, and what is written + to ``input.analysed_sequence``. + """ return self.analysed.replace("N", "G") @property def sha256(self) -> str: - """SHA-256 of the bases qsidd reports, for comparing results.""" + """SHA-256 of :attr:`bases`, as 64 lowercase hex characters. + + Written to ``input.sequence_sha256``, for comparing which sequence two + results came from. + """ return hashlib.sha256(self.bases.encode("ascii")).hexdigest() @property diff --git a/src/sist/results/writer.py b/src/sist/results/writer.py index 985006c..803abc7 100644 --- a/src/sist/results/writer.py +++ b/src/sist/results/writer.py @@ -1,4 +1,10 @@ -"""Check a result against the schema and write it as JSON.""" +"""Check a result against the schema and write it as JSON. + +:class:`ResultWriter` turns a :class:`Result` into a dictionary with +``Result.to_dict``, checks it with :class:`ResultValidator`, and writes it:: + + ResultWriter().write(result, Path("result.json")) +""" from __future__ import annotations @@ -14,26 +20,30 @@ class ResultWriter: """Check results against the schema before writing them. + A result that fails the check raises :class:`ResultValidationError`, and + nothing is written. + Attributes: validator: Validator every result must pass. """ def __init__(self, validator: ResultValidator | None = None) -> None: - """Set up the writer. + """Set up the writer with the validator it checks results against. Args: - validator: Validator to use, or None for a new one. + validator: Validator to use, or None to create a new + :class:`ResultValidator`. """ self.validator = validator or ResultValidator() def check(self, result: Result) -> dict[str, Any]: - """Turn a result into its schema shape and make sure it is valid. + """Turn a result into its schema shape and check it. Args: result: The result to check. Returns: - The result as a dictionary. + The result as a dictionary, from ``Result.to_dict``. Raises: ResultValidationError: If the result is not valid. @@ -44,11 +54,11 @@ def check(self, result: Result) -> dict[str, Any]: return data def write(self, result: Result, path: Path) -> None: - """Check a result and write it as JSON. + """Check a result and write it as JSON, in UTF-8. Args: result: The result to write. - path: File to write it to. + path: File to write it to. An existing file is replaced. Raises: ResultValidationError: If the result is not valid. @@ -59,8 +69,14 @@ def write(self, result: Result, path: Path) -> None: def to_json(data: dict[str, Any]) -> str: """Write a result dictionary as JSON. - Objects are indented, and arrays of plain values are written on one - line. + Objects are indented by two spaces, and arrays of plain values, such + as a per-position probability array, are written on one line:: + + { + "transitions": { + "melting": { + "profile": { + "probability": [2.4e-07, 3.3e-07, 0.0] Args: data: The result as a dictionary.