lingzhi227 commited on
Commit
dcd21f3
·
verified ·
1 Parent(s): afcf13d

Upload tasks/somatic-variant-calling/scripts/compile_report.py with huggingface_hub

Browse files
tasks/somatic-variant-calling/scripts/compile_report.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compile somatic variant calling report from pipeline outputs."""
3
+ import csv, os, json, subprocess
4
+
5
+ OUTDIR = "outputs"
6
+
7
+ def count_vcf_variants(path):
8
+ """Count variants in a VCF file (excluding header lines)."""
9
+ if not os.path.exists(path):
10
+ return 0
11
+ count = 0
12
+ import gzip
13
+ opener = gzip.open if path.endswith('.gz') else open
14
+ try:
15
+ with opener(path, 'rt') as f:
16
+ for line in f:
17
+ if not line.startswith('#'):
18
+ count += 1
19
+ except Exception:
20
+ return 0
21
+ return count
22
+
23
+ def count_pass_variants(path):
24
+ """Count PASS variants in a VCF."""
25
+ if not os.path.exists(path):
26
+ return 0
27
+ count = 0
28
+ import gzip
29
+ opener = gzip.open if path.endswith('.gz') else open
30
+ try:
31
+ with opener(path, 'rt') as f:
32
+ for line in f:
33
+ if not line.startswith('#'):
34
+ fields = line.split('\t')
35
+ if len(fields) >= 7 and (fields[6] == 'PASS' or fields[6] == '.'):
36
+ count += 1
37
+ except Exception:
38
+ return 0
39
+ return count
40
+
41
+ def parse_mosdepth_summary(path):
42
+ """Parse mosdepth summary file."""
43
+ if not os.path.exists(path):
44
+ return {'mean': 0, 'min': 0, 'max': 0}
45
+ with open(path) as f:
46
+ reader = csv.DictReader(f, delimiter='\t')
47
+ for row in reader:
48
+ if row.get('chrom') == 'total' or row.get('chrom', '').startswith('total'):
49
+ return {
50
+ 'mean': float(row.get('mean', 0)),
51
+ 'min': float(row.get('min', 0)),
52
+ 'max': float(row.get('max', 0))
53
+ }
54
+ return {'mean': 0, 'min': 0, 'max': 0}
55
+
56
+ def parse_fastp_json(path):
57
+ """Parse fastp JSON report."""
58
+ if not os.path.exists(path):
59
+ return {'before': 0, 'after': 0}
60
+ with open(path) as f:
61
+ j = json.load(f)
62
+ return {
63
+ 'before': j['summary']['before_filtering']['total_reads'],
64
+ 'after': j['summary']['after_filtering']['total_reads']
65
+ }
66
+
67
+ def parse_markdup_metrics(path):
68
+ """Parse GATK MarkDuplicates metrics."""
69
+ if not os.path.exists(path):
70
+ return {'dup_pct': 0}
71
+ with open(path) as f:
72
+ in_metrics = False
73
+ headers = []
74
+ for line in f:
75
+ if line.startswith('## METRICS CLASS'):
76
+ in_metrics = True
77
+ continue
78
+ if in_metrics and not headers:
79
+ headers = line.strip().split('\t')
80
+ continue
81
+ if in_metrics and headers:
82
+ vals = line.strip().split('\t')
83
+ if len(vals) >= len(headers):
84
+ d = dict(zip(headers, vals))
85
+ return {'dup_pct': float(d.get('PERCENT_DUPLICATION', 0))}
86
+ break
87
+ return {'dup_pct': 0}
88
+
89
+ # Gather results
90
+ tumor_fastp = parse_fastp_json(f"{OUTDIR}/fastp/tumor_fastp.json")
91
+ normal_fastp = parse_fastp_json(f"{OUTDIR}/fastp/normal_fastp.json")
92
+
93
+ tumor_dup = parse_markdup_metrics(f"{OUTDIR}/markdup/tumor.metrics.txt")
94
+ normal_dup = parse_markdup_metrics(f"{OUTDIR}/markdup/normal.metrics.txt")
95
+
96
+ tumor_cov = parse_mosdepth_summary(f"{OUTDIR}/coverage/tumor.mosdepth.summary.txt")
97
+ normal_cov = parse_mosdepth_summary(f"{OUTDIR}/coverage/normal.mosdepth.summary.txt")
98
+
99
+ # Variant counts per caller
100
+ caller1_raw = count_vcf_variants(f"{OUTDIR}/mutect2/somatic_raw.vcf.gz")
101
+ caller1_pass = count_pass_variants(f"{OUTDIR}/mutect2/somatic_filtered.vcf.gz")
102
+ caller2_raw = count_vcf_variants(f"{OUTDIR}/freebayes/joint_raw.vcf")
103
+ caller3_raw = count_vcf_variants(f"{OUTDIR}/bcftools_call/pileup_raw.vcf.gz")
104
+
105
+ # Annotated counts
106
+ ann1 = count_vcf_variants(f"{OUTDIR}/annotate/mutect2_annotated.vcf.gz")
107
+ ann2 = count_vcf_variants(f"{OUTDIR}/annotate/freebayes_annotated.vcf.gz")
108
+ ann3 = count_vcf_variants(f"{OUTDIR}/annotate/bcftools_annotated.vcf.gz")
109
+
110
+ # Contamination
111
+ contamination = 0.0
112
+ contam_file = f"{OUTDIR}/mutect2/contamination.table"
113
+ if os.path.exists(contam_file):
114
+ with open(contam_file) as f:
115
+ for line in f:
116
+ if not line.startswith('sample'):
117
+ parts = line.strip().split('\t')
118
+ if len(parts) >= 2:
119
+ contamination = float(parts[1])
120
+
121
+ report = [
122
+ ('tumor_input_reads', tumor_fastp['before']),
123
+ ('tumor_qc_reads', tumor_fastp['after']),
124
+ ('normal_input_reads', normal_fastp['before']),
125
+ ('normal_qc_reads', normal_fastp['after']),
126
+ ('tumor_duplication_rate', round(tumor_dup['dup_pct'], 4)),
127
+ ('normal_duplication_rate', round(normal_dup['dup_pct'], 4)),
128
+ ('tumor_mean_coverage', round(tumor_cov['mean'], 2)),
129
+ ('normal_mean_coverage', round(normal_cov['mean'], 2)),
130
+ ('caller1_raw_variants', caller1_raw),
131
+ ('caller1_pass_variants', caller1_pass),
132
+ ('caller2_raw_variants', caller2_raw),
133
+ ('caller3_raw_variants', caller3_raw),
134
+ ('callers_used', 3),
135
+ ('annotated_variants_caller1', ann1),
136
+ ('annotated_variants_caller2', ann2),
137
+ ('annotated_variants_caller3', ann3),
138
+ ('estimated_contamination', round(contamination, 4)),
139
+ ]
140
+
141
+ with open("results/report.csv", 'w') as f:
142
+ writer = csv.writer(f)
143
+ writer.writerow(['metric', 'value'])
144
+ writer.writerows(report)
145
+
146
+ print("=== Final Report ===")
147
+ for m, v in report:
148
+ print(f" {m} = {v}")