RBCeq2 2.1.0__py3-none-any.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.
@@ -0,0 +1,132 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Optimized VCF Validator Module with Faster Control Character Check
4
+ ------------------------------
5
+ This module validates VCF files for correct formatting and scans for malicious content in a single pass.
6
+ It replaces the regex-based control character check with a set-based lookup, which is faster.
7
+ """
8
+
9
+ import os
10
+ import gzip
11
+ from dataclasses import dataclass
12
+
13
+ # Precompute a set of disallowed control characters (allowed: tab, newline, carriage return)
14
+ SUSPICIOUS_CHARS = {chr(c) for c in list(range(0, 9)) + list(range(11, 13)) + list(range(14, 32))}
15
+
16
+
17
+ @dataclass
18
+ class VCFValidationResult:
19
+ """
20
+ A data class representing the result of VCF validation.
21
+ ----------
22
+ Attributes
23
+ ----------
24
+ is_valid (bool):
25
+ Indicates if the validation passed.
26
+ errors (list[str]):
27
+ List of error messages encountered during validation.
28
+ """
29
+ is_valid: bool
30
+ errors: list[str]
31
+
32
+
33
+ def open_vcf_file(file_path: str, mode: str = "rt"):
34
+ """
35
+ Open a VCF file that may be plain text or gzip compressed.
36
+
37
+ Args:
38
+ file_path (str): Path to the VCF file.
39
+ mode (str, optional): File open mode. Defaults to "rt".
40
+
41
+ Returns:
42
+ A file object.
43
+ """
44
+ if str(file_path).endswith(".gz"):
45
+ return gzip.open(file_path, mode, encoding="utf-8")
46
+ return open(file_path, mode, encoding="utf-8")
47
+
48
+
49
+ class VCFValidator:
50
+ """
51
+ A class for validating VCF files in a single pass.
52
+ """
53
+ MAX_FILE_SIZE = 2 * 1024 * 1024 * 1024 # 2GB file size limit
54
+
55
+ @staticmethod
56
+ def validate_file(file_path: str) -> VCFValidationResult:
57
+ """
58
+ Validate the VCF file for correct format and malicious content in a single pass.
59
+
60
+ Args:
61
+ file_path (str): Path to the VCF file.
62
+
63
+ Returns:
64
+ VCFValidationResult: Result of validation.
65
+ """
66
+ errors: list[str] = []
67
+
68
+ if not os.path.exists(file_path):
69
+ return VCFValidationResult(False, ["File does not exist."])
70
+
71
+ file_size: int = os.path.getsize(file_path)
72
+ if file_size > VCFValidator.MAX_FILE_SIZE:
73
+ return VCFValidationResult(False, ["File size exceeds allowed limit."])
74
+
75
+ found_fileformat = False
76
+ header_line: str | None = None
77
+
78
+ try:
79
+ with open_vcf_file(file_path, "rt") as f:
80
+ for line in f:
81
+ # Check for malicious content.
82
+ if "\0" in line:
83
+ errors.append("File contains null byte(s).")
84
+ # Replace regex search with set intersection for control characters.
85
+ if set(line) & SUSPICIOUS_CHARS:
86
+ errors.append("File contains suspicious control characters.")
87
+ if "<script" in line.lower():
88
+ errors.append("File contains embedded script tags.")
89
+
90
+ # Check for meta-information header.
91
+ if not found_fileformat and line.startswith("##fileformat=VCF"):
92
+ found_fileformat = True
93
+ # Find header line: first line starting with '#' but not '##'.
94
+ if header_line is None and line.startswith("#") and not line.startswith("##"):
95
+ header_line = line.strip()
96
+ except UnicodeDecodeError:
97
+ return VCFValidationResult(False, ["File is not valid UTF-8 text."])
98
+ except Exception as e:
99
+ return VCFValidationResult(False, [f"Error reading file: {str(e)}"])
100
+
101
+ if not found_fileformat:
102
+ errors.append("Missing '##fileformat=VCF' header.")
103
+
104
+ if header_line is None:
105
+ errors.append("Missing header line starting with '#CHROM'.")
106
+ else:
107
+ columns = header_line.split("\t")
108
+ if len(columns) < 8:
109
+ errors.append("Header line has insufficient columns.")
110
+ else:
111
+ required = ["#CHROM", "POS", "ID", "REF", "ALT", "QUAL", "FILTER", "INFO"]
112
+ for i, col in enumerate(required):
113
+ if columns[i] != col:
114
+ errors.append(f"Header column {i + 1} expected '{col}', found '{columns[i]}'.")
115
+ break
116
+
117
+ # Remove duplicate errors.
118
+ unique_errors = list(dict.fromkeys(errors))
119
+ return VCFValidationResult(len(unique_errors) == 0, unique_errors)
120
+
121
+
122
+ def validate_vcf(file_path: str) -> VCFValidationResult:
123
+ """
124
+ Validate a VCF file for proper format and absence of malicious content.
125
+
126
+ Args:
127
+ file_path (str): Path to the VCF file.
128
+
129
+ Returns:
130
+ VCFValidationResult: Combined result of format and security checks.
131
+ """
132
+ return VCFValidator.validate_file(file_path)
rbceq2/IO/vcf.py ADDED
@@ -0,0 +1,363 @@
1
+ import gzip
2
+ import io
3
+ import os
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import pandas as pd
9
+ from icecream import ic
10
+
11
+ os.environ["POLARS_MAX_THREADS"] = "7" # Must be set before polars import
12
+ import polars as pl
13
+ from loguru import logger
14
+
15
+ from rbceq2.core_logic.constants import COMMON_COLS, HOM_REF_DUMMY_QUAL
16
+
17
+
18
+ @dataclass(slots=True, frozen=False)
19
+ class VCF:
20
+ """A data class to process VCF files for variant calling and analysis.
21
+
22
+ Attributes
23
+ input_vcf (Path | pd.DataFrame):
24
+ The input VCF file path or DataFrame.
25
+ lane_variants (dict[str, Any]):
26
+ Mapping of chromosome to variants specific to lanes.
27
+ unique_variants (set[str]):
28
+ A set of unique variant identifiers.
29
+ """
30
+
31
+ input_vcf: Path | pd.DataFrame | None
32
+ lane_variants: dict[str, Any]
33
+ unique_variants: set[str]
34
+ sample: str = field(init=False)
35
+ df: pd.DataFrame = field(init=False)
36
+ loci: set[str] = field(init=False)
37
+ variants: dict[str, str] = field(init=False)
38
+
39
+ def __post_init__(self):
40
+ """Handle initialization after data class creation."""
41
+ object.__setattr__(self, "df", self.handle_single_or_multi())
42
+ object.__setattr__(self, "sample", self.get_sample())
43
+ self.rename_chrom()
44
+ self.remove_home_ref()
45
+ self.encode_variants()
46
+ self.add_loci()
47
+ object.__setattr__(self, "loci", self.set_loci())
48
+ self.add_lane_variants()
49
+ object.__setattr__(self, "variants", self.get_variants())
50
+
51
+ def handle_single_or_multi(self) -> pd.DataFrame:
52
+ """Handle single or multiple entries in the VCF, returning a DataFrame.
53
+
54
+ Returns:
55
+ pd.DataFrame: The DataFrame representation of the VCF data.
56
+ """
57
+ if isinstance(self.input_vcf, Path):
58
+ vcf = read_vcf(self.input_vcf)
59
+ return filter_VCF_to_BG_variants(vcf, self.unique_variants)
60
+ else:
61
+ return self.input_vcf[0]
62
+
63
+ def rename_chrom(self) -> None:
64
+ """Rename chromosome identifiers by removing the 'chr' prefix."""
65
+ self.df["CHROM"] = self.df["CHROM"].apply(lambda x: x.replace("chr", ""))
66
+
67
+ def remove_home_ref(self) -> None:
68
+ """Remove homozygous reference calls from the DataFrame."""
69
+ self.df = self.df[~self.df["SAMPLE"].str.startswith("0/0")].copy(deep=True)
70
+
71
+ def encode_variants(self) -> None:
72
+ """Encode variants into a unified format in the DataFrame."""
73
+
74
+ def join_vars(chrom: str, pos: str, ref: str, alts: str) -> bool:
75
+ return ",".join([f"{chrom}:{pos}_{ref}_{alt}" for alt in alts.split(",")])
76
+
77
+ self.df["variant"] = self.df.apply(
78
+ lambda x: join_vars(
79
+ x["CHROM"],
80
+ x["POS"],
81
+ x["REF"],
82
+ x["ALT"],
83
+ ),
84
+ axis=1,
85
+ )
86
+
87
+ def add_loci(self) -> None:
88
+ """Add loci identifiers to the DataFrame."""
89
+ self.df["loci"] = self.df.CHROM + ":" + self.df.POS
90
+
91
+ def get_sample(self) -> str:
92
+ """Determine the sample name from the VCF path or DataFrame.
93
+
94
+ Returns:
95
+ str: The sample name.
96
+ """
97
+ if isinstance(self.input_vcf, Path):
98
+ return self.input_vcf.stem
99
+ else:
100
+ return self.input_vcf[-1]
101
+
102
+ def set_loci(self) -> set[str]:
103
+ """Create a set of loci identifiers from the DataFrame.
104
+
105
+ Returns:
106
+ set[str]: The set of loci identifiers.
107
+ """
108
+ return set(self.df.loci)
109
+
110
+ def add_lane_variants(self) -> None:
111
+ """Add lane-specific variants to the DataFrame based on existing loci,
112
+ where Lane variants are those of the type first brought to my attention
113
+ by a paper by Dr. Lane. they are those where a variant in the context
114
+ of a given transcript is just wildtype in a genomic reference. ie
115
+ GRCh37/8
116
+
117
+ Example:
118
+
119
+ 1 - new lanes - HOM loci:
120
+ Generic middle cols = ... =
121
+ ID REF ALT QUAL FILTER INFO GT:GQ:DP:AD:AF:PS ./.:3,89:92:99:0.967:.
122
+
123
+ 1 25643553 ... 1:25643553_ref loci
124
+
125
+ 2 - HET at loci:
126
+ 1 159175354 G A ... 1:159175354_G_A 1:159175354
127
+ Becomes:
128
+ 1 159175354 G A ... 1:159175354_G_A,1:159175354_ref 1:159175354
129
+
130
+ """
131
+
132
+ new_lanes = {}
133
+
134
+ for chrom, loci in self.lane_variants.items():
135
+ # assert 'CHR' not in chrom.upper() #del after a few months of use TODO
136
+ chrom = chrom.replace("chr", "")
137
+ for pos in loci:
138
+ # TODO blindly adding is problematic, what if there's just no read
139
+ # depth - vcf should be forced to report these
140
+ lane_loci = f"{chrom}:{pos}"
141
+ if lane_loci in self.loci:
142
+ GT = (
143
+ self.df.loc[self.df.loci == lane_loci, "SAMPLE"]
144
+ .values[0]
145
+ .split(":")[0]
146
+ )
147
+ assert GT.count("/") == 1 or GT.count("|") == 1
148
+ assert (
149
+ "2" not in GT
150
+ ) # these 2 asserts are designed to find examples so I can sort
151
+ # complex/multi var
152
+ if GT.startswith(("0/1", "0|1", "1/0", "1|0")):
153
+ self.df.loc[self.df.loci == lane_loci, "variant"] = (
154
+ self.df.loc[self.df.loci == lane_loci, "variant"].values[0]
155
+ + f",{lane_loci}_ref"
156
+ )
157
+ else:
158
+ new_lanes[lane_loci] = (
159
+ [chrom, pos]
160
+ + COMMON_COLS[2:-1]
161
+ + ["GT:AD:GQ:DP:PS"]
162
+ + [
163
+ HOM_REF_DUMMY_QUAL,
164
+ f"{lane_loci}_ref",
165
+ "loci",
166
+ ]
167
+ )
168
+ if new_lanes:
169
+ new_lanes_df = pd.DataFrame.from_dict(new_lanes, orient="index")
170
+ new_lanes_df.columns = self.df.columns
171
+ self.df = pd.concat([self.df, new_lanes_df])
172
+
173
+ def get_variants(self) -> dict[str, str]:
174
+ """Retrieve variant information from the DataFrame.
175
+
176
+ Returns:
177
+ dict[str, str]: A dictionary of variants and their associated metrics.
178
+ """
179
+ vcf_variants = {}
180
+ for varaint, metrics, format in zip(
181
+ list(self.df.variant), list(self.df["SAMPLE"]), list(self.df["FORMAT"])
182
+ ):
183
+ if isinstance(metrics, float):
184
+ continue
185
+ assert format.startswith("GT") # needed for add_lane_variants
186
+ mapped_metrics = dict(
187
+ zip(format.strip().split(":"), metrics.strip().split(":"))
188
+ )
189
+ mapped_metrics["GT"] == mapped_metrics["GT"].replace("|", "/")
190
+ if mapped_metrics["GT"] == "0/0":
191
+ continue
192
+ if "," in varaint:
193
+ for variant in varaint.split(","):
194
+ vcf_variants[variant] = mapped_metrics
195
+ else:
196
+ vcf_variants[varaint] = mapped_metrics
197
+
198
+ return vcf_variants
199
+
200
+
201
+ def split_vcf_to_dfs(vcf_df: pd.DataFrame) -> pd.DataFrame:
202
+ """Split multi-sample VCF DataFrame into individual sample DataFrames.
203
+
204
+ Args:
205
+ vcf_df (pd.DataFrame): Multi-sample VCF loaded into a DataFrame.
206
+
207
+ Returns:
208
+ Dict[str, pd.DataFrame]: Dictionary of sample-specific DataFrames.
209
+ """
210
+ # Extract column names related to samples
211
+ sample_cols = [col for col in vcf_df.columns if col not in COMMON_COLS]
212
+
213
+ for sample in sample_cols:
214
+ try:
215
+ assert all(row[1] == "/" for row in vcf_df[sample])
216
+ except TypeError:
217
+ logger.info(f"Sample {sample} is not diploid")
218
+ cols: list[str] = COMMON_COLS + [sample]
219
+ sample_vcf_df = vcf_df[cols].copy(deep=True)
220
+ sample_vcf_df.columns = COMMON_COLS + ["SAMPLE"]
221
+ yield sample_vcf_df, sample
222
+
223
+
224
+ def filter_VCF_to_BG_variants(df: pl.DataFrame, unique_variants) -> pd.DataFrame:
225
+ """Filter a VCF represented as a Polars DataFrame to only include specified variants.
226
+
227
+ This function creates a temporary column 'LOCI' by concatenating the 'CHROM' and
228
+ 'POS' columns, filters the DataFrame to retain only rows where 'LOCI' is in the
229
+ provided unique_variants list, converts the result to a Pandas DataFrame, and
230
+ removes the temporary 'LOCI' column.
231
+
232
+ Args:
233
+ df (pl.DataFrame): A Polars DataFrame containing VCF file data with columns
234
+ such as "CHROM" and "POS".
235
+ unique_variants (list[str]): A list of unique variant identifiers (e.g.,
236
+ "chr:pos") to filter the DataFrame.
237
+
238
+ Returns:
239
+ pd.DataFrame: A Pandas DataFrame containing only the filtered variants from
240
+ the original DataFrame, with the temporary 'LOCI' column removed.
241
+ """
242
+ df = df.with_columns(
243
+ pl.concat_str(pl.col("CHROM"), pl.lit(":"), pl.col("POS")).alias("LOCI")
244
+ )
245
+ filtered_df = df.filter(pl.col("LOCI").is_in(unique_variants))
246
+ if filtered_df.height == 0: # empty
247
+ pandas_df = df.to_pandas(use_pyarrow_extension_array=False)
248
+ else:
249
+ pandas_df = filtered_df.to_pandas(use_pyarrow_extension_array=False)
250
+
251
+ del pandas_df["LOCI"]
252
+
253
+ return pandas_df
254
+
255
+
256
+ class VcfMissingHeaderError(Exception):
257
+ """
258
+ Custom exception raised when a VCF file's header is missing,
259
+ empty, or critically invalid (e.g., missing ##fileformat or #CHROM line).
260
+ """
261
+
262
+ def __init__(
263
+ self, filename=None, message="VCF header is missing or invalid", reason=None
264
+ ):
265
+ """
266
+ Initializes the VcfMissingHeaderError exception.
267
+
268
+ Args:
269
+ filename (str, optional): The path or name of the VCF file. Defaults to None.
270
+ message (str, optional): The base error message.
271
+ Defaults to "VCF header is missing or invalid".
272
+ reason (str, optional): A specific reason for the header failure
273
+ (e.g., "File is empty",
274
+ "Missing '##fileformat' line",
275
+ "Missing '#CHROM' line"). Defaults to None.
276
+ """
277
+ self.filename = filename
278
+ self.base_message = message
279
+ self.reason = reason
280
+
281
+ full_message = self.base_message
282
+ if filename:
283
+ base_filename = os.path.basename(filename)
284
+ full_message += f" in file: '{base_filename}'"
285
+ if reason:
286
+ full_message += f". Reason: {reason}"
287
+
288
+ super().__init__(full_message)
289
+
290
+
291
+ class VcfNoDataError(Exception):
292
+ """
293
+ Custom exception raised when a VCF file is found to contain no
294
+ variant data records (potentially only a header).
295
+ """
296
+
297
+ def __init__(self, filename=None, message="VCF contains no data records"):
298
+ """
299
+ Initializes the VcfNoDataError exception.
300
+
301
+ Args:
302
+ filename (str, optional): The path or name of the VCF file. Defaults to None.
303
+ message (str, optional): The base error message.
304
+ Defaults to "VCF contains no data records".
305
+ """
306
+ self.filename = filename
307
+ self.message = message
308
+
309
+ if filename:
310
+ base_filename = os.path.basename(filename)
311
+ full_message = f"{message} in file: '{base_filename}'"
312
+ else:
313
+ full_message = message
314
+
315
+ super().__init__(full_message)
316
+
317
+ def __str__(self):
318
+ return super().__str__()
319
+
320
+
321
+ def read_vcf(file_path: str) -> pl.DataFrame:
322
+ """Read a VCF file using polars while preserving the header and sample names.
323
+
324
+ This function manually extracts the header (line starting with "#CHROM")
325
+ and skips meta-information lines (starting with "##"). It then constructs a
326
+ CSV-formatted string and parses it with polars.
327
+
328
+ Args:
329
+ file_path (str): Path to the VCF file (can be gzipped).
330
+
331
+ Returns:
332
+ pl.DataFrame: DataFrame containing the VCF data.
333
+ """
334
+ header = None
335
+ # Use gzip.open if file is gzipped, else standard open.
336
+ open_func = gzip.open if str(file_path).endswith(".gz") else open
337
+ with open_func(file_path, "rt") as f:
338
+ # Find header line starting with "#CHROM"
339
+ for line in f:
340
+ if line.startswith("##"):
341
+ continue
342
+ if line.startswith("#"):
343
+ header = line.lstrip("#").strip().split("\t")
344
+ if len(header) == 10:
345
+ header[-1] = "SAMPLE"
346
+ break
347
+
348
+ if header is None:
349
+ raise VcfMissingHeaderError(filename=file_path)
350
+
351
+ header_line = "\t".join(header) + "\n"
352
+ data = f.read()
353
+
354
+ csv_content = header_line + data
355
+ df = pl.read_csv(
356
+ io.StringIO(csv_content),
357
+ separator="\t",
358
+ schema_overrides=dict.fromkeys(["CHROM", "POS", "QUAL"], str),
359
+ )
360
+ if df.is_empty():
361
+ raise VcfNoDataError(filename=file_path)
362
+ df = df.with_columns(df["CHROM"].str.replace("chr", "", literal=True))
363
+ return df
rbceq2/__init__.py ADDED
File without changes
File without changes