Coverage for src/python/ensembl/vep/corpus/exporter/formats/file/base.py: 100%

41 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-18 14:41 +0000

1# See the NOTICE file distributed with this work for additional information 

2# regarding copyright ownership. 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14"""A coordinated FASTA, GFF3 and VCF corpus exporter.""" 

15 

16from __future__ import annotations 

17 

18import hashlib 

19from pathlib import Path 

20from tempfile import TemporaryDirectory 

21 

22from ensembl.vep.corpus.base import Corpus 

23from ensembl.vep.corpus.exporter.formats.file.fasta import FASTA_NAME, fasta_lines 

24from ensembl.vep.corpus.exporter.formats.file.gff3 import GFF3_NAME, gff3_lines 

25from ensembl.vep.corpus.exporter.formats.file.vcf import VCF_NAME, distinct_variants, vcf_lines 

26from ensembl.vep.corpus.exporter.manifest import CorpusManifest 

27from ensembl.vep.corpus.exporter.registry import register_exporter 

28 

29__all__ = [ 

30 "CORPUS_FILES", 

31 "FileCorpusExporter", 

32 "MANIFEST_NAME", 

33 "distinct_variants", 

34] 

35 

36MANIFEST_NAME = "manifest.json" 

37CORPUS_FILES = (FASTA_NAME, GFF3_NAME, VCF_NAME, MANIFEST_NAME) 

38 

39 

40def _optional_integer(value: object) -> int | None: 

41 """Return an optional integer manifest value.""" 

42 return value if isinstance(value, int) and not isinstance(value, bool) else None 

43 

44 

45def _identity(contents: dict[str, str]) -> str: 

46 """Return a short digest over corpus files, in a fixed order.""" 

47 digest = hashlib.sha256() 

48 for file_name in sorted(contents): 

49 digest.update(file_name.encode("utf-8")) 

50 digest.update(contents[file_name].encode("utf-8")) 

51 return digest.hexdigest()[:16] 

52 

53 

54@register_exporter("file") 

55class FileCorpusExporter: 

56 """Write a corpus as one coordinated file bundle.""" 

57 

58 def export(self, corpus: Corpus, directory: Path, *, force: bool = False) -> CorpusManifest: 

59 """Write a corpus as FASTA, GFF3 and VCF, with a manifest describing it. 

60 

61 Args: 

62 corpus (Corpus): Corpus to render. 

63 directory (Path): Directory that receives the coordinated file bundle. 

64 force (bool): Whether existing corpus files may be replaced. 

65 

66 Returns: 

67 CorpusManifest: Counts, parameters, and content identity for the written files. 

68 

69 Raises: 

70 FileExistsError: If a corpus file exists and ``force`` was not given. 

71 """ 

72 directory.mkdir(parents=True, exist_ok=True) 

73 present = [name for name in CORPUS_FILES if (directory / name).exists()] 

74 if present and not force: 

75 raise FileExistsError( 

76 f"{directory} already holds {', '.join(present)}; pass --force to overwrite" 

77 ) 

78 

79 corpora = (corpus,) 

80 contents = { 

81 FASTA_NAME: "\n".join(fasta_lines(corpora)) + "\n", 

82 GFF3_NAME: "\n".join(gff3_lines(corpora)) + "\n", 

83 VCF_NAME: "\n".join(vcf_lines(corpora)) + "\n", 

84 } 

85 spec = corpus.spec 

86 manifest = CorpusManifest( 

87 kind=spec.kind, 

88 spec=spec.as_dict(), 

89 fuzz=_optional_integer(spec.parameter("fuzz")), 

90 step=_optional_integer(spec.parameter("step")), 

91 seeds=spec.seeds_by_kind(), 

92 parameters=spec.parameter_hash(), 

93 chromosomes=tuple(region.seq_region_name for region in corpus.sequence_regions), 

94 transcripts=len(corpus.transcripts), 

95 variants=len(distinct_variants(corpus)), 

96 overlaps=len(corpus.named_overlaps), 

97 identity=_identity(contents), 

98 files=tuple(contents), 

99 ) 

100 with TemporaryDirectory(prefix=".corpus-export-", dir=directory) as staging_name: 

101 staging = Path(staging_name) 

102 for file_name, text in contents.items(): 

103 (staging / file_name).write_text(text, encoding="utf-8") 

104 (staging / MANIFEST_NAME).write_text(manifest.to_json(), encoding="utf-8") 

105 for file_name in contents: 

106 (staging / file_name).replace(directory / file_name) 

107 # Commit the manifest last, so readers never see a new identity before its data. 

108 (staging / MANIFEST_NAME).replace(directory / MANIFEST_NAME) 

109 return manifest