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/detrorm.py ADDED
@@ -0,0 +1,239 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+ from typing import List, Optional, Tuple
5
+ import logging
6
+ import re
7
+ import numpy as np
8
+ import pandas as pd
9
+ import pybedtools as bed
10
+ import pysam as sam
11
+
12
+ from scipy import signal, ndimage
13
+
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format="%(asctime)s - %(module)s.%(funcName)s - %(levelname)s - %(message)s",
17
+ )
18
+ logging.basicConfig(
19
+ level=logging.WARNING,
20
+ format="%(asctime)s - %(module)s.%(funcName)s - %(levelname)s - %(message)s",
21
+ )
22
+ logger = logging.getLogger(__name__)
23
+
24
+ from .misc_util import getChromSizesDict
25
+ from .constants import EFFECTIVE_GENOME_SIZES
26
+
27
+
28
+ def getScaleFactor1x(
29
+ bamFile: str,
30
+ effectiveGenomeSize: int,
31
+ readLength: int,
32
+ excludeChroms: List[str],
33
+ chromSizesFile: str,
34
+ samThreads: int,
35
+ ) -> float:
36
+ r"""Generic normalization factor based on effective genome size and number of mapped reads in non-excluded chromosomes.
37
+
38
+ :param bamFile: See :class:`consenrich.core.inputParams`.
39
+ :type bamFile: str
40
+ :param effectiveGenomeSize: Effective genome size in base pairs. See :func:`consenrich.constants.getEffectiveGenomeSize`.
41
+ :type effectiveGenomeSize: int
42
+ :param readLength: read length or fragment length
43
+ :type readLength: int
44
+ :param excludeChroms: List of chromosomes to exclude from the analysis.
45
+ :type excludeChroms: List[str]
46
+ :param chromSizesFile: Path to the chromosome sizes file.
47
+ :type chromSizesFile: str
48
+ :param samThreads: See :class:`consenrich.core.samParams`.
49
+ :type samThreads: int
50
+ :return: Scale factor for 1x normalization.
51
+ :rtype: float
52
+ """
53
+ if excludeChroms is not None:
54
+ if chromSizesFile is None:
55
+ raise ValueError(
56
+ "`excludeChroms` is provided...so must be `chromSizesFile`."
57
+ )
58
+ chromSizes: dict = getChromSizesDict(chromSizesFile)
59
+ for chrom in excludeChroms:
60
+ if chrom not in chromSizes:
61
+ continue
62
+ effectiveGenomeSize -= chromSizes[chrom]
63
+ totalMappedReads: int = -1
64
+ with sam.AlignmentFile(bamFile, "rb", threads=samThreads) as aln:
65
+ totalMappedReads = aln.mapped
66
+ if excludeChroms is not None:
67
+ idxStats = aln.get_index_statistics()
68
+ for element in idxStats:
69
+ if element.contig in excludeChroms:
70
+ totalMappedReads -= element.mapped
71
+ if totalMappedReads <= 0 or effectiveGenomeSize <= 0:
72
+ raise ValueError(
73
+ f"Negative EGS after removing excluded chromosomes or no mapped reads: EGS={effectiveGenomeSize}, totalMappedReads={totalMappedReads}."
74
+ )
75
+ return round(effectiveGenomeSize / (totalMappedReads * readLength), 4)
76
+
77
+
78
+ def getScaleFactorPerMillion(bamFile: str, excludeChroms: List[str]) -> float:
79
+ r"""Generic normalization factor based on number of mapped reads in non-excluded chromosomes.
80
+
81
+ :param bamFile: See :class:`consenrich.core.inputParams`.
82
+ :type bamFile: str
83
+ :param excludeChroms: List of chromosomes to exclude when counting mapped reads.
84
+ :type excludeChroms: List[str]
85
+ :return: Scale factor accounting for number of mapped reads (only).
86
+ :rtype: float
87
+ """
88
+ if not os.path.exists(bamFile):
89
+ raise FileNotFoundError(f"BAM file {bamFile} does not exist.")
90
+ totalMappedReads: int = 0
91
+ with sam.AlignmentFile(bamFile, "rb") as aln:
92
+ totalMappedReads = aln.mapped
93
+ if excludeChroms is not None:
94
+ idxStats = aln.get_index_statistics()
95
+ for element in idxStats:
96
+ if element.contig in excludeChroms:
97
+ totalMappedReads -= element.mapped
98
+ if totalMappedReads <= 0:
99
+ raise ValueError(
100
+ f"After removing reads mapping to excluded chroms, totalMappedReads is {totalMappedReads}."
101
+ )
102
+ scalePM = round(1_000_000 / totalMappedReads, 4)
103
+ return scalePM
104
+
105
+
106
+ def getPairScaleFactors(
107
+ bamFileA: str,
108
+ bamFileB: str,
109
+ effectiveGenomeSizeA: int,
110
+ effectiveGenomeSizeB: int,
111
+ readLengthA: int,
112
+ readLengthB: int,
113
+ excludeChroms: List[str],
114
+ chromSizesFile: str,
115
+ samThreads: int,
116
+ scaleDown: bool = True,
117
+ ) -> Tuple[float, float]:
118
+ r"""Get scaling constants that normalize two alignment files to each other (e.g. ChIP-seq treatment and control) with respect to sequence coverage.
119
+
120
+ :param bamFileA: Path to the first BAM file.
121
+ :type bamFileA: str
122
+ :param bamFileB: Path to the second BAM file.
123
+ :type bamFileB: str
124
+ :param effectiveGenomeSizeA: Effective genome size for the first BAM file.
125
+ :type effectiveGenomeSizeA: int
126
+ :param effectiveGenomeSizeB: Effective genome size for the second BAM file.
127
+ :type effectiveGenomeSizeB: int
128
+ :param readLengthA: read length or fragment length for the first BAM file.
129
+ :type readLengthA: int
130
+ :param readLengthB: read length or fragment length for the second BAM file.
131
+ :type readLengthB: int
132
+ :param excludeChroms: List of chromosomes to exclude from the analysis.
133
+ :type excludeChroms: List[str]
134
+ :param chromSizesFile: Path to the chromosome sizes file.
135
+ :type chromSizesFile: str
136
+ :param samThreads: Number of threads to use for reading BAM files.
137
+ :type samThreads: int
138
+ :return: A tuple containing the scale factors for the first and second BAM files.
139
+ :rtype: Tuple[float, float]
140
+ """
141
+ scaleFactorA = getScaleFactor1x(
142
+ bamFileA,
143
+ effectiveGenomeSizeA,
144
+ readLengthA,
145
+ excludeChroms,
146
+ chromSizesFile,
147
+ samThreads,
148
+ )
149
+ scaleFactorB = getScaleFactor1x(
150
+ bamFileB,
151
+ effectiveGenomeSizeB,
152
+ readLengthB,
153
+ excludeChroms,
154
+ chromSizesFile,
155
+ samThreads,
156
+ )
157
+ logger.info(
158
+ f"Initial scale factors: {bamFileA}: {scaleFactorA}, {bamFileB}: {scaleFactorB}"
159
+ )
160
+ if not scaleDown:
161
+ return scaleFactorA, scaleFactorB
162
+ coverageA = 1 / scaleFactorA
163
+ coverageB = 1 / scaleFactorB
164
+ if coverageA < coverageB:
165
+ scaleFactorB *= coverageA / coverageB
166
+ scaleFactorA = 1.0
167
+ else:
168
+ scaleFactorA *= coverageB / coverageA
169
+ scaleFactorB = 1.0
170
+
171
+ logger.info(
172
+ f"Final scale factors: {bamFileA}: {scaleFactorA}, {bamFileB}: {scaleFactorB}"
173
+ )
174
+
175
+ ratio = max(scaleFactorA, scaleFactorB) / min(scaleFactorA, scaleFactorB)
176
+ if ratio > 5.0:
177
+ logger.warning(
178
+ f"Scale factors differ > 5x....\n"
179
+ f"\n\tAre effective genome sizes {effectiveGenomeSizeA} and {effectiveGenomeSizeB} correct?"
180
+ f"\n\tAre read/fragment lengths {readLengthA},{readLengthB} correct?"
181
+ )
182
+ return scaleFactorA, scaleFactorB
183
+
184
+
185
+ def detrendTrack(
186
+ values: np.ndarray,
187
+ stepSize: int,
188
+ detrendWindowLengthBP: int,
189
+ useOrderStatFilter: bool,
190
+ usePolyFilter: bool,
191
+ detrendTrackPercentile: float,
192
+ detrendSavitzkyGolayDegree: int,
193
+ ) -> np.ndarray:
194
+ r"""Detrend tracks using either an order statistic filter or a polynomial filter.
195
+
196
+ :param values: Values to detrend.
197
+ :type values: np.ndarray
198
+ :param stepSize: see :class:`consenrich.core.countingParams`.
199
+ :type stepSize: int
200
+ :param detrendWindowLengthBP: See :class:`consenrich.core.detrendParams`.
201
+ :type detrendWindowLengthBP: int
202
+ :param useOrderStatFilter: Whether to use a sliding order statistic filter.
203
+ :type useOrderStatFilter: bool
204
+ :param usePolyFilter: Whether to use a sliding polynomial/least squares filter.
205
+ :type usePolyFilter: bool
206
+ :param detrendTrackPercentile: Percentile to use for the order statistic filter.
207
+ :type detrendTrackPercentile: float
208
+ :param detrendSavitzkyGolayDegree: Degree of the polynomial for the Savitzky-Golay/Polynomial filter.
209
+ :type detrendSavitzkyGolayDegree: int
210
+ :return: Detrended values.
211
+ :rtype: np.ndarray
212
+ :raises ValueError: If the detrend window length is not greater than 3 times the step size
213
+ or if the values length is less than the detrend window length.
214
+ """
215
+ bothSpecified: bool = False
216
+ size = int(detrendWindowLengthBP / stepSize)
217
+ if size % 2 == 0:
218
+ size += 1
219
+ if size < 3:
220
+ raise ValueError("Required: windowLengthBP > 3*stepSize.")
221
+ if len(values) < size:
222
+ raise ValueError("values length must be greater than windowLength.")
223
+
224
+ if useOrderStatFilter and usePolyFilter:
225
+ logger.warning(
226
+ "Both order statistic and polynomial filters specified...using order statistic filter."
227
+ )
228
+ bothSpecified = True
229
+
230
+ if useOrderStatFilter or bothSpecified:
231
+ return values - ndimage.percentile_filter(
232
+ values, detrendTrackPercentile, size=size
233
+ )
234
+ elif usePolyFilter:
235
+ return values - signal.savgol_filter(
236
+ values, size, detrendSavitzkyGolayDegree
237
+ )
238
+
239
+ return values - ndimage.uniform_filter1d(values, size=size, mode="nearest")