consenrich 0.7.4b2__cp312-cp312-macosx_10_13_x86_64.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.
consenrich/matching.py ADDED
@@ -0,0 +1,901 @@
1
+ # -*- coding: utf-8 -*-
2
+ r"""Module implementing (experimental) 'structured peak detection' features using wavelet-based templates."""
3
+
4
+ import logging
5
+ import os
6
+ import math
7
+ from pybedtools import BedTool
8
+ from typing import List, Optional
9
+
10
+ import pandas as pd
11
+ import pywt as pw
12
+ import numpy as np
13
+ import numpy.typing as npt
14
+
15
+ from scipy import signal, stats
16
+
17
+ from . import cconsenrich
18
+ from . import core as core
19
+
20
+ logging.basicConfig(
21
+ level=logging.INFO,
22
+ format="%(asctime)s - %(module)s.%(funcName)s - %(levelname)s - %(message)s",
23
+ )
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ def autoMinLengthIntervals(
28
+ values: np.ndarray, initLen: int = 3
29
+ ) -> int:
30
+ r"""Determines a minimum matching length (in interval units) based on the input signal values.
31
+
32
+ Returns the mean length of non-zero contiguous segments in a log-scaled/centered version of `values`
33
+
34
+ :param values: A 1D array of signal-like values.
35
+ :type values: np.ndarray
36
+ :param initLen: Initial minimum length (in intervals). Defaults to 3.
37
+ :type initLen: int
38
+ :return: Estimated minimum matching length (in intervals)
39
+ :rtype: int
40
+
41
+ """
42
+ trValues = np.asinh(values) - signal.medfilt(
43
+ np.asinh(values),
44
+ kernel_size=max(
45
+ (2 * initLen) + 1,
46
+ 2 * (int(len(values) * 0.005)) + 1,
47
+ ),
48
+ )
49
+ nz = trValues[trValues > 0]
50
+ if len(nz) == 0:
51
+ return initLen
52
+ thr = np.quantile(nz, 0.90, method="interpolated_inverted_cdf")
53
+ mask = nz >= thr
54
+ if not np.any(mask):
55
+ return initLen
56
+ idx = np.flatnonzero(np.diff(np.r_[False, mask, False]))
57
+ runs = idx.reshape(-1, 2)
58
+ widths = runs[:, 1] - runs[:, 0]
59
+ widths = widths[widths >= initLen]
60
+ if len(widths) == 0:
61
+ return initLen
62
+ return int(np.mean(widths))
63
+
64
+
65
+ def scalarClip(value: float, low: float, high: float) -> float:
66
+ return low if value < low else high if value > high else value
67
+
68
+
69
+ def castableToFloat(value) -> bool:
70
+ if value is None:
71
+ return False
72
+ if isinstance(value, bool):
73
+ return False
74
+ if isinstance(value, str):
75
+ if value.lower().replace(" ", "") in [
76
+ "nan",
77
+ "inf",
78
+ "-inf",
79
+ "infinity",
80
+ "-infinity",
81
+ "",
82
+ " ",
83
+ ]:
84
+ return False
85
+
86
+ try:
87
+ float(value)
88
+ if np.isfinite(float(value)):
89
+ return True
90
+ except Exception:
91
+ return False
92
+ return False
93
+
94
+
95
+ def matchExistingBedGraph(
96
+ bedGraphFile: str,
97
+ templateName: str,
98
+ cascadeLevel: int,
99
+ alpha: float = 0.05,
100
+ minMatchLengthBP: Optional[int] = 250,
101
+ iters: int = 25_000,
102
+ minSignalAtMaxima: Optional[float | str] = "q:0.75",
103
+ maxNumMatches: Optional[int] = 100_000,
104
+ recenterAtPointSource: bool = True,
105
+ useScalingFunction: bool = True,
106
+ excludeRegionsBedFile: Optional[str] = None,
107
+ mergeGapBP: Optional[int] = None,
108
+ merge: bool = True,
109
+ weights: Optional[npt.NDArray[np.float64]] = None,
110
+ randSeed: int = 42,
111
+ ) -> Optional[str]:
112
+ r"""Match discrete templates in a bedGraph file of Consenrich estimates
113
+
114
+ This function is a simple wrapper. See :func:`consenrich.matching.matchWavelet` for details on parameters.
115
+
116
+ :param bedGraphFile: A bedGraph file with 'consensus' signal estimates derived from multiple samples, e.g., from Consenrich. The suffix '.bedGraph' is required.
117
+ :type bedGraphFile: str
118
+
119
+ :seealso: :func:`consenrich.matching.matchWavelet`, :class:`consenrich.core.matchingParams`, :ref:`matching`
120
+ """
121
+ if not os.path.isfile(bedGraphFile):
122
+ raise FileNotFoundError(f"Couldn't access {bedGraphFile}")
123
+ if not bedGraphFile.endswith(".bedGraph"):
124
+ raise ValueError(
125
+ f"Please use a suffix '.bedGraph' for `bedGraphFile`, got: {bedGraphFile}"
126
+ )
127
+
128
+ if mergeGapBP is None:
129
+ mergeGapBP = (
130
+ (minMatchLengthBP // 2) + 1
131
+ if minMatchLengthBP is not None
132
+ else 75
133
+ )
134
+
135
+ allowedTemplates = [
136
+ x for x in pw.wavelist(kind="discrete") if "bio" not in x
137
+ ]
138
+ if templateName not in allowedTemplates:
139
+ raise ValueError(
140
+ f"Unknown wavelet template: {templateName}\nAvailable templates: {allowedTemplates}"
141
+ )
142
+
143
+ cols = ["chromosome", "start", "end", "value"]
144
+ bedGraphDF = pd.read_csv(
145
+ bedGraphFile,
146
+ sep="\t",
147
+ header=None,
148
+ names=cols,
149
+ dtype={
150
+ "chromosome": str,
151
+ "start": np.uint32,
152
+ "end": np.uint32,
153
+ "value": np.float64,
154
+ },
155
+ )
156
+
157
+ outPaths: List[str] = []
158
+ outPathsMerged: List[str] = []
159
+ outPathAll: Optional[str] = None
160
+ outPathMergedAll: Optional[str] = None
161
+
162
+ for chrom_ in sorted(bedGraphDF["chromosome"].unique()):
163
+ df_ = bedGraphDF[bedGraphDF["chromosome"] == chrom_]
164
+ if len(df_) < 5:
165
+ logger.info(f"Skipping {chrom_}: less than 5 intervals.")
166
+ continue
167
+
168
+ try:
169
+ df__ = matchWavelet(
170
+ chrom_,
171
+ df_["start"].to_numpy(),
172
+ df_["value"].to_numpy(),
173
+ [templateName],
174
+ [cascadeLevel],
175
+ iters,
176
+ alpha,
177
+ minMatchLengthBP,
178
+ maxNumMatches,
179
+ recenterAtPointSource=recenterAtPointSource,
180
+ useScalingFunction=useScalingFunction,
181
+ excludeRegionsBedFile=excludeRegionsBedFile,
182
+ weights=weights,
183
+ minSignalAtMaxima=minSignalAtMaxima,
184
+ randSeed=randSeed,
185
+ )
186
+ except Exception as ex:
187
+ logger.info(
188
+ f"Skipping {chrom_} due to error in matchWavelet: {ex}"
189
+ )
190
+ continue
191
+
192
+ if df__.empty:
193
+ logger.info(f"No matches detected on {chrom_}.")
194
+ continue
195
+
196
+ perChromOut = bedGraphFile.replace(
197
+ ".bedGraph",
198
+ f".{chrom_}.matched.{templateName}_lvl{cascadeLevel}.narrowPeak",
199
+ )
200
+ df__.to_csv(perChromOut, sep="\t", index=False, header=False)
201
+ logger.info(f"Matches written to {perChromOut}")
202
+ outPaths.append(perChromOut)
203
+
204
+ if merge:
205
+ mergedPath = mergeMatches(
206
+ perChromOut, mergeGapBP=mergeGapBP
207
+ )
208
+ if mergedPath is not None:
209
+ logger.info(f"Merged matches written to {mergedPath}")
210
+ outPathsMerged.append(mergedPath)
211
+
212
+ if len(outPaths) == 0 and len(outPathsMerged) == 0:
213
+ raise ValueError("No matches were detected.")
214
+
215
+ if len(outPaths) > 0:
216
+ outPathAll = (
217
+ f"{bedGraphFile.replace('.bedGraph', '')}"
218
+ f".allChroms.matched.{templateName}_lvl{cascadeLevel}.narrowPeak"
219
+ )
220
+ with open(outPathAll, "w") as outF:
221
+ for path_ in outPaths:
222
+ if os.path.isfile(path_):
223
+ with open(path_, "r") as inF:
224
+ for line in inF:
225
+ outF.write(line)
226
+ logger.info(f"All unmerged matches written to {outPathAll}")
227
+
228
+ if merge and len(outPathsMerged) > 0:
229
+ outPathMergedAll = (
230
+ f"{bedGraphFile.replace('.bedGraph', '')}"
231
+ f".allChroms.matched.{templateName}_lvl{cascadeLevel}.mergedMatches.narrowPeak"
232
+ )
233
+ with open(outPathMergedAll, "w") as outF:
234
+ for path in outPathsMerged:
235
+ if os.path.isfile(path):
236
+ with open(path, "r") as inF:
237
+ for line in inF:
238
+ outF.write(line)
239
+ logger.info(
240
+ f"All merged matches written to {outPathMergedAll}"
241
+ )
242
+
243
+ for path_ in outPaths + outPathsMerged:
244
+ try:
245
+ if os.path.isfile(path_):
246
+ os.remove(path_)
247
+ except Exception:
248
+ pass
249
+
250
+ if merge and outPathMergedAll:
251
+ return outPathMergedAll
252
+ if outPathAll:
253
+ return outPathAll
254
+ logger.warning("No matches were detected...returning `None`")
255
+ return None
256
+
257
+
258
+ def matchWavelet(
259
+ chromosome: str,
260
+ intervals: npt.NDArray[int],
261
+ values: npt.NDArray[np.float64],
262
+ templateNames: List[str],
263
+ cascadeLevels: List[int],
264
+ iters: int,
265
+ alpha: float = 0.05,
266
+ minMatchLengthBP: Optional[int] = 250,
267
+ maxNumMatches: Optional[int] = 100_000,
268
+ minSignalAtMaxima: Optional[float | str] = "q:0.75",
269
+ randSeed: int = 42,
270
+ recenterAtPointSource: bool = True,
271
+ useScalingFunction: bool = True,
272
+ excludeRegionsBedFile: Optional[str] = None,
273
+ weights: Optional[npt.NDArray[np.float64]] = None,
274
+ eps: float = 1.0e-2,
275
+ ) -> pd.DataFrame:
276
+ r"""Detect structured peaks in Consenrich tracks by matching wavelet- or scaling-function–based templates.
277
+
278
+ :param chromosome: Chromosome name for the input intervals and values.
279
+ :type chromosome: str
280
+ :param values: A 1D array of signal-like values. In this documentation, we refer to values derived from Consenrich,
281
+ but other continuous-valued tracks at evenly spaced genomic intervals may be suitable, too.
282
+ :type values: npt.NDArray[np.float64]
283
+ :param templateNames: A list of str values -- each entry references a mother wavelet (or its corresponding scaling function). e.g., `[haar, db2]`
284
+ :type templateNames: List[str]
285
+ :param cascadeLevels: Number of cascade iterations used to approximate each template (wavelet or scaling function).
286
+ Must have the same length as `templateNames`, with each entry aligned to the
287
+ corresponding template. e.g., given templateNames `[haar, db2]`, then `[2,2]` would use 2 cascade levels for both templates.
288
+ :type cascadeLevels: List[int]
289
+ :param iters: Number of random blocks to sample in the response sequence while building
290
+ an empirical null to test significance. See :func:`cconsenrich.csampleBlockStats`.
291
+ :type iters: int
292
+ :param alpha: Primary significance threshold on detected matches. Specifically, the
293
+ minimum corr. empirical p-value approximated from randomly sampled blocks in the
294
+ response sequence.
295
+ :type alpha: float
296
+ :param minMatchLengthBP: Within a window of `minMatchLengthBP` length (bp), relative maxima in
297
+ the signal-template convolution must be greater in value than others to qualify as matches.
298
+ If set to a value less than 1, the minimum length is determined via :func:`consenrich.matching.autoMinLengthIntervals`.
299
+ If set to `None`, defaults to 250 bp.
300
+ :type minMatchLengthBP: Optional[int]
301
+ :param minSignalAtMaxima: Secondary significance threshold coupled with `alpha`. Requires the *signal value*
302
+ at relative maxima in the response sequence to be greater than this threshold. Comparisons are made in log-scale
303
+ to temper genome-wide dynamic range. If a `float` value is provided, the minimum signal value must be greater
304
+ than this (absolute) value. *Set to a negative value to disable the threshold*.
305
+ If a `str` value is provided, looks for 'q:quantileValue', e.g., 'q:0.90'. The
306
+ threshold is then set to the corresponding quantile of the non-zero signal estimates.
307
+ Defaults to str value 'q:0.75' --- the 75th percentile of signal values.
308
+ :type minSignalAtMaxima: Optional[str | float]
309
+ :param useScalingFunction: If True, use (only) the scaling function to build the matching template.
310
+ If False, use (only) the wavelet function.
311
+ :type useScalingFunction: bool
312
+ :param excludeRegionsBedFile: A BED file with regions to exclude from matching
313
+ :type excludeRegionsBedFile: Optional[str]
314
+ :param recenterAtPointSource: If True, recenter detected matches at the point source (max value)
315
+ :type recenterAtPointSource: bool
316
+ :param weights: Optional weights to apply to `values` prior to matching. Must have the same length as `values`.
317
+ :type weights: Optional[npt.NDArray[np.float64]]
318
+ :param eps: Tolerance parameter for relative maxima detection in the response sequence. Set to zero to enforce strict
319
+ inequalities when identifying discrete relative maxima.
320
+ :type eps: float
321
+ :seealso: :class:`consenrich.core.matchingParams`, :func:`cconsenrich.csampleBlockStats`, :ref:`matching`
322
+ :return: A pandas DataFrame with detected matches
323
+ :rtype: pd.DataFrame
324
+ """
325
+
326
+ rng = np.random.default_rng(int(randSeed))
327
+ if len(intervals) < 5:
328
+ raise ValueError("`intervals` must be at least length 5")
329
+
330
+ if len(values) != len(intervals):
331
+ raise ValueError(
332
+ "`values` must have the same length as `intervals`"
333
+ )
334
+
335
+ if len(templateNames) != len(cascadeLevels):
336
+ raise ValueError(
337
+ "\n\t`templateNames` and `cascadeLevels` must have the same length."
338
+ "\n\tSet products are not supported, i.e., each template needs an explicitly defined cascade level."
339
+ "\t\ne.g., for `templateNames = [haar, db2]`, use `cascadeLevels = [2, 2]`, not `[2]`.\n"
340
+ )
341
+
342
+ intervalLengthBp = intervals[1] - intervals[0]
343
+
344
+ if minMatchLengthBP is not None and minMatchLengthBP < 1:
345
+ minMatchLengthBP = autoMinLengthIntervals(values) * int(
346
+ intervalLengthBp
347
+ )
348
+ elif minMatchLengthBP is None:
349
+ minMatchLengthBP = 250
350
+
351
+ logger.info(f"\n\tUsing minMatchLengthBP: {minMatchLengthBP}")
352
+
353
+ if not np.all(np.abs(np.diff(intervals)) == intervalLengthBp):
354
+ raise ValueError("`intervals` must be evenly spaced.")
355
+
356
+ if weights is not None:
357
+ if len(weights) != len(values):
358
+ logger.warning(
359
+ f"`weights` length {len(weights)} does not match `values` length {len(values)}. Ignoring..."
360
+ )
361
+ else:
362
+ values = values * weights
363
+
364
+ asinhValues = np.asinh(values, dtype=np.float32)
365
+ asinhNonZeroValues = asinhValues[asinhValues > 0]
366
+
367
+ iters = max(int(iters), 1000)
368
+ defQuantile = 0.75
369
+ chromMin = int(intervals[0])
370
+ chromMax = int(intervals[-1])
371
+ chromMid = chromMin + (chromMax - chromMin) // 2 # for split
372
+ halfLeftMask = intervals < chromMid
373
+ halfRightMask = ~halfLeftMask
374
+ excludeMaskGlobal = np.zeros(len(intervals), dtype=np.uint8)
375
+ if excludeRegionsBedFile is not None:
376
+ excludeMaskGlobal = core.getBedMask(
377
+ chromosome, excludeRegionsBedFile, intervals
378
+ ).astype(np.uint8)
379
+ allRows = []
380
+
381
+ def bhFdr(p: np.ndarray) -> np.ndarray:
382
+ m = len(p)
383
+ order = np.argsort(p, kind="mergesort")
384
+ ranked = np.arange(1, m + 1, dtype=float)
385
+ q = (p[order] * m) / ranked
386
+ q = np.minimum.accumulate(q[::-1])[::-1]
387
+ out = np.empty_like(q)
388
+ out[order] = q
389
+ return np.clip(out, 0.0, 1.0)
390
+
391
+ def parseMinSignalThreshold(val):
392
+ if val is None:
393
+ return -1e6
394
+ if isinstance(val, str):
395
+ if val.startswith("q:"):
396
+ qVal = float(val.split("q:")[-1])
397
+ if not (0 <= qVal <= 1):
398
+ raise ValueError(
399
+ f"Quantile {qVal} is out of range"
400
+ )
401
+ return float(
402
+ np.quantile(
403
+ asinhNonZeroValues,
404
+ qVal,
405
+ method="interpolated_inverted_cdf",
406
+ )
407
+ )
408
+ elif castableToFloat(val):
409
+ v = float(val)
410
+ return -1e6 if v < 0 else float(np.asinh(v))
411
+ else:
412
+ return float(
413
+ np.quantile(
414
+ asinhNonZeroValues,
415
+ defQuantile,
416
+ method="interpolated_inverted_cdf",
417
+ )
418
+ )
419
+ if isinstance(val, (float, int)):
420
+ v = float(val)
421
+ return -1e6 if v < 0 else float(np.asinh(v))
422
+ return float(
423
+ np.quantile(
424
+ asinhNonZeroValues,
425
+ defQuantile,
426
+ method="interpolated_inverted_cdf",
427
+ )
428
+ )
429
+
430
+ def relativeMaxima(
431
+ resp: np.ndarray, orderBins: int, eps: float = None
432
+ ) -> np.ndarray:
433
+ order_: int = max(int(orderBins), 1)
434
+ if eps is None:
435
+ eps = np.finfo(resp.dtype).eps * 10
436
+
437
+ def ge_with_tol(a, b):
438
+ return a > (b - eps)
439
+
440
+ # get initial set using loosened criterion
441
+ idx = signal.argrelextrema(
442
+ resp, comparator=ge_with_tol, order=order_
443
+ )[0]
444
+ if idx.size == 0:
445
+ return idx
446
+
447
+ if eps > 0.0:
448
+ groups = []
449
+ start, prev = idx[0], idx[0]
450
+ for x in idx[1:]:
451
+ # case: still contiguous
452
+ if x == prev + 1:
453
+ prev = x
454
+ else:
455
+ # case: a gap --> break off from previous group
456
+ groups.append((start, prev))
457
+ start = x
458
+ prev = x
459
+ groups.append((start, prev))
460
+
461
+ centers: list[int] = []
462
+ for s, e in groups:
463
+ if s == e:
464
+ centers.append(s)
465
+ else:
466
+ # for each `group` of tied indices, picks the center
467
+ centers.append((s + e) // 2)
468
+
469
+ return np.asarray(centers, dtype=np.intp)
470
+
471
+ return idx
472
+
473
+ def sampleBlockMaxima(
474
+ resp: np.ndarray,
475
+ halfMask: np.ndarray,
476
+ relWindowBins: int,
477
+ nsamp: int,
478
+ seed: int,
479
+ eps: float,
480
+ ):
481
+ exMask = excludeMaskGlobal.astype(np.uint8).copy()
482
+ exMask |= (~halfMask).astype(np.uint8)
483
+ vals = np.array(
484
+ cconsenrich.csampleBlockStats(
485
+ intervals.astype(np.uint32),
486
+ resp,
487
+ int(relWindowBins),
488
+ int(nsamp),
489
+ int(seed),
490
+ exMask.astype(np.uint8),
491
+ np.float64(eps if eps is not None else 0.0),
492
+ ),
493
+ dtype=float,
494
+ )
495
+ if len(vals) == 0:
496
+ return vals
497
+ low = np.quantile(vals, 0.001)
498
+ high = np.quantile(vals, 0.999)
499
+ return vals[(vals > low) & (vals < high)]
500
+
501
+ for templateName, cascadeLevel in zip(
502
+ templateNames, cascadeLevels
503
+ ):
504
+ if templateName not in pw.wavelist(kind="discrete"):
505
+ logger.warning(
506
+ f"Skipping unknown wavelet template: {templateName}"
507
+ )
508
+ continue
509
+
510
+ wav = pw.Wavelet(str(templateName))
511
+ scalingFunc, waveletFunc, _ = wav.wavefun(
512
+ level=int(cascadeLevel)
513
+ )
514
+ template = np.array(
515
+ scalingFunc if useScalingFunction else waveletFunc,
516
+ dtype=np.float64,
517
+ )
518
+ template /= np.linalg.norm(template)
519
+
520
+ logger.info(
521
+ f"\n\tMatching template: {templateName}"
522
+ f"\n\tcascade level: {cascadeLevel}"
523
+ f"\n\ttemplate length: {len(template)}"
524
+ )
525
+
526
+ # efficient FFT-based cross-correlation
527
+ # (OA may be better for smaller templates, TODO add a check)
528
+ response = signal.fftconvolve(
529
+ values, template[::-1], mode="same"
530
+ )
531
+ thisMinMatchBp = minMatchLengthBP
532
+ if thisMinMatchBp is None or thisMinMatchBp < 1:
533
+ thisMinMatchBp = len(template) * intervalLengthBp
534
+ if thisMinMatchBp % intervalLengthBp != 0:
535
+ thisMinMatchBp += intervalLengthBp - (
536
+ thisMinMatchBp % intervalLengthBp
537
+ )
538
+ relWindowBins = int(
539
+ ((thisMinMatchBp / intervalLengthBp) / 2) + 1
540
+ )
541
+ relWindowBins = max(relWindowBins, 1)
542
+ asinhThreshold = parseMinSignalThreshold(minSignalAtMaxima)
543
+ for nullMask, testMask, tag in [
544
+ (halfLeftMask, halfRightMask, "R"),
545
+ (halfRightMask, halfLeftMask, "L"),
546
+ ]:
547
+ blockMaxima = sampleBlockMaxima(
548
+ response,
549
+ nullMask,
550
+ relWindowBins,
551
+ nsamp=max(iters, 1000),
552
+ seed=rng.integers(1, 10_000),
553
+ eps=eps,
554
+ )
555
+ if len(blockMaxima) < 25:
556
+ pooledMask = ~excludeMaskGlobal.astype(bool)
557
+ blockMaxima = sampleBlockMaxima(
558
+ response,
559
+ pooledMask,
560
+ relWindowBins,
561
+ nsamp=max(iters, 1000),
562
+ seed=rng.integers(1, 10_000),
563
+ eps=eps,
564
+ )
565
+ ecdfSf = stats.ecdf(blockMaxima).sf
566
+ candidateIdx = relativeMaxima(
567
+ response, relWindowBins, eps=eps
568
+ )
569
+
570
+ candidateMask = (
571
+ (candidateIdx >= relWindowBins)
572
+ & (candidateIdx < len(response) - relWindowBins)
573
+ & (testMask[candidateIdx])
574
+ & (excludeMaskGlobal[candidateIdx] == 0)
575
+ & (asinhValues[candidateIdx] > asinhThreshold)
576
+ )
577
+
578
+ candidateIdx = candidateIdx[candidateMask]
579
+ if len(candidateIdx) == 0:
580
+ continue
581
+ if (
582
+ maxNumMatches is not None
583
+ and len(candidateIdx) > maxNumMatches
584
+ ):
585
+ candidateIdx = candidateIdx[
586
+ np.argsort(asinhValues[candidateIdx])[
587
+ -maxNumMatches:
588
+ ]
589
+ ]
590
+ pEmp = np.clip(
591
+ ecdfSf.evaluate(response[candidateIdx]),
592
+ 1.0e-10,
593
+ 1.0,
594
+ )
595
+ startsIdx = np.maximum(candidateIdx - relWindowBins, 0)
596
+ endsIdx = np.minimum(
597
+ len(values) - 1, candidateIdx + relWindowBins
598
+ )
599
+ pointSourcesIdx = []
600
+ for s, e in zip(startsIdx, endsIdx):
601
+ pointSourcesIdx.append(
602
+ np.argmax(values[s : e + 1]) + s
603
+ )
604
+ pointSourcesIdx = np.array(pointSourcesIdx)
605
+ starts = intervals[startsIdx]
606
+ ends = intervals[endsIdx]
607
+ pointSourcesAbs = (intervals[pointSourcesIdx]) + max(
608
+ 1, intervalLengthBp // 2
609
+ )
610
+ if recenterAtPointSource:
611
+ starts = pointSourcesAbs - (
612
+ relWindowBins * intervalLengthBp
613
+ )
614
+ ends = pointSourcesAbs + (
615
+ relWindowBins * intervalLengthBp
616
+ )
617
+ pointSourcesRel = (
618
+ intervals[pointSourcesIdx] - starts
619
+ ) + max(1, intervalLengthBp // 2)
620
+ sqScores = (1 + response[candidateIdx]) ** 2
621
+ minR, maxR = (
622
+ float(np.min(sqScores)),
623
+ float(np.max(sqScores)),
624
+ )
625
+ rangeR = max(maxR - minR, 1.0)
626
+ scores = (250 + 750 * (sqScores - minR) / rangeR).astype(
627
+ int
628
+ )
629
+ for i, idxVal in enumerate(candidateIdx):
630
+ allRows.append(
631
+ {
632
+ "chromosome": chromosome,
633
+ "start": int(starts[i]),
634
+ "end": int(ends[i]),
635
+ "name": f"{templateName}_{cascadeLevel}_{idxVal}_{tag}",
636
+ "score": int(scores[i]),
637
+ "strand": ".",
638
+ "signal": float(response[idxVal]),
639
+ "p_raw": float(pEmp[i]),
640
+ "pointSource": int(pointSourcesRel[i]),
641
+ }
642
+ )
643
+
644
+ if not allRows:
645
+ logger.warning(
646
+ "No matches detected, returning empty DataFrame."
647
+ )
648
+
649
+ return pd.DataFrame(
650
+ columns=[
651
+ "chromosome",
652
+ "start",
653
+ "end",
654
+ "name",
655
+ "score",
656
+ "strand",
657
+ "signal",
658
+ "pValue",
659
+ "qValue",
660
+ "pointSource",
661
+ ]
662
+ )
663
+
664
+ df = pd.DataFrame(allRows)
665
+ qVals = bhFdr(df["p_raw"].values.astype(float))
666
+ df["pValue"] = -np.log10(
667
+ np.clip(df["p_raw"].values, 1.0e-10, 1.0)
668
+ )
669
+ df["qValue"] = -np.log10(np.clip(qVals, 1.0e-10, 1.0))
670
+ df.drop(columns=["p_raw"], inplace=True)
671
+ df = df[qVals <= alpha].copy()
672
+ df["chromosome"] = df["chromosome"].astype(str)
673
+ df.sort_values(by=["chromosome", "start", "end"], inplace=True)
674
+ df.reset_index(drop=True, inplace=True)
675
+ df = df[
676
+ [
677
+ "chromosome",
678
+ "start",
679
+ "end",
680
+ "name",
681
+ "score",
682
+ "strand",
683
+ "signal",
684
+ "pValue",
685
+ "qValue",
686
+ "pointSource",
687
+ ]
688
+ ]
689
+ return df
690
+
691
+
692
+ def mergeMatches(
693
+ filePath: str,
694
+ mergeGapBP: Optional[int],
695
+ ) -> Optional[str]:
696
+ r"""Merge overlapping or nearby structured peaks ('matches') in a narrowPeak file.
697
+
698
+ The harmonic mean of p-values and q-values is computed for each merged region within `mergeGapBP` base pairs.
699
+ The fourth column (name) of each merged peak contains information about the number of features that were merged
700
+ and the range of q-values among them.
701
+
702
+ Expects a `narrowPeak <https://genome.ucsc.edu/FAQ/FAQformat.html#format12>`_ file as input (all numeric columns, '.' for strand if unknown).
703
+
704
+ :param filePath: narrowPeak file containing matches detected with :func:`consenrich.matching.matchWavelet`
705
+ :type filePath: str
706
+ :param mergeGapBP: Maximum gap size (in base pairs) to consider for merging. Defaults to 75 bp if `None` or less than 1.
707
+ :type mergeGapBP: Optional[int]
708
+
709
+ :seealso: :ref:`matching`, :class:`consenrich.core.matchingParams`
710
+ """
711
+
712
+ if mergeGapBP is None or mergeGapBP < 1:
713
+ mergeGapBP = 75
714
+
715
+ MAX_NEGLOGP = 10.0
716
+ MIN_NEGLOGP = 1.0e-10
717
+
718
+ if not os.path.isfile(filePath):
719
+ logger.warning(f"Couldn't access {filePath}...skipping merge")
720
+ return None
721
+ bed = None
722
+ try:
723
+ bed = BedTool(filePath)
724
+ except Exception as ex:
725
+ logger.warning(
726
+ f"Couldn't create BedTool for {filePath}:\n{ex}\n\nskipping merge..."
727
+ )
728
+ return None
729
+ if bed is None:
730
+ logger.warning(
731
+ f"Couldn't create BedTool for {filePath}...skipping merge"
732
+ )
733
+ return None
734
+
735
+ bed = bed.sort()
736
+ clustered = bed.cluster(d=mergeGapBP)
737
+ groups = {}
738
+ for f in clustered:
739
+ fields = f.fields
740
+ chrom = fields[0]
741
+ start = int(fields[1])
742
+ end = int(fields[2])
743
+ score = float(fields[4])
744
+ signal = float(fields[6])
745
+ pLog10 = float(fields[7])
746
+ qLog10 = float(fields[8])
747
+ peak = int(fields[9])
748
+ clusterID = fields[-1]
749
+ if clusterID not in groups:
750
+ groups[clusterID] = {
751
+ "chrom": chrom,
752
+ "sMin": start,
753
+ "eMax": end,
754
+ "scSum": 0.0,
755
+ "sigSum": 0.0,
756
+ "n": 0,
757
+ "maxS": float("-inf"),
758
+ "peakAbs": -1,
759
+ "pMax": float("-inf"),
760
+ "pTail": 0.0,
761
+ "pHasInf": False,
762
+ "qMax": float("-inf"),
763
+ "qMin": float("inf"),
764
+ "qTail": 0.0,
765
+ "qHasInf": False,
766
+ }
767
+ g = groups[clusterID]
768
+ if start < g["sMin"]:
769
+ g["sMin"] = start
770
+ if end > g["eMax"]:
771
+ g["eMax"] = end
772
+ g["scSum"] += score
773
+ g["sigSum"] += signal
774
+ g["n"] += 1
775
+
776
+ if math.isinf(pLog10) or pLog10 >= MAX_NEGLOGP:
777
+ g["pHasInf"] = True
778
+ else:
779
+ if pLog10 > g["pMax"]:
780
+ if g["pMax"] == float("-inf"):
781
+ g["pTail"] = 1.0
782
+ else:
783
+ g["pTail"] = (
784
+ g["pTail"] * (10 ** (g["pMax"] - pLog10))
785
+ + 1.0
786
+ )
787
+ g["pMax"] = pLog10
788
+ else:
789
+ g["pTail"] += 10 ** (pLog10 - g["pMax"])
790
+
791
+ if (
792
+ math.isinf(qLog10)
793
+ or qLog10 >= MAX_NEGLOGP
794
+ or qLog10 <= MIN_NEGLOGP
795
+ ):
796
+ g["qHasInf"] = True
797
+ else:
798
+ if qLog10 < g["qMin"]:
799
+ if qLog10 < MIN_NEGLOGP:
800
+ g["qMin"] = MIN_NEGLOGP
801
+ else:
802
+ g["qMin"] = qLog10
803
+
804
+ if qLog10 > g["qMax"]:
805
+ if g["qMax"] == float("-inf"):
806
+ g["qTail"] = 1.0
807
+ else:
808
+ g["qTail"] = (
809
+ g["qTail"] * (10 ** (g["qMax"] - qLog10))
810
+ + 1.0
811
+ )
812
+ g["qMax"] = qLog10
813
+ else:
814
+ g["qTail"] += 10 ** (qLog10 - g["qMax"])
815
+
816
+ if signal > g["maxS"]:
817
+ g["maxS"] = signal
818
+ g["peakAbs"] = start + peak if peak >= 0 else -1
819
+
820
+ items = []
821
+ for clusterID, g in groups.items():
822
+ items.append((g["chrom"], g["sMin"], g["eMax"], g))
823
+ items.sort(key=lambda x: (str(x[0]), x[1], x[2]))
824
+
825
+ outPath = f"{filePath.replace('.narrowPeak', '')}.mergedMatches.narrowPeak"
826
+ lines = []
827
+ i = 0
828
+ for chrom, sMin, eMax, g in items:
829
+ i += 1
830
+ avgScore = g["scSum"] / g["n"]
831
+ if avgScore < 0:
832
+ avgScore = 0
833
+ if avgScore > 1000:
834
+ avgScore = 1000
835
+ scoreInt = int(round(avgScore))
836
+ sigAvg = g["sigSum"] / g["n"]
837
+
838
+ if g["pHasInf"]:
839
+ pHMLog10 = MAX_NEGLOGP
840
+ else:
841
+ if (
842
+ g["pMax"] == float("-inf")
843
+ or not (g["pTail"] > 0.0)
844
+ or math.isnan(g["pTail"])
845
+ ):
846
+ pHMLog10 = MIN_NEGLOGP
847
+ else:
848
+ pHMLog10 = -math.log10(g["n"]) + (
849
+ g["pMax"] + math.log10(g["pTail"])
850
+ )
851
+ pHMLog10 = max(
852
+ MIN_NEGLOGP, min(pHMLog10, MAX_NEGLOGP)
853
+ )
854
+
855
+ if g["qHasInf"]:
856
+ qHMLog10 = MAX_NEGLOGP
857
+ else:
858
+ if (
859
+ g["qMax"] == float("-inf")
860
+ or not (g["qTail"] > 0.0)
861
+ or math.isnan(g["qTail"])
862
+ ):
863
+ qHMLog10 = MIN_NEGLOGP
864
+ else:
865
+ qHMLog10 = -math.log10(g["n"]) + (
866
+ g["qMax"] + math.log10(g["qTail"])
867
+ )
868
+ qHMLog10 = max(
869
+ MIN_NEGLOGP, min(qHMLog10, MAX_NEGLOGP)
870
+ )
871
+
872
+ pointSource = (
873
+ g["peakAbs"] - sMin
874
+ if g["peakAbs"] >= 0
875
+ else (eMax - sMin) // 2
876
+ )
877
+
878
+ qMinLog10 = g["qMin"]
879
+ qMaxLog10 = g["qMax"]
880
+ if math.isfinite(qMinLog10) and qMinLog10 < MIN_NEGLOGP:
881
+ qMinLog10 = MIN_NEGLOGP
882
+ if math.isfinite(qMaxLog10) and qMaxLog10 > MAX_NEGLOGP:
883
+ qMaxLog10 = MAX_NEGLOGP
884
+ elif (
885
+ not math.isfinite(qMaxLog10)
886
+ or not math.isfinite(qMinLog10)
887
+ ) or (qMaxLog10 < MIN_NEGLOGP):
888
+ qMinLog10 = 0.0
889
+ qMaxLog10 = 0.0
890
+
891
+ # informative+parsable name
892
+ # e.g., regex: ^consenrichPeak\|i=(?P<i>\d+)\|gap=(?P<gap>\d+)bp\|ct=(?P<ct>\d+)\|qRange=(?P<qmin>\d+\.\d{3})_(?P<qmax>\d+\_\d{3})$
893
+ name = f"consenrichPeak|i={i}|gap={mergeGapBP}bp|ct={g['n']}|qRange={qMinLog10:.3f}_{qMaxLog10:.3f}"
894
+ lines.append(
895
+ f"{chrom}\t{int(sMin)}\t{int(eMax)}\t{name}\t{scoreInt}\t.\t{sigAvg:.3f}\t{pHMLog10:.3f}\t{qHMLog10:.3f}\t{int(pointSource)}"
896
+ )
897
+
898
+ with open(outPath, "w") as outF:
899
+ outF.write("\n".join(lines) + ("\n" if lines else ""))
900
+ logger.info(f"Merged matches written to {outPath}")
901
+ return outPath