Coverage for src/python/ensembl/vep/corpus/spec.py: 100%

152 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"""The registered corpus and parameters to construct.""" 

15 

16from __future__ import annotations 

17 

18import hashlib 

19import json 

20from collections.abc import Mapping, Sequence 

21from typing import TypeAlias 

22 

23from attrs import frozen 

24 

25__all__ = ["CorpusParameter", "CorpusSpec"] 

26 

27CorpusParameter: TypeAlias = str | int | float | bool | None 

28"""A scalar parameter accepted by a registered corpus factory.""" 

29 

30_DEFAULT_PARAMETERS: dict[str, CorpusParameter] = { 

31 "fuzz": 4000, 

32 "step": 13, 

33 "genome_seed": 7, 

34 "boundary_seed": 11, 

35 "fuzz_seed": 23, 

36 "heavy_genome_seed": 31, 

37 "sweep_seed": 41, 

38} 

39 

40_SYNTHETIC_KINDS = ("synthetic.default", "synthetic.heavy", "synthetic.all") 

41 

42 

43def _parameter_items( 

44 parameters: Mapping[str, CorpusParameter], 

45) -> tuple[tuple[str, CorpusParameter], ...]: 

46 """Freeze parameters in stable key order.""" 

47 return tuple(sorted(parameters.items())) 

48 

49 

50def _parameter_value(raw: str) -> CorpusParameter: 

51 """Decode a command-line JSON scalar, retaining ordinary strings.""" 

52 try: 

53 decoded = json.loads(raw) 

54 except json.JSONDecodeError: 

55 return raw 

56 if decoded is None or isinstance(decoded, (str, int, float, bool)): 

57 return decoded 

58 raise ValueError(f"corpus parameter values must be scalars, got {raw!r}") 

59 

60 

61def _option_parameters(options: object) -> dict[str, CorpusParameter]: 

62 """Return generic parameters declared by a config-like object.""" 

63 configured = getattr(options, "parameters", None) 

64 if configured is None: 

65 return {} 

66 if isinstance(configured, Mapping): 

67 mapping_parameters: dict[str, CorpusParameter] = {} 

68 for name, value in configured.items(): 

69 if not isinstance(name, str): 

70 raise TypeError("corpus parameter names must be strings") 

71 if value is not None and not isinstance(value, (str, int, float, bool)): 

72 raise TypeError(f"corpus parameter {name!r} must be a scalar") 

73 mapping_parameters[name] = value 

74 return mapping_parameters 

75 if isinstance(configured, Sequence) and not isinstance(configured, str): 

76 sequence_parameters: dict[str, CorpusParameter] = {} 

77 for item in configured: 

78 if not isinstance(item, str) or "=" not in item: 

79 raise ValueError(f"corpus parameter must be KEY=VALUE, got {item!r}") 

80 name, raw_value = item.split("=", 1) 

81 if not name: 

82 raise ValueError(f"corpus parameter needs a name, got {item!r}") 

83 sequence_parameters[name] = _parameter_value(raw_value) 

84 return sequence_parameters 

85 raise TypeError("corpus parameters must be a mapping or a sequence of KEY=VALUE strings") 

86 

87 

88@frozen(init=False, kw_only=True, auto_attribs=True) 

89class CorpusSpec: 

90 """Describe a registered corpus construction. 

91 

92 ``parameters`` is deliberately open: each registered factory owns its parameter validation. 

93 Synthetic convenience arguments remain available alongside generic factory parameters. 

94 

95 Attributes: 

96 kind (str): Registered corpus name. 

97 parameters (Mapping[str, CorpusParameter]): Factory-owned construction parameters. 

98 """ 

99 

100 kind: str 

101 _parameter_items: tuple[tuple[str, CorpusParameter], ...] 

102 

103 def __init__( 

104 self, 

105 *, 

106 kind: str = "synthetic.all", 

107 parameters: Mapping[str, CorpusParameter] | None = None, 

108 fuzz: int | None = None, 

109 step: int | None = None, 

110 genome_seed: int | None = None, 

111 boundary_seed: int | None = None, 

112 fuzz_seed: int | None = None, 

113 heavy_genome_seed: int | None = None, 

114 sweep_seed: int | None = None, 

115 ) -> None: 

