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/core.py ADDED
@@ -0,0 +1,1342 @@
1
+ # -*- coding: utf-8 -*-
2
+ r"""
3
+ Consenrich core functions and classes.
4
+
5
+ """
6
+
7
+ import logging
8
+ import os
9
+ from tempfile import NamedTemporaryFile
10
+ from typing import Callable, List, Optional, Tuple, DefaultDict, Any, NamedTuple
11
+
12
+ import numpy as np
13
+ import numpy.typing as npt
14
+ import pybedtools as bed
15
+ from scipy import signal, ndimage
16
+
17
+ from . import cconsenrich
18
+
19
+ logging.basicConfig(
20
+ level=logging.INFO,
21
+ format="%(asctime)s - %(module)s.%(funcName)s - %(levelname)s - %(message)s",
22
+ )
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ def resolveExtendBP(extendBP, bamFiles: List[str]) -> List[int]:
28
+ numFiles = len(bamFiles)
29
+
30
+ if isinstance(extendBP, str):
31
+ stringValue = extendBP.replace(" ", "")
32
+ try:
33
+ extendBP = (
34
+ [int(x) for x in stringValue.split(",")] if stringValue else []
35
+ )
36
+ except ValueError:
37
+ raise ValueError(
38
+ "`extendBP` string must be comma-separated values (castable to integers)"
39
+ )
40
+ if extendBP is None:
41
+ return [0] * numFiles
42
+ elif isinstance(extendBP, list):
43
+ valuesList = [int(x) for x in extendBP]
44
+ valuesLen = len(valuesList)
45
+ if valuesLen == 0:
46
+ return [0] * numFiles
47
+ if valuesLen == 1:
48
+ return [valuesList[0]] * numFiles
49
+ if valuesLen == numFiles:
50
+ return valuesList
51
+ raise ValueError(
52
+ f"extendBP length {valuesLen} does not match number of bamFiles {numFiles}; "
53
+ f"provide 0, 1, or {numFiles} values."
54
+ )
55
+ elif isinstance(extendBP, int) or isinstance(extendBP, float):
56
+ return [int(extendBP)] * numFiles
57
+ raise TypeError(
58
+ f"Invalid extendBP type: {type(extendBP).__name__}. "
59
+ "Expecting a single number (broadcast), a list of numbers matching `bamFiles`."
60
+ )
61
+
62
+
63
+ class processParams(NamedTuple):
64
+ r"""Parameters related to the process model of Consenrich.
65
+
66
+ The process model governs the signal and variance propagation
67
+ through the state transition :math:`\mathbf{F} \in \mathbb{R}^{2 \times 2}`
68
+ and process noise covariance :math:`\mathbf{Q}_{[i]} \in \mathbb{R}^{2 \times 2}`
69
+ matrices.
70
+
71
+ :param deltaF: Scales the signal and variance propagation between adjacent genomic intervals.
72
+ :param minQ: Minimum process noise level (diagonal in :math:`\mathbf{Q}_{[i]}`)
73
+ for each state variable. Adjust relative to data quality (more reliable data --> lower minQ).
74
+ :type minQ: float
75
+ :param dStatAlpha: Threshold on the deviation between the data and estimated signal -- used to determine whether the process noise is scaled up.
76
+ :type dStatAlpha: float
77
+ :param dStatd: Constant :math:`d` in the scaling expression :math:`\sqrt{d|D_{[i]} - \alpha_D| + c}`
78
+ that is used to up/down-scale the process noise covariance in the event of a model mismatch.
79
+ :type dStatd: float
80
+ :param dStatPC: Constant :math:`c` in the scaling expression :math:`\sqrt{d|D_{[i]} - \alpha_D| + c}`
81
+ that is used to up/down-scale the process noise covariance in the event of a model mismatch.
82
+ :type dStatPC: float
83
+ :param scaleResidualsByP11: If `True`, the primary state variances :math:`\widetilde{P}_{[i], (11)}, i=1\ldots n` are included in the inverse-variance (precision) weighting of residuals :math:`\widetilde{\mathbf{y}}_{[i]}, i=1\ldots n`.
84
+ If `False`, only the per-sample observation noise levels are used to reduce computational overhead.
85
+ :type scaleResidualsByP11: Optional[bool]
86
+
87
+ """
88
+
89
+ deltaF: float
90
+ minQ: float
91
+ maxQ: float
92
+ offDiagQ: float
93
+ dStatAlpha: float
94
+ dStatd: float
95
+ dStatPC: float
96
+ scaleResidualsByP11: Optional[bool] = False
97
+
98
+
99
+ class observationParams(NamedTuple):
100
+ r"""Parameters related to the observation model of Consenrich.
101
+ The observation model is used to integrate sequence alignment count
102
+ data from the multiple input samples and account for region-and-sample-specific
103
+ noise processes corrupting data. The observation model matrix
104
+ :math:`\mathbf{H} \in \mathbb{R}^{m \times 2}` maps from the state dimension (2)
105
+ to the dimension of measurements/data (:math:`m`).
106
+
107
+ :param minR: The minimum observation noise level for each sample
108
+ :math:`j=1\ldots m` in the observation noise covariance
109
+ matrix :math:`\mathbf{R}_{[i, (11:mm)]}`.
110
+ :type minR: float
111
+ :param numNearest: The number of nearest nearby sparse features to use for local
112
+ variance calculation. Ignored if `useALV` is True.
113
+ :type numNearest: int
114
+ :param localWeight: The coefficient for the local noise level (based on the local surrounding window / `numNearest` features) used in the weighted sum measuring sample-specific noise level at the current interval.
115
+ :type localWeight: float
116
+ :param globalWeight: The coefficient for the global noise level (based on all genomic intervals :math:`i=1\ldots n`) used in the weighted sum measuring sample-specific noise level at the current interval.
117
+ :type globalWeight: float
118
+ :param approximationWindowLengthBP: The length of the local approximation window in base pairs (BP)
119
+ for the local variance calculation.
120
+ :type approximationWindowLengthBP: int
121
+ :param sparseBedFile: The path to a BED file of 'sparse' regions for the local variance calculation.
122
+ :type sparseBedFile: str, optional
123
+ :param noGlobal: If True, only the 'local' variances are used to approximate observation noise
124
+ covariance :math:`\mathbf{R}_{[:, (11:mm)]}`.
125
+ :type noGlobal: bool
126
+ :param useALV: Whether to use average local variance (ALV) to approximate observation noise
127
+ covariances per-sample, per-interval. Recommended for estimating signals associated with
128
+ repressive/heterochromatic elements.
129
+ :type useALV: bool
130
+ :param useConstantNoiseLevel: Whether to use a constant noise level in the observation model.
131
+ :type useConstantNoiseLevel: bool
132
+ :param lowPassFilterType: The type of low-pass filter to use (e.g., 'median', 'mean').
133
+ :type lowPassFilterType: Optional[str]
134
+ """
135
+
136
+ minR: float
137
+ maxR: float
138
+ useALV: bool
139
+ useConstantNoiseLevel: bool
140
+ noGlobal: bool
141
+ numNearest: int
142
+ localWeight: float
143
+ globalWeight: float
144
+ approximationWindowLengthBP: int
145
+ lowPassWindowLengthBP: int
146
+ lowPassFilterType: Optional[str]
147
+ returnCenter: bool
148
+
149
+
150
+ class stateParams(NamedTuple):
151
+ r"""Parameters related to state and uncertainty bounds and initialization.
152
+
153
+ :param stateInit: Initial value of the 'primary' state/signal at the first genomic interval: :math:`x_{[1]}`
154
+ :type stateInit: float
155
+ :param stateCovarInit: Initial state covariance (covariance) scale. Note, the *initial* state uncertainty :math:`\mathbf{P}_{[1]}` is a multiple of the identity matrix :math:`\mathbf{I}`
156
+ :type stateCovarInit: float
157
+ :param boundState: If True, the primary state estimate for :math:`x_{[i]}` is constrained within `stateLowerBound` and `stateUpperBound`.
158
+ :type boundState: bool
159
+ :param stateLowerBound: Lower bound for the state estimate.
160
+ :type stateLowerBound: float
161
+ :param stateUpperBound: Upper bound for the state estimate.
162
+ :type stateUpperBound: float
163
+ """
164
+
165
+ stateInit: float
166
+ stateCovarInit: float
167
+ boundState: bool
168
+ stateLowerBound: float
169
+ stateUpperBound: float
170
+
171
+
172
+ class samParams(NamedTuple):
173
+ r"""Parameters related to reading BAM files
174
+
175
+ :param samThreads: The number of threads to use for reading BAM files.
176
+ :type samThreads: int
177
+ :param samFlagExclude: The SAM flag to exclude certain reads.
178
+ :type samFlagExclude: int
179
+ :param oneReadPerBin: If 1, only the interval with the greatest read overlap is incremented.
180
+ :type oneReadPerBin: int
181
+ :param chunkSize: maximum number of intervals' data to hold in memory before flushing to disk.
182
+ :type chunkSize: int
183
+ :param offsetStr: A string of two comma-separated integers -- first for the 5' shift on forward strand, second for the 5' shift on reverse strand.
184
+ :type offsetStr: str
185
+ :param extendBP: A list of integers specifying the number of base pairs to extend reads for each BAM file after shifting per `offsetStr`.
186
+ If all BAM files share the same expected frag. length, can supply a single numeric value to be broadcasted. Ignored for PE reads.
187
+ :type extendBP: List[int]
188
+ :param maxInsertSize: Maximum frag length/insert for paired-end reads.
189
+ :type maxInsertSize: int
190
+ :param pairedEndMode: If > 0, only proper pairs are counted subject to `maxInsertSize`.
191
+ :type pairedEndMode: int
192
+ :param inferFragmentLength: Intended for single-end data: if > 0, the maximum correlation lag
193
+ (avg.) between *strand-specific* read tracks is taken as the fragment length estimate and used to
194
+ extend reads from 5'. Ignored if `pairedEndMode > 0` or `extendBP` set. This parameter is particularly
195
+ important when targeting broader marks (e.g., ChIP-seq H3K27me3).
196
+ :type inferFragmentLength: int
197
+ :param countEndsOnly: If True, only the 5' ends of reads are counted. Overrides `inferFragmentLength` and `pairedEndMode`.
198
+ :type countEndsOnly: Optional[bool]
199
+
200
+ .. tip::
201
+
202
+ For an overview of SAM flags, see https://broadinstitute.github.io/picard/explain-flags.html
203
+
204
+ """
205
+
206
+ samThreads: int
207
+ samFlagExclude: int
208
+ oneReadPerBin: int
209
+ chunkSize: int
210
+ offsetStr: Optional[str] = "0,0"
211
+ extendBP: Optional[List[int]] = []
212
+ maxInsertSize: Optional[int] = 1000
213
+ pairedEndMode: Optional[int] = 0
214
+ inferFragmentLength: Optional[int] = 0
215
+ countEndsOnly: Optional[bool] = False
216
+
217
+
218
+ class detrendParams(NamedTuple):
219
+ r"""Parameters related detrending and background-removal
220
+
221
+ :param useOrderStatFilter: Whether to use a local/moving order statistic (percentile filter) to model and remove trends in the read density data.
222
+ :type useOrderStatFilter: bool
223
+ :param usePolyFilter: Whether to use a low-degree polynomial fit to model and remove trends in the read density data.
224
+ :type usePolyFilter: bool
225
+ :param detrendSavitzkyGolayDegree: The polynomial degree of the Savitzky-Golay filter to use for detrending
226
+ :type detrendSavitzkyGolayDegree: int
227
+ :param detrendTrackPercentile: The percentile to use for the local/moving order-statistic filter.
228
+ Decrease for broad marks + sparse data if `useOrderStatFilter` is True.
229
+ :type detrendTrackPercentile: float
230
+ :param detrendWindowLengthBP: The length of the window in base pairs for detrending.
231
+ Increase for broader marks + sparse data.
232
+ :type detrendWindowLengthBP: int
233
+ """
234
+
235
+ useOrderStatFilter: bool
236
+ usePolyFilter: bool
237
+ detrendTrackPercentile: float
238
+ detrendSavitzkyGolayDegree: int
239
+ detrendWindowLengthBP: int
240
+
241
+
242
+ class inputParams(NamedTuple):
243
+ r"""Parameters related to the input data for Consenrich.
244
+
245
+ :param bamFiles: A list of paths to distinct coordinate-sorted and indexed BAM files.
246
+ :type bamFiles: List[str]
247
+
248
+ :param bamFilesControl: A list of paths to distinct coordinate-sorted and
249
+ indexed control BAM files. e.g., IgG control inputs for ChIP-seq.
250
+
251
+ :type bamFilesControl: List[str], optional
252
+
253
+ """
254
+
255
+ bamFiles: List[str]
256
+ bamFilesControl: Optional[List[str]]
257
+ pairedEnd: Optional[bool]
258
+
259
+
260
+ class genomeParams(NamedTuple):
261
+ r"""Specify assembly-specific resources, parameters.
262
+
263
+ :param genomeName: If supplied, default resources for the assembly (sizes file, blacklist, and 'sparse' regions) in `src/consenrich/data` are used.
264
+ ``ce10, ce11, dm6, hg19, hg38, mm10, mm39`` have default resources available.
265
+ :type genomeName: str
266
+ :param chromSizesFile: A two-column TSV-like file with chromosome names and sizes (in base pairs).
267
+ :type chromSizesFile: str
268
+ :param blacklistFile: A BED file with regions to exclude.
269
+ :type blacklistFile: str, optional
270
+ :param sparseBedFile: A BED file with sparse regions used to estimate noise levels -- ignored if `observationParams.useALV` is True.
271
+ :type sparseBedFile: str, optional
272
+ :param chromosomes: A list of chromosome names to analyze. If None, all chromosomes in `chromSizesFile` are used.
273
+ :type chromosomes: List[str]
274
+ """
275
+
276
+ genomeName: str
277
+ chromSizesFile: str
278
+ blacklistFile: Optional[str]
279
+ sparseBedFile: Optional[str]
280
+ chromosomes: List[str]
281
+ excludeChroms: List[str]
282
+ excludeForNorm: List[str]
283
+
284
+
285
+ class countingParams(NamedTuple):
286
+ r"""Parameters related to counting reads in genomic intervals.
287
+
288
+ :param stepSize: Step size (bp) for the genomic intervals (AKA bin size, interval length, width, etc.)
289
+ :type stepSize: int
290
+ :param scaleDown: If using paired treatment and control BAM files, whether to
291
+ scale down the larger of the two before computing the difference/ratio
292
+ :type scaleDown: bool, optional
293
+ :param scaleFactors: Scale factors for the read counts.
294
+ :type scaleFactors: List[float], optional
295
+ :param scaleFactorsControl: Scale factors for the control read counts.
296
+ :type scaleFactorsControl: List[float], optional
297
+ :param numReads: Number of reads to sample.
298
+ :type numReads: int
299
+ :param applyAsinh: If true, :math:`\textsf{arsinh}(x)` applied to counts :math:`x` (log-like for large values and linear near the origin)
300
+ :type applyAsinh: bool, optional
301
+ :param applyLog: If true, :math:`\textsf{log}(x + 1)` applied to counts :math:`x`
302
+ :type applyLog: bool, optional
303
+ """
304
+
305
+ stepSize: int
306
+ scaleDown: Optional[bool]
307
+ scaleFactors: Optional[List[float]]
308
+ scaleFactorsControl: Optional[List[float]]
309
+ numReads: int
310
+ applyAsinh: Optional[bool]
311
+ applyLog: Optional[bool]
312
+ rescaleToTreatmentCoverage: Optional[bool] = False
313
+
314
+
315
+ class matchingParams(NamedTuple):
316
+ r"""Parameters related to the matching algorithm.
317
+
318
+ See :ref:`matching` for an overview of the approach.
319
+
320
+ :param templateNames: A list of str values -- each entry references a mother wavelet (or its corresponding scaling function). e.g., `[haar, db2]`
321
+ :type templateNames: List[str]
322
+ :param cascadeLevels: Number of cascade iterations used to approximate each template (wavelet or scaling function).
323
+ Must have the same length as `templateNames`, with each entry aligned to the
324
+ corresponding template. e.g., given templateNames `[haar, db2]`, then `[2,2]` would use 2 cascade levels for both templates.
325
+ :type cascadeLevels: List[int]
326
+ :param iters: Number of random blocks to sample in the response sequence while building
327
+ an empirical null to test significance. See :func:`cconsenrich.csampleBlockStats`.
328
+ :type iters: int
329
+ :param alpha: Primary significance threshold on detected matches. Specifically, the
330
+ minimum corr. empirical p-value approximated from randomly sampled blocks in the
331
+ response sequence.
332
+ :type alpha: float
333
+ :param minMatchLengthBP: Within a window of `minMatchLengthBP` length (bp), relative maxima in
334
+ the signal-template convolution must be greater in value than others to qualify as matches.
335
+ If set to a value less than 1, the minimum length is determined via :func:`consenrich.matching.autoMinLengthIntervals`.
336
+ If set to `None`, defaults to 250 bp.
337
+ :param minSignalAtMaxima: Secondary significance threshold coupled with `alpha`. Requires the *signal value*
338
+ at relative maxima in the response sequence to be greater than this threshold. Comparisons are made in log-scale
339
+ to temper genome-wide dynamic range. If a `float` value is provided, the minimum signal value must be greater
340
+ than this (absolute) value. *Set to a negative value to disable the threshold*.
341
+ If a `str` value is provided, looks for 'q:quantileValue', e.g., 'q:0.90'. The
342
+ threshold is then set to the corresponding quantile of the non-zero signal estimates.
343
+ :type minSignalAtMaxima: Optional[str | float]
344
+ :param useScalingFunction: If True, use (only) the scaling function to build the matching template.
345
+ If False, use (only) the wavelet function.
346
+ :type useScalingFunction: bool
347
+ :param excludeRegionsBedFile: A BED file with regions to exclude from matching
348
+ :type excludeRegionsBedFile: Optional[str]
349
+ :param penalizeBy: Specify a positional metric to scale/weight signal values by when matching.
350
+ For example, 'absResiduals' divides signal values by :math:`|\widetilde{y}_i|` at each
351
+ position :math:`i`, thereby down-weighting positions where the signal estimate deviates from
352
+ the data after accounting for observation noise. 'stateUncertainty' divides signal values by
353
+ the square root of the primary state variance :math:`\sqrt{\wildetilde{P}_{i,(11)}}` at each position :math:`i`,
354
+ thereby down-weighting positions where the posterior state uncertainty is high.
355
+ :type penalizeBy: Optional[str]
356
+ :seealso: :func:`cconsenrich.csampleBlockStats`, :ref:`matching`
357
+ """
358
+
359
+ templateNames: List[str]
360
+ cascadeLevels: List[int]
361
+ iters: int
362
+ alpha: float
363
+ useScalingFunction: Optional[bool]
364
+ minMatchLengthBP: Optional[int]
365
+ maxNumMatches: Optional[int]
366
+ minSignalAtMaxima: Optional[str | float]
367
+ merge: Optional[bool]
368
+ mergeGapBP: Optional[int]
369
+ excludeRegionsBedFile: Optional[str]
370
+ penalizeBy: Optional[str]
371
+ randSeed: Optional[int] = 42
372
+
373
+
374
+ def _numIntervals(start: int, end: int, step: int) -> int:
375
+ # helper for consistency
376
+ length = max(0, end - start)
377
+ return (length + step) // step
378
+
379
+
380
+ def getChromRanges(
381
+ bamFile: str,
382
+ chromosome: str,
383
+ chromLength: int,
384
+ samThreads: int,
385
+ samFlagExclude: int,
386
+ ) -> Tuple[int, int]:
387
+ r"""Get the start and end positions of reads in a chromosome from a BAM file.
388
+
389
+ :param bamFile: See :class:`inputParams`.
390
+ :type bamFile: str
391
+ :param chromosome: the chromosome to read in `bamFile`.
392
+ :type chromosome: str
393
+ :param chromLength: Base pair length of the chromosome.
394
+ :type chromLength: int
395
+ :param samThreads: See :class:`samParams`.
396
+ :type samThreads: int
397
+ :param samFlagExclude: See :class:`samParams`.
398
+ :type samFlagExclude: int
399
+ :return: Tuple of start and end positions (nucleotide coordinates) in the chromosome.
400
+ :rtype: Tuple[int, int]
401
+
402
+ :seealso: :func:`getChromRangesJoint`, :func:`cconsenrich.cgetFirstChromRead`, :func:`cconsenrich.cgetLastChromRead`
403
+ """
404
+ start: int = cconsenrich.cgetFirstChromRead(
405
+ bamFile, chromosome, chromLength, samThreads, samFlagExclude
406
+ )
407
+ end: int = cconsenrich.cgetLastChromRead(
408
+ bamFile, chromosome, chromLength, samThreads, samFlagExclude
409
+ )
410
+ return start, end
411
+
412
+
413
+ def getChromRangesJoint(
414
+ bamFiles: List[str],
415
+ chromosome: str,
416
+ chromSize: int,
417
+ samThreads: int,
418
+ samFlagExclude: int,
419
+ ) -> Tuple[int, int]:
420
+ r"""For multiple BAM files, reconcile a single start and end position over which to count reads,
421
+ where the start and end positions are defined by the first and last reads across all BAM files.
422
+
423
+ :param bamFiles: List of BAM files to read.
424
+ :type bamFiles: List[str]
425
+ :param chromosome: Chromosome to read.
426
+ :type chromosome: str
427
+ :param chromSize: Size of the chromosome.
428
+ :type chromSize: int
429
+ :param samThreads: Number of threads to use for reading the BAM files.
430
+ :type samThreads: int
431
+ :param samFlagExclude: SAM flag to exclude certain reads.
432
+ :type samFlagExclude: int
433
+ :return: Tuple of start and end positions.
434
+ :rtype: Tuple[int, int]
435
+
436
+ :seealso: :func:`getChromRanges`, :func:`cconsenrich.cgetFirstChromRead`, :func:`cconsenrich.cgetLastChromRead`
437
+ """
438
+ starts = []
439
+ ends = []
440
+ for bam_ in bamFiles:
441
+ start, end = getChromRanges(
442
+ bam_,
443
+ chromosome,
444
+ chromLength=chromSize,
445
+ samThreads=samThreads,
446
+ samFlagExclude=samFlagExclude,
447
+ )
448
+ starts.append(start)
449
+ ends.append(end)
450
+ return min(starts), max(ends)
451
+
452
+
453
+ def getReadLength(
454
+ bamFile: str,
455
+ numReads: int,
456
+ maxIterations: int,
457
+ samThreads: int,
458
+ samFlagExclude: int,
459
+ ) -> int:
460
+ r"""Infer read length from mapped reads in a BAM file.
461
+
462
+ Samples at least `numReads` reads passing criteria given by `samFlagExclude`
463
+ and returns the median read length.
464
+
465
+ :param bamFile: See :class:`inputParams`.
466
+ :type bamFile: str
467
+ :param numReads: Number of reads to sample.
468
+ :type numReads: int
469
+ :param maxIterations: Maximum number of iterations to perform.
470
+ :type maxIterations: int
471
+ :param samThreads: See :class:`samParams`.
472
+ :type samThreads: int
473
+ :param samFlagExclude: See :class:`samParams`.
474
+ :type samFlagExclude: int
475
+ :return: The median read length.
476
+ :rtype: int
477
+
478
+ :raises ValueError: If the read length cannot be determined after scanning `maxIterations` reads.
479
+
480
+ :seealso: :func:`cconsenrich.cgetReadLength`
481
+ """
482
+ init_rlen = cconsenrich.cgetReadLength(
483
+ bamFile, numReads, samThreads, maxIterations, samFlagExclude
484
+ )
485
+ if init_rlen == 0:
486
+ raise ValueError(
487
+ f"Failed to determine read length in {bamFile}. Revise `numReads`, and/or `samFlagExclude` parameters?"
488
+ )
489
+ return init_rlen
490
+
491
+
492
+ def getReadLengths(
493
+ bamFiles: List[str],
494
+ numReads: int,
495
+ maxIterations: int,
496
+ samThreads: int,
497
+ samFlagExclude: int,
498
+ ) -> List[int]:
499
+ r"""Get read lengths for a list of BAM files.
500
+
501
+ :seealso: :func:`getReadLength`
502
+ """
503
+ return [
504
+ getReadLength(
505
+ bamFile,
506
+ numReads=numReads,
507
+ maxIterations=maxIterations,
508
+ samThreads=samThreads,
509
+ samFlagExclude=samFlagExclude,
510
+ )
511
+ for bamFile in bamFiles
512
+ ]
513
+
514
+
515
+ def readBamSegments(
516
+ bamFiles: List[str],
517
+ chromosome: str,
518
+ start: int,
519
+ end: int,
520
+ stepSize: int,
521
+ readLengths: List[int],
522
+ scaleFactors: List[float],
523
+ oneReadPerBin: int,
524
+ samThreads: int,
525
+ samFlagExclude: int,
526
+ offsetStr: Optional[str] = "0,0",
527
+ applyAsinh: Optional[bool] = False,
528
+ applyLog: Optional[bool] = False,
529
+ extendBP: List[int] = [],
530
+ maxInsertSize: Optional[int] = 1000,
531
+ pairedEndMode: Optional[int] = 0,
532
+ inferFragmentLength: Optional[int] = 0,
533
+ countEndsOnly: Optional[bool] = False,
534
+ ) -> npt.NDArray[np.float32]:
535
+ r"""Calculate tracks of read counts (or a function thereof) for each BAM file.
536
+
537
+ See :func:`cconsenrich.creadBamSegment` for the underlying implementation in Cython.
538
+
539
+ :param bamFiles: See :class:`inputParams`.
540
+ :type bamFiles: List[str]
541
+ :param chromosome: Chromosome to read.
542
+ :type chromosome: str
543
+ :param start: Start position of the genomic segment.
544
+ :type start: int
545
+ :param end: End position of the genomic segment.
546
+ :type end: int
547
+ :param readLengths: List of read lengths for each BAM file.
548
+ :type readLengths: List[int]
549
+ :param scaleFactors: List of scale factors for each BAM file.
550
+ :type scaleFactors: List[float]
551
+ :param stepSize: See :class:`countingParams`.
552
+ :type stepSize: int
553
+ :param oneReadPerBin: See :class:`samParams`.
554
+ :type oneReadPerBin: int
555
+ :param samThreads: See :class:`samParams`.
556
+ :type samThreads: int
557
+ :param samFlagExclude: See :class:`samParams`.
558
+ :type samFlagExclude: int
559
+ :param offsetStr: See :class:`samParams`.
560
+ :type offsetStr: str
561
+ :param extendBP: See :class:`samParams`.
562
+ :type extendBP: int
563
+ :param maxInsertSize: See :class:`samParams`.
564
+ :type maxInsertSize: int
565
+ :param pairedEndMode: See :class:`samParams`.
566
+ :type pairedEndMode: int
567
+ :param inferFragmentLength: See :class:`samParams`.
568
+ :type inferFragmentLength: int
569
+ :param countEndsOnly: If True, only the 5' ends of reads are counted. This overrides `inferFragmentLength` and `pairedEndMode`.
570
+ :type countEndsOnly: Optional[bool]
571
+
572
+ """
573
+
574
+ if len(bamFiles) == 0:
575
+ raise ValueError("bamFiles list is empty")
576
+
577
+ if len(readLengths) != len(bamFiles) or len(scaleFactors) != len(bamFiles):
578
+ raise ValueError(
579
+ "readLengths and scaleFactors must match bamFiles length"
580
+ )
581
+
582
+ extendBP = resolveExtendBP(extendBP, bamFiles)
583
+ offsetStr = ((str(offsetStr) or "0,0").replace(" ", "")).split(",")
584
+ numIntervals = ((end - start) + stepSize - 1) // stepSize
585
+ counts = np.empty((len(bamFiles), numIntervals), dtype=np.float32)
586
+
587
+ if isinstance(countEndsOnly, bool) and countEndsOnly:
588
+ # note: setting this option ignores inferFragmentLength, pairedEndMode
589
+ inferFragmentLength = 0
590
+ pairedEndMode = 0
591
+
592
+ for j, bam in enumerate(bamFiles):
593
+ logger.info(f"Reading {chromosome}: {bam}")
594
+ arr = cconsenrich.creadBamSegment(
595
+ bam,
596
+ chromosome,
597
+ start,
598
+ end,
599
+ stepSize,
600
+ readLengths[j],
601
+ oneReadPerBin,
602
+ samThreads,
603
+ samFlagExclude,
604
+ int(offsetStr[0]),
605
+ int(offsetStr[1]),
606
+ extendBP[j],
607
+ maxInsertSize,
608
+ pairedEndMode,
609
+ inferFragmentLength,
610
+ )
611
+ # FFR: use ufuncs?
612
+ counts[j, :] = arr
613
+ counts[j, :] *= np.float32(scaleFactors[j])
614
+ if applyAsinh:
615
+ counts[j, :] = np.arcsinh(counts[j, :])
616
+ elif applyLog:
617
+ counts[j, :] = np.log1p(counts[j, :])
618
+ return counts
619
+
620
+
621
+ def getAverageLocalVarianceTrack(
622
+ values: np.ndarray,
623
+ stepSize: int,
624
+ approximationWindowLengthBP: int,
625
+ lowPassWindowLengthBP: int,
626
+ minR: float,
627
+ maxR: float,
628
+ lowPassFilterType: Optional[str] = "median",
629
+ ) -> npt.NDArray[np.float32]:
630
+ r"""Approximate a positional/local noise level track for a single sample's read-density-based values.
631
+
632
+ First computes a moving average of ``values`` using a bp-length window
633
+ ``approximationWindowLengthBP`` and a moving average of ``values**2`` over the
634
+ same window. Their difference is used to approximate the local variance. A low-pass filter
635
+ (median or mean) with window ``lowPassWindowLengthBP`` then smooths the variance track.
636
+ Finally, the track is clipped to ``[minR, maxR]`` to yield the local noise level track.
637
+
638
+ :param values: 1D array of read-density-based values for a single sample.
639
+ :type values: np.ndarray
640
+ :param stepSize: Bin size (bp).
641
+ :type stepSize: int
642
+ :param approximationWindowLengthBP: Window (bp) for local mean and second-moment. See :class:`observationParams`.
643
+ :type approximationWindowLengthBP: int
644
+ :param lowPassWindowLengthBP: Window (bp) for the low-pass filter on the variance track. See :class:`observationParams`.
645
+ :type lowPassWindowLengthBP: int
646
+ :param minR: Lower clip for the returned noise level. See :class:`observationParams`.
647
+ :type minR: float
648
+ :param maxR: Upper clip for the returned noise level. See :class:`observationParams`.
649
+ :type maxR: float
650
+ :param lowPassFilterType: ``"median"`` (default) or ``"mean"``. Type of low-pass filter to use for smoothing the local variance track. See :class:`observationParams`.
651
+ :type lowPassFilterType: Optional[str]
652
+ :return: Local noise level per interval.
653
+ :rtype: npt.NDArray[np.float32]
654
+
655
+ :seealso: :class:`observationParams`
656
+ """
657
+ values = np.asarray(values, dtype=np.float32)
658
+ windowLength = int(approximationWindowLengthBP / stepSize)
659
+ if windowLength % 2 == 0:
660
+ windowLength += 1
661
+ if len(values) < 3:
662
+ constVar = np.var(values)
663
+ if constVar < minR:
664
+ return np.full_like(values, minR, dtype=np.float32)
665
+ return np.full_like(values, constVar, dtype=np.float32)
666
+
667
+ # first get a simple moving average of the values
668
+ localMeanTrack: npt.NDArray[np.float32] = ndimage.uniform_filter(
669
+ values, size=windowLength, mode="nearest"
670
+ )
671
+
672
+ # ~ E[X_i^2] - E[X_i]^2 ~
673
+ localVarTrack: npt.NDArray[np.float32] = (
674
+ ndimage.uniform_filter(values**2, size=windowLength, mode="nearest")
675
+ - localMeanTrack**2
676
+ )
677
+
678
+ # safe-guard: difference of convolutions returns negative values.
679
+ # shouldn't actually happen, but just in case there are some
680
+ # ...potential artifacts i'm unaware of edge effects, etc.
681
+ localVarTrack = np.maximum(localVarTrack, 0.0)
682
+
683
+ # low-pass filter on the local variance track: positional 'noise level' track
684
+ lpassWindowLength = int(lowPassWindowLengthBP / stepSize)
685
+ if lpassWindowLength % 2 == 0:
686
+ lpassWindowLength += 1
687
+
688
+ noiseLevel: npt.NDArray[np.float32] = np.zeros_like(
689
+ localVarTrack, dtype=np.float32
690
+ )
691
+ if lowPassFilterType is None or (
692
+ isinstance(lowPassFilterType, str)
693
+ and lowPassFilterType.lower() == "median"
694
+ ):
695
+ noiseLevel = ndimage.median_filter(
696
+ localVarTrack, size=lpassWindowLength
697
+ )
698
+ elif (
699
+ isinstance(lowPassFilterType, str)
700
+ and lowPassFilterType.lower() == "mean"
701
+ ):
702
+ noiseLevel = ndimage.uniform_filter(
703
+ localVarTrack, size=lpassWindowLength
704
+ )
705
+
706
+ return np.clip(noiseLevel, minR, maxR).astype(np.float32)
707
+
708
+
709
+ def constructMatrixF(deltaF: float) -> npt.NDArray[np.float32]:
710
+ r"""Build the state transition matrix for the process model
711
+
712
+ :param deltaF: See :class:`processParams`.
713
+ :type deltaF: float
714
+ :return: The state transition matrix :math:`\mathbf{F}`
715
+ :rtype: npt.NDArray[np.float32]
716
+
717
+ :seealso: :class:`processParams`
718
+ """
719
+ initMatrixF: npt.NDArray[np.float32] = np.eye(2, dtype=np.float32)
720
+ initMatrixF[0, 1] = np.float32(deltaF)
721
+ return initMatrixF
722
+
723
+
724
+ def constructMatrixQ(
725
+ minDiagQ: float, offDiagQ: float = 0.0
726
+ ) -> npt.NDArray[np.float32]:
727
+ r"""Build the initial process noise covariance matrix :math:`\mathbf{Q}_{[1]}`.
728
+
729
+ :param minDiagQ: See :class:`processParams`.
730
+ :type minDiagQ: float
731
+ :param offDiagQ: See :class:`processParams`.
732
+ :type offDiagQ: float
733
+ :return: The initial process noise covariance matrix :math:`\mathbf{Q}_{[1]}`.
734
+ :rtype: npt.NDArray[np.float32]
735
+
736
+ :seealso: :class:`processParams`
737
+ """
738
+ minDiagQ = np.float32(minDiagQ)
739
+ offDiagQ = np.float32(offDiagQ)
740
+ initMatrixQ: npt.NDArray[np.float32] = np.zeros((2, 2), dtype=np.float32)
741
+ initMatrixQ[0, 0] = minDiagQ
742
+ initMatrixQ[1, 1] = minDiagQ
743
+ initMatrixQ[0, 1] = offDiagQ
744
+ initMatrixQ[1, 0] = offDiagQ
745
+ return initMatrixQ
746
+
747
+
748
+ def constructMatrixH(
749
+ m: int, coefficients: Optional[np.ndarray] = None
750
+ ) -> npt.NDArray[np.float32]:
751
+ r"""Build the observation model matrix :math:`\mathbf{H}`.
752
+
753
+ :param m: Number of observations.
754
+ :type m: int
755
+ :param coefficients: Optional coefficients for the observation model,
756
+ which can be used to weight the observations manually.
757
+ :type coefficients: Optional[np.ndarray]
758
+ :return: The observation model matrix :math:`\mathbf{H}`.
759
+ :rtype: npt.NDArray[np.float32]
760
+
761
+ :seealso: :class:`observationParams`, class:`inputParams`
762
+ """
763
+ if coefficients is None:
764
+ coefficients = np.ones(m, dtype=np.float32)
765
+ elif isinstance(coefficients, list):
766
+ coefficients = np.array(coefficients, dtype=np.float32)
767
+ initMatrixH = np.empty((m, 2), dtype=np.float32)
768
+ initMatrixH[:, 0] = coefficients.astype(np.float32)
769
+ initMatrixH[:, 1] = np.zeros(m, dtype=np.float32)
770
+ return initMatrixH
771
+
772
+
773
+ def runConsenrich(
774
+ matrixData: np.ndarray,
775
+ matrixMunc: np.ndarray,
776
+ deltaF: float,
777
+ minQ: float,
778
+ maxQ: float,
779
+ offDiagQ: float,
780
+ dStatAlpha: float,
781
+ dStatd: float,
782
+ dStatPC: float,
783
+ stateInit: float,
784
+ stateCovarInit: float,
785
+ boundState: bool,
786
+ stateLowerBound: float,
787
+ stateUpperBound: float,
788
+ chunkSize: int,
789
+ progressIter: int,
790
+ coefficientsH: Optional[np.ndarray] = None,
791
+ residualCovarInversionFunc: Optional[Callable] = None,
792
+ adjustProcessNoiseFunc: Optional[Callable] = None,
793
+ ) -> Tuple[
794
+ npt.NDArray[np.float32], npt.NDArray[np.float32], npt.NDArray[np.float32]
795
+ ]:
796
+ r"""Run consenrich on a contiguous segment (e.g. a chromosome) of read-density-based data.
797
+ Completes the forward and backward passes given data and approximated observation noise
798
+ covariance matrices :math:`\mathbf{R}_{[1:n, (11:mm)]}`.
799
+
800
+ :param matrixData: Read density data for a single chromosome or general contiguous segment,
801
+ possibly preprocessed. Two-dimensional array of shape :math:`m \times n` where :math:`m`
802
+ is the number of samples/tracks and :math:`n` the number of genomic intervals.
803
+ :type matrixData: np.ndarray
804
+ :param matrixMunc: Uncertainty estimates for the read coverage data.
805
+ Two-dimensional array of shape :math:`m \times n` where :math:`m` is the number of samples/tracks
806
+ and :math:`n` the number of genomic intervals. See :func:`getMuncTrack`.
807
+ :type matrixMunc: np.ndarray
808
+ :param deltaF: See :class:`processParams`.
809
+ :type deltaF: float
810
+ :param minQ: See :class:`processParams`.
811
+ :type minQ: float
812
+ :param maxQ: See :class:`processParams`.
813
+ :type maxQ: float
814
+ :param offDiagQ: See :class:`processParams`.
815
+ :type offDiagQ: float
816
+ :param dStatAlpha: See :class:`processParams`.
817
+ :type dStatAlpha: float
818
+ :param dStatd: See :class:`processParams`.
819
+ :type dStatd: float
820
+ :param dStatPC: See :class:`processParams`.
821
+ :type dStatPC: float
822
+ :param stateInit: See :class:`stateParams`.
823
+ :type stateInit: float
824
+ :param stateCovarInit: See :class:`stateParams`.
825
+ :type stateCovarInit: float
826
+ :param chunkSize: Number of genomic intervals' data to keep in memory before flushing to disk.
827
+ :type chunkSize: int
828
+ :param progressIter: The number of iterations after which to log progress.
829
+ :type progressIter: int
830
+ :param coefficientsH: Optional coefficients for the observation model matrix :math:`\mathbf{H}`.
831
+ If None, the coefficients are set to 1.0 for all samples.
832
+ :type coefficientsH: Optional[np.ndarray]
833
+ :param residualCovarInversionFunc: Callable function to invert the observation covariance matrix :math:`\mathbf{E}_{[i]}`.
834
+ If None, defaults to :func:`cconsenrich.cinvertMatrixE`.
835
+ :type residualCovarInversionFunc: Optional[Callable]
836
+ :param adjustProcessNoiseFunc: Function to adjust the process noise covariance matrix :math:`\mathbf{Q}_{[i]}`.
837
+ If None, defaults to :func:`cconsenrich.updateProcessNoiseCovariance`.
838
+ :type adjustProcessNoiseFunc: Optional[Callable]
839
+ :return: Tuple of three numpy arrays:
840
+ - state estimates :math:`\widetilde{\mathbf{x}}_{[i]}` of shape :math:`n \times 2`
841
+ - state covariance estimates :math:`\widetilde{\mathbf{P}}_{[i]}` of shape :math:`n \times 2 \times 2`
842
+ - post-fit residuals :math:`\widetilde{\mathbf{y}}_{[i]}` of shape :math:`n \times m`
843
+ :rtype: Tuple[np.ndarray, np.ndarray, np.ndarray]
844
+
845
+ :raises ValueError: If the number of samples in `matrixData` is not equal to the number of samples in `matrixMunc`.
846
+ :seealso: :class:`observationParams`, :class:`processParams`, :class:`stateParams`
847
+ """
848
+ matrixData = np.ascontiguousarray(matrixData, dtype=np.float32)
849
+ matrixMunc = np.ascontiguousarray(matrixMunc, dtype=np.float32)
850
+ m: int = 1 if matrixData.ndim == 1 else matrixData.shape[0]
851
+ n: int = 1 if matrixData.ndim == 1 else matrixData.shape[1]
852
+ inflatedQ: bool = False
853
+ dStat: float = np.float32(0.0)
854
+ IKH: np.ndarray = np.zeros(shape=(2, 2), dtype=np.float32)
855
+ matrixEInverse: np.ndarray = np.zeros(shape=(m, m), dtype=np.float32)
856
+
857
+ matrixF: np.ndarray = constructMatrixF(deltaF)
858
+ matrixQ: np.ndarray = constructMatrixQ(minQ, offDiagQ=offDiagQ)
859
+ matrixQCopy: np.ndarray = matrixQ.copy()
860
+ matrixP: np.ndarray = np.eye(2, dtype=np.float32) * np.float32(
861
+ stateCovarInit
862
+ )
863
+ matrixH: np.ndarray = constructMatrixH(m, coefficients=coefficientsH)
864
+ matrixK: np.ndarray = np.zeros((2, m), dtype=np.float32)
865
+ vectorX: np.ndarray = np.array([stateInit, 0.0], dtype=np.float32)
866
+ vectorY: np.ndarray = np.zeros(m, dtype=np.float32)
867
+ matrixI2: np.ndarray = np.eye(2, dtype=np.float32)
868
+
869
+ if residualCovarInversionFunc is None:
870
+ residualCovarInversionFunc = cconsenrich.cinvertMatrixE
871
+ if adjustProcessNoiseFunc is None:
872
+ adjustProcessNoiseFunc = cconsenrich.updateProcessNoiseCovariance
873
+
874
+ # ==========================
875
+ # forward: 0,1,2,...,n-1
876
+ # ==========================
877
+ stateForward = np.memmap(
878
+ NamedTemporaryFile(delete=True),
879
+ dtype=np.float32,
880
+ mode="w+",
881
+ shape=(n, 2),
882
+ )
883
+ stateCovarForward = np.memmap(
884
+ NamedTemporaryFile(delete=True),
885
+ dtype=np.float32,
886
+ mode="w+",
887
+ shape=(n, 2, 2),
888
+ )
889
+ pNoiseForward = np.memmap(
890
+ NamedTemporaryFile(delete=True),
891
+ dtype=np.float32,
892
+ mode="w+",
893
+ shape=(n, 2, 2),
894
+ )
895
+ progressIter = max(1, progressIter)
896
+ for i in range(n):
897
+ if i % progressIter == 0:
898
+ logger.info(f"Forward pass interval: {i + 1}/{n}")
899
+ vectorZ = matrixData[:, i]
900
+ vectorX = matrixF @ vectorX
901
+ matrixP = matrixF @ matrixP @ matrixF.T + matrixQ
902
+ vectorY = vectorZ - (matrixH @ vectorX)
903
+
904
+ matrixEInverse = residualCovarInversionFunc(
905
+ matrixMunc[:, i], np.float32(matrixP[0, 0])
906
+ )
907
+ Einv_diag = np.diag(matrixEInverse)
908
+ dStat = np.median((vectorY**2) * Einv_diag)
909
+ matrixQ, inflatedQ = adjustProcessNoiseFunc(
910
+ matrixQ,
911
+ matrixQCopy,
912
+ dStat,
913
+ dStatAlpha,
914
+ dStatd,
915
+ dStatPC,
916
+ inflatedQ,
917
+ maxQ,
918
+ minQ,
919
+ )
920
+ matrixK = (matrixP @ matrixH.T) @ matrixEInverse
921
+ IKH = matrixI2 - (matrixK @ matrixH)
922
+
923
+ vectorX = vectorX + (matrixK @ vectorY)
924
+ matrixP = (IKH) @ matrixP @ (IKH).T + (
925
+ matrixK * matrixMunc[:, i]
926
+ ) @ matrixK.T
927
+ stateForward[i] = vectorX.astype(np.float32)
928
+ stateCovarForward[i] = matrixP.astype(np.float32)
929
+ pNoiseForward[i] = matrixQ.astype(np.float32)
930
+
931
+ if i % chunkSize == 0 and i > 0:
932
+ stateForward.flush()
933
+ stateCovarForward.flush()
934
+ pNoiseForward.flush()
935
+
936
+ stateForward.flush()
937
+ stateCovarForward.flush()
938
+ pNoiseForward.flush()
939
+ stateForwardArr = stateForward
940
+ stateCovarForwardArr = stateCovarForward
941
+ pNoiseForwardArr = pNoiseForward
942
+
943
+ # ==========================
944
+ # backward: n,n-1,n-2,...,0
945
+ # ==========================
946
+ stateSmoothed = np.memmap(
947
+ NamedTemporaryFile(delete=True),
948
+ dtype=np.float32,
949
+ mode="w+",
950
+ shape=(n, 2),
951
+ )
952
+ stateCovarSmoothed = np.memmap(
953
+ NamedTemporaryFile(delete=True),
954
+ dtype=np.float32,
955
+ mode="w+",
956
+ shape=(n, 2, 2),
957
+ )
958
+ postFitResiduals = np.memmap(
959
+ NamedTemporaryFile(delete=True),
960
+ dtype=np.float32,
961
+ mode="w+",
962
+ shape=(n, m),
963
+ )
964
+
965
+ stateSmoothed[-1] = np.float32(stateForwardArr[-1])
966
+ stateCovarSmoothed[-1] = np.float32(stateCovarForwardArr[-1])
967
+ postFitResiduals[-1] = np.float32(
968
+ matrixData[:, -1] - (matrixH @ stateSmoothed[-1])
969
+ )
970
+
971
+ for k in range(n - 2, -1, -1):
972
+ if k % progressIter == 0:
973
+ logger.info(f"Backward pass interval: {k + 1}/{n}")
974
+ forwardStatePosterior = stateForwardArr[k]
975
+ forwardCovariancePosterior = stateCovarForwardArr[k]
976
+ backwardInitialState = matrixF @ forwardStatePosterior
977
+ backwardInitialCovariance = (
978
+ matrixF @ forwardCovariancePosterior @ matrixF.T
979
+ + pNoiseForwardArr[k + 1]
980
+ )
981
+
982
+ smootherGain = np.linalg.solve(
983
+ backwardInitialCovariance.T,
984
+ (forwardCovariancePosterior @ matrixF.T).T,
985
+ ).T
986
+ stateSmoothed[k] = (
987
+ forwardStatePosterior
988
+ + smootherGain @ (stateSmoothed[k + 1] - backwardInitialState)
989
+ ).astype(np.float32)
990
+
991
+ stateCovarSmoothed[k] = (
992
+ forwardCovariancePosterior
993
+ + smootherGain
994
+ @ (stateCovarSmoothed[k + 1] - backwardInitialCovariance)
995
+ @ smootherGain.T
996
+ ).astype(np.float32)
997
+ postFitResiduals[k] = np.float32(
998
+ matrixData[:, k] - matrixH @ stateSmoothed[k]
999
+ )
1000
+
1001
+ if k % chunkSize == 0 and k > 0:
1002
+ stateSmoothed.flush()
1003
+ stateCovarSmoothed.flush()
1004
+ postFitResiduals.flush()
1005
+
1006
+ stateSmoothed.flush()
1007
+ stateCovarSmoothed.flush()
1008
+ postFitResiduals.flush()
1009
+ if boundState:
1010
+ stateSmoothed[:, 0] = np.clip(
1011
+ stateSmoothed[:, 0], stateLowerBound, stateUpperBound
1012
+ ).astype(np.float32)
1013
+
1014
+ return stateSmoothed[:], stateCovarSmoothed[:], postFitResiduals[:]
1015
+
1016
+
1017
+ def getPrimaryState(
1018
+ stateVectors: np.ndarray, roundPrecision: int = 3
1019
+ ) -> npt.NDArray[np.float32]:
1020
+ r"""Get the primary state estimate from each vector after running Consenrich.
1021
+
1022
+ :param stateVectors: State vectors from :func:`runConsenrich`.
1023
+ :type stateVectors: npt.NDArray[np.float32]
1024
+ :return: A one-dimensional numpy array of the primary state estimates.
1025
+ :rtype: npt.NDArray[np.float32]
1026
+ """
1027
+ out_ = np.ascontiguousarray(stateVectors[:,0], dtype=np.float32)
1028
+ np.round(out_, decimals=roundPrecision, out=out_)
1029
+ return out_
1030
+
1031
+
1032
+ def getStateCovarTrace(
1033
+ stateCovarMatrices: np.ndarray, roundPrecision: int = 3
1034
+ ) -> npt.NDArray[np.float32]:
1035
+ r"""Get a one-dimensional array of state covariance traces after running Consenrich
1036
+
1037
+ :param stateCovarMatrices: Estimated state covariance matrices :math:`\widetilde{\mathbf{P}}_{[i]}`
1038
+ :type stateCovarMatrices: np.ndarray
1039
+ :return: A one-dimensional numpy array of the traces of the state covariance matrices.
1040
+ :rtype: npt.NDArray[np.float32]
1041
+ """
1042
+ stateCovarMatrices = np.ascontiguousarray(
1043
+ stateCovarMatrices, dtype=np.float32
1044
+ )
1045
+ out_ = cconsenrich.cgetStateCovarTrace(stateCovarMatrices)
1046
+ np.round(out_, decimals=roundPrecision, out=out_)
1047
+ return out_
1048
+
1049
+
1050
+ def getPrecisionWeightedResidual(
1051
+ postFitResiduals: np.ndarray,
1052
+ matrixMunc: np.ndarray,
1053
+ roundPrecision: int = 3,
1054
+ stateCovarSmoothed: Optional[np.ndarray] = None,
1055
+ ) -> npt.NDArray[np.float32]:
1056
+ r"""Get a one-dimensional precision-weighted array residuals after running Consenrich.
1057
+
1058
+ Applies an inverse-variance weighting of the post-fit residuals :math:`\widetilde{\mathbf{y}}_{[i]}` and
1059
+ returns a one-dimensional array of "precision-weighted residuals". The state-level uncertainty can also be
1060
+ incorporated given `stateCovarSmoothed`.
1061
+
1062
+ :param postFitResiduals: Post-fit residuals :math:`\widetilde{\mathbf{y}}_{[i]}` from :func:`runConsenrich`.
1063
+ :type postFitResiduals: np.ndarray
1064
+ :param matrixMunc: An :math:`m \times n` sample-by-interval matrix -- At genomic intervals :math:`i = 1,2,\ldots,n`, the respective length-:math:`m` column is :math:`\mathbf{R}_{[i,11:mm]}`.
1065
+ That is, the observation noise levels for each sample :math:`j=1,2,\ldots,m` at interval :math:`i`. To keep memory usage minimal `matrixMunc` is not returned in full or computed in
1066
+ in :func:`runConsenrich`. If using Consenrich programmatically, run :func:`consenrich.core.getMuncTrack` for each sample's count data (rows in the matrix output of :func:`readBamSegments`).
1067
+ :type matrixMunc: np.ndarray
1068
+ :param stateCovarSmoothed: Smoothed state covariance matrices :math:`\widetilde{\mathbf{P}}_{[i]}` from :func:`runConsenrich`.
1069
+ :type stateCovarSmoothed: Optional[np.ndarray]
1070
+ :return: A one-dimensional array of "precision-weighted residuals"
1071
+ :rtype: npt.NDArray[np.float32]
1072
+ """
1073
+
1074
+ n, m = postFitResiduals.shape
1075
+ if matrixMunc.shape != (m, n):
1076
+ raise ValueError(
1077
+ f"matrixMunc should be (m,n)=({m}, {n}): observed {matrixMunc.shape}"
1078
+ )
1079
+ if stateCovarSmoothed is not None and (
1080
+ stateCovarSmoothed.ndim < 3 or len(stateCovarSmoothed) != n
1081
+ ):
1082
+ raise ValueError(
1083
+ "stateCovarSmoothed must be shape (n) x (2,2) (if provided)"
1084
+ )
1085
+
1086
+ postFitResiduals_CContig = np.ascontiguousarray(
1087
+ postFitResiduals, dtype=np.float32
1088
+ )
1089
+
1090
+ needsCopy = (
1091
+ (stateCovarSmoothed is not None) and len(stateCovarSmoothed) == n) or (not matrixMunc.flags.writeable)
1092
+
1093
+ matrixMunc_CContig = np.array(
1094
+ matrixMunc, dtype=np.float32, order="C", copy=needsCopy
1095
+ )
1096
+
1097
+ if needsCopy:
1098
+ # adds the 'primary' state uncertainty to observation noise covariance :math:`\mathbf{R}_{[i,:]}`
1099
+ # primary state uncertainty (0,0) :math:`\mathbf{P}_{[i]} \in \mathbb{R}^{2 \times 2}`
1100
+ stateCovarArr00 = np.asarray(stateCovarSmoothed[:, 0, 0], dtype=np.float32)
1101
+ matrixMunc_CContig += stateCovarArr00
1102
+
1103
+ np.maximum(matrixMunc_CContig, np.float32(1e-8), out=matrixMunc_CContig)
1104
+ out = cconsenrich.cgetPrecisionWeightedResidual(
1105
+ postFitResiduals_CContig, matrixMunc_CContig
1106
+ )
1107
+ np.round(out, decimals=roundPrecision, out=out)
1108
+ return out
1109
+
1110
+
1111
+ def getMuncTrack(
1112
+ chromosome: str,
1113
+ intervals: np.ndarray,
1114
+ stepSize: int,
1115
+ rowValues: np.ndarray,
1116
+ minR: float,
1117
+ maxR: float,
1118
+ useALV: bool,
1119
+ useConstantNoiseLevel: bool,
1120
+ noGlobal: bool,
1121
+ localWeight: float,
1122
+ globalWeight: float,
1123
+ approximationWindowLengthBP: int,
1124
+ lowPassWindowLengthBP: int,
1125
+ returnCenter: bool,
1126
+ sparseMap: Optional[dict[int, int]] = None,
1127
+ lowPassFilterType: Optional[str] = "median",
1128
+ ) -> npt.NDArray[np.float32]:
1129
+ r"""Get observation noise variance :math:`R_{[:,jj]}` for the sample :math:`j`.
1130
+
1131
+ Combines a local ALV estimate (see :func:`getAverageLocalVarianceTrack`) with an
1132
+ optional global component. If ``useALV`` is True, *only* the ALV is used. If
1133
+ ``useConstantNoiseLevel`` is True, a constant track set to the global mean is used.
1134
+ When a ``sparseMap`` is provided, local values are aggregated over nearby 'sparse'
1135
+ regions before mixing with the global component.
1136
+
1137
+ For heterochromatic or repressive marks (H3K9me3, H3K27me3, MNase-seq, etc.), consider setting
1138
+ `useALV=True` to prevent inflated sample-level noise estimates.
1139
+
1140
+ :param chromosome: Tracks are approximated for this chromosome.
1141
+ :type chromosome: str
1142
+ :param intervals: Genomic intervals for which to compute the noise track.
1143
+ :param stepSize: See :class:`countingParams`.
1144
+ :type stepSize: int
1145
+ :param rowValues: Read-density-based values for the sample :math:`j` at the genomic intervals :math:`i=1,2,\ldots,n`.
1146
+ :type rowValues: np.ndarray
1147
+ :param minR: See :class:`observationParams`.
1148
+ :type minR: float
1149
+ :param maxR: See :class:`observationParams`.
1150
+ :type maxR: float
1151
+ :param useALV: See :class:`observationParams`.
1152
+ :type useALV: bool
1153
+ :param useConstantNoiseLevel: See :class:`observationParams`.
1154
+ :type useConstantNoiseLevel: bool
1155
+ :param noGlobal: See :class:`observationParams`.
1156
+ :type noGlobal: bool
1157
+ :param localWeight: See :class:`observationParams`.
1158
+ :type localWeight: float
1159
+ :param globalWeight: See :class:`observationParams`.
1160
+ :type globalWeight: float
1161
+ :param approximationWindowLengthBP: See :class:`observationParams` and/or :func:`getAverageLocalVarianceTrack`.
1162
+ :type approximationWindowLengthBP: int
1163
+ :param lowPassWindowLengthBP: See :class:`observationParams` and/or :func:`getAverageLocalVarianceTrack`.
1164
+ :type lowPassWindowLengthBP: int
1165
+ :param sparseMap: Optional mapping (dictionary) of interval indices to the nearest sparse regions. See :func:`getSparseMap`.
1166
+ :type sparseMap: Optional[dict[int, int]]
1167
+ :param lowPassFilterType: The type of low-pass filter to use in average local variance track (e.g., 'median', 'mean').
1168
+ :type lowPassFilterType: Optional[str]
1169
+ :return: A one-dimensional numpy array of the observation noise track for the sample :math:`j`.
1170
+ :rtype: npt.NDArray[np.float32]
1171
+
1172
+ """
1173
+ trackALV = getAverageLocalVarianceTrack(
1174
+ rowValues,
1175
+ stepSize,
1176
+ approximationWindowLengthBP,
1177
+ lowPassWindowLengthBP,
1178
+ minR,
1179
+ maxR,
1180
+ lowPassFilterType,
1181
+ ).astype(np.float32)
1182
+
1183
+ globalNoise: float = np.float32(np.mean(trackALV))
1184
+ if noGlobal or globalWeight == 0 or useALV:
1185
+ return np.clip(trackALV, minR, maxR).astype(np.float32)
1186
+
1187
+ if useConstantNoiseLevel or localWeight == 0 and sparseMap is None:
1188
+ return np.clip(
1189
+ globalNoise * np.ones_like(rowValues), minR, maxR
1190
+ ).astype(np.float32)
1191
+
1192
+ if sparseMap is not None:
1193
+ trackALV = cconsenrich.cSparseAvg(trackALV, sparseMap)
1194
+
1195
+ return np.clip(
1196
+ trackALV * localWeight + np.mean(trackALV) * globalWeight, minR, maxR
1197
+ ).astype(np.float32)
1198
+
1199
+
1200
+ def sparseIntersection(
1201
+ chromosome: str, intervals: np.ndarray, sparseBedFile: str
1202
+ ) -> npt.NDArray[np.int64]:
1203
+ r"""Returns intervals in the chromosome that overlap with the sparse features.
1204
+
1205
+ Not relevant if `observationParams.useALV` is True.
1206
+
1207
+ :param chromosome: The chromosome name.
1208
+ :type chromosome: str
1209
+ :param intervals: The genomic intervals to consider.
1210
+ :type intervals: np.ndarray
1211
+ :param sparseBedFile: Path to the sparse BED file.
1212
+ :type sparseBedFile: str
1213
+ :return: A numpy array of start positions of the sparse features that overlap with the intervals
1214
+ :rtype: np.ndarray[Tuple[Any], np.dtype[Any]]
1215
+ """
1216
+
1217
+ stepSize: int = intervals[1] - intervals[0]
1218
+ chromFeatures: bed.BedTool = (
1219
+ bed.BedTool(sparseBedFile)
1220
+ .sort()
1221
+ .merge()
1222
+ .filter(
1223
+ lambda b: (
1224
+ b.chrom == chromosome
1225
+ and b.start > intervals[0]
1226
+ and b.end < intervals[-1]
1227
+ and (b.end - b.start) >= stepSize
1228
+ )
1229
+ )
1230
+ )
1231
+ centeredFeatures: bed.BedTool = chromFeatures.each(
1232
+ adjustFeatureBounds, stepSize=stepSize
1233
+ )
1234
+
1235
+ start0: int = int(intervals[0])
1236
+ last: int = int(intervals[-1])
1237
+ chromFeatures: bed.BedTool = (
1238
+ bed.BedTool(sparseBedFile)
1239
+ .sort()
1240
+ .merge()
1241
+ .filter(
1242
+ lambda b: (
1243
+ b.chrom == chromosome
1244
+ and b.start > start0
1245
+ and b.end < last
1246
+ and (b.end - b.start) >= stepSize
1247
+ )
1248
+ )
1249
+ )
1250
+ centeredFeatures: bed.BedTool = chromFeatures.each(
1251
+ adjustFeatureBounds, stepSize=stepSize
1252
+ )
1253
+ centeredStarts = []
1254
+ for f in centeredFeatures:
1255
+ s = int(f.start)
1256
+ if start0 <= s <= last and (s - start0) % stepSize == 0:
1257
+ centeredStarts.append(s)
1258
+ return np.asarray(centeredStarts, dtype=np.int64)
1259
+
1260
+
1261
+ def adjustFeatureBounds(feature: bed.Interval, stepSize: int) -> bed.Interval:
1262
+ r"""Adjust the start and end positions of a BED feature to be centered around a step."""
1263
+ feature.start = cconsenrich.stepAdjustment(
1264
+ (feature.start + feature.end) // 2, stepSize
1265
+ )
1266
+ feature.end = feature.start + stepSize
1267
+ return feature
1268
+
1269
+
1270
+ def getSparseMap(
1271
+ chromosome: str,
1272
+ intervals: np.ndarray,
1273
+ numNearest: int,
1274
+ sparseBedFile: str,
1275
+ ) -> dict:
1276
+ r"""Build a map between each genomic interval and numNearest sparse features
1277
+
1278
+ :param chromosome: The chromosome name. Note, this function only needs to be run once per chromosome.
1279
+ :type chromosome: str
1280
+ :param intervals: The genomic intervals to map.
1281
+ :type intervals: np.ndarray
1282
+ :param numNearest: The number of nearest sparse features to consider
1283
+ :type numNearest: int
1284
+ :param sparseBedFile: path to the sparse BED file.
1285
+ :type sparseBedFile: str
1286
+ :return: A dictionary mapping each interval index to the indices of the nearest sparse regions.
1287
+ :rtype: dict[int, np.ndarray]
1288
+
1289
+ """
1290
+ numNearest = numNearest
1291
+ sparseStarts = sparseIntersection(chromosome, intervals, sparseBedFile)
1292
+ idxSparseInIntervals = np.searchsorted(intervals, sparseStarts, side="left")
1293
+ centers = np.searchsorted(sparseStarts, intervals, side="left")
1294
+ sparseMap: dict = {}
1295
+ for i, (interval, center) in enumerate(zip(intervals, centers)):
1296
+ left = max(0, center - numNearest)
1297
+ right = min(len(sparseStarts), center + numNearest)
1298
+ candidates = np.arange(left, right)
1299
+ dists = np.abs(sparseStarts[candidates] - interval)
1300
+ take = np.argsort(dists)[:numNearest]
1301
+ sparseMap[i] = idxSparseInIntervals[candidates[take]]
1302
+ return sparseMap
1303
+
1304
+
1305
+ def getBedMask(
1306
+ chromosome: str,
1307
+ bedFile: str,
1308
+ intervals: np.ndarray,
1309
+ ) -> np.ndarray:
1310
+ r"""Return a 1/0 mask for intervals overlapping a sorted and merged BED file.
1311
+
1312
+ This function is a wrapper for :func:`cconsenrich.cbedMask`.
1313
+
1314
+ :param chromosome: The chromosome name.
1315
+ :type chromosome: str
1316
+ :param intervals: chromosome-specific, sorted, non-overlapping start positions of genomic intervals.
1317
+ Each interval is assumed `stepSize`.
1318
+ :type intervals: np.ndarray
1319
+ :param bedFile: Path to a sorted and merged BED file
1320
+ :type bedFile: str
1321
+ :return: An `intervals`-length mask s.t. True indicates the interval overlaps a feature in the BED file.
1322
+ :rtype: np.ndarray
1323
+ """
1324
+ if not os.path.exists(bedFile):
1325
+ raise ValueError(f"Could not find {bedFile}")
1326
+ if len(intervals) < 2:
1327
+ raise ValueError("intervals must contain at least two positions")
1328
+ bedFile_ = str(bedFile)
1329
+
1330
+ # (possibly redundant) creation of uint32 version
1331
+ # + quick check for constant steps
1332
+ intervals_ = np.asarray(intervals, dtype=np.uint32)
1333
+ if (intervals_[1] - intervals_[0]) != (intervals_[-1] - intervals_[-2]):
1334
+ raise ValueError("Intervals are not fixed in size")
1335
+
1336
+ stepSize_: int = intervals[1] - intervals[0]
1337
+ return cconsenrich.cbedMask(
1338
+ chromosome,
1339
+ bedFile_,
1340
+ intervals_,
1341
+ stepSize_,
1342
+ ).astype(np.bool_)