|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Annotate neoantigen TSV with RNA-seq data from FORTE outputs.""" |
| 3 | + |
| 4 | +import argparse |
| 5 | +import gzip |
| 6 | +import re |
| 7 | +import sys |
| 8 | + |
| 9 | +import pandas as pd |
| 10 | + |
| 11 | +VERSION = "1.0.0" |
| 12 | + |
| 13 | + |
| 14 | +def build_mutation_id(row): |
| 15 | + """Reconstruct mutation_id from MAF columns. |
| 16 | +
|
| 17 | + Matches the format used by generate_input.py: |
| 18 | + - SNP/DNP/TNP: chr_pos_ref_alt |
| 19 | + - DEL: chr_pos_ref_D |
| 20 | + - INS: chr_pos_I_alt |
| 21 | + """ |
| 22 | + chrom = str(row["Chromosome"]) |
| 23 | + pos = str(row["Start_Position"]) |
| 24 | + ref = str(row["Reference_Allele"]) |
| 25 | + alt = str(row["Tumor_Seq_Allele2"]) |
| 26 | + vtype = str(row["Variant_Type"]) |
| 27 | + |
| 28 | + if vtype == "DEL": |
| 29 | + return f"{chrom}_{pos}_{ref}_D" |
| 30 | + elif vtype == "INS": |
| 31 | + return f"{chrom}_{pos}_I_{alt}" |
| 32 | + else: |
| 33 | + return f"{chrom}_{pos}_{ref}_{alt}" |
| 34 | + |
| 35 | + |
| 36 | +def extract_rna_columns_from_maf(maf_df): |
| 37 | + """Extract RNA VAF columns from MAF if present. |
| 38 | +
|
| 39 | + Returns DataFrame with mutation_id, rna_alt_count, rna_ref_count, rna_vaf. |
| 40 | + If rna columns are absent, returns DataFrame with NaN values. |
| 41 | + """ |
| 42 | + maf_df = maf_df.copy() |
| 43 | + maf_df["mutation_id"] = maf_df.apply(build_mutation_id, axis=1) |
| 44 | + |
| 45 | + has_rna = "rna_t_alt_count" in maf_df.columns |
| 46 | + |
| 47 | + result = pd.DataFrame({"mutation_id": maf_df["mutation_id"]}) |
| 48 | + |
| 49 | + if has_rna: |
| 50 | + result["rna_alt_count"] = maf_df["rna_t_alt_count"].values |
| 51 | + result["rna_ref_count"] = maf_df["rna_t_ref_count"].values |
| 52 | + result["rna_vaf"] = maf_df["rna_t_variant_frequency"].values |
| 53 | + else: |
| 54 | + result["rna_alt_count"] = pd.NA |
| 55 | + result["rna_ref_count"] = pd.NA |
| 56 | + result["rna_vaf"] = pd.NA |
| 57 | + |
| 58 | + return result |
| 59 | + |
| 60 | + |
| 61 | +def parse_gtf_gene_map(gtf_path): |
| 62 | + """Parse GTF to build transcript_id -> gene_name mapping.""" |
| 63 | + tx2gene = {} |
| 64 | + opener = gzip.open if gtf_path.endswith(".gz") else open |
| 65 | + with opener(gtf_path, "rt") as f: |
| 66 | + for line in f: |
| 67 | + if line.startswith("#"): |
| 68 | + continue |
| 69 | + fields = line.strip().split("\t") |
| 70 | + if len(fields) < 9: |
| 71 | + continue |
| 72 | + attrs = fields[8] |
| 73 | + tx_match = re.search(r'transcript_id "([^"]+)"', attrs) |
| 74 | + gene_match = re.search(r'gene_name "([^"]+)"', attrs) |
| 75 | + if tx_match and gene_match: |
| 76 | + tx_id = tx_match.group(1).split(".")[0] |
| 77 | + gene_name = gene_match.group(1) |
| 78 | + tx2gene[tx_id] = gene_name |
| 79 | + return tx2gene |
| 80 | + |
| 81 | + |
| 82 | +def annotate_expression(abundance_path, gtf_path): |
| 83 | + """Parse Kallisto abundance and map to gene-level TPM. |
| 84 | +
|
| 85 | + Returns DataFrame with Gene, rna_tpm columns. |
| 86 | + Returns None if abundance_path is None. |
| 87 | + """ |
| 88 | + if abundance_path is None: |
| 89 | + return None |
| 90 | + |
| 91 | + abundance = pd.read_csv(abundance_path, sep="\t") |
| 92 | + tx2gene = parse_gtf_gene_map(gtf_path) |
| 93 | + |
| 94 | + abundance["transcript_id"] = abundance["target_id"].str.split(".").str[0] |
| 95 | + abundance["Gene"] = abundance["transcript_id"].map(tx2gene) |
| 96 | + |
| 97 | + gene_tpm = ( |
| 98 | + abundance.dropna(subset=["Gene"]) |
| 99 | + .groupby("Gene")["tpm"] |
| 100 | + .sum() |
| 101 | + .reset_index() |
| 102 | + .rename(columns={"tpm": "rna_tpm"}) |
| 103 | + ) |
| 104 | + |
| 105 | + return gene_tpm |
| 106 | + |
| 107 | + |
| 108 | +def merge_annotations(neo_tsv, rna_vaf_df, expression_df, tpm_threshold=1.0): |
| 109 | + """Merge RNA annotations onto neoantigen TSV. |
| 110 | +
|
| 111 | + Returns annotated DataFrame with rna_tpm, rna_vaf, rna_alt_count, |
| 112 | + rna_ref_count, rna_expressed columns. |
| 113 | + """ |
| 114 | + result = neo_tsv.copy() |
| 115 | + |
| 116 | + if rna_vaf_df is not None: |
| 117 | + result = result.merge(rna_vaf_df, on="mutation_id", how="left") |
| 118 | + else: |
| 119 | + result["rna_alt_count"] = pd.NA |
| 120 | + result["rna_ref_count"] = pd.NA |
| 121 | + result["rna_vaf"] = pd.NA |
| 122 | + |
| 123 | + if expression_df is not None: |
| 124 | + result = result.merge(expression_df, on="Gene", how="left") |
| 125 | + else: |
| 126 | + result["rna_tpm"] = pd.NA |
| 127 | + |
| 128 | + tpm_ok = result["rna_tpm"].notna() & (result["rna_tpm"] > tpm_threshold) |
| 129 | + vaf_ok = result["rna_alt_count"].isna() | (result["rna_alt_count"] > 0) |
| 130 | + result["rna_expressed"] = tpm_ok & vaf_ok |
| 131 | + |
| 132 | + return result |
| 133 | + |
| 134 | + |
| 135 | +def main(): |
| 136 | + parser = argparse.ArgumentParser(description="Annotate neoantigens with RNA data") |
| 137 | + parser.add_argument("--neoantigen_tsv", required=True, help="Neoantigen TSV from convertannotjson") |
| 138 | + parser.add_argument("--maf", required=True, help="Input MAF (may contain rna_* columns)") |
| 139 | + parser.add_argument("--kallisto_abundance", default=None, help="Kallisto abundance.tsv (optional)") |
| 140 | + parser.add_argument("--gtf", default=None, help="GTF file for transcript-to-gene mapping") |
| 141 | + parser.add_argument("--tpm_threshold", type=float, default=1.0, help="TPM threshold for expressed") |
| 142 | + parser.add_argument("--output_annotated", required=True, help="Output annotated TSV") |
| 143 | + parser.add_argument("--output_report", required=True, help="Output detailed RNA report") |
| 144 | + parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {VERSION}") |
| 145 | + args = parser.parse_args() |
| 146 | + |
| 147 | + neo_tsv = pd.read_csv(args.neoantigen_tsv, sep="\t") |
| 148 | + maf_df = pd.read_csv(args.maf, sep="\t", comment="#") |
| 149 | + |
| 150 | + rna_vaf_df = extract_rna_columns_from_maf(maf_df) |
| 151 | + expression_df = annotate_expression(args.kallisto_abundance, args.gtf) |
| 152 | + |
| 153 | + annotated = merge_annotations(neo_tsv, rna_vaf_df, expression_df, args.tpm_threshold) |
| 154 | + annotated.to_csv(args.output_annotated, sep="\t", index=False) |
| 155 | + |
| 156 | + report_cols = ["mutation_id", "Gene", "rna_tpm", "rna_vaf", "rna_alt_count", "rna_ref_count", "rna_expressed"] |
| 157 | + available_cols = [c for c in report_cols if c in annotated.columns] |
| 158 | + report = annotated[available_cols].drop_duplicates() |
| 159 | + report.to_csv(args.output_report, sep="\t", index=False) |
| 160 | + |
| 161 | + |
| 162 | +if __name__ == "__main__": |
| 163 | + main() |
0 commit comments