116 """Create a specification, accepting synthetic parameter overrides. 

117 

118 Explicit synthetic arguments replace values from ``parameters``; unspecified synthetic 

119 parameters retain their defaults. 

120 

121 Args: 

122 kind (str): Registered corpus name. 

123 parameters (Mapping[str, CorpusParameter] | None): Factory-owned scalar parameters. 

124 fuzz (int | None): Default synthetic random-variant count override. 

125 step (int | None): Heavy synthetic variant spacing override. 

126 genome_seed (int | None): Default synthetic genome seed override. 

127 boundary_seed (int | None): Boundary-variant seed override. 

128 fuzz_seed (int | None): Random-variant seed override. 

129 heavy_genome_seed (int | None): Heavy synthetic genome seed override. 

130 sweep_seed (int | None): Heavy synthetic variant seed override. 

131 

132 Raises: 

133 TypeError: If a parameter name or value is not a supported scalar. 

134 ValueError: If the kind is empty or a built-in count or step is invalid. 

135 """ 

136 if not kind: 

137 raise ValueError("corpus kind must not be empty") 

138 

139 resolved = dict(_DEFAULT_PARAMETERS) if kind in _SYNTHETIC_KINDS else {} 

140 if parameters is not None: 

141 resolved.update(parameters) 

142 overrides = { 

143 "fuzz": fuzz, 

144 "step": step, 

145 "genome_seed": genome_seed, 

146 "boundary_seed": boundary_seed, 

147 "fuzz_seed": fuzz_seed, 

148 "heavy_genome_seed": heavy_genome_seed, 

149 "sweep_seed": sweep_seed, 

150 } 

151 for name, override_value in overrides.items(): 

152 if override_value is not None: 

153 resolved[name] = override_value 

154 for name, parameter_value in resolved.items(): 

155 if not isinstance(name, str): 

156 raise TypeError("corpus parameter names must be strings") 

157 if parameter_value is not None and not isinstance(parameter_value, (str, int, float, bool)): 

158 raise TypeError(f"corpus parameter {name!r} must be a scalar") 

159 

160 if kind in _SYNTHETIC_KINDS: 

161 resolved_fuzz = resolved.get("fuzz") 

162 resolved_step = resolved.get("step") 

163 if not isinstance(resolved_fuzz, int) or isinstance(resolved_fuzz, bool) or resolved_fuzz < 0: 

164 raise ValueError("fuzz must be a non-negative integer") 

165 if not isinstance(resolved_step, int) or isinstance(resolved_step, bool) or resolved_step <= 0: 

166 raise ValueError("step must be a positive integer") 

167 

168 object.__setattr__(self, "kind", kind) 

169 object.__setattr__(self, "_parameter_items", _parameter_items(resolved)) 

170 

171 @classmethod 

172 def from_options(cls, options: object) -> CorpusSpec: 

173 """Build a specification from corpus configuration attributes. 

174 

175 Args: 

176 options (object): Configuration-like object with ``kind`` and corpus parameters. 

177 

178 Returns: 

179 CorpusSpec: Normalised construction specification. 

180 

181 Raises: 

182 TypeError: If configured generic parameters have invalid types. 

183 ValueError: If generic parameters are malformed or built-in values are invalid. 

184 """ 

185 kind = getattr(options, "kind", "synthetic.all") 

186 parameters: dict[str, CorpusParameter] = {} 

187 corpus_directory = getattr(options, "corpus_dir", None) 

188 if corpus_directory is not None and kind == "loaded.files": 

189 parameters.update( 

190 { 

191 "fasta": str(corpus_directory / "corpus.fa"), 

192 "gff3": str(corpus_directory / "corpus.gff3"), 

193 "vcf": str(corpus_directory / "corpus.vcf"), 

194 } 

195 ) 

196 elif corpus_directory is not None and kind == "golden.file": 

197 parameters["directory"] = str(corpus_directory) 

198 parameters.update(_option_parameters(options)) 

199 if kind in _SYNTHETIC_KINDS: 

200 for name in _DEFAULT_PARAMETERS: 

201 if hasattr(options, name): 

202 parameters[name] = getattr(options, name) 

203 return cls(kind=kind, parameters=parameters) 

204 

205 @classmethod 

206 def from_dict(cls, value: Mapping[str, object]) -> CorpusSpec: 

207 """Build a specification from its JSON-compatible representation. 

208 

209 Args: 

210 value (Mapping[str, object]): Mapping produced by ``as_dict``. 

211 

212 Returns: 

213 CorpusSpec: Decoded construction specification. 

214 

215 Raises: 

216 TypeError: If the kind or parameters have invalid types. 

217 ValueError: If decoded built-in parameters are invalid. 

218 """ 

219 kind = value.get("kind", "synthetic.all") 

220 if not isinstance(kind, str): 

