|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +# Copyright 2026 EMBL - European Bioinformatics Institute |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | + |
| 18 | +import argparse |
| 19 | +import gzip |
| 20 | +import logging |
| 21 | +import sys |
| 22 | +from pathlib import Path |
| 23 | +from typing import Iterator |
| 24 | + |
| 25 | +logging.basicConfig( |
| 26 | + format="%(levelname)s: %(message)s", |
| 27 | + level=logging.INFO, |
| 28 | + stream=sys.stderr, |
| 29 | +) |
| 30 | + |
| 31 | + |
| 32 | +def _open(path: Path | str): |
| 33 | + """Open a plain or gzip-compressed text file for reading. |
| 34 | +
|
| 35 | + :param path: Path to the file. |
| 36 | + :return: A text-mode file object. |
| 37 | + """ |
| 38 | + if Path(path).suffix == ".gz": |
| 39 | + return gzip.open(path, "rt") |
| 40 | + return open(path, "r") |
| 41 | + |
| 42 | + |
| 43 | +def _contig_ids_from_fasta(fasta_path: Path) -> set[str]: |
| 44 | + """Parse a FASTA file and return the set of sequence IDs. |
| 45 | +
|
| 46 | + Only the first whitespace-delimited token of each header line is used, |
| 47 | + matching the behaviour of seqkit and other common tools. |
| 48 | +
|
| 49 | + :param fasta_path: Path to the FASTA file (plain or gzip). |
| 50 | + :return: Set of contig IDs (without the leading '>'). |
| 51 | + """ |
| 52 | + ids: set[str] = set() |
| 53 | + with _open(fasta_path) as handle: |
| 54 | + for line in handle: |
| 55 | + if line.startswith(">"): |
| 56 | + ids.add(line[1:].split()[0]) |
| 57 | + |
| 58 | + if not ids: |
| 59 | + logging.error(f"No sequences found in {fasta_path}") |
| 60 | + sys.exit(1) |
| 61 | + |
| 62 | + return ids |
| 63 | + |
| 64 | + |
| 65 | +def _contig_id_from_protein_id(protein_id: str, contig_ids: set[str]) -> str | None: |
| 66 | + """Derive the contig ID from a protein ID, handling both CGC callers. |
| 67 | +
|
| 68 | + The CGC produces two protein ID formats: |
| 69 | +
|
| 70 | + - Pyrodigal: ``{contig_id}_{cds_n}`` — strip the last component. |
| 71 | + - FragGeneScanRS: ``{contig_id}_{start}_{end}_{strand}`` — strip the last three. |
| 72 | +
|
| 73 | + Both are tried in order; the first match against *contig_ids* is returned. |
| 74 | + Returns ``None`` if neither resolves to a known contig. |
| 75 | +
|
| 76 | + :param protein_id: Protein identifier from the IPS TSV. |
| 77 | + :param contig_ids: Set of known contig IDs. |
| 78 | + :return: Matching contig ID, or ``None``. |
| 79 | + """ |
| 80 | + for candidate in (protein_id.rsplit("_", 1)[0], protein_id.rsplit("_", 3)[0]): |
| 81 | + if candidate in contig_ids: |
| 82 | + return candidate |
| 83 | + return None |
| 84 | + |
| 85 | + |
| 86 | +def _iter_filtered_rows( |
| 87 | + ips_path: Path, |
| 88 | + contig_ids: set[str], |
| 89 | +) -> Iterator[tuple[str, str]]: |
| 90 | + """Stream IPS TSV rows that belong to contigs in *contig_ids*. |
| 91 | +
|
| 92 | + The protein ID is column 1 (0-indexed: column 0) of the tab-separated file. |
| 93 | + Both Pyrodigal (``{contig_id}_{cds_n}``) and FragGeneScanRS |
| 94 | + (``{contig_id}_{start}_{end}_{strand}``) protein ID formats are handled. |
| 95 | +
|
| 96 | + :param ips_path: Path to the InterProScan TSV (plain or gzip). |
| 97 | + :param contig_ids: Set of contig IDs to keep. |
| 98 | + :return: Iterator of ``(protein_id, raw_line)`` tuples for matching rows. |
| 99 | + :raises SystemExit: If a malformed row (no tab separator) is encountered. |
| 100 | + """ |
| 101 | + with _open(ips_path) as handle: |
| 102 | + for lineno, line in enumerate(handle, start=1): |
| 103 | + if not line.strip() or line.startswith("#"): |
| 104 | + continue |
| 105 | + parts = line.split("\t", 1) |
| 106 | + if len(parts) < 2: |
| 107 | + logging.error( |
| 108 | + f"Malformed IPS row at line {lineno} (no tab separator): {line.rstrip()}" |
| 109 | + ) |
| 110 | + sys.exit(1) |
| 111 | + protein_id = parts[0] |
| 112 | + contig_id = _contig_id_from_protein_id(protein_id, contig_ids) |
| 113 | + if contig_id is not None: |
| 114 | + yield protein_id, line |
| 115 | + |
| 116 | + |
| 117 | +def filter_ips( |
| 118 | + contigs_path: Path, |
| 119 | + ips_path: Path, |
| 120 | + out_path: Path, |
| 121 | +) -> None: |
| 122 | + """Filter *ips_path* to rows whose proteins belong to the provided contigs. |
| 123 | +
|
| 124 | + Each matched protein ID is written to stdout (one per line) so the caller |
| 125 | + can pipe them into ``seqkit grep -f -``. |
| 126 | +
|
| 127 | + :param contigs_path: FASTA file containing the contig subset. |
| 128 | + :param ips_path: Full InterProScan TSV to filter. |
| 129 | + :param out_path: Destination for the filtered TSV (written as gzip). |
| 130 | + """ |
| 131 | + contig_ids = _contig_ids_from_fasta(contigs_path) |
| 132 | + |
| 133 | + with gzip.open(out_path, "wt") as out_fh: |
| 134 | + for protein_id, line in _iter_filtered_rows(ips_path, contig_ids): |
| 135 | + out_fh.write(line) |
| 136 | + sys.stdout.write(protein_id + "\n") |
| 137 | + sys.stdout.flush() |
| 138 | + |
| 139 | + |
| 140 | +if __name__ == "__main__": |
| 141 | + """Filter an InterProScan TSV to rows whose proteins belong to a given set of contigs. |
| 142 | +
|
| 143 | + Matched protein IDs are written to stdout so the caller can pipe them directly |
| 144 | + into ``seqkit grep -f -`` to subset a FAA file without creating a temporary file. |
| 145 | + """ |
| 146 | + parser = argparse.ArgumentParser() |
| 147 | + parser.add_argument( |
| 148 | + "--contigs", |
| 149 | + required=True, |
| 150 | + type=Path, |
| 151 | + metavar="FASTA", |
| 152 | + help="Contig chunk FASTA (plain or gzip).", |
| 153 | + ) |
| 154 | + parser.add_argument( |
| 155 | + "--ips", |
| 156 | + required=True, |
| 157 | + type=Path, |
| 158 | + metavar="TSV", |
| 159 | + help="Full InterProScan TSV (plain or gzip).", |
| 160 | + ) |
| 161 | + parser.add_argument( |
| 162 | + "--out", |
| 163 | + required=True, |
| 164 | + type=Path, |
| 165 | + metavar="TSV_GZ", |
| 166 | + help="Output filtered TSV (written as gzip).", |
| 167 | + ) |
| 168 | + args = parser.parse_args() |
| 169 | + filter_ips( |
| 170 | + contigs_path=args.contigs, |
| 171 | + ips_path=args.ips, |
| 172 | + out_path=args.out, |
| 173 | + ) |
0 commit comments