consenrich 0.7.5b2__cp314-cp314-macosx_10_15_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.

Potentially problematic release.


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

consenrich/detrorm.py ADDED
@@ -0,0 +1,295 @@
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(
76
+ effectiveGenomeSize / (totalMappedReads * readLength), 5
77
+ )
78
+
79
+
80
+ def getScaleFactorPerMillion(
81
+ bamFile: str, excludeChroms: List[str], stepSize: int
82
+ ) -> float:
83
+ r"""Generic normalization factor based on number of mapped reads in non-excluded chromosomes.
84
+
85
+ :param bamFile: See :class:`consenrich.core.inputParams`.
86
+ :type bamFile: str
87
+ :param excludeChroms: List of chromosomes to exclude when counting mapped reads.
88
+ :type excludeChroms: List[str]
89
+ :return: Scale factor accounting for number of mapped reads (only).
90
+ :rtype: float
91
+ """
92
+ if not os.path.exists(bamFile):
93
+ raise FileNotFoundError(f"BAM file {bamFile} does not exist.")
94
+ totalMappedReads: int = 0
95
+ with sam.AlignmentFile(bamFile, "rb") as aln:
96
+ totalMappedReads = aln.mapped
97
+ if excludeChroms is not None:
98
+ idxStats = aln.get_index_statistics()
99
+ for element in idxStats:
100
+ if element.contig in excludeChroms:
101
+ totalMappedReads -= element.mapped
102
+ if totalMappedReads <= 0:
103
+ raise ValueError(
104
+ f"After removing reads mapping to excluded chroms, totalMappedReads is {totalMappedReads}."
105
+ )
106
+ scalePM = round((1_000_000 / totalMappedReads)*(1000/stepSize), 5)
107
+ return scalePM
108
+
109
+
110
+ def getPairScaleFactors(
111
+ bamFileA: str,
112
+ bamFileB: str,
113
+ effectiveGenomeSizeA: int,
114
+ effectiveGenomeSizeB: int,
115
+ readLengthA: int,
116
+ readLengthB: int,
117
+ excludeChroms: List[str],
118
+ chromSizesFile: str,
119
+ samThreads: int,
120
+ stepSize: int,
121
+ scaleDown: bool = False,
122
+ normMethod: str = "EGS",
123
+ ) -> Tuple[float, float]:
124
+ r"""Get scaling constants that normalize two alignment files to each other (e.g. ChIP-seq treatment and control) with respect to sequence coverage.
125
+
126
+ :param bamFileA: Path to the first BAM file.
127
+ :type bamFileA: str
128
+ :param bamFileB: Path to the second BAM file.
129
+ :type bamFileB: str
130
+ :param effectiveGenomeSizeA: Effective genome size for the first BAM file.
131
+ :type effectiveGenomeSizeA: int
132
+ :param effectiveGenomeSizeB: Effective genome size for the second BAM file.
133
+ :type effectiveGenomeSizeB: int
134
+ :param readLengthA: read length or fragment length for the first BAM file.
135
+ :type readLengthA: int
136
+ :param readLengthB: read length or fragment length for the second BAM file.
137
+ :type readLengthB: int
138
+ :param excludeChroms: List of chromosomes to exclude from the analysis.
139
+ :type excludeChroms: List[str]
140
+ :param chromSizesFile: Path to the chromosome sizes file.
141
+ :type chromSizesFile: str
142
+ :param samThreads: Number of threads to use for reading BAM files.
143
+ :type samThreads: int
144
+ :param normMethod: Normalization method to use ("RPKM" or "EGS").
145
+ :type normMethod: str
146
+ :return: A tuple containing the scale factors for the first and second BAM files.
147
+ :rtype: Tuple[float, float]
148
+ """
149
+ # RPKM
150
+ if normMethod.upper() == "RPKM":
151
+ scaleFactorA = getScaleFactorPerMillion(
152
+ bamFileA,
153
+ excludeChroms,
154
+ stepSize,
155
+ )
156
+ scaleFactorB = getScaleFactorPerMillion(
157
+ bamFileB,
158
+ excludeChroms,
159
+ stepSize,
160
+ )
161
+ logger.info(
162
+ f"Initial scale factors (per million): {bamFileA}: {scaleFactorA}, {bamFileB}: {scaleFactorB}"
163
+ )
164
+
165
+ if not scaleDown:
166
+ return scaleFactorA, scaleFactorB
167
+ coverageA = 1 / scaleFactorA
168
+ coverageB = 1 / scaleFactorB
169
+ if coverageA < coverageB:
170
+ scaleFactorB *= coverageA / coverageB
171
+ scaleFactorA = 1.0
172
+ else:
173
+ scaleFactorA *= coverageB / coverageA
174
+ scaleFactorB = 1.0
175
+
176
+ logger.info(
177
+ f"Final scale factors (per million): {bamFileA}: {scaleFactorA}, {bamFileB}: {scaleFactorB}"
178
+ )
179
+
180
+ ratio = max(scaleFactorA, scaleFactorB) / min(
181
+ scaleFactorA, scaleFactorB
182
+ )
183
+ if ratio > 5.0:
184
+ logger.warning(
185
+ f"Scale factors differ > 5x....\n"
186
+ f"\n\tAre read/fragment lengths {readLengthA},{readLengthB} correct?"
187
+ )
188
+ return scaleFactorA, scaleFactorB
189
+
190
+ # EGS normalization
191
+ scaleFactorA = getScaleFactor1x(
192
+ bamFileA,
193
+ effectiveGenomeSizeA,
194
+ readLengthA,
195
+ excludeChroms,
196
+ chromSizesFile,
197
+ samThreads,
198
+ )
199
+ scaleFactorB = getScaleFactor1x(
200
+ bamFileB,
201
+ effectiveGenomeSizeB,
202
+ readLengthB,
203
+ excludeChroms,
204
+ chromSizesFile,
205
+ samThreads,
206
+ )
207
+ logger.info(
208
+ f"Initial scale factors: {bamFileA}: {scaleFactorA}, {bamFileB}: {scaleFactorB}"
209
+ )
210
+ if not scaleDown:
211
+ return scaleFactorA, scaleFactorB
212
+ coverageA = 1 / scaleFactorA
213
+ coverageB = 1 / scaleFactorB
214
+ if coverageA < coverageB:
215
+ scaleFactorB *= coverageA / coverageB
216
+ scaleFactorA = 1.0
217
+ else:
218
+ scaleFactorA *= coverageB / coverageA
219
+ scaleFactorB = 1.0
220
+
221
+ logger.info(
222
+ f"Final scale factors: {bamFileA}: {scaleFactorA}, {bamFileB}: {scaleFactorB}"
223
+ )
224
+
225
+ ratio = max(scaleFactorA, scaleFactorB) / min(
226
+ scaleFactorA, scaleFactorB
227
+ )
228
+ if ratio > 5.0:
229
+ logger.warning(
230
+ f"Scale factors differ > 5x....\n"
231
+ f"\n\tAre effective genome sizes {effectiveGenomeSizeA} and {effectiveGenomeSizeB} correct?"
232
+ f"\n\tAre read/fragment lengths {readLengthA},{readLengthB} correct?"
233
+ )
234
+ return scaleFactorA, scaleFactorB
235
+
236
+
237
+ def detrendTrack(
238
+ values: np.ndarray,
239
+ stepSize: int,
240
+ detrendWindowLengthBP: int,
241
+ useOrderStatFilter: bool,
242
+ usePolyFilter: bool,
243
+ detrendTrackPercentile: float,
244
+ detrendSavitzkyGolayDegree: int,
245
+ ) -> np.ndarray:
246
+ r"""Detrend tracks using either an order statistic filter or a polynomial filter.
247
+
248
+ :param values: Values to detrend.
249
+ :type values: np.ndarray
250
+ :param stepSize: see :class:`consenrich.core.countingParams`.
251
+ :type stepSize: int
252
+ :param detrendWindowLengthBP: See :class:`consenrich.core.detrendParams`.
253
+ :type detrendWindowLengthBP: int
254
+ :param useOrderStatFilter: Whether to use a sliding order statistic filter.
255
+ :type useOrderStatFilter: bool
256
+ :param usePolyFilter: Whether to use a sliding polynomial/least squares filter.
257
+ :type usePolyFilter: bool
258
+ :param detrendTrackPercentile: Percentile to use for the order statistic filter.
259
+ :type detrendTrackPercentile: float
260
+ :param detrendSavitzkyGolayDegree: Degree of the polynomial for the Savitzky-Golay/Polynomial filter.
261
+ :type detrendSavitzkyGolayDegree: int
262
+ :return: Detrended values.
263
+ :rtype: np.ndarray
264
+ :raises ValueError: If the detrend window length is not greater than 3 times the step size
265
+ or if the values length is less than the detrend window length.
266
+ """
267
+ bothSpecified: bool = False
268
+ size = int(detrendWindowLengthBP / stepSize)
269
+ if size % 2 == 0:
270
+ size += 1
271
+ if size < 3:
272
+ raise ValueError("Required: windowLengthBP > 3*stepSize.")
273
+ if len(values) < size:
274
+ raise ValueError(
275
+ "values length must be greater than windowLength."
276
+ )
277
+
278
+ if useOrderStatFilter and usePolyFilter:
279
+ logger.warning(
280
+ "Both order statistic and polynomial filters specified...using order statistic filter."
281
+ )
282
+ bothSpecified = True
283
+
284
+ if useOrderStatFilter or bothSpecified:
285
+ return values - ndimage.percentile_filter(
286
+ values, detrendTrackPercentile, size=size
287
+ )
288
+ elif usePolyFilter:
289
+ return values - signal.savgol_filter(
290
+ values, size, detrendSavitzkyGolayDegree
291
+ )
292
+
293
+ return values - ndimage.uniform_filter1d(
294
+ values, size=size, mode="nearest"
295
+ )