|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2025 - GHGA |
| 4 | +# Author: Kuebra Narci - @kubranarci |
| 5 | +''' |
| 6 | +Generates a CSV file from a VCF |
| 7 | +Expected usage: |
| 8 | + $ python split_sompy_features.py <vcf_file> <prefix> |
| 9 | +Use --help for more information. |
| 10 | +''' |
| 11 | + |
| 12 | +import csv |
| 13 | +import argparse |
| 14 | +from collections import defaultdict |
| 15 | +import os |
| 16 | + |
| 17 | +KEY_COLUMNS = ["CHROM", "POS", "tag"] |
| 18 | +FIELDS_TO_EXTRACT = ["CHROM", "POS", "tag", "REF", "REF.truth", "ALT", "ALT.truth", "QUAL", "FILTER"] |
| 19 | +FIELDS_TO_SUFFIX = ["REF", "ALT"] |
| 20 | + |
| 21 | +def extract_sample_suffix(filename): |
| 22 | + """Extract sample suffix from filename (without extension).""" |
| 23 | + return os.path.splitext(os.path.basename(filename))[0] |
| 24 | + |
| 25 | +def load_csv_by_key(filepath, suffix): |
| 26 | + """Read a CSV file, filter relevant fields, and suffix REF/ALT.""" |
| 27 | + with open(filepath, newline='') as f: |
| 28 | + reader = csv.DictReader(f) |
| 29 | + data = {} |
| 30 | + for row in reader: |
| 31 | + key = tuple(row[k] for k in KEY_COLUMNS) |
| 32 | + filtered = {} |
| 33 | + |
| 34 | + for field in FIELDS_TO_EXTRACT: |
| 35 | + if field in FIELDS_TO_SUFFIX: |
| 36 | + filtered[f"{field}_{suffix}"] = row.get(field, "") |
| 37 | + elif field in KEY_COLUMNS: |
| 38 | + filtered[field] = row.get(field, "") |
| 39 | + else: |
| 40 | + if field not in data.get(key, {}): |
| 41 | + filtered[field] = row.get(field, "") |
| 42 | + |
| 43 | + if key not in data: |
| 44 | + data[key] = filtered |
| 45 | + else: |
| 46 | + data[key].update(filtered) |
| 47 | + |
| 48 | + return data |
| 49 | + |
| 50 | +def merge_dicts_by_key(dicts): |
| 51 | + """Merge all dicts on shared key.""" |
| 52 | + merged = defaultdict(dict) |
| 53 | + for d in dicts: |
| 54 | + for key, row in d.items(): |
| 55 | + merged[key].update(row) |
| 56 | + return merged |
| 57 | + |
| 58 | +def write_merged_csv(merged_data, output_file): |
| 59 | + """Write merged dictionary to CSV.""" |
| 60 | + sorted_keys = sorted(merged_data.keys(), key=lambda x: (x[0], int(x[1]))) |
| 61 | + |
| 62 | + # Determine full set of columns |
| 63 | + all_fields = set() |
| 64 | + for row in merged_data.values(): |
| 65 | + all_fields.update(row.keys()) |
| 66 | + |
| 67 | + # Reorder fields: key columns first, then others |
| 68 | + fieldnames = KEY_COLUMNS + sorted(all_fields - set(KEY_COLUMNS)) |
| 69 | + |
| 70 | + with open(output_file, 'w', newline='') as f: |
| 71 | + writer = csv.DictWriter(f, fieldnames=fieldnames) |
| 72 | + writer.writeheader() |
| 73 | + for key in sorted_keys: |
| 74 | + writer.writerow(merged_data[key]) |
| 75 | + |
| 76 | +def main(): |
| 77 | + parser = argparse.ArgumentParser( |
| 78 | + description="Merge TP/FP/FN CSVs by CHROM,POS,tag, keep selected fields, and suffix REF/ALT from filename." |
| 79 | + ) |
| 80 | + parser.add_argument("files", nargs='+', help="Input CSV files (e.g. *_TP.csv)") |
| 81 | + parser.add_argument("--output", required=True, help="Output merged CSV file") |
| 82 | + args = parser.parse_args() |
| 83 | + |
| 84 | + all_dicts = [] |
| 85 | + for file in args.files: |
| 86 | + suffix = extract_sample_suffix(file) |
| 87 | + print(f"Processing {file} (sample: {suffix})") |
| 88 | + sample_dict = load_csv_by_key(file, suffix) |
| 89 | + all_dicts.append(sample_dict) |
| 90 | + |
| 91 | + merged = merge_dicts_by_key(all_dicts) |
| 92 | + write_merged_csv(merged, args.output) |
| 93 | + print(f"Merged CSV written to {args.output}") |
| 94 | + |
| 95 | +if __name__ == "__main__": |
| 96 | + main() |
0 commit comments