RBCeq2 2.1.2__tar.gz → 2.3.4__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 (58) hide show
  1. rbceq2-2.3.4/MANIFEST.in +3 -0
  2. rbceq2-2.3.4/PKG-INFO +92 -0
  3. rbceq2-2.3.4/README.md +59 -0
  4. {rbceq2-2.1.2 → rbceq2-2.3.4}/pyproject.toml +4 -7
  5. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/IO/record_data.py +14 -32
  6. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/IO/vcf.py +162 -18
  7. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/core_logic/alleles.py +56 -50
  8. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/core_logic/co_existing.py +30 -10
  9. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/core_logic/constants.py +187 -19
  10. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/core_logic/data_procesing.py +328 -264
  11. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/core_logic/utils.py +2 -21
  12. rbceq2-2.3.4/src/rbceq2/db/db.py +697 -0
  13. rbceq2-2.3.4/src/rbceq2/filters/geno.py +934 -0
  14. rbceq2-2.3.4/src/rbceq2/filters/knops.py +816 -0
  15. rbceq2-2.3.4/src/rbceq2/filters/phased.py +713 -0
  16. rbceq2-2.3.4/src/rbceq2/filters/shared_filter_functionality.py +109 -0
  17. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/main.py +95 -30
  18. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/phenotype/antigens.py +401 -20
  19. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/phenotype/choose_pheno.py +169 -20
  20. rbceq2-2.3.4/src/rbceq2/resources/db.tsv +2012 -0
  21. rbceq2-2.3.4/src/rbceq2.egg-info/PKG-INFO +92 -0
  22. {rbceq2-2.1.2/src/RBCeq2.egg-info → rbceq2-2.3.4/src/rbceq2.egg-info}/SOURCES.txt +14 -8
  23. {rbceq2-2.1.2 → rbceq2-2.3.4}/tests/test_VCF.py +5 -50
  24. {rbceq2-2.1.2 → rbceq2-2.3.4}/tests/test_alleles.py +9 -20
  25. {rbceq2-2.1.2 → rbceq2-2.3.4}/tests/test_choose_pheno.py +66 -68
  26. rbceq2-2.3.4/tests/test_co_filters.py +1711 -0
  27. {rbceq2-2.1.2 → rbceq2-2.3.4}/tests/test_coexisting.py +91 -52
  28. {rbceq2-2.1.2 → rbceq2-2.3.4}/tests/test_data_processing.py +277 -761
  29. rbceq2-2.3.4/tests/test_db.py +646 -0
  30. rbceq2-2.3.4/tests/test_filters_phase.py +190 -0
  31. rbceq2-2.3.4/tests/test_geno_filters.py +829 -0
  32. {rbceq2-2.1.2 → rbceq2-2.3.4}/tests/test_utils.py +24 -69
  33. rbceq2-2.1.2/PKG-INFO +0 -147
  34. rbceq2-2.1.2/README.rst +0 -114
  35. rbceq2-2.1.2/src/RBCeq2.egg-info/PKG-INFO +0 -147
  36. rbceq2-2.1.2/src/rbceq2/db/db.py +0 -282
  37. rbceq2-2.1.2/src/rbceq2/filters/geno.py +0 -1234
  38. rbceq2-2.1.2/src/rbceq2/resources/db.tsv +0 -1869
  39. rbceq2-2.1.2/tests/test_db.py +0 -178
  40. rbceq2-2.1.2/tests/test_filters.py +0 -2345
  41. {rbceq2-2.1.2 → rbceq2-2.3.4}/LICENSE +0 -0
  42. {rbceq2-2.1.2 → rbceq2-2.3.4}/setup.cfg +0 -0
  43. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/IO/PDF_reports.py +0 -0
  44. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/IO/__init__.py +0 -0
  45. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/IO/validation.py +0 -0
  46. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/__init__.py +0 -0
  47. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/core_logic/__init__.py +0 -0
  48. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/db/__init__.py +0 -0
  49. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/filters/__init__.py +0 -0
  50. {rbceq2-2.1.2 → rbceq2-2.3.4}/src/rbceq2/phenotype/__init__.py +0 -0
  51. {rbceq2-2.1.2/src/RBCeq2.egg-info → rbceq2-2.3.4/src/rbceq2.egg-info}/dependency_links.txt +0 -0
  52. {rbceq2-2.1.2/src/RBCeq2.egg-info → rbceq2-2.3.4/src/rbceq2.egg-info}/entry_points.txt +0 -0
  53. {rbceq2-2.1.2/src/RBCeq2.egg-info → rbceq2-2.3.4/src/rbceq2.egg-info}/requires.txt +0 -0
  54. {rbceq2-2.1.2/src/RBCeq2.egg-info → rbceq2-2.3.4/src/rbceq2.egg-info}/top_level.txt +0 -0
  55. {rbceq2-2.1.2 → rbceq2-2.3.4}/tests/test_IO.py +0 -0
  56. {rbceq2-2.1.2 → rbceq2-2.3.4}/tests/test_ants.py +0 -0
  57. {rbceq2-2.1.2 → rbceq2-2.3.4}/tests/test_main.py +0 -0
  58. {rbceq2-2.1.2 → rbceq2-2.3.4}/tests/test_pdf.py +0 -0
@@ -0,0 +1,3 @@
1
+ recursive-include src/rbceq2/resources *.tsv
2
+ include LICENSE
3
+ include README.md
rbceq2-2.3.4/PKG-INFO ADDED
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: rbceq2
3
+ Version: 2.3.4
4
+ Summary: Call ISBT alleles from VCF/s
5
+ Author-email: Liam McIntyre <limcintyre@redcrossblood.org.au>
6
+ License: Copyright 2025 Australian Red Cross Lifeblood
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
11
+
12
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Intended Audience :: Science/Research
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
20
+ Requires-Python: >=3.12
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: pandas>=2.2.2
24
+ Requires-Dist: polars>=0.20.26
25
+ Requires-Dist: icecream>=2.1
26
+ Requires-Dist: loguru>=0.7.2
27
+ Requires-Dist: pyarrow>=18.1
28
+ Requires-Dist: reportlab>=4.3.1
29
+ Provides-Extra: dev
30
+ Requires-Dist: flake8>=3.9.2; extra == "dev"
31
+ Requires-Dist: coverage>=7.0; extra == "dev"
32
+ Dynamic: license-file
33
+
34
+ <table>
35
+ <tr>
36
+ <td>
37
+ <h1>RBCeq2: blood group allele inference</h1>
38
+ </td>
39
+ <td align="right">
40
+ <img src="images/Lifeblood-R_Primary_Keyline_RGB.jpg" alt="Lifeblood Logo" width="150">
41
+ </td>
42
+ </tr>
43
+ </table>
44
+
45
+ > [!WARNING]
46
+ > NOT FOR CLINICAL USE
47
+
48
+ ## Version v2.3.4
49
+
50
+ 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
+ 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
+ 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
+
56
+ ## 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.
59
+
60
+ ## Documentation
61
+
62
+ Documentation can be downloaded from the release page, you will need to be signed in to github to access it.
63
+
64
+ ## How To
65
+
66
+ Install via pip (python3.12+) or clone the git repository:
67
+
68
+ ```bash
69
+ pip install RBCeq2
70
+
71
+ rbceq2 -h
72
+
73
+ usage: rbceq2 --vcf example_multi_sample.vcf.gz --out example --reference_genome GRCh37
74
+
75
+ options:
76
+ -h, --help show this help message and exit
77
+ -v, --version Show programs version number and exit.
78
+ --vcf VCF Path to VCF file/s. Give a folder if you want to pass multiple separate files (file names must end in .vcf or .vcf.gz), or alternatively give a file if using a multi-sample VCF. (default: None)
79
+ --out OUT Prefix for output files (default: None)
80
+ --depth DEPTH Minimum number of reads for a variant (default: 10)
81
+ --quality QUALITY Minimum average genotype quality for a variant (default: 10)
82
+ --processes PROCESSES
83
+ Number of processes. I.e., how many CPUs are available? ~1GB RAM required per process (default: 1)
84
+ --reference_genome {GRCh37,GRCh38}
85
+ GRCh37/8 (default: None)
86
+ --phased Use phase information (default: False)
87
+ --microarray Input is from a microarray. (default: False)
88
+ --debug Enable debug logging. If not set, logging will be at info level. (default: False)
89
+ --validate Enable VCF validation. Doubles run time. Might help you identify input issues (default: False)
90
+ --PDFs Generate a per sample PDF report (default: False)
91
+ --HPAs Generate results for HPA (default: False)
92
+ ```
rbceq2-2.3.4/README.md ADDED
@@ -0,0 +1,59 @@
1
+ <table>
2
+ <tr>
3
+ <td>
4
+ <h1>RBCeq2: blood group allele inference</h1>
5
+ </td>
6
+ <td align="right">
7
+ <img src="images/Lifeblood-R_Primary_Keyline_RGB.jpg" alt="Lifeblood Logo" width="150">
8
+ </td>
9
+ </tr>
10
+ </table>
11
+
12
+ > [!WARNING]
13
+ > NOT FOR CLINICAL USE
14
+
15
+ ## Version v2.3.4
16
+
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
+
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
+
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.
22
+
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.
26
+
27
+ ## Documentation
28
+
29
+ Documentation can be downloaded from the release page, you will need to be signed in to github to access it.
30
+
31
+ ## How To
32
+
33
+ Install via pip (python3.12+) or clone the git repository:
34
+
35
+ ```bash
36
+ pip install RBCeq2
37
+
38
+ rbceq2 -h
39
+
40
+ usage: rbceq2 --vcf example_multi_sample.vcf.gz --out example --reference_genome GRCh37
41
+
42
+ options:
43
+ -h, --help show this help message and exit
44
+ -v, --version Show programs version number and exit.
45
+ --vcf VCF Path to VCF file/s. Give a folder if you want to pass multiple separate files (file names must end in .vcf or .vcf.gz), or alternatively give a file if using a multi-sample VCF. (default: None)
46
+ --out OUT Prefix for output files (default: None)
47
+ --depth DEPTH Minimum number of reads for a variant (default: 10)
48
+ --quality QUALITY Minimum average genotype quality for a variant (default: 10)
49
+ --processes PROCESSES
50
+ Number of processes. I.e., how many CPUs are available? ~1GB RAM required per process (default: 1)
51
+ --reference_genome {GRCh37,GRCh38}
52
+ GRCh37/8 (default: None)
53
+ --phased Use phase information (default: False)
54
+ --microarray Input is from a microarray. (default: False)
55
+ --debug Enable debug logging. If not set, logging will be at info level. (default: False)
56
+ --validate Enable VCF validation. Doubles run time. Might help you identify input issues (default: False)
57
+ --PDFs Generate a per sample PDF report (default: False)
58
+ --HPAs Generate results for HPA (default: False)
59
+ ```
@@ -5,10 +5,10 @@ requires = ["setuptools>=61.0"] # Minimum version of setuptools needed
5
5
  build-backend = "setuptools.build_meta"
