consenrich 0.7.2b2__cp313-cp313-macosx_11_0_arm64.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.

Potentially problematic release.


This version of consenrich might be problematic. Click here for more details.

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