-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchipdiff.py
More file actions
2061 lines (1763 loc) · 74.5 KB
/
Copy pathchipdiff.py
File metadata and controls
2061 lines (1763 loc) · 74.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""chipdiff.py
End-to-end pipeline for CUT&Tag / ChIP-seq differential analysis.
The script expects a sample sheet describing the input BAM files and
(optional) pre-computed peak files. The sample sheet must be a tab- or
comma-delimited text file with the following required columns:
sample Unique sample identifier (no spaces)
condition Experimental condition or group label
bam Path to the aligned reads in BAM format
Optional columns:
control_bam Path to a matched control/input BAM to be passed to
MACS2/MACS3 via ``-c`` during automatic peak calling.
This is strongly recommended for ChIP-seq and usually
omitted for ATAC-seq and CUT&Tag.
peaks Path to an existing peak file (narrowPeak or broadPeak)
peak_type One of {auto, narrow, broad}. ``auto`` (default)
attempts to infer the peak type from the file name.
Use ``narrow`` for punctate enrichments (e.g., TF/CUT&Tag
factor peaks) and ``broad`` for diffuse domains (e.g.,
many histone-mark ChIP-seq datasets).
Example TSV sample sheet::
sample condition bam control_bam peaks peak_type
T1 treated data/T1.bam data/input.bam data/T1_peaks.narrowPeak narrow
T2 treated data/T2.bam data/input.bam data/T2_peaks.narrowPeak narrow
C1 control data/C1.bam data/input.bam data/C1_peaks.narrowPeak narrow
C2 control data/C2.bam data/input.bam data/C2_peaks.narrowPeak narrow
For a single analysis, using a consistent peak type across samples is
recommended.
The pipeline performs the following steps:
1. Peak calling with MACS2/3 (if required, optionally using matched controls).
2. Construction of consensus peaks across samples.
3. Counting read overlaps per consensus peak using deepTools
``multiBamSummary``.
4. Differential analysis with PyDESeq2 (replicated designs) or the
MARS method (no replicates).
5. Optional annotation against a GTF file and Enrichr enrichment via
gseapy.
6. Plot generation (volcano, MA, correlation, heatmap) and metadata
capture.
Dependencies: numpy, pandas, scipy, statsmodels, matplotlib, seaborn,
pyranges, gseapy, MACS2, deepTools.
"""
from __future__ import annotations
import argparse
import json
import logging
import math
import os
import shutil
import subprocess
import sys
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Sequence, Set
import numpy as np
import pandas as pd
import pyranges as pr
import seaborn as sns
from matplotlib import pyplot as plt
from matplotlib.colors import Normalize
from matplotlib.lines import Line2D
from scipy import stats
try:
from pydeseq2.dds import DeseqDataSet
from pydeseq2.ds import DeseqStats
except ImportError: # pragma: no cover - optional dependency
DeseqDataSet = None # type: ignore[assignment]
DeseqStats = None # type: ignore[assignment]
try:
import gseapy
except ImportError: # pragma: no cover - optional dependency
gseapy = None
try:
import pysam
except ImportError: # pragma: no cover - optional dependency
pysam = None
import peak_shape
from io_utils import ensure_integer_columns, read_bed_frame
from motif_ranking import run_pairwise_motif_ranking
def _detect_macs_command() -> str:
"""Resolve the available MACS executable.
Preference is given to ``macs3`` when it can be executed successfully;
otherwise a working ``macs2`` is used as fallback. A runtime error is
raised when neither executable is runnable on ``PATH``.
"""
for candidate in ("macs3", "macs2"):
resolved = shutil.which(candidate)
if resolved is None:
continue
try:
result = subprocess.run(
[candidate, "--version"],
check=False,
capture_output=True,
text=True,
timeout=15,
)
except subprocess.TimeoutExpired:
logging.warning("Skipping unusable MACS executable %s at %s (timed out)", candidate, resolved)
continue
if result.returncode == 0:
return candidate
logging.warning(
"Skipping unusable MACS executable %s at %s (exit %s): %s",
candidate,
resolved,
result.returncode,
(result.stderr or result.stdout).strip(),
)
raise RuntimeError(
"Missing a runnable MACS executable. Install MACS via 'pip install macs3' "
"(recommended) or install a working macs2 binary."
)
MACS_COMMAND: Optional[str] = None
"""Name of the resolved MACS executable (``macs3`` preferred, ``macs2`` fallback)."""
# ---------------------------------------------------------------------------
# Data classes and utility helpers
# ---------------------------------------------------------------------------
@dataclass
class SampleEntry:
"""Representation of a single sample entry from the metadata sheet."""
sample: str
condition: str
bam: Path
control_bam: Optional[Path] = None
peaks: Optional[Path] = None
peak_type: str = "auto"
is_paired: Optional[bool] = None
def ensure_paths(self) -> None:
if not self.bam.exists():
raise FileNotFoundError(f"BAM file not found for sample {self.sample}: {self.bam}")
if self.control_bam is not None and not self.control_bam.exists():
raise FileNotFoundError(
f"Control/Input BAM file not found for sample {self.sample}: {self.control_bam}"
)
if self.peaks is not None and not self.peaks.exists():
raise FileNotFoundError(f"Peak file not found for sample {self.sample}: {self.peaks}")
# ---------------------------------------------------------------------------
# File and command helpers
# ---------------------------------------------------------------------------
def ensure_commands(commands: Sequence[str]) -> None:
missing = [cmd for cmd in commands if shutil.which(cmd) is None]
if missing:
joined = ", ".join(sorted(missing))
raise RuntimeError(
"Missing required command(s): "
f"{joined}. Install MACS via 'pip install macs3' (recommended) or a working macs2; deepTools via "
"'pip install deeptools' "
"and samtools via 'conda install -c bioconda samtools'."
)
def get_macs_command() -> str:
"""Return the available MACS executable, preferring ``macs3``.
The resolved command is cached for subsequent calls.
"""
global MACS_COMMAND
if MACS_COMMAND is None:
MACS_COMMAND = _detect_macs_command()
return MACS_COMMAND
def ensure_python_version(min_version: tuple[int, int] = (3, 10)) -> None:
"""Guard against unsupported Python interpreters."""
if sys.version_info < min_version:
formatted = ".".join(str(part) for part in min_version)
raise RuntimeError(
f"PeakForge requires Python {formatted} or newer; detected {sys.version.split()[0]}"
)
def run_command(cmd: Sequence[str], *, workdir: Optional[Path] = None, log: bool = True) -> None:
"""Run a subprocess command with logging and error handling."""
if log:
logging.info("Running command: %s", " ".join(cmd))
result = subprocess.run(cmd, cwd=str(workdir) if workdir else None, check=False)
if result.returncode != 0:
raise RuntimeError(f"Command failed with exit code {result.returncode}: {' '.join(cmd)}")
def ensure_directory(path: Path) -> Path:
path.mkdir(parents=True, exist_ok=True)
return path
def _bam_index_candidates(bam: Path) -> List[Path]:
candidates: List[Path] = []
candidates.append(Path(f"{bam}.bai"))
if bam.suffix:
candidates.append(bam.with_suffix(".bai"))
# Remove duplicates while preserving order
seen: Set[Path] = set()
unique: List[Path] = []
for candidate in candidates:
if candidate not in seen:
unique.append(candidate)
seen.add(candidate)
return unique
def ensure_bam_index(bam: Path, samtools_path: str, threads: int = 1) -> None:
for candidate in _bam_index_candidates(bam):
if candidate.exists():
return
logging.info("Indexing BAM for library size estimation: %s", bam)
cmd = [samtools_path, "index"]
if threads > 1:
cmd.extend(["-@", str(threads)])
cmd.append(str(bam))
run_command(cmd)
def detect_paired_end_bam(bam: Path, samtools_path: str, threads: int = 1) -> bool:
"""Return ``True`` if the BAM contains paired-end reads."""
cmd = [samtools_path, "view", "-c", "-f", "1"]
if threads > 1:
cmd.extend(["-@", str(threads)])
cmd.append(str(bam))
result = subprocess.run(cmd, check=False, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(
f"samtools view failed for {bam} with exit code {result.returncode}: {result.stderr.strip()}"
)
try:
count = int(result.stdout.strip() or 0)
except ValueError as exc: # pragma: no cover - defensive
raise RuntimeError(f"Unable to parse samtools view output for {bam}: {result.stdout!r}") from exc
paired = count > 0
logging.info("Detected %s BAM for %s", "paired-end" if paired else "single-end", bam)
return paired
def bam_total_mapped_reads(bam: Path, samtools_path: str, threads: int = 1) -> int:
ensure_bam_index(bam, samtools_path, threads)
result = subprocess.run(
[samtools_path, "idxstats", str(bam)],
check=False,
capture_output=True,
text=True,
)
if result.returncode != 0:
raise RuntimeError(
f"samtools idxstats failed for {bam} with exit code {result.returncode}: {result.stderr.strip()}"
)
total = 0
for line in result.stdout.splitlines():
if not line.strip():
continue
fields = line.split("\t")
if len(fields) < 3:
continue
try:
total += int(fields[2])
except ValueError:
continue
if total <= 0:
raise ValueError(f"Unable to determine mapped reads for BAM {bam}")
return total
def compute_library_sizes(samples: Sequence[SampleEntry], samtools_path: str, threads: int = 1) -> pd.Series:
sizes = {}
for sample in samples:
logging.info("Estimating library size for sample %s", sample.sample)
sizes[sample.sample] = bam_total_mapped_reads(sample.bam, samtools_path, threads)
return pd.Series(sizes, dtype=float)
def read_table(path: Path) -> pd.DataFrame:
"""Read a delimited table inferring delimiter automatically."""
try:
df = pd.read_csv(path, sep=None, engine="python")
except Exception as exc: # pragma: no cover - passthrough error
raise RuntimeError(f"Failed to read metadata file {path}: {exc}")
return df
# ---------------------------------------------------------------------------
# Metadata parsing
# ---------------------------------------------------------------------------
def _normalise_optional_path(value: object) -> Optional[Path]:
if isinstance(value, Path):
return value
if isinstance(value, str):
stripped = value.strip()
if stripped and stripped not in {"-", "NA", "None", "nan"}:
return Path(stripped)
return None
def load_samples(metadata_path: Path) -> List[SampleEntry]:
df = read_table(metadata_path)
required = {"sample", "condition", "bam"}
missing = required - set(df.columns)
if missing:
raise ValueError(f"Metadata file missing required columns: {', '.join(sorted(missing))}")
entries: List[SampleEntry] = []
for row in df.itertuples(index=False):
sample = getattr(row, "sample")
condition = getattr(row, "condition")
bam = getattr(row, "bam")
control_bam = _normalise_optional_path(
getattr(row, "control_bam", getattr(row, "input_bam", None))
)
peaks = _normalise_optional_path(getattr(row, "peaks", None))
peak_type_raw = getattr(row, "peak_type", "auto")
peak_type = str(peak_type_raw).lower() if peak_type_raw is not None else "auto"
entry = SampleEntry(
sample=str(sample),
condition=str(condition),
bam=Path(str(bam)),
control_bam=control_bam,
peaks=peaks,
peak_type=peak_type,
)
entry.ensure_paths()
entries.append(entry)
return entries
# ---------------------------------------------------------------------------
# Peak handling
# ---------------------------------------------------------------------------
def infer_peak_type(path: Path, declared: str, default: str) -> str:
if declared and declared not in {"", "auto", "nan"}:
if declared not in {"narrow", "broad"}:
raise ValueError(
f"Unknown peak_type '{declared}' for file {path}; only 'narrow' and 'broad' are supported"
)
return declared
name = path.name.lower()
if name.endswith(".broadpeak"):
return "broad"
if name.endswith(".narrowpeak"):
return "narrow"
if "summit" in name:
raise ValueError(
"Summit-only BED files are no longer supported; please provide a narrowPeak or broadPeak file"
)
return default
def read_peak_file(path: Path, peak_type: str, peak_extension: int) -> pr.PyRanges:
"""Load peaks into a :class:`pyranges.PyRanges` object."""
frame = read_bed_frame(path)
frame = ensure_integer_columns(frame, ("Start", "End"))
if peak_type == "narrow":
start = frame["Start"].to_numpy() - peak_extension
end = frame["End"].to_numpy() + peak_extension
frame["Start"] = np.maximum(start, 0)
frame["End"] = end
return pr.PyRanges(frame)
def _macs2_command(
sample: SampleEntry,
*,
output_dir: Path,
macs2_genome: str,
macs2_qval: float,
peak_type: str,
macs2_extra: Optional[List[str]] = None,
) -> tuple[list[str], Path]:
ensure_directory(output_dir)
macs2_extra = macs2_extra or []
name = sample.sample
out_prefix = output_dir / name
cmd = [
get_macs_command(),
"callpeak",
"-t",
str(sample.bam),
"-n",
str(out_prefix),
"-g",
macs2_genome,
"-q",
str(macs2_qval),
]
if sample.control_bam is not None:
cmd.extend(["-c", str(sample.control_bam)])
if sample.is_paired:
cmd.extend(["-f", "BAMPE"])
if peak_type == "broad":
cmd.extend(["--broad"])
cmd.extend(macs2_extra)
if peak_type == "broad":
peak_path = output_dir / f"{name}_peaks.broadPeak"
else:
peak_path = output_dir / f"{name}_peaks.narrowPeak"
return cmd, peak_path
def call_macs2(
sample: SampleEntry,
*,
output_dir: Path,
macs2_genome: str,
macs2_qval: float,
peak_type: str,
macs2_extra: Optional[List[str]] = None,
) -> Path:
"""Call MACS2 for a sample and return the resulting peak file path."""
cmd, peak_path = _macs2_command(
sample,
output_dir=output_dir,
macs2_genome=macs2_genome,
macs2_qval=macs2_qval,
peak_type=peak_type,
macs2_extra=macs2_extra,
)
run_command(cmd)
if not peak_path.exists():
raise FileNotFoundError(f"MACS2 output not found for sample {sample.sample}: {peak_path}")
return peak_path
@dataclass
class Macs2Job:
sample: SampleEntry
peak_type: str
peak_path: Path
process: subprocess.Popen[str]
def load_all_peaks(
samples: List[SampleEntry],
*,
peak_extension: int,
default_peak_type: str,
macs2_params: Dict[str, str],
peak_output_dir: Path,
) -> Dict[str, pr.PyRanges]:
"""Ensure every sample has peak calls and return PyRanges per sample."""
peak_ranges: Dict[str, pr.PyRanges] = {}
macs2_jobs: List[Macs2Job] = []
for sample in samples:
if sample.peaks is None:
peak_type = sample.peak_type if sample.peak_type != "auto" else default_peak_type
logging.info("Launching MACS2 for sample %s (type=%s)", sample.sample, peak_type)
cmd, peak_path = _macs2_command(
sample,
output_dir=peak_output_dir,
macs2_genome=macs2_params["genome"],
macs2_qval=float(macs2_params["qvalue"]),
peak_type=peak_type,
macs2_extra=macs2_params.get("extra", []),
)
process = subprocess.Popen(cmd)
macs2_jobs.append(
Macs2Job(
sample=sample,
peak_type=peak_type,
peak_path=peak_path,
process=process,
)
)
else:
peak_type = infer_peak_type(sample.peaks, sample.peak_type, default_peak_type)
peak_path = sample.peaks
logging.info("Using provided peaks for sample %s (%s)", sample.sample, peak_type)
pr_obj = read_peak_file(Path(peak_path), peak_type, peak_extension)
df = pr_obj.df
df["Sample"] = sample.sample
pr_obj = pr.PyRanges(df)
peak_ranges[sample.sample] = pr_obj
macs2_results: List[tuple[Macs2Job, int]] = []
for job in macs2_jobs:
returncode = job.process.wait()
macs2_results.append((job, returncode))
failed = [job for job, code in macs2_results if code != 0]
if failed:
errors = ", ".join(f"{job.sample.sample} (exit {job.process.returncode})" for job in failed)
raise RuntimeError(f"MACS2 failed for sample(s): {errors}")
for job, _ in macs2_results:
if not job.peak_path.exists():
raise FileNotFoundError(
f"MACS2 output not found for sample {job.sample.sample}: {job.peak_path}"
)
pr_obj = read_peak_file(Path(job.peak_path), job.peak_type, peak_extension)
df = pr_obj.df
df["Sample"] = job.sample.sample
pr_obj = pr.PyRanges(df)
peak_ranges[job.sample.sample] = pr_obj
return peak_ranges
def build_consensus(peak_ranges: Dict[str, pr.PyRanges], *, min_overlap: int) -> pr.PyRanges:
"""Build consensus peaks across samples with minimum overlap criteria."""
logging.info("Building consensus peaks across %d samples", len(peak_ranges))
if not peak_ranges:
return pr.PyRanges()
combined = pr.concat(list(peak_ranges.values()))
clustered = combined.cluster()
df = clustered.df
grouped = (
df.groupby("Cluster")
.agg(
Chromosome=("Chromosome", "first"),
Start=("Start", "min"),
End=("End", "max"),
Support=("Sample", pd.Series.nunique),
)
.reset_index(drop=True)
)
consensus_df = grouped[grouped["Support"] >= max(1, min_overlap)].copy()
consensus_df.sort_values(["Chromosome", "Start", "End"], inplace=True)
consensus_df.reset_index(drop=True, inplace=True)
consensus_df["Name"] = [f"consensus_{i + 1}" for i in range(len(consensus_df))]
return pr.PyRanges(consensus_df[["Chromosome", "Start", "End", "Name", "Support"]])
def write_consensus_bed(consensus: pr.PyRanges, output_path: Path) -> None:
"""Write consensus intervals to a BED file."""
ensure_directory(output_path.parent)
consensus.df[["Chromosome", "Start", "End", "Name"]].to_csv(
output_path,
sep="\t",
header=False,
index=False,
)
def load_consensus_bed(path: Path) -> pr.PyRanges:
"""Load an existing consensus BED file into a ``PyRanges`` object."""
if not path.exists():
raise FileNotFoundError(f"Consensus BED file not found: {path}")
df = pd.read_csv(path, sep="\t", comment="#", header=None)
if df.shape[1] < 3:
raise ValueError(
f"Consensus BED {path} must have at least three columns (chrom, start, end)"
)
base = df.iloc[:, :3].copy()
base.columns = ["Chromosome", "Start", "End"]
base = ensure_integer_columns(base, ("Start", "End"))
names: List[str] = []
provided_names = df.iloc[:, 3] if df.shape[1] >= 4 else None
seen: Set[str] = set()
for idx in range(len(base)):
value: Optional[str] = None
if provided_names is not None:
raw = provided_names.iloc[idx]
if pd.notna(raw):
raw_str = str(raw).strip()
if raw_str:
value = raw_str
if not value:
value = f"consensus_{idx + 1}"
# Guarantee uniqueness in case the BED supplies duplicates
candidate = value
suffix = 1
while candidate in seen:
suffix += 1
candidate = f"{value}_{suffix}"
seen.add(candidate)
names.append(candidate)
base["Name"] = names
support = pd.Series([pd.NA] * len(base))
if df.shape[1] >= 5:
support = pd.to_numeric(df.iloc[:, 4], errors="coerce")
base["Support"] = support
return pr.PyRanges(base[["Chromosome", "Start", "End", "Name", "Support"]])
def load_interval_bed(path: Path) -> pr.PyRanges:
"""Load a generic BED file as intervals suitable for overlap filtering."""
if not path.exists():
raise FileNotFoundError(f"BED file not found: {path}")
frame = read_bed_frame(path)
frame = ensure_integer_columns(frame, ("Start", "End"))
return pr.PyRanges(frame[["Chromosome", "Start", "End"]])
def filter_consensus_by_blacklist(
consensus: pr.PyRanges,
blacklist_path: Path,
) -> tuple[pr.PyRanges, Dict[str, object], pd.DataFrame]:
"""Drop consensus peaks with any overlap against a blacklist BED."""
blacklist = load_interval_bed(blacklist_path)
df = consensus.df.copy()
if df.empty:
summary = {
"applied": True,
"blacklist_bed": str(blacklist_path),
"total_peaks": 0,
"kept_peaks": 0,
"removed_peaks": 0,
"overlapped_peaks": 0,
"max_blacklist_overlaps": 0,
}
empty_report = pd.DataFrame(
columns=[
"Chromosome",
"Start",
"End",
"Name",
"Support",
"blacklist_overlaps",
"keep",
"filter_reason",
]
)
return consensus, summary, empty_report
if len(blacklist) == 0:
report_df = df[["Chromosome", "Start", "End", "Name", "Support"]].copy()
report_df["blacklist_overlaps"] = 0
report_df["keep"] = True
report_df["filter_reason"] = ""
summary = {
"applied": True,
"blacklist_bed": str(blacklist_path),
"total_peaks": int(len(report_df)),
"kept_peaks": int(len(report_df)),
"removed_peaks": 0,
"overlapped_peaks": 0,
"max_blacklist_overlaps": 0,
}
return consensus, summary, report_df
overlap_df = consensus.count_overlaps(blacklist).df.copy()
overlap_df["blacklist_overlaps"] = (
pd.to_numeric(overlap_df.get("NumberOverlaps", 0), errors="coerce")
.fillna(0)
.astype(int)
)
overlap_df["keep"] = overlap_df["blacklist_overlaps"] == 0
overlap_df["filter_reason"] = np.where(overlap_df["keep"], "", "blacklist")
kept_df = overlap_df.loc[
overlap_df["keep"],
["Chromosome", "Start", "End", "Name", "Support"],
].copy()
filtered_consensus = pr.PyRanges(kept_df)
overlapped = int((overlap_df["blacklist_overlaps"] > 0).sum())
max_overlaps = int(overlap_df["blacklist_overlaps"].max()) if len(overlap_df) else 0
summary = {
"applied": True,
"blacklist_bed": str(blacklist_path),
"total_peaks": int(len(overlap_df)),
"kept_peaks": int(len(kept_df)),
"removed_peaks": int(len(overlap_df) - len(kept_df)),
"overlapped_peaks": overlapped,
"max_blacklist_overlaps": max_overlaps,
}
report_df = overlap_df[
[
"Chromosome",
"Start",
"End",
"Name",
"Support",
"blacklist_overlaps",
"keep",
"filter_reason",
]
].copy()
return filtered_consensus, summary, report_df
def validate_fraction_threshold(name: str, value: Optional[float]) -> Optional[float]:
"""Validate a fraction threshold constrained to the [0, 1] interval."""
if value is None:
return None
if not 0.0 <= value <= 1.0:
raise ValueError(f"{name} must be between 0 and 1 inclusive")
return value
def filter_consensus_by_sequence_mask(
consensus: pr.PyRanges,
fasta_path: Path,
*,
max_n_fraction: Optional[float] = None,
max_lowercase_fraction: Optional[float] = None,
) -> tuple[pr.PyRanges, Dict[str, object], pd.DataFrame]:
"""Filter consensus peaks by sequence masking metrics from a reference FASTA."""
if max_n_fraction is None and max_lowercase_fraction is None:
raise ValueError("At least one sequence-mask threshold must be provided")
if pysam is None:
raise ImportError(
"pysam is required for genome-FASTA masking filters; install it with 'pip install pysam'"
)
if not fasta_path.exists():
raise FileNotFoundError(f"Genome FASTA not found: {fasta_path}")
df = consensus.df.copy()
if df.empty:
summary = {
"applied": True,
"genome_fasta": str(fasta_path),
"max_n_fraction": max_n_fraction,
"max_lowercase_fraction": max_lowercase_fraction,
"total_peaks": 0,
"kept_peaks": 0,
"removed_peaks": 0,
"missing_sequence_peaks": 0,
"mean_n_fraction_kept": None,
"mean_lowercase_fraction_kept": None,
}
empty_report = pd.DataFrame(
columns=[
"Chromosome",
"Start",
"End",
"Name",
"Support",
"length",
"n_fraction",
"lowercase_fraction",
"missing_sequence",
"keep",
"filter_reason",
]
)
return consensus, summary, empty_report
records: List[Dict[str, object]] = []
try:
fasta_reader = pysam.FastaFile(str(fasta_path))
except (OSError, ValueError) as exc:
raise RuntimeError(
f"Unable to open/index genome FASTA {fasta_path}; ensure it is bgzip/faidx compatible and run 'samtools faidx' if needed"
) from exc
with fasta_reader as fasta:
references = set(fasta.references)
for row in df.itertuples(index=False):
chrom = str(row.Chromosome)
start = int(row.Start)
end = int(row.End)
name = str(row.Name)
support = getattr(row, "Support", pd.NA)
seq = ""
missing_sequence = chrom not in references
if not missing_sequence:
try:
seq = fasta.fetch(chrom, start, end)
except (KeyError, ValueError, OSError):
missing_sequence = True
seq_length = len(seq)
n_fraction = math.nan
lowercase_fraction = math.nan
if not missing_sequence and seq_length > 0:
n_fraction = sum(base.upper() == "N" for base in seq) / seq_length
lowercase_fraction = sum(base.islower() for base in seq) / seq_length
elif seq_length == 0:
missing_sequence = True
keep = True
reasons: List[str] = []
if missing_sequence:
keep = False
reasons.append("missing_sequence")
if max_n_fraction is not None and not math.isnan(n_fraction) and n_fraction > max_n_fraction:
keep = False
reasons.append("n_fraction")
if (
max_lowercase_fraction is not None
and not math.isnan(lowercase_fraction)
and lowercase_fraction > max_lowercase_fraction
):
keep = False
reasons.append("lowercase_fraction")
records.append(
{
"Chromosome": chrom,
"Start": start,
"End": end,
"Name": name,
"Support": support,
"length": max(0, end - start),
"n_fraction": n_fraction,
"lowercase_fraction": lowercase_fraction,
"missing_sequence": missing_sequence,
"keep": keep,
"filter_reason": ",".join(reasons),
}
)
metrics_df = pd.DataFrame(records)
missing_sequence_count = int(metrics_df["missing_sequence"].sum())
if missing_sequence_count == len(metrics_df):
raise ValueError(
"No consensus intervals could be fetched from the genome FASTA; check the genome build and chromosome naming."
)
kept_metrics = metrics_df[metrics_df["keep"]].copy()
kept_df = kept_metrics[["Chromosome", "Start", "End", "Name", "Support"]].copy()
filtered_consensus = pr.PyRanges(kept_df)
mean_n_fraction = kept_metrics["n_fraction"].dropna().mean()
mean_lowercase_fraction = kept_metrics["lowercase_fraction"].dropna().mean()
summary = {
"applied": True,
"genome_fasta": str(fasta_path),
"max_n_fraction": max_n_fraction,
"max_lowercase_fraction": max_lowercase_fraction,
"total_peaks": int(len(metrics_df)),
"kept_peaks": int(len(kept_metrics)),
"removed_peaks": int(len(metrics_df) - len(kept_metrics)),
"missing_sequence_peaks": missing_sequence_count,
"mean_n_fraction_kept": None if pd.isna(mean_n_fraction) else float(mean_n_fraction),
"mean_lowercase_fraction_kept": None
if pd.isna(mean_lowercase_fraction)
else float(mean_lowercase_fraction),
}
return filtered_consensus, summary, metrics_df
# ---------------------------------------------------------------------------
# Counting with deepTools
# ---------------------------------------------------------------------------
def run_multibamsummary(consensus_bed: Path, samples: List[SampleEntry], output_dir: Path,
threads: int = 1) -> Path:
ensure_directory(output_dir)
out_npz = output_dir / "counts.npz"
out_tsv = output_dir / "counts.tsv"
cmd = [
"multiBamSummary",
"BED-file",
"--BED",
str(consensus_bed),
"--bamfiles",
]
cmd.extend(str(sample.bam) for sample in samples)
cmd.extend([
"--outFileName",
str(out_npz),
"--outRawCounts",
str(out_tsv),
"--numberOfProcessors",
str(threads),
])
run_command(cmd)
if not out_tsv.exists():
raise FileNotFoundError("multiBamSummary failed to produce counts TSV")
return out_tsv
# ---------------------------------------------------------------------------
# Differential analysis utilities
# ---------------------------------------------------------------------------
def benjamini_hochberg(pvalues: pd.Series) -> pd.Series:
pvals = pvalues.fillna(1.0).to_numpy(dtype=float, copy=True)
n = len(pvals)
if n == 0:
return pd.Series(index=pvalues.index, dtype=float)
order = np.argsort(pvals)
ranks = np.arange(1, n + 1, dtype=float)
adjusted_sorted = pvals[order] * n / ranks
adjusted_sorted = np.minimum.accumulate(adjusted_sorted[::-1])[::-1]
adjusted = np.empty_like(adjusted_sorted)
adjusted[order] = adjusted_sorted
adjusted = np.clip(adjusted, 0, 1)
return pd.Series(adjusted, index=pvalues.index)
def pydeseq2_differential(counts: pd.DataFrame, conditions: pd.Series) -> pd.DataFrame:
if DeseqDataSet is None or DeseqStats is None:
raise ImportError("pydeseq2 is required for the DESeq2 workflow but is not installed")
logging.info("Running PyDESeq2 differential analysis")
samples = counts.columns.tolist()
cond = conditions.loc[samples]
if cond.nunique() != 2:
raise ValueError("PyDESeq2 differential analysis requires exactly two conditions")
condition_order = list(dict.fromkeys(cond.tolist()))
reference = condition_order[0]
contrast = condition_order[1]
metadata = pd.DataFrame({"condition": cond.astype("category")}, index=samples)
dds = DeseqDataSet(counts=counts.T.astype(int), metadata=metadata, design="~condition")
dds.deseq2()
stats = DeseqStats(dds, contrast=("condition", contrast, reference))
stats.summary()
res = stats.results_df.copy()
res.index.name = "Peak"
result = pd.DataFrame(index=res.index)
if "baseMean" in res.columns:
result["baseMean"] = res["baseMean"]
result["log2FC"] = res["log2FoldChange"]
if "lfcSE" in res.columns:
result["lfcSE"] = res["lfcSE"]
if "stat" in res.columns:
result["waldStat"] = res["stat"]
result["pvalue"] = res["pvalue"]
result["padj"] = res["padj"].fillna(1.0)
result["log2FC_shrunk"] = result["log2FC"]
result["method"] = "pydeseq2"
return result
def mars_differential(
counts: pd.DataFrame, conditions: pd.Series, library_sizes: pd.Series
) -> pd.DataFrame:
"""Implement the MARS method for designs without replicates."""
logging.info("Running MARS differential analysis (no replicates)")
samples = counts.columns.tolist()
cond_series = conditions.loc[samples]
unique_conditions = list(dict.fromkeys(cond_series.tolist()))
if len(unique_conditions) != 2:
raise ValueError("MARS method requires exactly two conditions")
reference, contrast = unique_conditions
contrast_cols = cond_series[cond_series == contrast].index