221 raise TypeError("corpus kind must be a string") 

222 raw_parameters = value.get("parameters") 

223 if raw_parameters is None: 

224 parameters = {name: value[name] for name in _DEFAULT_PARAMETERS if name in value} 

225 elif isinstance(raw_parameters, Mapping): 

226 parameters = dict(raw_parameters) 

227 else: 

228 raise TypeError("corpus parameters must be a mapping") 

229 return cls(kind=kind, parameters=parameters) # type: ignore[arg-type] 

230 

231 @property 

232 def parameters(self) -> dict[str, CorpusParameter]: 

233 """Return a copy of the registered factory parameters.""" 

234 return dict(self._parameter_items) 

235 

236 def parameter(self, name: str, default: CorpusParameter = None) -> CorpusParameter: 

237 """Return one factory parameter or ``default`` when absent. 

238 

239 Args: 

240 name (str): Parameter name. 

241 default (CorpusParameter): Value returned when the parameter is absent. 

242 

243 Returns: 

244 CorpusParameter: Configured or default scalar value. 

245 """ 

246 return self.parameters.get(name, default) 

247 

248 def with_parameters(self, **parameters: CorpusParameter) -> CorpusSpec: 

249 """Return a specification with selected parameters replaced. 

250 

251 Args: 

252 parameters (CorpusParameter): Scalar values to add or replace. 

253 

254 Returns: 

255 CorpusSpec: New specification retaining the same corpus kind. 

256 """ 

257 merged = self.parameters 

258 merged.update(parameters) 

259 return CorpusSpec(kind=self.kind, parameters=merged) 

260 

261 def as_dict(self) -> dict[str, object]: 

262 """Return the JSON-compatible representation.""" 

263 return {"kind": self.kind, "parameters": self.parameters} 

264 

265 def _integer_parameter(self, name: str) -> int: 

266 """Return a synthetic integer parameter with its type checked.""" 

267 value = self.parameters[name] 

268 if not isinstance(value, int) or isinstance(value, bool): 

269 raise TypeError(f"corpus parameter {name!r} must be an integer") 

270 return value 

271 

272 @property 

273 def fuzz(self) -> int: 

274 """Return the default synthetic corpus random-variant count.""" 

275 return self._integer_parameter("fuzz") 

276 

277 @property 

278 def step(self) -> int: 

279 """Return the heavy-locus sweep step.""" 

280 return self._integer_parameter("step") 

281 

282 @property 

283 def genome_seed(self) -> int: 

284 """Return the default synthetic genome seed.""" 

285 return self._integer_parameter("genome_seed") 

286 

287 @property 

288 def boundary_seed(self) -> int: 

289 """Return the boundary-variant seed.""" 

290 return self._integer_parameter("boundary_seed") 

291 

292 @property 

293 def fuzz_seed(self) -> int: 

294 """Return the random-variant seed.""" 

295 return self._integer_parameter("fuzz_seed") 

296 

297 @property 

298 def heavy_genome_seed(self) -> int: 

299 """Return the heavy-locus genome seed.""" 

300 return self._integer_parameter("heavy_genome_seed") 

301 

302 @property 

303 def sweep_seed(self) -> int: 

304 """Return the heavy-locus sweep seed.""" 

305 return self._integer_parameter("sweep_seed") 

306 

307 @property 

308 def kinds(self) -> tuple[str, ...]: 

309 """Return the concrete corpus kinds represented by the specification.""" 

310 if self.kind == "synthetic.all": 

311 return ("synthetic.default", "synthetic.heavy") 

312 return (self.kind,) 

313 

314 def seeds_by_kind(self) -> dict[str, dict[str, int]]: 

315 """Return synthetic seeds for the selected built-in corpora.""" 

316 seeds: dict[str, dict[str, int]] = {} 

317 if "synthetic.default" in self.kinds: 

318 seeds["synthetic.default"] = { 

319 "genome": self.genome_seed, 

320 "boundary": self.boundary_seed, 

321 "fuzz": self.fuzz_seed, 

322 } 

323 if "synthetic.heavy" in self.kinds: 

324 seeds["synthetic.heavy"] = { 

325 "genome": self.heavy_genome_seed, 

326 "sweep": self.sweep_seed, 

327 } 

328 return seeds 

329 

330 def parameter_hash(self) -> str: 

331 """Return a short stable digest of the requested construction.""" 

332 payload = json.dumps(self.as_dict(), sort_keys=True).encode("utf-8") 

333 return hashlib.sha256(payload).hexdigest()[:16]