RBCeq2 2.3.6__tar.gz → 2.4.1__tar.gz

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.
Files changed (56) hide show
  1. {rbceq2-2.3.6/src/rbceq2.egg-info → rbceq2-2.4.1}/PKG-INFO +7 -6
  2. {rbceq2-2.3.6 → rbceq2-2.4.1}/README.md +5 -5
  3. {rbceq2-2.3.6 → rbceq2-2.4.1}/pyproject.toml +2 -1
  4. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/IO/PDF_reports.py +26 -8
  5. rbceq2-2.4.1/src/rbceq2/IO/encoders.py +237 -0
  6. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/IO/record_data.py +34 -19
  7. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/IO/validation.py +30 -11
  8. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/IO/vcf.py +180 -65
  9. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/core_logic/alleles.py +55 -42
  10. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/core_logic/co_existing.py +3 -11
  11. rbceq2-2.4.1/src/rbceq2/core_logic/constants.py +4104 -0
  12. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/core_logic/data_procesing.py +659 -204
  13. rbceq2-2.4.1/src/rbceq2/core_logic/large_variants.py +801 -0
  14. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/core_logic/utils.py +35 -0
  15. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/db/db.py +135 -104
  16. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/filters/geno.py +17 -2
  17. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/filters/knops.py +199 -197
  18. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/filters/phased.py +641 -51
  19. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/filters/shared_filter_functionality.py +23 -24
  20. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/main.py +98 -45
  21. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/phenotype/antigens.py +224 -115
  22. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/phenotype/choose_pheno.py +128 -21
  23. rbceq2-2.4.1/src/rbceq2/resources/db.tsv +2008 -0
  24. rbceq2-2.4.1/src/rbceq2/resources/db_backup.tsv +2008 -0
  25. {rbceq2-2.3.6 → rbceq2-2.4.1/src/rbceq2.egg-info}/PKG-INFO +7 -6
  26. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2.egg-info/SOURCES.txt +4 -0
  27. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2.egg-info/requires.txt +1 -0
  28. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_VCF.py +58 -89
  29. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_data_processing.py +33 -71
  30. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_filters_phase.py +153 -35
  31. rbceq2-2.4.1/tests/test_large_variants.py +292 -0
  32. rbceq2-2.3.6/src/rbceq2/core_logic/constants.py +0 -511
  33. rbceq2-2.3.6/src/rbceq2/resources/db.tsv +0 -2012
  34. {rbceq2-2.3.6 → rbceq2-2.4.1}/LICENSE +0 -0
  35. {rbceq2-2.3.6 → rbceq2-2.4.1}/MANIFEST.in +0 -0
  36. {rbceq2-2.3.6 → rbceq2-2.4.1}/setup.cfg +0 -0
  37. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/IO/__init__.py +0 -0
  38. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/__init__.py +0 -0
  39. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/core_logic/__init__.py +0 -0
  40. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/db/__init__.py +0 -0
  41. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/filters/__init__.py +0 -0
  42. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2/phenotype/__init__.py +0 -0
  43. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2.egg-info/dependency_links.txt +0 -0
  44. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2.egg-info/entry_points.txt +0 -0
  45. {rbceq2-2.3.6 → rbceq2-2.4.1}/src/rbceq2.egg-info/top_level.txt +0 -0
  46. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_IO.py +0 -0
  47. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_alleles.py +0 -0
  48. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_ants.py +0 -0
  49. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_choose_pheno.py +0 -0
  50. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_co_filters.py +0 -0
  51. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_coexisting.py +0 -0
  52. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_db.py +0 -0
  53. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_geno_filters.py +0 -0
  54. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_main.py +0 -0
  55. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_pdf.py +0 -0
  56. {rbceq2-2.3.6 → rbceq2-2.4.1}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rbceq2
3
- Version: 2.3.6
3
+ Version: 2.4.1
4
4
  Summary: Call ISBT alleles from VCF/s
5
5
  Author-email: Liam McIntyre <limcintyre@redcrossblood.org.au>
6
6
  License: Copyright 2025 Australian Red Cross Lifeblood
@@ -26,6 +26,7 @@ Requires-Dist: icecream>=2.1
26
26
  Requires-Dist: loguru>=0.7.2
27
27
  Requires-Dist: pyarrow>=18.1
