strainphase 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- strainphase/__init__.py +76 -0
- strainphase/cli.py +532 -0
- strainphase/coherence.py +69 -0
- strainphase/core.py +3719 -0
- strainphase/lineages.py +102 -0
- strainphase/longitudinal.py +853 -0
- strainphase/simulation/__init__.py +17 -0
- strainphase/simulation/synthetic_data.py +486 -0
- strainphase/sv_encoding.py +514 -0
- strainphase/track_merge.py +242 -0
- strainphase/window_groups.py +64 -0
- strainphase-0.1.0.dist-info/METADATA +297 -0
- strainphase-0.1.0.dist-info/RECORD +17 -0
- strainphase-0.1.0.dist-info/WHEEL +5 -0
- strainphase-0.1.0.dist-info/entry_points.txt +2 -0
- strainphase-0.1.0.dist-info/licenses/LICENSE +29 -0
- strainphase-0.1.0.dist-info/top_level.txt +1 -0
strainphase/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Strainphase: strain-resolved haplotype phasing for PacBio HiFi metagenomes.
|
|
2
|
+
|
|
3
|
+
Reads that share alleles are clustered into candidate haplotypes within
|
|
4
|
+
overlapping genomic windows, refined by a quality-weighted EM model, and linked
|
|
5
|
+
across windows and timepoints into contig-spanning lineages.
|
|
6
|
+
|
|
7
|
+
Python:
|
|
8
|
+
>>> from strainphase import HaplotyperConfig, process_contig
|
|
9
|
+
>>> config = HaplotyperConfig(window_size=20000, identity_distance=0.02)
|
|
10
|
+
>>> results = process_contig(bam, vcf, contig_id, contig_length, config)
|
|
11
|
+
|
|
12
|
+
CLI:
|
|
13
|
+
$ strainphase run --bam sample.bam --vcf variants.vcf.gz --contig ctg1 --length 50000
|
|
14
|
+
$ strainphase longitudinal --samples T1,T2,T3 --bams mapping/{sample}.bam ...
|
|
15
|
+
$ strainphase sv reconcile ...
|
|
16
|
+
$ strainphase test
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
# Single source of truth is pyproject.toml. Hard-coding it here meant the two
|
|
20
|
+
# could drift - and they had: pyproject said 0.1.0rc1 while this said 0.1.0, so
|
|
21
|
+
# `strainphase version` would have misreported a release. The fallback covers a
|
|
22
|
+
# source tree that was never installed.
|
|
23
|
+
try: # pragma: no cover - trivial, and the except path needs an uninstalled tree
|
|
24
|
+
from importlib.metadata import PackageNotFoundError, version as _version
|
|
25
|
+
|
|
26
|
+
__version__ = _version("strainphase")
|
|
27
|
+
except PackageNotFoundError: # pragma: no cover
|
|
28
|
+
__version__ = "0.0.0+unknown"
|
|
29
|
+
__author__ = "Renee Oles"
|
|
30
|
+
__email__ = "roles@ucsd.edu"
|
|
31
|
+
|
|
32
|
+
from strainphase.core import (
|
|
33
|
+
DEFAULT_CONFIG,
|
|
34
|
+
EMHaplotyper,
|
|
35
|
+
GraphInitializer,
|
|
36
|
+
Haplotype,
|
|
37
|
+
HaplotyperConfig,
|
|
38
|
+
LogProbCache,
|
|
39
|
+
LongitudinalIntegrator,
|
|
40
|
+
PostProcessor,
|
|
41
|
+
Read,
|
|
42
|
+
Window,
|
|
43
|
+
WindowResult,
|
|
44
|
+
link_windows,
|
|
45
|
+
process_contig,
|
|
46
|
+
results_to_dataframe,
|
|
47
|
+
)
|
|
48
|
+
from strainphase.longitudinal import process_mag_longitudinal
|
|
49
|
+
|
|
50
|
+
# Core algorithms and pipeline entry points.
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
# Version info
|
|
54
|
+
"__version__",
|
|
55
|
+
"__author__",
|
|
56
|
+
"__email__",
|
|
57
|
+
# Configuration
|
|
58
|
+
"HaplotyperConfig",
|
|
59
|
+
"DEFAULT_CONFIG",
|
|
60
|
+
# Data structures
|
|
61
|
+
"Read",
|
|
62
|
+
"Window",
|
|
63
|
+
"Haplotype",
|
|
64
|
+
"WindowResult",
|
|
65
|
+
# Core algorithms
|
|
66
|
+
"GraphInitializer",
|
|
67
|
+
"EMHaplotyper",
|
|
68
|
+
"PostProcessor",
|
|
69
|
+
"LongitudinalIntegrator",
|
|
70
|
+
"LogProbCache",
|
|
71
|
+
# Main functions
|
|
72
|
+
"process_contig",
|
|
73
|
+
"process_mag_longitudinal",
|
|
74
|
+
"link_windows",
|
|
75
|
+
"results_to_dataframe",
|
|
76
|
+
]
|
strainphase/cli.py
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Strainphase command-line interface.
|
|
4
|
+
|
|
5
|
+
Usage:
|
|
6
|
+
strainphase run # Process single contig
|
|
7
|
+
strainphase longitudinal # Process MAG across timepoints
|
|
8
|
+
strainphase sv # Sidecar tools (reconcile, verify)
|
|
9
|
+
strainphase test # Run test suite
|
|
10
|
+
strainphase version # Show version
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
|
|
17
|
+
from strainphase.core import DEFAULT_CONFIG as _D
|
|
18
|
+
import logging
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
|
|
22
|
+
from strainphase import __version__
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def setup_logging(level: str = "INFO") -> None:
|
|
26
|
+
"""Configure logging."""
|
|
27
|
+
numeric_level = getattr(logging, level.upper(), logging.INFO)
|
|
28
|
+
logging.basicConfig(
|
|
29
|
+
level=numeric_level,
|
|
30
|
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
|
31
|
+
datefmt="%Y-%m-%d %H:%M:%S",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _input_errors(bam: str, vcf: str) -> list[str]:
|
|
36
|
+
"""What is wrong with one sample's BAM and VCF, in words; empty when usable.
|
|
37
|
+
|
|
38
|
+
Both are read by region, so both need an index, and a VCF can only be indexed
|
|
39
|
+
once it is bgzip-compressed. Checked up front because pysam reports a missing
|
|
40
|
+
index as "fetch requires an index" from deep inside the first window.
|
|
41
|
+
"""
|
|
42
|
+
errors = []
|
|
43
|
+
if not os.path.exists(bam):
|
|
44
|
+
errors.append(f"BAM not found: {bam}")
|
|
45
|
+
elif not any(os.path.exists(p) for p in (bam + ".bai", bam[:-4] + ".bai", bam + ".csi")):
|
|
46
|
+
errors.append(f"BAM is not indexed: {bam}. Run: samtools index {bam}")
|
|
47
|
+
if not os.path.exists(vcf):
|
|
48
|
+
errors.append(f"VCF not found: {vcf}")
|
|
49
|
+
elif not vcf.endswith((".gz", ".bgz", ".bcf")):
|
|
50
|
+
errors.append(
|
|
51
|
+
f"VCF must be bgzip-compressed and indexed: {vcf}. "
|
|
52
|
+
f"Run: bgzip {vcf} && tabix -p vcf {vcf}.gz"
|
|
53
|
+
)
|
|
54
|
+
elif not any(os.path.exists(vcf + ext) for ext in (".tbi", ".csi")):
|
|
55
|
+
errors.append(f"VCF is not indexed: {vcf}. Run: tabix -p vcf {vcf}")
|
|
56
|
+
return errors
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def cmd_run(args: argparse.Namespace) -> int:
|
|
60
|
+
"""Run haplotyper on a single contig."""
|
|
61
|
+
from strainphase import process_contig, results_to_dataframe
|
|
62
|
+
from strainphase.core import config_from_args
|
|
63
|
+
|
|
64
|
+
setup_logging(args.log_level)
|
|
65
|
+
|
|
66
|
+
errors = _input_errors(args.bam, args.vcf)
|
|
67
|
+
if errors:
|
|
68
|
+
for e in errors:
|
|
69
|
+
logging.error(e)
|
|
70
|
+
return 1
|
|
71
|
+
|
|
72
|
+
config = config_from_args(args)
|
|
73
|
+
|
|
74
|
+
logging.info(f"Processing contig {args.contig} ({args.length} bp)")
|
|
75
|
+
|
|
76
|
+
results = process_contig(
|
|
77
|
+
bam_path=args.bam,
|
|
78
|
+
vcf_path=args.vcf,
|
|
79
|
+
contig_id=args.contig,
|
|
80
|
+
contig_length=args.length,
|
|
81
|
+
config=config,
|
|
82
|
+
sample_id=args.sample,
|
|
83
|
+
vcf_sample_name=args.vcf_sample,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
records = results_to_dataframe({args.contig: results})
|
|
87
|
+
|
|
88
|
+
if records:
|
|
89
|
+
import csv
|
|
90
|
+
|
|
91
|
+
with open(args.output, "w", newline="") as f:
|
|
92
|
+
writer = csv.DictWriter(f, fieldnames=records[0].keys(), delimiter="\t")
|
|
93
|
+
writer.writeheader()
|
|
94
|
+
writer.writerows(records)
|
|
95
|
+
logging.info(f"Wrote {len(records)} haplotypes to {args.output}")
|
|
96
|
+
else:
|
|
97
|
+
logging.warning("No haplotypes found")
|
|
98
|
+
|
|
99
|
+
return 0
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _report_mem_profile() -> None:
|
|
103
|
+
"""Log tracemalloc peak + top allocation sites. Call at the integration point."""
|
|
104
|
+
import collections
|
|
105
|
+
import tracemalloc
|
|
106
|
+
snap = tracemalloc.take_snapshot()
|
|
107
|
+
cur, peak = tracemalloc.get_traced_memory()
|
|
108
|
+
logging.info(f"[mem-profile] tracemalloc peak={peak / 1e9:.2f} GB resident-now={cur / 1e9:.2f} GB")
|
|
109
|
+
by_file: collections.Counter = collections.Counter()
|
|
110
|
+
for st in snap.statistics("lineno"):
|
|
111
|
+
by_file[os.path.basename(st.traceback[0].filename)] += st.size
|
|
112
|
+
logging.info("[mem-profile] top modules (resident at integration point):")
|
|
113
|
+
for fn_, sz in by_file.most_common(8):
|
|
114
|
+
logging.info(f"[mem-profile] {sz / 1e9:6.3f} GB {fn_}")
|
|
115
|
+
logging.info("[mem-profile] top 15 allocation sites:")
|
|
116
|
+
for st in snap.statistics("lineno")[:15]:
|
|
117
|
+
fr = st.traceback[0]
|
|
118
|
+
logging.info(f"[mem-profile] {st.size / 1e9:6.3f} GB {os.path.basename(fr.filename)}:{fr.lineno}")
|
|
119
|
+
tracemalloc.stop()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def cmd_longitudinal(args: argparse.Namespace) -> int:
|
|
123
|
+
"""Run longitudinal analysis across multiple samples."""
|
|
124
|
+
setup_logging(args.log_level)
|
|
125
|
+
|
|
126
|
+
_mem_profile = getattr(args, "mem_profile", False)
|
|
127
|
+
if _mem_profile:
|
|
128
|
+
import tracemalloc
|
|
129
|
+
tracemalloc.start(25)
|
|
130
|
+
|
|
131
|
+
# Import here to avoid pysam requirement for other commands
|
|
132
|
+
import importlib.util
|
|
133
|
+
|
|
134
|
+
if importlib.util.find_spec("pysam") is None:
|
|
135
|
+
logging.error(
|
|
136
|
+
"pysam is required for longitudinal analysis. Install with: pip install pysam"
|
|
137
|
+
)
|
|
138
|
+
return 1
|
|
139
|
+
|
|
140
|
+
from strainphase.core import config_from_args
|
|
141
|
+
from strainphase.longitudinal import (
|
|
142
|
+
build_window_tables,
|
|
143
|
+
load_allowed_contigs,
|
|
144
|
+
parse_reference_contigs,
|
|
145
|
+
process_mag_longitudinal,
|
|
146
|
+
write_window_tables,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# Parse samples
|
|
150
|
+
samples = [s.strip() for s in args.samples.split(",")]
|
|
151
|
+
logging.info(f"Processing {len(samples)} samples: {samples}")
|
|
152
|
+
|
|
153
|
+
if len(set(samples)) != len(samples):
|
|
154
|
+
logging.error(f"--samples contains duplicates: {args.samples}")
|
|
155
|
+
return 1
|
|
156
|
+
|
|
157
|
+
# Build path mappings
|
|
158
|
+
bam_paths = {s: args.bams.format(sample=s) for s in samples}
|
|
159
|
+
vcf_paths = {s: args.vcfs.format(sample=s) for s in samples}
|
|
160
|
+
sv_sidecar_paths = None
|
|
161
|
+
if getattr(args, "sv_sidecars", None):
|
|
162
|
+
sv_sidecar_paths = {s: args.sv_sidecars.format(sample=s) for s in samples}
|
|
163
|
+
|
|
164
|
+
# A --bams template without {sample} resolves to ONE BAM for every timepoint, so
|
|
165
|
+
# every timepoint is phased from one sample's reads and the run looks normal. A
|
|
166
|
+
# shared --vcfs or --sv-sidecars is legitimate by contrast (variant catalogues);
|
|
167
|
+
# the BAM is what makes a sample a sample.
|
|
168
|
+
if len(set(bam_paths.values())) != len(samples):
|
|
169
|
+
logging.error(
|
|
170
|
+
f"--bams does not resolve to a distinct BAM per sample: {args.bams!r} -> "
|
|
171
|
+
f"{sorted(set(bam_paths.values()))}. The template must contain {{sample}}."
|
|
172
|
+
)
|
|
173
|
+
return 1
|
|
174
|
+
|
|
175
|
+
# Verify every input before any phasing starts
|
|
176
|
+
errors = []
|
|
177
|
+
for sample in samples:
|
|
178
|
+
errors += _input_errors(bam_paths[sample], vcf_paths[sample])
|
|
179
|
+
if sv_sidecar_paths and not os.path.exists(sv_sidecar_paths[sample]):
|
|
180
|
+
errors.append(f"SV sidecar not found: {sv_sidecar_paths[sample]}")
|
|
181
|
+
if not os.path.exists(args.reference + ".fai"):
|
|
182
|
+
errors.append(
|
|
183
|
+
f"Reference is not indexed: {args.reference}. "
|
|
184
|
+
f"Run: samtools faidx {args.reference}"
|
|
185
|
+
)
|
|
186
|
+
if errors:
|
|
187
|
+
for e in errors:
|
|
188
|
+
logging.error(e)
|
|
189
|
+
return 1
|
|
190
|
+
|
|
191
|
+
# Load contig filter if provided
|
|
192
|
+
allowed_contigs = None
|
|
193
|
+
if args.contig_filter:
|
|
194
|
+
allowed_contigs = load_allowed_contigs(args.contig_filter)
|
|
195
|
+
|
|
196
|
+
# Parse reference to get MAGs and contigs
|
|
197
|
+
mags = parse_reference_contigs(args.reference, allowed_contigs)
|
|
198
|
+
|
|
199
|
+
# Filter to requested MAGs
|
|
200
|
+
if args.mags:
|
|
201
|
+
requested = set(args.mags.split(","))
|
|
202
|
+
mags = {k: v for k, v in mags.items() if k in requested}
|
|
203
|
+
|
|
204
|
+
if not mags:
|
|
205
|
+
logging.error("No MAGs to process")
|
|
206
|
+
return 1
|
|
207
|
+
|
|
208
|
+
logging.info(f"Processing {len(mags)} MAGs")
|
|
209
|
+
|
|
210
|
+
# Configure
|
|
211
|
+
config = config_from_args(args)
|
|
212
|
+
|
|
213
|
+
# Create output directory
|
|
214
|
+
os.makedirs(args.output_dir, exist_ok=True)
|
|
215
|
+
|
|
216
|
+
# Process each MAG
|
|
217
|
+
all_results = {}
|
|
218
|
+
for mag_name, mag_contigs in mags.items():
|
|
219
|
+
logging.info(f"Processing MAG {mag_name}")
|
|
220
|
+
|
|
221
|
+
results, _ = process_mag_longitudinal(
|
|
222
|
+
mag_name=mag_name,
|
|
223
|
+
mag_contigs=mag_contigs,
|
|
224
|
+
samples=samples,
|
|
225
|
+
bam_paths=bam_paths,
|
|
226
|
+
vcf_paths=vcf_paths,
|
|
227
|
+
config=config,
|
|
228
|
+
sv_sidecar_paths=sv_sidecar_paths,
|
|
229
|
+
# REQUIRED for read spilling. Without it _SpillStore falls back to
|
|
230
|
+
# _NullSpill and every sample's reads stay resident for the whole MAG,
|
|
231
|
+
# which is the OOM the spill work exists to prevent.
|
|
232
|
+
output_dir=args.output_dir,
|
|
233
|
+
)
|
|
234
|
+
all_results[mag_name] = results
|
|
235
|
+
|
|
236
|
+
if _mem_profile:
|
|
237
|
+
_report_mem_profile()
|
|
238
|
+
|
|
239
|
+
# ---- Window-level tables (the deliverables) ----
|
|
240
|
+
# lineages.tsv comes back from here too: the cross-sample track merge that
|
|
241
|
+
# produces the lineages runs inside build_window_tables.
|
|
242
|
+
hap_rows, within_rows, across_rows, mismatch_rows, lineage_rows = build_window_tables(
|
|
243
|
+
args.output_dir, all_results, config
|
|
244
|
+
)
|
|
245
|
+
write_window_tables(
|
|
246
|
+
hap_rows, within_rows, across_rows, args.output_dir, mismatch_rows, lineage_rows
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
n_within = len({(r["sample"], r["contig"], r["within_sample_id"]) for r in within_rows})
|
|
250
|
+
logging.info(
|
|
251
|
+
f"DONE: {len(hap_rows)} window-haplotypes | {n_within} within-sample entities | "
|
|
252
|
+
f"{len(across_rows)} across-sample window groups | {len(lineage_rows)} lineage rows"
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
return 0
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def cmd_test(args: argparse.Namespace) -> int:
|
|
259
|
+
"""Run test suite."""
|
|
260
|
+
setup_logging("INFO")
|
|
261
|
+
|
|
262
|
+
print(f"\n{'=' * 60}")
|
|
263
|
+
print(f"STRAINPHASE v{__version__} - TEST SUITE")
|
|
264
|
+
print(f"{'=' * 60}\n")
|
|
265
|
+
|
|
266
|
+
# The tests live beside the package in a source checkout and are not installed
|
|
267
|
+
# with it, so find them from this file rather than from the working directory.
|
|
268
|
+
import importlib.util
|
|
269
|
+
import subprocess
|
|
270
|
+
|
|
271
|
+
tests_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tests")
|
|
272
|
+
if not os.path.isdir(tests_dir):
|
|
273
|
+
logging.error(
|
|
274
|
+
"The test suite is not part of an installed strainphase. Clone "
|
|
275
|
+
"https://github.com/rolesucsd/strainphase and run: "
|
|
276
|
+
"pip install -e '.[dev]' && strainphase test"
|
|
277
|
+
)
|
|
278
|
+
return 1
|
|
279
|
+
if importlib.util.find_spec("pytest") is None:
|
|
280
|
+
logging.error("pytest is not installed. Run: pip install 'strainphase[dev]'")
|
|
281
|
+
return 1
|
|
282
|
+
cmd = [sys.executable, "-m", "pytest", tests_dir, "-v" if args.verbose else "-q"]
|
|
283
|
+
return subprocess.run(cmd).returncode
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def cmd_version(args: argparse.Namespace) -> int:
|
|
287
|
+
"""Show version information."""
|
|
288
|
+
print(f"strainphase {__version__}")
|
|
289
|
+
return 0
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
# Tuning flags shared by every subcommand that phases reads. `run` calls
|
|
293
|
+
# process_contig, which calls link_windows, so these gates already act on `run`.
|
|
294
|
+
# Declared once so `run` and `longitudinal` cannot drift.
|
|
295
|
+
def _add_phasing_args(p) -> None:
|
|
296
|
+
p.add_argument("--window-size", type=int, default=_D.window_size, help="Window size (bp)")
|
|
297
|
+
p.add_argument("--max-reads", type=int, default=_D.max_reads_per_window,
|
|
298
|
+
help="Max reads per window")
|
|
299
|
+
p.add_argument("--min-mapq", type=int, default=_D.min_mapq, help="Minimum MAPQ")
|
|
300
|
+
p.add_argument(
|
|
301
|
+
"--min-depth-site", type=int, default=_D.min_depth_site,
|
|
302
|
+
help="Min VCF DP to load a site. Set 1 for pre-called SNV lists (e.g. SNooPy) "
|
|
303
|
+
"where the BAM re-genotyping is the real depth gate.",
|
|
304
|
+
)
|
|
305
|
+
p.add_argument(
|
|
306
|
+
"--af-range", type=float, nargs=2, metavar=("LOW", "HIGH"), default=None,
|
|
307
|
+
help="Only load VCF sites whose alt-allele frequency falls in [LOW, HIGH]. "
|
|
308
|
+
"Off by default, which loads every site that clears --min-depth-site.",
|
|
309
|
+
)
|
|
310
|
+
p.add_argument(
|
|
311
|
+
"--seed", type=int, default=_D.random_seed,
|
|
312
|
+
help="Random seed. Seeded by default: it drives both read subsampling above "
|
|
313
|
+
"--max-reads and Louvain read clustering, so an unseeded run is not "
|
|
314
|
+
"reproducible.",
|
|
315
|
+
)
|
|
316
|
+
# --- depth policy ---
|
|
317
|
+
p.add_argument(
|
|
318
|
+
"--min-reads-per-window", type=int, default=_D.min_reads_per_window,
|
|
319
|
+
help="Reads needed to PHASE a window de novo.",
|
|
320
|
+
)
|
|
321
|
+
p.add_argument(
|
|
322
|
+
"--min-reads-for-rescue", type=int, default=_D.min_reads_for_rescue,
|
|
323
|
+
help="Reads needed for a window to be BUILT, so rescue can still populate it.",
|
|
324
|
+
)
|
|
325
|
+
# --- identity: ONE rate, and per-stage evidence ---
|
|
326
|
+
p.add_argument(
|
|
327
|
+
"--identity-distance", type=float, default=_D.identity_distance,
|
|
328
|
+
help="Max mismatch RATE at which two things are one entity. ONE rate for every "
|
|
329
|
+
"comparison - read to read, haplotype to haplotype, and rescue. How much "
|
|
330
|
+
"evidence each needs first is a separate per-stage threshold.",
|
|
331
|
+
)
|
|
332
|
+
p.add_argument(
|
|
333
|
+
"--min-shared-markers", type=int, default=_D.min_shared_markers,
|
|
334
|
+
help="Shared markers required before that rate means anything, comparing two "
|
|
335
|
+
"haplotype consensuses.",
|
|
336
|
+
)
|
|
337
|
+
p.add_argument(
|
|
338
|
+
"--min-shared-snvs-for-link", type=int, default=_D.min_shared_snvs_for_link,
|
|
339
|
+
help="Shared SNV POSITIONS two overlapping windows need before their haplotypes "
|
|
340
|
+
"are compared at all. A cheap precheck for --min-shared-markers.",
|
|
341
|
+
)
|
|
342
|
+
p.add_argument(
|
|
343
|
+
"--min-overlap-bp", type=int, default=_D.min_entity_overlap_bp,
|
|
344
|
+
help="Physical overlap two things must share before they are compared at all - "
|
|
345
|
+
"read against window, read against read, and entity against entity.",
|
|
346
|
+
)
|
|
347
|
+
p.add_argument(
|
|
348
|
+
"--min-cosupported-span-frac", type=float, default=_D.min_cosupported_span_frac,
|
|
349
|
+
help="Min co-supported span between two haplotypes as a fraction of their "
|
|
350
|
+
"shared region.",
|
|
351
|
+
)
|
|
352
|
+
# --- abundance: one threshold for every abundance verdict ---
|
|
353
|
+
p.add_argument(
|
|
354
|
+
"--abundance-coherence-alpha", type=float, default=_D.abundance_coherence_alpha,
|
|
355
|
+
help="Significance at which two read counts are declared incompatible "
|
|
356
|
+
"abundances. Step 1's eliminator and the merge's gap-filling test share it.",
|
|
357
|
+
)
|
|
358
|
+
p.add_argument(
|
|
359
|
+
"--min-reads-for-coherence", type=int, default=_D.min_reads_for_coherence,
|
|
360
|
+
help="Reads a window needs before its abundance is tested at all.",
|
|
361
|
+
)
|
|
362
|
+
# --- step-1 linking ---
|
|
363
|
+
p.add_argument(
|
|
364
|
+
"--link-window-reach", type=int, default=_D.link_window_reach,
|
|
365
|
+
help="How many windows ahead step 1 may link. 1 is the overlap-only rule; above "
|
|
366
|
+
"1 also links NON-overlapping windows on shared reads.",
|
|
367
|
+
)
|
|
368
|
+
p.add_argument(
|
|
369
|
+
"--link-min-shared-reads", type=int, default=_D.link_min_shared_reads,
|
|
370
|
+
help="Reads two haplotypes must share to link a NON-overlapping window pair. "
|
|
371
|
+
"Consensus cannot gate those, so this is the whole evidence bar.",
|
|
372
|
+
)
|
|
373
|
+
p.add_argument(
|
|
374
|
+
"--link-shared-read-frac", type=float, default=_D.link_shared_read_frac,
|
|
375
|
+
help="Coverage-invariant add-on to --link-min-shared-reads: a NON-overlapping link "
|
|
376
|
+
"also needs shared reads >= this fraction of each haplotype's continuing "
|
|
377
|
+
"reads. Scales the bar with depth so high coverage stops over-merging. "
|
|
378
|
+
"0.0 = off (default); ~0.25 is a good starting value.",
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
# Flags that only mean something with MANY samples: the cross-sample merge, the
|
|
383
|
+
# cross-timepoint anchor panel, and the multi-sample driver's memory behaviour.
|
|
384
|
+
def _add_longitudinal_args(p) -> None:
|
|
385
|
+
p.add_argument(
|
|
386
|
+
"--track-merge-min-shared-markers", type=int,
|
|
387
|
+
default=_D.track_merge_min_shared_markers,
|
|
388
|
+
help="Agreeing markers two step-1 tracks need before the cross-sample merge "
|
|
389
|
+
"joins them. 1 is a permissive first pass.",
|
|
390
|
+
)
|
|
391
|
+
p.add_argument("--min-anchor-weight", type=float, default=_D.min_weight_for_anchor,
|
|
392
|
+
help="Min weight for anchor")
|
|
393
|
+
p.add_argument("--rescued-min-weight", type=float, default=_D.rescued_min_weight,
|
|
394
|
+
help="Min weight after rescue")
|
|
395
|
+
p.add_argument(
|
|
396
|
+
"--no-spill", action="store_true",
|
|
397
|
+
help="Keep every sample's reads in memory until the whole MAG finishes.",
|
|
398
|
+
)
|
|
399
|
+
p.add_argument(
|
|
400
|
+
"--window-batch-factor", type=int, default=_D.window_batch_factor,
|
|
401
|
+
help="Windows are dispatched to the worker pool in batches of workers * this. "
|
|
402
|
+
"Lower it to cut peak memory on variant-dense contigs.",
|
|
403
|
+
)
|
|
404
|
+
p.add_argument(
|
|
405
|
+
"--mem-profile", action="store_true",
|
|
406
|
+
help="Trace peak memory with tracemalloc and log the top allocation sites at the "
|
|
407
|
+
"integration point. Diagnostic only; adds tracing overhead.",
|
|
408
|
+
)
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def cmd_sv(args) -> int:
|
|
412
|
+
from strainphase.sv_encoding import run_sv
|
|
413
|
+
|
|
414
|
+
return run_sv(args.sv_args)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def main(argv: list | None = None) -> int:
|
|
418
|
+
"""Main entry point."""
|
|
419
|
+
parser = argparse.ArgumentParser(
|
|
420
|
+
prog="strainphase",
|
|
421
|
+
description="Hybrid graph-probabilistic haplotype reconstruction for PacBio HiFi metagenomic data",
|
|
422
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
423
|
+
epilog="""
|
|
424
|
+
Examples:
|
|
425
|
+
# Process single contig
|
|
426
|
+
strainphase run --bam sample.bam --vcf variants.vcf.gz --contig ctg1 --length 50000
|
|
427
|
+
|
|
428
|
+
# Longitudinal analysis
|
|
429
|
+
strainphase longitudinal --samples T1,T2,T3 \\
|
|
430
|
+
--bams mapping/{sample}.bam --vcfs variants/{sample}.vcf.gz \\
|
|
431
|
+
--reference ref.fasta --output-dir results/
|
|
432
|
+
|
|
433
|
+
# Run tests
|
|
434
|
+
strainphase test
|
|
435
|
+
""",
|
|
436
|
+
)
|
|
437
|
+
parser.add_argument(
|
|
438
|
+
"-V",
|
|
439
|
+
"--version",
|
|
440
|
+
action="version",
|
|
441
|
+
version=f"%(prog)s {__version__}",
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
subparsers = parser.add_subparsers(dest="command", help="Available commands")
|
|
445
|
+
|
|
446
|
+
# =========== RUN subcommand ===========
|
|
447
|
+
run_parser = subparsers.add_parser(
|
|
448
|
+
"run",
|
|
449
|
+
help="Process a single contig",
|
|
450
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
451
|
+
)
|
|
452
|
+
run_parser.add_argument("--bam", required=True, help="Input BAM file")
|
|
453
|
+
run_parser.add_argument("--vcf", required=True, help="Input VCF file (Clair3)")
|
|
454
|
+
run_parser.add_argument("--contig", required=True, help="Contig ID to process")
|
|
455
|
+
run_parser.add_argument("--length", type=int, required=True, help="Contig length")
|
|
456
|
+
run_parser.add_argument("--sample", help="Sample ID")
|
|
457
|
+
run_parser.add_argument("--vcf-sample", help="Sample name in VCF")
|
|
458
|
+
run_parser.add_argument("--output", "-o", default="haplotypes.tsv", help="Output file")
|
|
459
|
+
run_parser.add_argument(
|
|
460
|
+
"--log-level", default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR"]
|
|
461
|
+
)
|
|
462
|
+
_add_phasing_args(run_parser)
|
|
463
|
+
run_parser.set_defaults(func=cmd_run)
|
|
464
|
+
|
|
465
|
+
# =========== LONGITUDINAL subcommand ===========
|
|
466
|
+
long_parser = subparsers.add_parser(
|
|
467
|
+
"longitudinal",
|
|
468
|
+
help="Process MAG across multiple timepoints",
|
|
469
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
470
|
+
)
|
|
471
|
+
long_parser.add_argument("--samples", required=True, help="Comma-separated sample IDs")
|
|
472
|
+
long_parser.add_argument("--bams", required=True, help="BAM path template with {sample}")
|
|
473
|
+
long_parser.add_argument("--vcfs", required=True, help="VCF path template with {sample}")
|
|
474
|
+
long_parser.add_argument(
|
|
475
|
+
"--sv-sidecars",
|
|
476
|
+
help="Optional SV sidecar TSV template with {sample} "
|
|
477
|
+
"(from strainphase.sv_encoding) to co-phase structural variants",
|
|
478
|
+
)
|
|
479
|
+
long_parser.add_argument("--reference", required=True, help="Reference FASTA")
|
|
480
|
+
long_parser.add_argument("--output-dir", "-o", required=True, help="Output directory")
|
|
481
|
+
long_parser.add_argument("--mags", help="Comma-separated MAG names (default: all)")
|
|
482
|
+
long_parser.add_argument("--contig-filter", help="File with allowed contig names")
|
|
483
|
+
long_parser.add_argument(
|
|
484
|
+
"-j",
|
|
485
|
+
"--workers",
|
|
486
|
+
type=int,
|
|
487
|
+
default=1,
|
|
488
|
+
help="Parallel worker processes for within-MAG window processing "
|
|
489
|
+
"(default: 1). Set to --cpus-per-task so reserved cores are used.",
|
|
490
|
+
)
|
|
491
|
+
long_parser.add_argument(
|
|
492
|
+
"--log-level", default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR"]
|
|
493
|
+
)
|
|
494
|
+
_add_phasing_args(long_parser)
|
|
495
|
+
_add_longitudinal_args(long_parser)
|
|
496
|
+
long_parser.set_defaults(func=cmd_longitudinal)
|
|
497
|
+
|
|
498
|
+
# =========== SV subcommand ===========
|
|
499
|
+
sv_parser = subparsers.add_parser(
|
|
500
|
+
"sv", help="SV sidecar tools (reconcile, verify)",
|
|
501
|
+
)
|
|
502
|
+
sv_parser.add_argument(
|
|
503
|
+
"sv_args", nargs=argparse.REMAINDER,
|
|
504
|
+
help="{reconcile,verify} plus that tool's own arguments",
|
|
505
|
+
)
|
|
506
|
+
sv_parser.set_defaults(func=cmd_sv)
|
|
507
|
+
|
|
508
|
+
# =========== TEST subcommand ===========
|
|
509
|
+
test_parser = subparsers.add_parser(
|
|
510
|
+
"test",
|
|
511
|
+
help="Run test suite",
|
|
512
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
513
|
+
)
|
|
514
|
+
test_parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output")
|
|
515
|
+
test_parser.set_defaults(func=cmd_test)
|
|
516
|
+
|
|
517
|
+
# =========== VERSION subcommand ===========
|
|
518
|
+
version_parser = subparsers.add_parser("version", help="Show version")
|
|
519
|
+
version_parser.set_defaults(func=cmd_version)
|
|
520
|
+
|
|
521
|
+
# Parse and execute
|
|
522
|
+
args = parser.parse_args(argv)
|
|
523
|
+
|
|
524
|
+
if args.command is None:
|
|
525
|
+
parser.print_help()
|
|
526
|
+
return 0
|
|
527
|
+
|
|
528
|
+
return args.func(args)
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
if __name__ == "__main__":
|
|
532
|
+
sys.exit(main())
|
strainphase/coherence.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Abundance-coherence checking.
|
|
3
|
+
|
|
4
|
+
Single timepoint only. A genome cannot hold two frequencies at one locus at one
|
|
5
|
+
time, so two windows merged into one entity within one sample must agree on
|
|
6
|
+
abundance to within sampling error; applied across timepoints this would reject
|
|
7
|
+
real dynamics, so it never compares different samples.
|
|
8
|
+
|
|
9
|
+
The test is Fisher's exact on ``[[k1, n1-k1], [k2, n2-k2]]`` over the raw counts
|
|
10
|
+
(``k`` = supporting reads, ``n`` = non-junk reads), not the derived ``abundance``.
|
|
11
|
+
A likelihood test rather than a fixed cutoff so it self-tightens as depth grows.
|
|
12
|
+
See docs/design/coherence.md.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
from scipy.stats import fisher_exact
|
|
20
|
+
|
|
21
|
+
from strainphase.core import DEFAULT_CONFIG, HaplotyperConfig
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"CoherenceResult",
|
|
25
|
+
"abundance_coherent",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class CoherenceResult:
|
|
31
|
+
coherent: bool
|
|
32
|
+
n_tested: int
|
|
33
|
+
n_incoherent: int
|
|
34
|
+
min_p: float
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def abundance_coherent(
|
|
38
|
+
counts: list[tuple[int, int]],
|
|
39
|
+
config: HaplotyperConfig = DEFAULT_CONFIG,
|
|
40
|
+
) -> CoherenceResult:
|
|
41
|
+
"""Are these ``(supporting_reads, non_junk_reads)`` pairs mutually compatible?
|
|
42
|
+
|
|
43
|
+
``counts`` are per-window raw counts for one entity in one sample. Windows below
|
|
44
|
+
``min_reads_for_coherence`` are excluded, not failed: at low depth the test has no
|
|
45
|
+
power. Coherent unless more than half the tested pairs are incoherent; at exactly
|
|
46
|
+
half it still merges, so a single unlucky pair cannot veto a merge. See
|
|
47
|
+
docs/design/coherence.md.
|
|
48
|
+
"""
|
|
49
|
+
usable = [(k, n) for k, n in counts if n >= config.min_reads_for_coherence]
|
|
50
|
+
if len(usable) < 2:
|
|
51
|
+
# Not enough evidence to reject; absence of a test is not a failure.
|
|
52
|
+
return CoherenceResult(True, 0, 0, 1.0)
|
|
53
|
+
|
|
54
|
+
n_tested = 0
|
|
55
|
+
n_incoherent = 0
|
|
56
|
+
min_p = 1.0
|
|
57
|
+
for i in range(len(usable)):
|
|
58
|
+
for j in range(i + 1, len(usable)):
|
|
59
|
+
k1, n1 = usable[i]
|
|
60
|
+
k2, n2 = usable[j]
|
|
61
|
+
table = [[k1, max(n1 - k1, 0)], [k2, max(n2 - k2, 0)]]
|
|
62
|
+
p = float(fisher_exact(table)[1])
|
|
63
|
+
n_tested += 1
|
|
64
|
+
min_p = min(min_p, p)
|
|
65
|
+
if p < config.abundance_coherence_alpha:
|
|
66
|
+
n_incoherent += 1
|
|
67
|
+
|
|
68
|
+
coherent = n_incoherent <= n_tested / 2
|
|
69
|
+
return CoherenceResult(coherent, n_tested, n_incoherent, min_p)
|