cdot 0.2.35__tar.gz → 0.2.37__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 (53) hide show
  1. {cdot-0.2.35 → cdot-0.2.37}/PKG-INFO +1 -1
  2. {cdot-0.2.35 → cdot-0.2.37}/cdot/__init__.py +1 -1
  3. {cdot-0.2.35 → cdot-0.2.37}/cdot/hgvs/clean.py +6 -1
  4. {cdot-0.2.35 → cdot-0.2.37}/cdot/hgvs/dataproviders/fasta_seqfetcher.py +34 -3
  5. {cdot-0.2.35 → cdot-0.2.37}/cdot/hgvs/dataproviders/json_data_provider.py +15 -0
  6. {cdot-0.2.35 → cdot-0.2.37}/cdot.egg-info/PKG-INFO +1 -1
  7. {cdot-0.2.35 → cdot-0.2.37}/tests/test_clean_hgvs.py +16 -0
  8. {cdot-0.2.35 → cdot-0.2.37}/tests/test_fasta_seqfetcher.py +86 -2
  9. {cdot-0.2.35 → cdot-0.2.37}/LICENSE +0 -0
  10. {cdot-0.2.35 → cdot-0.2.37}/README.md +0 -0
  11. {cdot-0.2.35 → cdot-0.2.37}/cdot/data_release.py +0 -0
  12. {cdot-0.2.35 → cdot-0.2.37}/cdot/hgvs/__init__.py +0 -0
  13. {cdot-0.2.35 → cdot-0.2.37}/cdot/hgvs/_version_replacement_blocklist.py +0 -0
  14. {cdot-0.2.35 → cdot-0.2.37}/cdot/hgvs/dataproviders/__init__.py +0 -0
  15. {cdot-0.2.35 → cdot-0.2.37}/cdot/hgvs/dataproviders/ensembl_tark_data_provider.py +0 -0
  16. {cdot-0.2.35 → cdot-0.2.37}/cdot/hgvs/dataproviders/seqfetcher.py +0 -0
  17. {cdot-0.2.35 → cdot-0.2.37}/cdot/hgvs/gene_hgvs.py +0 -0
  18. {cdot-0.2.35 → cdot-0.2.37}/cdot/hgvs/translation.py +0 -0
  19. {cdot-0.2.35 → cdot-0.2.37}/cdot/hgvs/version_safety.py +0 -0
  20. {cdot-0.2.35 → cdot-0.2.37}/cdot/models.py +0 -0
  21. {cdot-0.2.35 → cdot-0.2.37}/cdot/pyhgvs/__init__.py +0 -0
  22. {cdot-0.2.35 → cdot-0.2.37}/cdot/pyhgvs/pyhgvs_transcript.py +0 -0
  23. {cdot-0.2.35 → cdot-0.2.37}/cdot.egg-info/SOURCES.txt +0 -0
  24. {cdot-0.2.35 → cdot-0.2.37}/cdot.egg-info/dependency_links.txt +0 -0
  25. {cdot-0.2.35 → cdot-0.2.37}/cdot.egg-info/requires.txt +0 -0
  26. {cdot-0.2.35 → cdot-0.2.37}/cdot.egg-info/top_level.txt +0 -0
  27. {cdot-0.2.35 → cdot-0.2.37}/pyproject.toml +0 -0
  28. {cdot-0.2.35 → cdot-0.2.37}/setup.cfg +0 -0
  29. {cdot-0.2.35 → cdot-0.2.37}/tests/test_cdot_gene_info.py +0 -0
  30. {cdot-0.2.35 → cdot-0.2.37}/tests/test_cdot_json_gencode_hgnc.py +0 -0
  31. {cdot-0.2.35 → cdot-0.2.37}/tests/test_cdot_json_gene_info.py +0 -0
  32. {cdot-0.2.35 → cdot-0.2.37}/tests/test_cdot_json_merge.py +0 -0
  33. {cdot-0.2.35 → cdot-0.2.37}/tests/test_check_new_sources.py +0 -0
  34. {cdot-0.2.35 → cdot-0.2.37}/tests/test_data_release.py +0 -0
  35. {cdot-0.2.35 → cdot-0.2.37}/tests/test_docs_in_sync.py +0 -0
  36. {cdot-0.2.35 → cdot-0.2.37}/tests/test_gene_hgvs.py +0 -0
  37. {cdot-0.2.35 → cdot-0.2.37}/tests/test_gff_parser_golden.py +0 -0
  38. {cdot-0.2.35 → cdot-0.2.37}/tests/test_gff_parsers.py +0 -0
  39. {cdot-0.2.35 → cdot-0.2.37}/tests/test_json_data_provider_ensembl.py +0 -0
  40. {cdot-0.2.35 → cdot-0.2.37}/tests/test_json_data_provider_refseq.py +0 -0
  41. {cdot-0.2.35 → cdot-0.2.37}/tests/test_json_loading.py +0 -0
  42. {cdot-0.2.35 → cdot-0.2.37}/tests/test_models.py +0 -0
  43. {cdot-0.2.35 → cdot-0.2.37}/tests/test_public_api.py +0 -0
  44. {cdot-0.2.35 → cdot-0.2.37}/tests/test_pyhgvs.py +0 -0
  45. {cdot-0.2.35 → cdot-0.2.37}/tests/test_quickstart.py +0 -0
  46. {cdot-0.2.35 → cdot-0.2.37}/tests/test_rest_data_provider_errors.py +0 -0
  47. {cdot-0.2.35 → cdot-0.2.37}/tests/test_rest_data_provider_prefetch.py +0 -0
  48. {cdot-0.2.35 → cdot-0.2.37}/tests/test_retrieve_many.py +0 -0
  49. {cdot-0.2.35 → cdot-0.2.37}/tests/test_struct_dict_compat.py +0 -0
  50. {cdot-0.2.35 → cdot-0.2.37}/tests/test_translation.py +0 -0
  51. {cdot-0.2.35 → cdot-0.2.37}/tests/test_uta_conversion.py +0 -0
  52. {cdot-0.2.35 → cdot-0.2.37}/tests/test_version_safety.py +0 -0
  53. {cdot-0.2.35 → cdot-0.2.37}/tests/test_version_safety_real_records.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cdot
