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