28
28
  Requires-Dist: reportlab>=4.3.1
29
+ Requires-Dist: frozendict>=2.4.6
29
30
  Provides-Extra: dev
30
31
  Requires-Dist: flake8>=3.9.2; extra == "dev"
31
32
  Requires-Dist: coverage>=7.0; extra == "dev"
@@ -45,17 +46,16 @@ Dynamic: license-file
45
46
  > [!WARNING]
46
47
  > NOT FOR CLINICAL USE
47
48
 
48
- ## Version v2.3.6
49
+ ## Version v2.4.1
49
50
 
50
51
  RBCeq2 reads in genomic variant data in the form of variant call files (VCF) and outputs blood group (BG) genotype and phenotype inference.
51
52
 
52
- At the highest level RBCeq2 finds all possible alleles, then filters out those that fail certain logic checks. This allows for an auditable trail of why it has reached a certain result. Every effort has been made to be explicit both in encoding alleles in our database and while writing code. This results in verbose but unambiguous results. Last, some liberties have been taken to standardise syntax and nomenclature across blood groups.
53
+ At the highest level RBCeq2 finds all possible alleles, then filters out those that fail certain logic checks. This allows for an auditable trail of why it has reached a certain result. Every effort has been made to be explicit both in encoding alleles in our database and while writing code. This results in verbose but unambiguous results. Last, some liberties have been taken to standardise syntax and nomenclature across blood groups.
53
54
 
54
- The initial release of RBCeq2 was focused on perfecting the calling of International Society for Blood Transfusion (ISBT) defined BG alleles from simple variants; single nucleotide variants (SNVs) and small insertions and deletions (indels). Further, it supported the use of long read derived VCFs (i.e. addition of large indels and phased data). However, these features were not as polished. This release (v2.3.1) includes major improvements to the phasing logic – see section 7 of the docs and the change log for details.
55
+ The initial release of RBCeq2 was focused on perfecting the calling of International Society for Blood Transfusion (ISBT) defined BG alleles from simple variants; single nucleotide variants (SNVs) and small insertions and deletions (indels). v2.3.0 focussed on phasing. V2.4.0 (current) focuses on large variants and the RH region, using long read sequencing data.
55
56
 
56
57
  ## Bugs
57
-
58
- This software is extensively tested and accurately reports genotypes/phenotypes based on our inhouse definitions of the ‘correct’ answer, however, there are some examples where the ‘correct’ answer is subjective. The docs are detailed – if you find what you think is a bug in the results from RBCeq2 please take the time to understand if it inline with what we intended or not (use --debug and look to see what happened). We will endeavor to fix any black and white bugs ASAP. Most of these will be rare variants that are encoded wrong in our database. We value any and all feedback and feature requests.
58
+ This software is extensively tested and accurately reports genotypes/phenotypes based on our inhouse definitions of the ‘correct’ answer, however, there are some examples where the ‘correct’ answer is subjective. The docs are detailed – if you find what you think is a bug in the results from RBCeq2 please take the time to understand if it inline with what we intended or not (use --debug and look to see what happened).
59
59
 
60
60
  ## Documentation
61
61
 
@@ -89,4 +89,5 @@ options:
89
89
  --validate Enable VCF validation. Doubles run time. Might help you identify input issues (default: False)
90
90
  --PDFs Generate a per sample PDF report (default: False)
91
91
  --HPAs Generate results for HPA (default: False)
92
+ --RH Generate results for RHD and RHCE. WARNING! Long read only! (default: False)
92
93
  ```
@@ -12,17 +12,16 @@
12
12
  > [!WARNING]
13
13
  > NOT FOR CLINICAL USE
14
14
 
15
- ## Version v2.3.6
15
+ ## Version v2.4.1
16
16
 
17
17
  RBCeq2 reads in genomic variant data in the form of variant call files (VCF) and outputs blood group (BG) genotype and phenotype inference.
18
18
 
19
- At the highest level RBCeq2 finds all possible alleles, then filters out those that fail certain logic checks. This allows for an auditable trail of why it has reached a certain result. Every effort has been made to be explicit both in encoding alleles in our database and while writing code. This results in verbose but unambiguous results. Last, some liberties have been taken to standardise syntax and nomenclature across blood groups.
19
+ At the highest level RBCeq2 finds all possible alleles, then filters out those that fail certain logic checks. This allows for an auditable trail of why it has reached a certain result. Every effort has been made to be explicit both in encoding alleles in our database and while writing code. This results in verbose but unambiguous results. Last, some liberties have been taken to standardise syntax and nomenclature across blood groups.
20
20
 
21
- The initial release of RBCeq2 was focused on perfecting the calling of International Society for Blood Transfusion (ISBT) defined BG alleles from simple variants; single nucleotide variants (SNVs) and small insertions and deletions (indels). Further, it supported the use of long read derived VCFs (i.e. addition of large indels and phased data). However, these features were not as polished. This release (v2.3.1) includes major improvements to the phasing logic – see section 7 of the docs and the change log for details.
21
+ The initial release of RBCeq2 was focused on perfecting the calling of International Society for Blood Transfusion (ISBT) defined BG alleles from simple variants; single nucleotide variants (SNVs) and small insertions and deletions (indels). v2.3.0 focussed on phasing. V2.4.0 (current) focuses on large variants and the RH region, using long read sequencing data.
22
22
 
23
23
  ## Bugs
24
-
25
- This software is extensively tested and accurately reports genotypes/phenotypes based on our inhouse definitions of the ‘correct’ answer, however, there are some examples where the ‘correct’ answer is subjective. The docs are detailed – if you find what you think is a bug in the results from RBCeq2 please take the time to understand if it inline with what we intended or not (use --debug and look to see what happened). We will endeavor to fix any black and white bugs ASAP. Most of these will be rare variants that are encoded wrong in our database. We value any and all feedback and feature requests.
24
+ This software is extensively tested and accurately reports genotypes/phenotypes based on our inhouse definitions of the ‘correct’ answer, however, there are some examples where the ‘correct’ answer is subjective. The docs are detailed – if you find what you think is a bug in the results from RBCeq2 please take the time to understand if it inline with what we intended or not (use --debug and look to see what happened).
26
25
 
27
26
  ## Documentation
28
27
 
@@ -56,4 +55,5 @@ options:
56
55
  --validate Enable VCF validation. Doubles run time. Might help you identify input issues (default: False)
57
56
  --PDFs Generate a per sample PDF report (default: False)
58
57
  --HPAs Generate results for HPA (default: False)
58
+ --RH Generate results for RHD and RHCE. WARNING! Long read only! (default: False)
59
59
  ```
@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
6
6
 
7
7
  [project]
8
8
  name = "rbceq2"
9
- version = "2.3.6"
9
+ version = "2.4.1"
10
10
  description = "Call ISBT alleles from VCF/s"
11
11
  readme = "README.md"
12
12
  license = { file = "LICENSE" }
@@ -30,6 +30,7 @@ dependencies = [
30
30
  "loguru>=0.7.2",
31
31
  "pyarrow>=18.1",
32
32
  "reportlab>=4.3.1",
33
+ "frozendict>=2.4.6"
33
34
  ]
34
35
 
35
36
 
@@ -196,6 +196,7 @@ def _prepare_dataframes(
196
196
  # }
197
197
  # return custom_styles
198
198
 
199
+
199
200
  def _setup_styles() -> Dict[str, ParagraphStyle]:
200
201
  """Creates and returns a dictionary of ReportLab ParagraphStyle objects.
201
202
 
@@ -204,18 +205,24 @@ def _setup_styles() -> Dict[str, ParagraphStyle]:
204
205
  to their corresponding ParagraphStyle objects.
205
206
  """
206
207
  styles = getSampleStyleSheet()
207
- body_style = ParagraphStyle(name='BodyTextSmall', parent=styles['BodyText'], fontSize=9)
208
+ body_style = ParagraphStyle(
209
+ name="BodyTextSmall", parent=styles["BodyText"], fontSize=9
210
+ )
208
211
 
209
212
  table_cell_style = ParagraphStyle(
210
213
  name="TableCell",
211
214
  parent=body_style,
212
- fontSize=7,
213
- leading=9,
215
+ fontSize=7,
216
+ leading=9,
214
217
  )
215
218
  # ****************************************************************
216
219
 
217
220
  footer_style = ParagraphStyle(
218
- name='FooterStyle', parent=styles['Normal'], alignment=1, fontSize=7, textColor=colors.grey # Centered footer
221
+ name="FooterStyle",
222
+ parent=styles["Normal"],
223
+ alignment=1,
224
+ fontSize=7,
225
+ textColor=colors.grey, # Centered footer
219
226
  )
220
227
 
221
228
  custom_styles = {
@@ -223,20 +230,31 @@ def _setup_styles() -> Dict[str, ParagraphStyle]:
223
230
  "heading": styles["h2"],
224
231
  "title": styles["h1"],
225
232
  "report_title": ParagraphStyle(
226
- name="ReportTitle", parent=styles["h1"], alignment=1, fontSize=16 # Centered H1
233
+ name="ReportTitle",
234
+ parent=styles["h1"],
235
+ alignment=1,
236
+ fontSize=16, # Centered H1
227
237
  ),
228
238
  "warning": ParagraphStyle(
229
- name="Warning", parent=styles["Heading1"], textColor=colors.red, alignment=1, fontSize=14
239
+ name="Warning",
240
+ parent=styles["Heading1"],
241
+ textColor=colors.red,
242
+ alignment=1,
243
+ fontSize=14,
230
244
  ),
231
245
  "table_header": ParagraphStyle(
232
246
  # Keep header size reasonable or reduce slightly if needed too
233
- name="TableHeader", parent=styles["BodyText"], fontName="Helvetica-Bold", fontSize=8
247
+ name="TableHeader",
248
+ parent=styles["BodyText"],
249
+ fontName="Helvetica-Bold",
250
+ fontSize=8,
234
251
  ),
235
- "table_cell": table_cell_style, # Use the modified style
252
+ "table_cell": table_cell_style, # Use the modified style
236
253
  "footer": footer_style,
237
254
  }
238
255
  return custom_styles
239
256
 
257
+
240
258
  def _add_page_footer(
241
259
  canvas: canvas.Canvas,
242
260
  doc: BaseDocTemplate,
@@ -0,0 +1,237 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Protocol
3
+ import pandas as pd
4
+ from loguru import logger
5
+
6
+
7
+ class VariantEncoder(Protocol):
8
+ """Protocol defining the interface for variant encoders."""
9
+
10
+ def can_encode(self, row: pd.Series) -> bool:
11
+ """Check if this encoder can handle the given variant row."""
12
+ ...
13
+
14
+ def encode(self, row: pd.Series) -> str:
15
+ """Encode the variant into the desired format."""
16
+ ...
17
+
18
+
19
+ @dataclass(slots=True, frozen=True)
20
+ class SmallVariantEncoder:
21
+ """Encoder for small variants (SNPs, small indels)."""
22
+
23
+ def can_encode(self, row: pd.Series) -> bool:
24
+ """Check if variant is a small variant (not SV)."""
25
+ ref = str(row["REF"])
26
+ alt = str(row["ALT"])
27
+ info = str(row.get("INFO", ""))
28
+
29
+ # Check if it's NOT a structural variant
30
+ return (
31
+ not alt.startswith("<") and not alt.endswith(">") and "SVTYPE=" not in info
32
+ )
33
+
34
+ def encode(self, row: pd.Series) -> str:
35
+ """Encode small variant as chrom:pos_ref_alt."""
36
+ chrom = str(row["CHROM"])
37
+ pos = str(row["POS"])
38
+ ref = str(row["REF"])
39
+ alts = str(row["ALT"]).split(",")
40
+
41
+ return ",".join([f"{chrom}:{pos}_{ref}_{alt}" for alt in alts])
42
+
43
+
44
+ @dataclass(slots=True, frozen=True)
45
+ class Sniffles2Encoder:
46
+ """Encoder for Sniffles2 structural variants.
47
+
48
+ Sniffles2 outputs SVs with SVTYPE and SVLEN in INFO field.
49
+ Example: SVTYPE=DEL;SVLEN=-78874
50
+ """
51
+
52
+ def can_encode(self, row: pd.Series) -> bool:
53
+ """Check if variant is from Sniffles2 (has SVTYPE and SVLEN)."""
54
+ info = str(row.get("INFO", ""))
55
+ return "SVTYPE=" in info and "SVLEN=" in info
56
+
57
+ def encode(self, row: pd.Series) -> str:
58
+ """Encode as chrom:pos_svtype_size (e.g., 4:143990187_del_78kb)."""
59
+ chrom = str(row["CHROM"])
60
+ pos = str(row["POS"])
61
+ info = str(row["INFO"])
62
+
63
+ # Extract SVTYPE
64
+ svtype = None
65
+ for field in info.split(";"):
66
+ if field.startswith("SVTYPE="):
67
+ svtype = field.split("=")[1].lower()
68
+ break
69
+
70
+ # Extract SVLEN
71
+ svlen = None
72
+ for field in info.split(";"):
73
+ if field.startswith("SVLEN="):
74
+ svlen_str = field.split("=")[1]
75
+ svlen = abs(int(svlen_str)) # Take absolute value
76
+ break
77
+
78
+ if svtype and svlen:
79
+ # Convert to kb format
80
+ kb = svlen / 1000
81
+ if kb >= 1:
82
+ size_str = f"{int(kb)}kb"
83
+ else:
84
+ size_str = f"{svlen}bp"
85
+
86
+ return f"{chrom}:{pos}_{svtype}_{size_str}"
87
+
88
+ # Fallback if parsing fails
89
+ return f"{chrom}:{pos}_{row['REF']}_{row['ALT']}"
90
+
91
+
92
+ @dataclass(slots=True, frozen=True)
93
+ class DellyEncoder:
94
+ """Encoder for Delly structural variants.
95
+
96
+ Delly outputs SVs with SVTYPE and END (but not SVLEN).
97
+ Example: SVTYPE=DEL;END=144069060
98
+ """
99
+
100
+ def can_encode(self, row: pd.Series) -> bool:
101
+ """Check if variant is from Delly (has SVTYPE and END but not SVLEN)."""
102
+ info = str(row.get("INFO", ""))
103
+ return "SVTYPE=" in info and "END=" in info and "SVLEN=" not in info
104
+
105
+ def encode(self, row: pd.Series) -> str:
106
+ """Encode as chrom:pos_svtype_size."""
107
+ chrom = str(row["CHROM"])
108
+ pos = int(row["POS"])
109
+ info = str(row["INFO"])
110
+
111
+ # Extract SVTYPE
112
+ svtype = None
113
+ for field in info.split(";"):
114
+ if field.startswith("SVTYPE="):
115
+ svtype = field.split("=")[1].lower()
116
+ break
117
+
118
+ # Extract END position
119
+ end = None
120
+ for field in info.split(";"):
121
+ if field.startswith("END="):
122
+ end = int(field.split("=")[1])
123
+ break
124
+
125
+ if svtype and end:
126
+ svlen = abs(end - pos)
127
+ kb = svlen / 1000
128
+ if kb >= 1:
129
+ size_str = f"{int(kb)}kb"
130
+ else:
131
+ size_str = f"{svlen}bp"
132
+
133
+ return f"{chrom}:{pos}_{svtype}_{size_str}"
134
+
135
+ # Fallback
136
+ return f"{chrom}:{pos}_{row['REF']}_{row['ALT']}"
137
+
138
+
139
+ @dataclass(slots=True, frozen=True)
140
+ class MantaEncoder:
141
+ """Encoder for Manta structural variants.
142
+
143
+ Manta outputs SVs with SVTYPE and may have SVLEN or END.
144
+ Example: SVTYPE=DEL;SVLEN=-5000 or SVTYPE=DEL;END=144069060
145
+ """
146
+
147
+ def can_encode(self, row: pd.Series) -> bool:
148
+ """Check if variant is from Manta (bracketed ALT with SVTYPE)."""
149
+ info = str(row.get("INFO", ""))
150
+ alt = str(row.get("ALT", ""))
151
+ return (alt.startswith("<") and alt.endswith(">")) and "SVTYPE=" in info
152
+
153
+ def encode(self, row: pd.Series) -> str:
154
+ """Encode as chrom:pos_svtype_size."""
155
+ chrom = str(row["CHROM"])
156
+ pos = str(row["POS"])
157
+ info = str(row["INFO"])
158
+
159
+ # Extract SVTYPE
160
+ svtype = None
161
+ for field in info.split(";"):
162
+ if field.startswith("SVTYPE="):
163
+ svtype = field.split("=")[1].lower()
164
+ break
165
+
166
+ # Try to extract SVLEN (Manta may have it)
167
+ svlen = None
168
+ for field in info.split(";"):
169
+ if field.startswith("SVLEN="):
170
+ svlen_str = field.split("=")[1]
171
+ svlen = abs(int(svlen_str))
172
+ break
173
+
174
+ # If no SVLEN, try END
175
+ if svlen is None:
176
+ end = None
177
+ for field in info.split(";"):
178
+ if field.startswith("END="):
179
+ end = int(field.split("=")[1])
180
+ break
181
+ if end:
182
+ svlen = abs(end - int(pos))
183
+
184
+ if svtype and svlen:
185
+ kb = svlen / 1000
186
+ if kb >= 1:
187
+ size_str = f"{int(kb)}kb"
188
+ else:
189
+ size_str = f"{svlen}bp"
190
+
191
+ return f"{chrom}:{pos}_{svtype}_{size_str}"
192
+
193
+ # Fallback
194
+ return f"{chrom}:{pos}_{row['REF']}_{row['ALT']}"
195
+
196
+
197
+ @dataclass(slots=True, frozen=False)
198
+ class VariantEncoderFactory:
199
+ """Factory to manage and apply variant encoders.
200
+
201
+ Encoders are tried in order until one matches. Order matters:
202
+ more specific encoders should come before general ones.
203
+ """
204
+
205
+ encoders: list[VariantEncoder] = field(
206
+ default_factory=lambda: [
207
+ Sniffles2Encoder(),
208
+ DellyEncoder(),
209
+ MantaEncoder(),
210
+ SmallVariantEncoder(), # Keep this last as fallback
211
+ ]
212
+ )
213
+
214
+ def add_encoder(self, encoder: VariantEncoder, priority: int = 0) -> None:
215
+ """Add a custom encoder at specified priority (lower index = higher priority).
216
+
217
+ Args:
218
+ encoder: The encoder instance to add.
219
+ priority: Position in the encoder list (0 = highest priority).
220
+ """
221
+ self.encoders.insert(priority, encoder)
222
+
223
+ def encode_variant(self, row: pd.Series) -> str:
224
+ """Encode a variant using the first matching encoder.
225
+
226
+ Args:
227
+ row: A pandas Series representing one row from the VCF DataFrame.
228
+
229
+ Returns:
230
+ Encoded variant string in the format appropriate for the variant type.
231
+ """
232
+ for encoder in self.encoders:
233
+ if encoder.can_encode(row):
234
+ return encoder.encode(row)
235
+ logger.warning("Variants encoded in an unsupported way")
236
+ # Ultimate fallback if no encoder matches
237
+ return f"{row['CHROM']}:{row['POS']}_{row['REF']}_{row['ALT']}"
@@ -7,9 +7,11 @@ import pandas as pd
7
7
  from loguru import logger
8
8
  import argparse
9
9
 
10
- from rbceq2.core_logic.constants import DB_VERSION, VERSION, AlleleState
10
+ from rbceq2.core_logic.constants import DB_VERSION, VERSION, AlleleState, GENOMIC_TO_TRANSCRIPT_GRCh37, GENOMIC_TO_TRANSCRIPT_GRCh38
11
11
  from rbceq2.IO.validation import validate_vcf
12
12
 
13
+ from rbceq2.core_logic.utils import collapse_variant
14
+
13
15
 
14
16
  def configure_logging(args: argparse.Namespace) -> str:
15
17
  """
@@ -31,8 +33,7 @@ def configure_logging(args: argparse.Namespace) -> str:
31
33
  compression="zip",
32
34
  )
33
35
 
34
-
35
- logger.info("="*20 + " SESSION START " + "="*20)
36
+ logger.info("=" * 20 + " SESSION START " + "=" * 20)
36
37
  logger.info("NOT FOR CLINICAL USE")
37
38
  logger.info(f"RBCeq2 Version: {VERSION}")
38
39
  logger.info(f"RBCeq2 database Version: {DB_VERSION}")
@@ -46,15 +47,13 @@ def configure_logging(args: argparse.Namespace) -> str:
46
47
  max_key_len = max(len(key) for key in args_dict.keys())
47
48
  for key, value in args_dict.items():
48
49
  logger.info(f" {key:<{max_key_len}} : {value}")
49
-
50
50
 
51
- logger.info("="*20 + " LOGGING STARTED " + "="*20)
51
+ logger.info("=" * 20 + " LOGGING STARTED " + "=" * 20)
52
52
 
53
53
  return UUID
54
54
 
55
55
 
56
-
57
- def record_filtered_data(results: tuple[Any]) -> None:
56
+ def record_filtered_data(results: tuple[Any], ref: str) -> None:
58
57
  """Record filtered data by logging debug information for each blood group.
59
58
 
60
59
  This function unpacks the results tuple into sample identifier, numeric and
@@ -72,10 +71,17 @@ def record_filtered_data(results: tuple[Any]) -> None:
72
71
  alphanumeric phenotypes.
73
72
  - res: A dict mapping blood group names to BloodGroup objects.
74
73
  """
74
+
75
75
  def format_vars(pool):
76
- return '\n' + '\n'.join([' : '.join([k, v]) for k, v in pool.items()])
77
-
78
- sample, genos, numeric_phenos, alphanumeric_phenos, res = results
76
+ transcripts = GENOMIC_TO_TRANSCRIPT_GRCh37 if ref == 'GRCh37' else GENOMIC_TO_TRANSCRIPT_GRCh38
77
+ return "\n" + "\n".join(
78
+ [" : ".join([collapse_variant(k), transcripts.get(k, '(None)'), v]) for k, v in pool.items()]
79
+ )
80
+
81
+ sample, genos, numeric_phenos, alphanumeric_phenos, res, var_map = results
82
+
83
+ logger.debug("\n### Blood group allele info ###:\n")
84
+
79
85
  for bg_name, bg_data in res.items():
80
86
  if bg_data.filtered_out:
81
87
  logger.debug(
@@ -90,16 +96,25 @@ def record_filtered_data(results: tuple[Any]) -> None:
90
96
  f"Vars_phase: {format_vars(bg_data.variant_pool_phase)}\n"
91
97
  f"Vars_phase_set: {format_vars(bg_data.variant_pool_phase_set)}\n"
92
98
  f"Raw: {'\n' + '\n'.join(map(str, bg_data.alleles[AlleleState.RAW]))}\n"
93
- f"\n#Filters applied:\n"
94
99
  )
100
+
101
+ for variant_db, variant_vcf in var_map.items():
102
+ if variant_db in bg_data.variant_pool:
103
+ logger.debug(
104
+ f"BIG VARIANT fuzzy matching map:\n"
105
+ f"\tDatabase_variant: {collapse_variant(variant_db)}\n"
106
+ f"\tVCF_variant: {collapse_variant(variant_vcf)}\n"
107
+ )
108
+
109
+ logger.debug("### Filters applied ###:\n")
95
110
  no_filters = True
96
111
  for k, v in bg_data.filtered_out.items():
97
112
  if v:
98
113
  logger.debug(f"\n{k}: {'\n'.join(map(str, v))}\n")
99
114
  no_filters = False
100
115
  if no_filters:
101
- logger.debug('No filters were applied\n')
102
- logger.debug('\n______\n')
116
+ logger.debug("No filters were applied\n")
117
+ logger.debug("\n__________________________________________\n")
103
118
 
104
119
 
105
120
  def check_VCF(VCF_file):
@@ -138,19 +153,19 @@ def save_df(df: pd.DataFrame, name: str, UUID: str) -> None:
138
153
  df.index.name = f"UUID: {UUID}"
139
154
  df.to_csv(name, sep="\t")
140
155
 
141
- def stamps(start: pd.Timestamp) -> str:
142
156
 
157
+ def stamps(start: pd.Timestamp) -> str:
143
158
  delta = pd.Timestamp.now() - start
144
159
  total_seconds = delta.total_seconds()
145
160
 
146
161
  # Calculate minutes and remaining seconds
147
- minutes = int(total_seconds // 60) # Get whole minutes
148
- remaining_seconds = total_seconds % 60 # Get the remainder seconds
162
+ minutes = int(total_seconds // 60) # Get whole minutes
163
+ remaining_seconds = total_seconds % 60 # Get the remainder seconds
149
164
 
150
165
  # Format the output string conditionally (optional, but nice)
151
166
  if minutes > 0:
152
167
  time_str = f"{minutes} minutes and {remaining_seconds:.2f} seconds"
153
168
  else:
154
- time_str = f"{remaining_seconds:.2f} seconds" # Or just total_seconds:.2f
155
-
156
- return time_str
169
+ time_str = f"{remaining_seconds:.2f} seconds" # Or just total_seconds:.2f
170
+
171
+ return time_str
@@ -11,7 +11,9 @@ import gzip
11
11
  from dataclasses import dataclass
12
12
 
13
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))}
14
+ SUSPICIOUS_CHARS = {
15
+ chr(c) for c in list(range(0, 9)) + list(range(11, 13)) + list(range(14, 32))
16
+ }
15
17
 
16
18
 
17
19
  @dataclass
@@ -26,6 +28,7 @@ class VCFValidationResult:
26
28
  errors (list[str]):
27
29
  List of error messages encountered during validation.
28
30
  """
31
+
29
32
  is_valid: bool
30
33
  errors: list[str]
31
34
 
@@ -33,11 +36,11 @@ class VCFValidationResult:
33
36
  def open_vcf_file(file_path: str, mode: str = "rt"):
34
37
  """
35
38
  Open a VCF file that may be plain text or gzip compressed.
36
-
39
+
37
40
  Args:
38
41
  file_path (str): Path to the VCF file.
39
42
  mode (str, optional): File open mode. Defaults to "rt".
40
-
43
+
41
44
  Returns:
42
45
  A file object.
43
46
  """
@@ -50,16 +53,17 @@ class VCFValidator:
50
53
  """
51
54
  A class for validating VCF files in a single pass.
52
55
  """
56
+
53
57
  MAX_FILE_SIZE = 2 * 1024 * 1024 * 1024 # 2GB file size limit
54
58
 
55
59
  @staticmethod
56
60
  def validate_file(file_path: str) -> VCFValidationResult:
57
61
  """
58
62
  Validate the VCF file for correct format and malicious content in a single pass.
59
-
63
+
60
64
  Args:
61
65
  file_path (str): Path to the VCF file.
62
-
66
+
63
67
  Returns:
64
68
  VCFValidationResult: Result of validation.
65
69
  """
@@ -91,7 +95,11 @@ class VCFValidator:
91
95
  if not found_fileformat and line.startswith("##fileformat=VCF"):
92
96
  found_fileformat = True
93
97
  # Find header line: first line starting with '#' but not '##'.
94
- if header_line is None and line.startswith("#") and not line.startswith("##"):
98
+ if (
99
+ header_line is None
100
+ and line.startswith("#")
101
+ and not line.startswith("##")
102
+ ):
95
103
  header_line = line.strip()
96
104
  except UnicodeDecodeError:
97
105
  return VCFValidationResult(False, ["File is not valid UTF-8 text."])
@@ -108,10 +116,21 @@ class VCFValidator:
108
116
  if len(columns) < 8:
109
117
  errors.append("Header line has insufficient columns.")
110
118
  else:
111
- required = ["#CHROM", "POS", "ID", "REF", "ALT", "QUAL", "FILTER", "INFO"]
119
+ required = [
120
+ "#CHROM",
121
+ "POS",
122
+ "ID",
123
+ "REF",
124
+ "ALT",
125
+ "QUAL",
126
+ "FILTER",
127
+ "INFO",
128
+ ]
112
129
  for i, col in enumerate(required):
113
130
  if columns[i] != col:
114
- errors.append(f"Header column {i + 1} expected '{col}', found '{columns[i]}'.")
131
+ errors.append(
132
+ f"Header column {i + 1} expected '{col}', found '{columns[i]}'."
133
+ )
115
134
  break
116
135
 
117
136
  # Remove duplicate errors.
@@ -122,11 +141,11 @@ class VCFValidator:
122
141
  def validate_vcf(file_path: str) -> VCFValidationResult:
123
142
  """
124
143
  Validate a VCF file for proper format and absence of malicious content.
125
-
144
+
126
145
  Args:
127
146
  file_path (str): Path to the VCF file.
128
-
147
+
129
148
  Returns:
130
149
  VCFValidationResult: Combined result of format and security checks.
131
150
  """
132
- return VCFValidator.validate_file(file_path)
151
+ return VCFValidator.validate_file(file_path)