3
- Version: 0.2.35
3
+ Version: 0.2.37
4
4
  Summary: Transcripts for HGVS libraries
5
5
  Author-email: Dave Lawrence <davmlaw@gmail.com>
6
6
  License-Expression: MIT
@@ -13,7 +13,7 @@
13
13
  a client can read data whose schema (major.minor) is not newer than its own, see
14
14
  :func:`get_data_schema_int`.
15
15
  """
16
- __version__ = "0.2.35"
16
+ __version__ = "0.2.37"
17
17
  # Data version is kept in generate_transcript_data/json_schema_version.py
18
18
 
19
19
  def get_data_schema_int(version: str) -> int:
@@ -295,6 +295,10 @@ _P_HGVS_REMOVAL = re.compile(r"^(?P<main>.*?)(?:\s*[,;]\s*|\s+)(p\.|[(]p\.).*$")
295
295
  # non-protein kind, or something other than "p." after the colon). Otherwise the
296
296
  # "p." is the allele itself, eg "NP_000050.2 p.Arg1Gly", and must be kept.
297
297
  _HAS_NUCLEOTIDE_ALLELE = re.compile(r":\s*(?!p\.)\S|[cgmnr]\.", re.IGNORECASE)
298
+ # A transcript or genomic accession in the text after the protein annotation means
299
+ # another variant follows ("... p.(Met1?) NM_000059.4:c.68del"), so nothing is stripped.
300
+ _NUCLEOTIDE_ACCESSION = re.compile(
301
+ rf"(?:{_TRANSCRIPT_ACCESSION_PREFIX}|{_GENOMIC_ACCESSION_PREFIX})\d", re.IGNORECASE)
298
302
 
299
303
  # Two-letter RefSeq accession prefixes (NM, NR, XM, XR, NC, NG, ...) taken from
300
304
  # the type table, used to repair an accession missing its underscore. Requires
@@ -705,7 +709,8 @@ def _validate(s: str) -> list[HGVSFix]:
705
709
 
706
710
  def _op_strip_protein_suffix(s: str) -> tuple[str, list[HGVSFix]]:
707
711
  # e.g. "NM_000059.4:c.316+5G>A p.Arg106*" → "NM_000059.4:c.316+5G>A"
708
- if (m := _P_HGVS_REMOVAL.match(s)) and _HAS_NUCLEOTIDE_ALLELE.search(m.group("main")):
712
+ if ((m := _P_HGVS_REMOVAL.match(s)) and _HAS_NUCLEOTIDE_ALLELE.search(m.group("main"))
713
+ and not _NUCLEOTIDE_ACCESSION.search(s, m.end("main"))):
709
714
  new_s = m.group("main")
710
715
  return new_s, [HGVSFix(
711
716
  severity=HGVSFixSeverity.WARNING,
@@ -2,7 +2,9 @@
2
2
 
3
3
  :class:`FastaSeqFetcher` is the one to use: genomic contigs straight from the FASTA, transcript
4
4
  sequences spliced together from their exons on it. See docs/fasta_seqfetcher.md. """
5
+ import os
5
6
  import re
7
+ import threading
6
8
  import warnings
7
9
  from enum import Enum
8
10
 
@@ -24,12 +26,38 @@ __all__ = [
24
26
  ]
25
27
 
26
28
 
29
+ class _ThreadLocalFastaFile:
30
+ """ A pysam FastaFile opened once per thread and process. Reads through one shared handle from
31
+ several threads, or from both sides of a fork, corrupt it for every later read """
32
+
33
+ def __init__(self, fasta_filename):
34
+ self._local = threading.local()
35
+ fasta_file = self._open(fasta_filename)
36
+ self.filename = fasta_file.filename
37
+ self.references = fasta_file.references
38
+
39
+ def _open(self, fasta_filename):
40
+ self._local.fasta_file = FastaFile(fasta_filename)
41
+ self._local.pid = os.getpid()
42
+ return self._local.fasta_file
43
+
44
+ def fetch(self, *args, **kwargs):
45
+ if getattr(self._local, "pid", None) == os.getpid():
46
+ fasta_file = self._local.fasta_file
47
+ else:
48
+ fasta_file = self._open(self.filename)
49
+ return fasta_file.fetch(*args, **kwargs)
50
+
51
+
27
52
  class GenomeFastaSeqFetcher:
53
+ """ Values of ``contig_fastas`` have ``fetch()`` and ``filename`` like a pysam FastaFile, but are
54
+ safe to share between threads and across a fork """
55
+
28
56
  def __init__(self, *args):
29
57
  self.source = "Local Fasta file reference"
30
58
  self.contig_fastas = {}
31
59
  for fasta_filename in args:
32
- fasta_file = FastaFile(fasta_filename)
60
+ fasta_file = _ThreadLocalFastaFile(fasta_filename)
33
61
  for contig in fasta_file.references:
34
62
  self.contig_fastas[contig] = fasta_file
35
63
 
@@ -154,8 +182,11 @@ class ExonsFromGenomeFastaSeqFetcher(AbstractTranscriptSeqFetcher):
154
182
 
155
183
  exon_seq_list = []
156
184
  start = 0
157
- # We are using HGVS cigar
158
- for (length_str, op) in self._CIGAR_PATTERN.findall(exon["cigar"]):
185
+ # HGVS CIGARs are in transcript order: walk them in genomic order along the exon
186
+ cigar_ops = self._CIGAR_PATTERN.findall(exon["cigar"])
187
+ if exon["alt_strand"] == -1:
188
+ cigar_ops.reverse()
189
+ for (length_str, op) in cigar_ops:
159
190
  length = int(length_str)
160
191
  if op == 'D': # Deletion in reference vs transcript
161
192
  exon_seq_list.append("N" * length)
@@ -287,6 +287,21 @@ class AbstractJSONDataProvider(Interface):
287
287
  }
288
288
  tx_exons.append(exon_data)
289
289
 
290
+ # A partial alignment can leave transcript bases unaligned, before the 5' exon or between two
291
+ # exons. biocommons builds transcript coordinates from the exon CIGARs starting at 0 and
292
+ # needs each exon to start where the previous one ends, so give those bases to the 5' exon
293
+ # as a leading transcript-only (D) op, and to the exon before a gap as a trailing one, as
294
+ # UTA does (CIGARs are in transcript order on both strands).
295
+ by_tx = sorted(tx_exons, key=lambda e: e["tx_start_i"])
296
+ first_exon = by_tx[0]
297
+ if unaligned := first_exon["tx_start_i"]:
298
+ first_exon["cigar"] = f"{unaligned}D" + first_exon["cigar"]
299
+ first_exon["tx_start_i"] = 0
300
+ for exon, next_exon in zip(by_tx, by_tx[1:]):
301
+ if unaligned := next_exon["tx_start_i"] - exon["tx_end_i"]:
302
+ exon["cigar"] += f"{unaligned}D"
303
+ exon["tx_end_i"] = next_exon["tx_start_i"]
304
+
290
305
  self._tx_exons_cache[cache_key] = tx_exons
291
306
  if len(self._tx_exons_cache) > self.TX_EXONS_CACHE_SIZE:
292
307
  self._tx_exons_cache.popitem(last=False)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cdot
3
- Version: 0.2.35
3
+ Version: 0.2.37
4
4
  Summary: Transcripts for HGVS libraries
5
5
  Author-email: Dave Lawrence <davmlaw@gmail.com>
6
6
  License-Expression: MIT
@@ -1029,6 +1029,22 @@ def test_pipeline_ordering(bad, expected, required_codes):
1029
1029
  assert E not in severities(fixes)
1030
1030
 
1031
1031
 
1032
+ @pytest.mark.parametrize("hgvs_string", [
1033
+ "NM_001754.5:c.1A>G p.(Met1?) NM_000059.4:c.68del",
1034
+ "RUNX1\tNM_001754.5:c.1A>G\tp.(Met1?) BRCA2\tNM_000059.4:c.68del\tp.(Asp23fs)",
1035
+ ])
1036
+ def test_protein_suffix_not_stripped_before_second_variant(hgvs_string):
1037
+ # Stripping would silently drop the second variant
1038
+ _cleaned, fixes = clean_hgvs(hgvs_string)
1039
+ assert C.STRIPPED_PROTEIN_SUFFIX not in codes(fixes)
1040
+
1041
+
1042
+ def test_protein_suffix_with_protein_accession_stripped():
1043
+ cleaned, fixes = clean_hgvs("NM_000059.4:c.68del p.(Asp23fs) NP_000050.2:p.Asp23fs")
1044
+ assert cleaned == "NM_000059.4:c.68del"
1045
+ assert C.STRIPPED_PROTEIN_SUFFIX in codes(fixes)
1046
+
1047
+
1032
1048
  def test_protein_allele_not_stripped_as_suffix():
1033
1049
  # "p." is the allele itself here, not a trailing annotation to drop
1034
1050
  cleaned, fixes = clean_hgvs("NP_000050.2 p.Arg1Gly")
@@ -5,15 +5,20 @@ Uses a tiny synthetic genome and transcripts. The genome_mismatch values are fro
5
5
  in #115: EGR2 NM_000399.3 (1 indel) and PTEN NM_000314.4 (1 substitution, 1 indel)
6
6
  """
7
7
  import json
8
+ import os
9
+ import random
10
+ import threading
8
11
  import warnings
12
+ from unittest import mock
9
13
 
14
+ from bioutils.sequences import reverse_complement
10
15
  import pysam
11
16
  import pytest
12
17
  from hgvs.exceptions import HGVSDataNotAvailableError
13
18
 
14
19
  from cdot.hgvs.dataproviders import ChainedSeqFetcher, JSONDataProvider
15
20
  from cdot.hgvs.dataproviders.fasta_seqfetcher import FastaSeqFetcher, ExonsFromGenomeFastaSeqFetcher, \
16
- GenomeMismatchError, GenomeMismatchPolicy, GenomeMismatchWarning
21
+ GenomeFastaSeqFetcher, GenomeMismatchError, GenomeMismatchPolicy, GenomeMismatchWarning
17
22
 
18
23
  CONTIG = "NC_000011.9" # GRCh37 chr11
19
24
  GENOME = "ACGTTGCAAC" * 10
@@ -161,6 +166,10 @@ PADDED_TRANSCRIPTS = {
161
166
  "NM_000001.1": ("+", [[10, 30, 0, 1, 22, "M10 I2 M10"], [40, 60, 1, 23, 42, None]]),
162
167
  "NM_000002.1": ("-", [[10, 30, 0, 1, 22, "M5 I2 M15"]]),
163
168
  "NM_000003.1": ("+", [[10, 30, 0, 4, 23, None]]),
169
+ "NM_000004.1": ("-", [[10, 30, 0, 4, 23, None]]),
170
+ # Transcript bases 21-23 align nowhere, between the two exons
171
+ "NM_000005.1": ("+", [[10, 30, 0, 1, 20, None], [40, 60, 1, 24, 43, None]]),
172
+ "NM_000006.1": ("-", [[10, 30, 1, 24, 43, None], [40, 60, 0, 1, 20, None]]),
164
173
  }
165
174
 
166
175
 
@@ -187,7 +196,7 @@ def _assembly_mapper(hdp):
187
196
 
188
197
 
189
198
  @pytest.mark.parametrize("ac, positions", [
190
- ("NM_000001.1", "n.11_12"), ("NM_000002.1", "n.16_17"), ("NM_000003.1", "n.1_3"),
199
+ ("NM_000001.1", "n.11_12"), ("NM_000002.1", "n.6_7"), ("NM_000003.1", "n.1_3"),
191
200
  ])
192
201
  def test_slice_with_padding_raises(padded_files, ac, positions):
193
202
  fasta_filename, json_filename = padded_files
@@ -239,3 +248,78 @@ def test_indel_normalized_into_padding_raises(padded_files):
239
248
  assert str(am.c_to_g(parser.parse("NM_000001.1:c.30G>A"))) == "NC_000011.9:g.48G>A"
240
249
  with pytest.raises(GenomeMismatchError):
241
250
  am.c_to_g(parser.parse("NM_000001.1:c.11A>G"))
251
+
252
+
253
+ @pytest.mark.parametrize("ac, n_pos, g_pos", [
254
+ ("NM_000003.1", 4, 11), ("NM_000003.1", 23, 30),
255
+ ("NM_000004.1", 4, 30), ("NM_000004.1", 23, 11),
256
+ ("NM_000005.1", 20, 30), ("NM_000005.1", 24, 41), ("NM_000005.1", 43, 60),
257
+ ("NM_000006.1", 20, 41), ("NM_000006.1", 24, 30), ("NM_000006.1", 43, 11),
258
+ ])
259
+ def test_unaligned_transcript_bases_map(padded_files, ac, n_pos, g_pos):
260
+ """ Unaligned transcript bases (n.1_3 at the start, n.21_23 between exons) are skipped """
261
+ from hgvs.alignmentmapper import AlignmentMapper
262
+ from hgvs.parser import Parser
263
+ _, json_filename = padded_files
264
+ hdp = _hdp(json_filename, StaticSeqFetcher())
265
+ interval = Parser().parse_n_interval(str(n_pos))
266
+ g_interval = AlignmentMapper(hdp, ac, CONTIG, "splign").n_to_g(interval)
267
+ assert (g_interval.start.base, g_interval.end.base) == (g_pos, g_pos)
268
+
269
+
270
+ @pytest.mark.parametrize("ac, seq", [
271
+ ("NM_000005.1", PADDED_GENOME[10:30] + "NNN" + PADDED_GENOME[40:60]),
272
+ ("NM_000006.1", reverse_complement(PADDED_GENOME[40:60]) + "NNN" + reverse_complement(PADDED_GENOME[10:30])),
273
+ ])
274
+ def test_unaligned_bases_between_exons_padded(padded_files, ac, seq):
275
+ fasta_filename, json_filename = padded_files
276
+ hdp = _hdp(json_filename, FastaSeqFetcher(fasta_filename))
277
+ with pytest.warns(GenomeMismatchWarning, match=f"{ac} n.21_23"):
278
+ assert hdp.seqfetcher.fetch_seq(ac) == seq
279
+
280
+
281
+ @pytest.fixture(scope="module")
282
+ def bgzipped_genome(tmp_path_factory):
283
+ """ 2 Mb, so reads land in many different bgzf blocks """
284
+ tmp_path = tmp_path_factory.mktemp("bgzip")
285
+ rng = random.Random(42)
286
+ genome = "".join(rng.choice("ACGT") for _ in range(2_000_000))
287
+ fasta_filename = str(tmp_path / "genome.fa")
288
+ with open(fasta_filename, "w") as f:
289
+ f.write(f">{CONTIG}\n{genome}\n")
290
+ pysam.tabix_compress(fasta_filename, fasta_filename + ".gz")
291
+ pysam.faidx(fasta_filename + ".gz")
292
+ return fasta_filename + ".gz", genome
293
+
294
+
295
+ def test_fetch_from_several_threads(bgzipped_genome):
296
+ fasta_filename, genome = bgzipped_genome
297
+ seqfetcher = GenomeFastaSeqFetcher(fasta_filename)
298
+ errors = []
299
+
300
+ def fetch_random(seed):
301
+ rng = random.Random(seed)
302
+ for _ in range(300):
303
+ pos = rng.randrange(len(genome) - 10)
304
+ try:
305
+ assert seqfetcher.fetch_seq(CONTIG, pos, pos + 10) == genome[pos:pos + 10]
306
+ except Exception as e:
307
+ errors.append(e)
308
+
309
+ threads = [threading.Thread(target=fetch_random, args=(seed,)) for seed in range(4)]
310
+ for thread in threads:
311
+ thread.start()
312
+ for thread in threads:
313
+ thread.join()
314
+ assert not errors
315
+
316
+
317
+ def test_forked_process_opens_own_handle(bgzipped_genome):
318
+ fasta_filename, genome = bgzipped_genome
319
+ seqfetcher = GenomeFastaSeqFetcher(fasta_filename)
320
+ fasta_file = seqfetcher.contig_fastas[CONTIG]
321
+ assert seqfetcher.fetch_seq(CONTIG, 0, 10) == genome[:10]
322
+ parent_handle = fasta_file._local.fasta_file
323
+ with mock.patch("os.getpid", return_value=os.getpid() + 1):
324
+ assert seqfetcher.fetch_seq(CONTIG, 0, 10) == genome[:10]
325
+ assert fasta_file._local.fasta_file is not parent_handle
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes