|
| 1 | +""" |
| 2 | +Runner for creating quality score models. |
| 3 | +
|
| 4 | +This module implements the core logic for generating quality score models |
| 5 | +from input FASTQ files. |
| 6 | +""" |
| 7 | + |
| 8 | +import gzip |
| 9 | +import pickle |
| 10 | +import logging |
| 11 | +from pathlib import Path |
| 12 | +from typing import Iterable, List, Optional, Tuple |
| 13 | + |
| 14 | +import numpy as np |
| 15 | + |
| 16 | +from ..common import validate_input_path, validate_output_path |
| 17 | +from ..model_sequencing_error.utils import parse_file |
| 18 | +from ..models import SequencingErrorModel, TraditionalQualityModel |
| 19 | +from ..models.markov_quality_model import MarkovQualityModel |
| 20 | +from ..quality_score_modeling.markov_utils import build_markov_model |
| 21 | + |
| 22 | +__all__ = ["model_qual_score_runner"] |
| 23 | + |
| 24 | +_LOG = logging.getLogger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +def _prepare_quality_scores_argument( |
| 28 | + qual_scores: int | Iterable[int | float], |
| 29 | +) -> Tuple[List[int], Optional[List[int]]]: |
| 30 | + """ |
| 31 | + Returns: |
| 32 | + - full_range_scores: required by parse_file indexing |
| 33 | + - allowed_bins: None (no binning) or sorted unique user bins (for Markov binning) |
| 34 | + """ |
| 35 | + |
| 36 | + if isinstance(qual_scores, int): |
| 37 | + max_q = int(qual_scores) |
| 38 | + return list(range(0, max_q + 1)), None |
| 39 | + |
| 40 | + bins = sorted({int(x) for x in qual_scores}) |
| 41 | + |
| 42 | + if not bins: |
| 43 | + raise ValueError("quality_scores list must not be empty.") |
| 44 | + |
| 45 | + max_q = max(bins) |
| 46 | + |
| 47 | + # parse_file requires indices up to max_q (it indexes by raw Q value) |
| 48 | + return list(range(0, max_q + 1)), bins |
| 49 | + |
| 50 | + |
| 51 | +def model_qual_score_runner( |
| 52 | + files: List[str], |
| 53 | + offset: int, |
| 54 | + qual_scores: int | Iterable[int | float], |
| 55 | + max_reads: int, |
| 56 | + use_markov: bool, |
| 57 | + overwrite: bool, |
| 58 | + output_dir: str, |
| 59 | + output_prefix: str, |
| 60 | +) -> None: |
| 61 | + """Create and save a quality score model from FASTQ data.""" |
| 62 | + |
| 63 | + if len(files) > 2: |
| 64 | + _LOG.info("Only processing the first two input files") |
| 65 | + files = files[:2] |
| 66 | + |
| 67 | + # Validate input paths |
| 68 | + for file in files: |
| 69 | + validate_input_path(file) |
| 70 | + |
| 71 | + _LOG.debug("Input files: %s", ", ".join(str(x) for x in files)) |
| 72 | + _LOG.debug("Quality offset: %d", offset) |
| 73 | + |
| 74 | + final_quality_scores, allowed_bins = _prepare_quality_scores_argument(qual_scores) |
| 75 | + _LOG.debug("Quality scores range: %s", final_quality_scores) |
| 76 | + |
| 77 | + if allowed_bins is not None: |
| 78 | + _LOG.debug("Markov binning enabled with bins: %s", allowed_bins) |
| 79 | + |
| 80 | + if max_reads in (-1, None): |
| 81 | + num_records_to_process = float("inf") |
| 82 | + |
| 83 | + else: |
| 84 | + num_records_to_process = max_reads |
| 85 | + |
| 86 | + # Validate output directory and file |
| 87 | + validate_output_path(output_dir, is_file=False) |
| 88 | + output_path = Path(output_dir) |
| 89 | + output_file = output_path / f"{output_prefix}.p.gz" |
| 90 | + validate_output_path(output_file, overwrite=overwrite) |
| 91 | + |
| 92 | + _LOG.info("Writing output to: %s", output_file) |
| 93 | + |
| 94 | + # Containers for per-file quality model parameters |
| 95 | + read_parameters: List[np.ndarray] = [] |
| 96 | + average_errors: List[float] = [] |
| 97 | + read_length = 0 |
| 98 | + |
| 99 | + # Traditional model parameters (existing NEAT utility) |
| 100 | + for idx_file, file in enumerate(files, start=1): |
| 101 | + |
| 102 | + _LOG.info("Reading file %d of %d", idx_file, len(files)) |
| 103 | + |
| 104 | + params_by_position, file_avg_error, read_length = parse_file( |
| 105 | + file, |
| 106 | + final_quality_scores, |
| 107 | + num_records_to_process, |
| 108 | + offset, |
| 109 | + read_length, |
| 110 | + ) |
| 111 | + |
| 112 | + read_parameters.append(params_by_position) |
| 113 | + average_errors.append(file_avg_error) |
| 114 | + |
| 115 | + _LOG.info("Finished reading file %d", idx_file) |
| 116 | + |
| 117 | + if not read_parameters: |
| 118 | + raise RuntimeError("No quality score parameters were computed. Check input FASTQ files.") |
| 119 | + |
| 120 | + average_error = float(np.average(average_errors)) if average_errors else 0.0 |
| 121 | + _LOG.info("Average sequencing error across files: %f", average_error) |
| 122 | + |
| 123 | + # Prepare models for each input file |
| 124 | + models: List[Tuple[SequencingErrorModel, TraditionalQualityModel, Optional[MarkovQualityModel]]] = [] |
| 125 | + |
| 126 | + for idx in range(len(read_parameters)): |
| 127 | + |
| 128 | + # Sequencing error model (always produced) |
| 129 | + seq_err_model = SequencingErrorModel(avg_seq_error=average_error, read_length=read_length) |
| 130 | + |
| 131 | + # Traditional quality model (always produced) |
| 132 | + trad_model = TraditionalQualityModel( |
| 133 | + average_error=average_error, |
| 134 | + quality_scores=np.array(final_quality_scores), |
| 135 | + qual_score_probs=read_parameters[idx], |
| 136 | + ) |
| 137 | + |
| 138 | + markov_model: Optional[MarkovQualityModel] = None |
| 139 | + |
| 140 | + # Optionally build Markov quality model |
| 141 | + |
| 142 | + if use_markov: |
| 143 | + |
| 144 | + # Position-specific transition matrices |
| 145 | + init_dist, pos_dists, trans_dists, max_quality, train_read_length = build_markov_model( |
| 146 | + [files[idx]], |
| 147 | + num_records_to_process, |
| 148 | + offset, |
| 149 | + allowed_quality_scores=allowed_bins, |
| 150 | + ) |
| 151 | + |
| 152 | + markov_model = MarkovQualityModel( |
| 153 | + initial_distribution=init_dist, |
| 154 | + position_distributions=pos_dists, |
| 155 | + max_quality=max_quality, |
| 156 | + read_length=train_read_length, |
| 157 | + transition_distributions=trans_dists, |
| 158 | + ) |
| 159 | + |
| 160 | + models.append((seq_err_model, trad_model, markov_model)) |
| 161 | + |
| 162 | + # Write out the models |
| 163 | + |
| 164 | + with gzip.open(output_file, "wb") as out_model: |
| 165 | + |
| 166 | + if len(models) == 1: |
| 167 | + |
| 168 | + seq_err1, trad1, markov1 = models[0] |
| 169 | + pickle.dump( |
| 170 | + { |
| 171 | + "error_model1": seq_err1, |
| 172 | + "error_model2": None, |
| 173 | + "qual_score_model1": markov1 if use_markov else trad1, |
| 174 | + "qual_score_model2": None, |
| 175 | + }, |
| 176 | + out_model, |
| 177 | + ) |
| 178 | + |
| 179 | + elif len(models) == 2: |
| 180 | + |
| 181 | + (seq_err1, trad1, markov1), (seq_err2, trad2, markov2) = models |
| 182 | + pickle.dump( |
| 183 | + { |
| 184 | + "error_model1": seq_err1, |
| 185 | + "error_model2": seq_err2, |
| 186 | + "qual_score_model1": markov1 if use_markov else trad1, |
| 187 | + "qual_score_model2": markov2 if use_markov else trad2, |
| 188 | + }, |
| 189 | + out_model, |
| 190 | + ) |
| 191 | + |
| 192 | + else: |
| 193 | + |
| 194 | + # NEAT's read simulator only understands one or two models |
| 195 | + raise RuntimeError(f"Expected at most two quality models, but constructed {len(models)}.") |
| 196 | + |
| 197 | + _LOG.info("Quality score model saved to %s", output_file) |
0 commit comments