degrseq 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.
degrseq/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """degrseq: subcommands for the rnadegradome pipeline."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ # pyproject.toml is the single source of the version.
6
+ __version__ = version("degrseq")
7
+
8
+ __all__ = ["__version__"]
degrseq/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Enable `python -m degrseq`."""
2
+
3
+ from degrseq.cli import main
4
+
5
+ main()
degrseq/cap_class.py ADDED
@@ -0,0 +1,271 @@
1
+ """Capped / noncapped 5' end features of a replicate group (EndClass, numeric part).
2
+
3
+ Implements specs/cap-class.md (approved 18/11/2026; DL-074-DL-076, DL-080, DL-081, DL-083,
4
+ DL-085, DL-086).
5
+ """
6
+
7
+ import argparse
8
+ import json
9
+ import math
10
+ import sys
11
+ from collections.abc import Sequence
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+
17
+ from degrseq.kde_peaks import KdePeaksError, data_lines, per_nt, read_bedgraph, read_lengths
18
+
19
+ SCHEMA_VERSION = 1
20
+ STRANDS = (("+", "plus"), ("-", "minus"))
21
+
22
+
23
+ class CapClassError(Exception):
24
+ pass
25
+
26
+
27
+ @dataclass
28
+ class Region:
29
+ chrom: str
30
+ start: int
31
+ end: int
32
+ name: str
33
+ strand: str
34
+
35
+
36
+ @dataclass
37
+ class Feature:
38
+ chrom: str
39
+ start: int # trimmed
40
+ end: int # trimmed, exclusive
41
+ strand: str
42
+ name: str # input region name
43
+ peak: int # offset from start
44
+ total: float = 0.0
45
+ ug: float = 0.0
46
+ fraction: float = 0.0
47
+
48
+ def key(self) -> tuple:
49
+ return (self.chrom, self.start, self.end, 0 if self.strand == "+" else 1)
50
+
51
+
52
+ def parse_args(argv: Sequence[str]) -> argparse.Namespace:
53
+ parser = argparse.ArgumentParser(
54
+ prog="degrseq cap-class",
55
+ description="Sum replicates, trim features, split capped / noncapped by uG fraction.",
56
+ )
57
+ for flag, what in (
58
+ ("--ends_plus", "5P ends (TSO-masked), plus"),
59
+ ("--ends_minus", "5P ends (TSO-masked), minus"),
60
+ ("--ug_plus", "cap (uG) track, plus"),
61
+ ("--ug_minus", "cap (uG) track, minus"),
62
+ ):
63
+ parser.add_argument(
64
+ flag, required=True, nargs="+", help=f"{what}: one bedgraph per replicate"
65
+ )
66
+ parser.add_argument("--features", required=True, help="replicable regions, BED6")
67
+ parser.add_argument("--lengths", required=True, help="chromosome lengths (name, length)")
68
+ parser.add_argument("--min_uug", type=float, default=0.1, help="capped if uG fraction >= this")
69
+ parser.add_argument(
70
+ "--min_reads", type=float, default=1.0, help="drop features with fewer 5P reads"
71
+ )
72
+ parser.add_argument("--decimals", type=int, default=4, help="decimals of the sum bedgraphs")
73
+ parser.add_argument("--nanopare_compat", action="store_true", help="reproduce nanoPARE quirks")
74
+ parser.add_argument("--prefix", required=True, help="output file prefix")
75
+ args = parser.parse_args(argv)
76
+ n = len(args.ends_plus)
77
+ if not len(args.ends_minus) == len(args.ug_plus) == len(args.ug_minus) == n:
78
+ parser.error(
79
+ "--ends_plus, --ends_minus, --ug_plus, --ug_minus need one file per replicate each"
80
+ )
81
+ if not (math.isfinite(args.min_uug) and 0 <= args.min_uug <= 1):
82
+ parser.error("--min_uug must be in [0, 1]")
83
+ if not (math.isfinite(args.min_reads) and args.min_reads >= 0):
84
+ parser.error("--min_reads must be >= 0")
85
+ if not 0 <= args.decimals <= 10:
86
+ parser.error("--decimals must be 0-10")
87
+ return args
88
+
89
+
90
+ def read_regions(path: str, lengths: dict[str, int]) -> list[Region]:
91
+ regions = []
92
+ for number, fields in data_lines(path):
93
+ try:
94
+ chrom, start, end, name, strand = (
95
+ fields[0],
96
+ int(fields[1]),
97
+ int(fields[2]),
98
+ fields[3],
99
+ fields[5],
100
+ )
101
+ except (IndexError, ValueError):
102
+ raise CapClassError(f"{path}:{number}: expected BED6") from None
103
+ if chrom not in lengths:
104
+ raise CapClassError(f"{path}:{number}: chromosome {chrom!r} not in --lengths")
105
+ if not 0 <= start < end <= lengths[chrom]:
106
+ raise CapClassError(f"{path}:{number}: interval outside chromosome {chrom!r}")
107
+ if strand not in ("+", "-"):
108
+ raise CapClassError(f"{path}:{number}: strand must be + or -")
109
+ regions.append(Region(chrom, start, end, name, strand))
110
+ return regions
111
+
112
+
113
+ def round2_python(values: np.ndarray) -> np.ndarray:
114
+ """Python round(x, 2) per value (exact decimal rounding)."""
115
+ out = np.zeros_like(values)
116
+ for i in np.flatnonzero(values):
117
+ out[i] = round(float(values[i]), 2)
118
+ return out
119
+
120
+
121
+ def read_tracks(paths: list[str], lengths: dict[str, int]) -> list[dict[str, list]]:
122
+ return [read_bedgraph(p, lengths).rows for p in paths]
123
+
124
+
125
+ def chrom_sum(tracks: list[dict[str, list]], chrom: str, size: int, compat: bool) -> np.ndarray:
126
+ """Rule 1: per-nt sum over replicates; compat: 2 decimals, position-0-only signal dropped."""
127
+ arr = np.zeros(size)
128
+ for rows in tracks:
129
+ if chrom in rows:
130
+ arr += per_nt(rows[chrom], size)
131
+ if compat:
132
+ arr = round2_python(arr)
133
+ nz = np.flatnonzero(arr)
134
+ if len(nz) == 1 and nz[0] == 0: # quirk 37
135
+ arr[0] = 0.0
136
+ return arr
137
+
138
+
139
+ def bedgraph_rows(arr: np.ndarray, text) -> list[tuple[int, int, str]]:
140
+ """Rule 2: non-zero positions, neighbours with equal written value merged."""
141
+ rows: list[tuple[int, int, str]] = []
142
+ for i in np.flatnonzero(arr):
143
+ t = text(float(arr[i]))
144
+ if rows and rows[-1][1] == i and rows[-1][2] == t:
145
+ rows[-1] = (rows[-1][0], i + 1, t)
146
+ else:
147
+ rows.append((int(i), int(i) + 1, t))
148
+ return rows
149
+
150
+
151
+ def auto_cutoff(fractions: list[float]) -> float:
152
+ """Compat --min_uug 0: lowest-count 0.01 bin(s) among bins 0-24; mean of their lower edges."""
153
+ hist = histogram(fractions)
154
+ low = min(hist[:25])
155
+ tied = [b for b in range(25) if hist[b] == low]
156
+ return sum(b / 100 for b in tied) / len(tied)
157
+
158
+
159
+ def histogram(fractions: list[float]) -> list[int]:
160
+ hist = [0] * 101
161
+ for f in fractions:
162
+ hist[min(100, math.floor(f * 100))] += 1
163
+ return hist
164
+
165
+
166
+ def process(args: argparse.Namespace, lengths: dict[str, int]):
167
+ compat = args.nanopare_compat
168
+ text = (lambda v: str(v)) if compat else (lambda v: f"{v:.{args.decimals}f}")
169
+ inputs = {
170
+ ("5P", "+"): read_tracks(args.ends_plus, lengths),
171
+ ("5P", "-"): read_tracks(args.ends_minus, lengths),
172
+ ("uG", "+"): read_tracks(args.ug_plus, lengths),
173
+ ("uG", "-"): read_tracks(args.ug_minus, lengths),
174
+ }
175
+ regions = read_regions(args.features, lengths)
176
+ by_chrom: dict[str, list[Region]] = {}
177
+ for r in regions:
178
+ by_chrom.setdefault(r.chrom, []).append(r)
179
+ stats = {"regions_in": len(regions), "dropped_zero_signal": 0, "dropped_below_min_reads": 0}
180
+ sums: dict[tuple, dict[str, list]] = {k: {} for k in inputs}
181
+ trimmed: list[Feature] = []
182
+ kept: list[Feature] = []
183
+
184
+ for chrom, size in lengths.items(): # one chromosome in memory at a time
185
+ arr = {k: chrom_sum(v, chrom, size, compat) for k, v in inputs.items()}
186
+ for k in inputs:
187
+ sums[k][chrom] = bedgraph_rows(arr[k], text)
188
+ feats = []
189
+ for r in by_chrom.get(chrom, []):
190
+ nz = np.flatnonzero(arr[("5P", r.strand)][r.start : r.end])
191
+ if not len(nz):
192
+ stats["dropped_zero_signal"] += 1
193
+ continue
194
+ a, b = r.start + int(nz[0]), r.start + int(nz[-1]) + 1
195
+ span = arr[("5P", r.strand)][a:b]
196
+ peak = int(len(span) - 1 - np.argmax(span[::-1])) # rightmost maximum
197
+ feats.append(Feature(chrom, a, b, r.strand, r.name, peak))
198
+ feats.sort(key=Feature.key)
199
+ trimmed += feats
200
+ for f in feats:
201
+ end = f.end + 1 if compat else f.end # quirk 15
202
+ five = arr[("5P", f.strand)][f.start : end]
203
+ ug = arr[("uG", f.strand)][f.start : end]
204
+ if compat:
205
+ f.total, f.ug = sum(float(x) for x in five), sum(float(x) for x in ug)
206
+ else:
207
+ f.total, f.ug = math.fsum(five), math.fsum(ug)
208
+ if f.total < args.min_reads:
209
+ stats["dropped_below_min_reads"] += 1
210
+ continue
211
+ f.fraction = f.ug / f.total if f.total else 0.0
212
+ if not compat and f.fraction > 1 + 1e-9:
213
+ raise CapClassError(
214
+ f"uG exceeds 5P in feature {chrom}:{f.start}-{f.end} {f.strand}; "
215
+ "cap track counted per G (compat end-counts)? "
216
+ "use --nanopare_compat for both (DL-074)"
217
+ )
218
+ kept.append(f)
219
+
220
+ cutoff = args.min_uug
221
+ if compat and cutoff == 0:
222
+ cutoff = auto_cutoff([f.fraction for f in kept])
223
+ capped = [f for f in kept if f.fraction >= cutoff]
224
+ noncapped = [f for f in kept if f.fraction < cutoff]
225
+ stats.update(
226
+ schema_version=SCHEMA_VERSION,
227
+ mode="nanopare_compat" if compat else "default",
228
+ replicates=len(args.ends_plus),
229
+ min_uug=cutoff,
230
+ min_reads=args.min_reads,
231
+ capped={s: sum(f.strand == s for f in capped) for s, _ in STRANDS},
232
+ noncapped={s: sum(f.strand == s for f in noncapped) for s, _ in STRANDS},
233
+ ug_fraction_histogram=histogram([f.fraction for f in kept]),
234
+ )
235
+ return sums, trimmed, capped, noncapped, stats
236
+
237
+
238
+ def write_outputs(args, lengths, sums, trimmed, capped, noncapped, stats) -> None:
239
+ compat = args.nanopare_compat
240
+ chroms = sorted(lengths) if compat else list(lengths)
241
+ for kind, tag in (("5P", ""), ("uG", "uG.")):
242
+ for st, label in STRANDS:
243
+ with open(f"{args.prefix}.{tag}{label}.bedgraph", "w", encoding="utf-8") as out:
244
+ for chrom in chroms:
245
+ for a, b, t in sums[(kind, st)][chrom]:
246
+ out.write(f"{chrom}\t{a}\t{b}\t{t}\n")
247
+ with open(f"{args.prefix}.peaks.bed", "w", encoding="utf-8") as out:
248
+ for f in trimmed:
249
+ out.write(f"{f.chrom}\t{f.start}\t{f.end}\t{f.name}\t{f.peak}\t{f.strand}\n")
250
+ for label, feats in (("capped", capped), ("noncapped", noncapped)):
251
+ with open(f"{args.prefix}.{label}.bed", "w", encoding="utf-8") as out:
252
+ for n, f in enumerate(feats, 1):
253
+ end, peak = (f.end + 1, f.peak + 1) if compat else (f.end, f.peak)
254
+ frac = str(round(f.fraction, 3)) if compat else f"{f.fraction:.3f}"
255
+ out.write(
256
+ f"{f.chrom}\t{f.start}\t{end}\t5P.{label}.{n}\t{peak}\t{f.strand}\t.\t.\t.\t{frac}\n"
257
+ )
258
+ Path(f"{args.prefix}.cap-class.stats.json").write_text(
259
+ json.dumps(stats, indent=2, sort_keys=True) + "\n", encoding="utf-8"
260
+ )
261
+
262
+
263
+ def main(argv: Sequence[str]) -> None:
264
+ args = parse_args(argv)
265
+ try:
266
+ lengths = read_lengths(args.lengths)
267
+ sums, trimmed, capped, noncapped, stats = process(args, lengths)
268
+ except (CapClassError, KdePeaksError, OSError) as error:
269
+ print(f"degrseq cap-class: error: {error}", file=sys.stderr)
270
+ sys.exit(1)
271
+ write_outputs(args, lengths, sums, trimmed, capped, noncapped, stats)