Coverage for src/python/ensembl/vep/runner/corpus/golden.py: 89%

70 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"""Golden corpus term generation and validation.""" 

15 

16from __future__ import annotations 

17 

18import logging 

19from typing import Any, ClassVar 

20 

21from attrs import asdict 

22 

23from ensembl.vep.annotators.factory import build_annotator 

24from ensembl.vep.config import Config, ConfigSource 

25from ensembl.vep.corpus.golden import GoldenReport, GoldenTerms, record_golden 

26from ensembl.vep.corpus.registry import build_corpus 

27from ensembl.vep.corpus.spec import CorpusSpec 

28from ensembl.vep.runner.base import ExitCode 

29from ensembl.vep.runner.registry import register_runner 

30 

31__all__ = ["Runner"] 

32 

33logger = logging.getLogger(__name__) 

34 

35 

36@register_runner("corpus.golden") 

37class Runner: 

38 """Runner for generating or validating golden corpus terms. 

39 

40 Checking reads the corpus spec from the golden file itself, so ``--golden_file`` alone is a 

41 complete check. The annotator comes from the file too, unless ``--annotator`` is given 

42 explicitly -- checking another strategy against one annotator's golden terms is a conformance 

43 check against a fixed expectation, which is the point. 

44 

45 Attributes: 

46 name (ClassVar[str]): The registry name. 

47 sections (ClassVar[tuple[str, ...]]): The configuration sections read. 

48 description (ClassVar[str]): One-line description for the subcommand list. 

49 """ 

50 

51 name: ClassVar[str] = "corpus.golden" 

52 sections: ClassVar[tuple[str, ...]] = ("logging", "corpus", "annotation", "corpus_golden") 

53 description: ClassVar[str] = "record or check the terms an annotator emits for a corpus" 

54 

55 def __init__(self, config: Config) -> None: 

56 """Hold the configuration.""" 

57 self.config = config 

58 

59 def run(self) -> ExitCode: 

60 """Record or check, as asked.""" 

61 golden = self.config.corpus_golden 

62 if golden.golden_file is None: 

63 logger.error("give --golden_file PATH to say which golden terms to check or record") 

64 return ExitCode.USAGE 

65 

66 if golden.update_golden: 

67 return self._update() 

68 return self._check() 

69 

70 def _check(self) -> ExitCode: 

71 """Check current annotations against an existing golden terms file.""" 

72 golden = self.config.corpus_golden 

73 assert golden.golden_file is not None 

74 if not golden.golden_file.exists(): 

75 logger.error("%s does not exist; record it first with --update_golden", golden.golden_file) 

76 return ExitCode.USAGE 

77 

78 try: 

79 expected = GoldenTerms.load(golden.golden_file) 

80 except (ValueError, KeyError) as unreadable: 

81 logger.error("cannot read %s: %s", golden.golden_file, unreadable) 

82 return ExitCode.FAILURE 

83 

84 annotator_name = expected.annotator 

85 if self.config.source_of("annotation", "annotator") is not ConfigSource.DEFAULT: 

86 annotator_name = self.config.annotation.annotator 

87 try: 

88 actual = self._record(expected.spec, annotator_name) 

89 except (KeyError, TypeError, ValueError, OSError) as unusable: 

90 logger.error("%s", unusable) 

91 return ExitCode.USAGE 

92 report = GoldenReport.compare(expected, actual) 

93 emit = logger.info if report.ok else logger.error 

94 for line in report.lines(): 

95 emit("%s", line) 

96 return ExitCode.OK if report.ok else ExitCode.FAILURE 

97 

98 def _update(self) -> ExitCode: 

99 """Record current annotations as the requested golden terms file.""" 

100 golden_file = self.config.corpus_golden.golden_file 

101 assert golden_file is not None 

102 try: 

103 spec = CorpusSpec.from_options(self.config.corpus) 

104 recorded = self._record(spec, self.config.annotation.annotator) 

105 except (KeyError, TypeError, ValueError, OSError) as unusable: 

106 logger.error("%s", unusable) 

107 return ExitCode.USAGE 

108 recorded.write(golden_file) 

109 logger.info( 

110 "recorded %d overlaps from %s over %s to %s", 

111 len(recorded.terms), 

112 recorded.annotator, 

113 spec.kind, 

114 golden_file, 

115 ) 

116 return ExitCode.OK 

117 

118 def _record(self, spec: CorpusSpec, annotator_name: str) -> GoldenTerms: 

119 """Annotate a corpus with the named annotator, configured caches applied.""" 

120 options: dict[str, Any] = asdict(self.config.annotation) 

121 options["annotator"] = annotator_name 

122 annotator = build_annotator( 

123 **options, 

124 upstream_distance=self.config.source.upstream_distance, 

125 downstream_distance=self.config.source.downstream_distance, 

126 ) 

127 with build_corpus(spec) as corpus: 

128 return record_golden(corpus, annotator, annotator_name)