6
6
 
7
7
  [project]
8
- name = "RBCeq2"
9
- version = "2.1.2"
8
+ name = "rbceq2"
9
+ version = "2.3.4"
10
10
  description = "Call ISBT alleles from VCF/s"
11
- readme = "README.rst" # <-- Use the RST file we created
11
+ readme = "README.md"
12
12
  license = { file = "LICENSE" }
13
13
  requires-python = ">=3.12"
14
14
  authors = [
@@ -42,8 +42,6 @@ dev = [
42
42
  "coverage>=7.0",
43
43
  ]
44
44
 
45
- # --- Setuptools specific configuration ---
46
- # Corresponds to [options] and sub-sections in setup.cfg
47
45
 
48
46
  [tool.setuptools]
49
47
  include-package-data = true # Corresponds to include_package_data in [options]
@@ -52,6 +50,5 @@ include-package-data = true # Corresponds to include_package_data in [options]
52
50
  where = ["src"] # Corresponds to package_dir = = src and where = src
53
51
 
54
52
  [tool.setuptools.package-data]
55
- # Corresponds to [options.package_data]
56
- # The key is the package name, the value is a list of glob patterns
53
+
57
54
  rbceq2 = ["resources/*.tsv"]
@@ -11,31 +11,6 @@ from rbceq2.core_logic.constants import DB_VERSION, VERSION, AlleleState
11
11
  from rbceq2.IO.validation import validate_vcf
12
12
 
13
13
 
14
- # def configure_logging(args) -> str:
15
- # """
16
- # Configures the logging for the application.
17
-
18
- # Args:
19
- # args: Command-line arguments containing debug flag and log file path.
20
- # """
21
- # log_level = "DEBUG" if args.debug else "INFO"
22
- # logger.remove() # Remove default logger configuration
23
- # logger.add(
24
- # f"{args.out}_log.txt", # Log file path from arguments
25
- # level=log_level,
26
- # format="{time} {level} {message}",
27
- # rotation="50 MB", # Rotate the file when it reaches 10 MB
28
- # compression="zip", # Compress old logs
29
- # )
30
- # UUID = str(uuid.uuid4())
31
- # logger.info("NOT FOR CLINICAL USE")
32
- # logger.info(f"RBCeq2 Version: {VERSION}")
33
- # logger.info(f"RBCeq2 database Version: {DB_VERSION}")
34
- # logger.info(f"Session UUID: {UUID}")
35
-
36
- # return UUID
37
-
38
-
39
14
  def configure_logging(args: argparse.Namespace) -> str:
40
15
  """
41
16
  Configures the logging for the application and logs arguments line by line.
@@ -43,8 +18,9 @@ def configure_logging(args: argparse.Namespace) -> str:
43
18
  Args:
44
19
  args: Command-line arguments (typically from argparse.parse_args()).
45
20
  """
21
+ UUID = str(uuid.uuid4())
46
22
  log_level = "DEBUG" if args.debug else "INFO"
47
- log_file_path = f"{args.out}_log.txt"
23
+ log_file_path = f"{args.out}_{UUID}_log.txt"
48
24
 
49
25
  logger.remove()
50
26
  logger.add(
@@ -55,7 +31,7 @@ def configure_logging(args: argparse.Namespace) -> str:
55
31
  compression="zip",
56
32
  )
57
33
 
58
- UUID = str(uuid.uuid4())
34
+
59
35
  logger.info("="*20 + " SESSION START " + "="*20)
60
36
  logger.info("NOT FOR CLINICAL USE")
61
37
  logger.info(f"RBCeq2 Version: {VERSION}")
@@ -96,17 +72,23 @@ def record_filtered_data(results: tuple[Any]) -> None:
96
72
  alphanumeric phenotypes.
97
73
  - res: A dict mapping blood group names to BloodGroup objects.
98
74
  """
99
- sample, _, numeric_phenos, alphanumeric_phenos, res = results
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
100
79
  for bg_name, bg_data in res.items():
101
80
  if bg_data.filtered_out:
102
81
  logger.debug(
103
82
  f"Sample: {sample} BG Name: {bg_name}\n"
104
83
  f"\n#Results:\n"
105
- f"Genotypes: {'\n'.join(bg_data.genotypes)}\n"
106
- f"Phenotypes (numeric): {numeric_phenos.get(bg_name, '')}\n"
107
- f"Phenotypes (alphanumeric): {alphanumeric_phenos.get(bg_name, '')}\n"
84
+ f"Genotypes count: {len(genos.get(bg_name, '').split(','))}\n"
85
+ f"Genotypes: {'\n'.join(genos.get(bg_name, '').split(','))}\n"
86
+ f"Phenotypes (numeric): {'\n'.join(numeric_phenos.get(bg_name, '').split(' | '))}\n"
87
+ f"Phenotypes (alphanumeric): {'\n'.join(alphanumeric_phenos.get(bg_name, '').split(' | '))}\n"
108
88
  f"\n#Data:\n"
109
- f"Vars: {bg_data.variant_pool}\n"
89
+ f"Vars: {format_vars(bg_data.variant_pool)}\n"
90
+ f"Vars_phase: {format_vars(bg_data.variant_pool_phase)}\n"
91
+ f"Vars_phase_set: {format_vars(bg_data.variant_pool_phase_set)}\n"
110
92
  f"Raw: {'\n' + '\n'.join(map(str, bg_data.alleles[AlleleState.RAW]))}\n"
111
93
  f"\n#Filters applied:\n"
112
94
  )
@@ -4,14 +4,14 @@ import os
4
4
  from dataclasses import dataclass, field
5
5
  from pathlib import Path
6
6
  from typing import Any
7
-
8
7
  import pandas as pd
8
+ import re
9
9
 
10
10
  os.environ["POLARS_MAX_THREADS"] = "7" # Must be set before polars import
11
11
  import polars as pl
12
12
  from loguru import logger
13
13
 
14
- from rbceq2.core_logic.constants import COMMON_COLS, HOM_REF_DUMMY_QUAL
14
+ from rbceq2.core_logic.constants import COMMON_COLS, HOM_REF_DUMMY_QUAL, LANE
15
15
 
16
16
 
17
17
  @dataclass(slots=True, frozen=False)
@@ -34,6 +34,7 @@ class VCF:
34
34
  df: pd.DataFrame = field(init=False)
35
35
  loci: set[str] = field(init=False)
36
36
  variants: dict[str, str] = field(init=False)
37
+ phase_sets: dict[str, dict[int, tuple[int, int]]] = field(init=False)
37
38
 
38
39
  def __post_init__(self):
39
40
  """Handle initialization after data class creation."""
@@ -46,6 +47,57 @@ class VCF:
46
47
  object.__setattr__(self, "loci", self.set_loci())
47
48
  self.add_lane_variants()
48
49
  object.__setattr__(self, "variants", self.get_variants())
50
+ self._create_phase_sets()
51
+
52
+ def _create_phase_sets(self) -> None:
53
+ """Parses the VCF DataFrame to find phased variants and stores their
54
+ chromosomal ranges (min and max position) by phase set ID.
55
+
56
+ This method populates the `self.phase_sets` attribute with a nested
57
+ dictionary: {chromosome: {phase_set_id: (min_position, max_position)}}.
58
+ """
59
+ # Temporary dict to aggregate all positions for each phase set
60
+ # Format: {chrom: {ps_id: [pos1, pos2, ...]}}
61
+ temp_phase_data = {}
62
+
63
+ # Filter for rows that might contain phasing info to reduce work
64
+ df_phased = self.df[self.df["FORMAT"].str.contains("PS", na=False)].copy()
65
+
66
+ # Convert POS to integer once for performance
67
+ df_phased["POS"] = pd.to_numeric(df_phased["POS"])
68
+
69
+ for _, row in df_phased.iterrows():
70
+ format_keys = row["FORMAT"].split(":")
71
+ try:
72
+ ps_index = format_keys.index("PS")
73
+ except ValueError:
74
+ continue # 'PS' not in this row's FORMAT string
75
+
76
+ sample_values = row["SAMPLE"].split(":")
77
+ genotype = sample_values[0]
78
+
79
+ # Ensure genotype is phased ('|') and the PS value is valid
80
+ if "|" in genotype and len(sample_values) > ps_index:
81
+ ps_value = sample_values[ps_index]
82
+ if ps_value != ".":
83
+ chrom = row["CHROM"]
84
+ pos = row["POS"]
85
+ ps_id = int(ps_value)
86
+
87
+ # Initialize nested dicts if they don't exist and append pos
88
+ temp_phase_data.setdefault(chrom, {}).setdefault(ps_id, []).append(
89
+ pos
90
+ )
91
+
92
+ # Convert the lists of positions to (min, max) tuples
93
+ final_phase_sets = {}
94
+ for chrom, ps_groups in temp_phase_data.items():
95
+ final_phase_sets[chrom] = {
96
+ ps_id: (min(positions), max(positions))
97
+ for ps_id, positions in ps_groups.items()
98
+ }
99
+
100
+ object.__setattr__(self, "phase_sets", final_phase_sets)
49
101
 
50
102
  def handle_single_or_multi(self) -> pd.DataFrame:
51
103
  """Handle single or multiple entries in the VCF, returning a DataFrame.
@@ -113,6 +165,10 @@ class VCF:
113
165
  of a given transcript is just wildtype in a genomic reference. ie
114
166
  GRCh37/8
115
167
 
168
+ Added variant details (LANE constant) in v2.3.4 after seeing instances
169
+ where 133257521 had a SNP, not ins,
170
+ so lane was created erroneously
171
+
116
172
  Example:
117
173
 
118
174
  1 - new lanes - HOM loci:
@@ -131,7 +187,6 @@ class VCF:
131
187
  new_lanes = {}
132
188
 
133
189
  for chrom, loci in self.lane_variants.items():
134
- # assert 'CHR' not in chrom.upper() #del after a few months of use TODO
135
190
  chrom = chrom.replace("chr", "")
136
191
  for pos in loci:
137
192
  # TODO blindly adding is problematic, what if there's just no read
@@ -143,16 +198,27 @@ class VCF:
143
198
  .values[0]
144
199
  .split(":")[0]
145
200
  )
146
- assert GT.count("/") == 1 or GT.count("|") == 1
147
- assert (
148
- "2" not in GT
149
- ) # these 2 asserts are designed to find examples so I can sort
150
- # complex/multi var
151
- if GT.startswith(("0/1", "0|1", "1/0", "1|0")):
152
- self.df.loc[self.df.loci == lane_loci, "variant"] = (
153
- self.df.loc[self.df.loci == lane_loci, "variant"].values[0]
154
- + f",{lane_loci}_ref"
155
- )
201
+ # try:
202
+ # assert GT.count("/") == 1 or GT.count("|") == 1
203
+ # assert ("2" not in GT) TODO, not sure if this is too defensive...
204
+ # except AssertionError:
205
+ # print('multi allele loci are not supported, please use bcftools norm -m -both ...')
206
+ # raise ValueError('multi allele loci are not supported, please use bcftools norm -m -both on your VCF/s')
207
+ if (
208
+ GT.startswith(("0/1", "0|1", "1/0", "1|0"))
209
+ and len(self.df.loc[self.df.loci == lane_loci, "SAMPLE"]) == 1
210
+ ):
211
+ # HET and not multi allelic = ref
212
+ ref = self.df.loc[self.df.loci == lane_loci, "REF"].values[0]
213
+ alt = self.df.loc[self.df.loci == lane_loci, "ALT"].values[0]
214
+ lane = LANE[f"chr{chrom}"][pos]
215
+ if f"{ref}_{alt}" == lane or lane == 'no_ALT':
216
+ self.df.loc[self.df.loci == lane_loci, "variant"] = (
217
+ self.df.loc[
218
+ self.df.loci == lane_loci, "variant"
219
+ ].values[0]
220
+ + f",{lane_loci}_ref"
221
+ )
156
222
  else:
157
223
  new_lanes[lane_loci] = (
158
224
  [chrom, pos]
@@ -176,7 +242,7 @@ class VCF:
176
242
  dict[str, str]: A dictionary of variants and their associated metrics.
177
243
  """
178
244
  vcf_variants = {}
179
- for varaint, metrics, format in zip(
245
+ for variant, metrics, format in zip(
180
246
  list(self.df.variant), list(self.df["SAMPLE"]), list(self.df["FORMAT"])
181
247
  ):
182
248
  if isinstance(metrics, float):
@@ -188,15 +254,32 @@ class VCF:
188
254
  mapped_metrics["GT"] == mapped_metrics["GT"].replace("|", "/")
189
255
  if mapped_metrics["GT"] == "0/0":
190
256
  continue
191
- if "," in varaint:
192
- for variant in varaint.split(","):
257
+
258
+ if "," in variant:
259
+ for variant in variant.split(","):
193
260
  vcf_variants[variant] = mapped_metrics
194
261
  else:
195
- vcf_variants[varaint] = mapped_metrics
262
+ vcf_variants[variant] = mapped_metrics
263
+ # if not all_ints_zero_or_one(mapped_metrics["GT"]):
264
+ # #ic(11111111111,mapped_metrics["GT"], vcf_variants)
265
+ # #raise ValueError('multi allele loci are not supported, please use bcftools norm -m -both on your VCF/s!')
196
266
 
197
267
  return vcf_variants
198
268
 
199
269
 
270
+ def all_ints_zero_or_one(text: str) -> bool:
271
+ """Check if all integers in string are 0 or 1.
272
+
273
+ Args:
274
+ text (str): Input string to check.
275
+
276
+ Returns:
277
+ bool: True if all integers are 0 or 1, False otherwise.
278
+ """
279
+ ints = re.findall(r"\d+", text)
280
+ return all(num in ("0", "1") for num in ints)
281
+
282
+
200
283
  def split_vcf_to_dfs(vcf_df: pd.DataFrame) -> pd.DataFrame:
201
284
  """Split multi-sample VCF DataFrame into individual sample DataFrames.
202
285
 
@@ -220,6 +303,65 @@ def split_vcf_to_dfs(vcf_df: pd.DataFrame) -> pd.DataFrame:
220
303
  yield sample_vcf_df, sample
221
304
 
222
305
 
306
+ def find_phased_neighbors(df: pd.DataFrame) -> set[str]:
307
+ """
308
+ rescues ABOs c.261delG - indels don't always get phased properly"""
309
+ central_loci_to_find = {
310
+ "9:133257521": 133257521,
311
+ "9:136132908": 136132908,
312
+ }
313
+
314
+ # 1. Create the sorted list of all PHASED loci on Chromosome 9
315
+ phased_on_chrom9 = (
316
+ df.filter(pl.col("CHROM") == "9")
317
+ .with_columns(pl.col("POS").cast(pl.Int64))
318
+ .filter(pl.col("FORMAT").str.contains("PS"))
319
+ .sort("POS")
320
+ )
321
+
322
+ # If there are no phased loci at all, exit
323
+ if phased_on_chrom9.height == 0:
324
+ return set()
325
+
326
+ # Extract the positions and loci as separate series for quick lookups
327
+ phased_positions = phased_on_chrom9.get_column("POS")
328
+ phased_loci_series = phased_on_chrom9.get_column("LOCI")
329
+
330
+ results = []
331
+ # 2. For each central locus, find its place in the sorted list
332
+ for locus_id, locus_pos in central_loci_to_find.items():
333
+ # search_sorted finds the index where `locus_pos` would be inserted
334
+ # to maintain the sort order. This is the index of the first variant
335
+ # at or after our central locus.
336
+ idx = phased_positions.search_sorted(locus_pos)
337
+
338
+ # 3. Use this index to find the neighbors from our list of phased loci
339
+ # We need to be careful about edges (e.g., asking for index -2 when idx is 0 or 1)
340
+ results.append(
341
+ {
342
+ "LOCI": locus_id,
343
+ "prev_2": phased_loci_series[idx - 2] if idx > 1 else None,
344
+ "prev_1": phased_loci_series[idx - 1] if idx > 0 else None,
345
+ "next_1": phased_loci_series[idx]
346
+ if idx < len(phased_loci_series)
347
+ else None,
348
+ "next_2": phased_loci_series[idx + 1]
349
+ if idx < len(phased_loci_series) - 1
350
+ else None,
351
+ }
352
+ )
353
+ neighbor_cols = ["prev_2", "prev_1", "next_1", "next_2"]
354
+ neighbours_df = pl.from_dicts(results)
355
+ # 4. Convert the list of dictionaries to a final DataFrame
356
+ unique_loci_set = {
357
+ locus
358
+ for row in neighbours_df.select(neighbor_cols).rows()
359
+ for locus in row
360
+ if locus is not None # Filter out the nulls
361
+ }
362
+ return unique_loci_set
363
+
364
+
223
365
  def filter_VCF_to_BG_variants(df: pl.DataFrame, unique_variants) -> pd.DataFrame:
224
366
  """Filter a VCF represented as a Polars DataFrame to only include specified variants.
225
367
 
@@ -241,7 +383,9 @@ def filter_VCF_to_BG_variants(df: pl.DataFrame, unique_variants) -> pd.DataFrame
241
383
  df = df.with_columns(
242
384
  pl.concat_str(pl.col("CHROM"), pl.lit(":"), pl.col("POS")).alias("LOCI")
243
385
  )
244
- filtered_df = df.filter(pl.col("LOCI").is_in(unique_variants))
386
+ neighbours = find_phased_neighbors(df)
387
+ merged_set = neighbours | unique_variants
388
+ filtered_df = df.filter(pl.col("LOCI").is_in(merged_set))
245
389
  if filtered_df.height == 0: # empty
246
390
  pandas_df = df.to_pandas(use_pyarrow_extension_array=False)
247
391
  else: