Coverage for rdgai/sampling.py: 90.91%

66 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-24 23:53 +0000

1""" 

2Reproducible random samples of variation units, split into example and test units. 

3 

4The sample is stored in a sidecar YAML file next to the TEI file (by default ``<file>.sample.yaml``) 

5so that the TEI file read by teiphy is unchanged, and so that an evaluation can rely on a split that the 

6annotation tools cannot alter. 

7""" 

8import os 

9import random 

10import tempfile 

11from datetime import datetime, timezone 

12from pathlib import Path 

13from typing import Literal 

14 

15import yaml 

16from pydantic import BaseModel, Field 

17 

18Role = Literal["example", "test"] 

19 

20 

21class SampleUnit(BaseModel): 

22 id: str 

23 role: Role 

24 

25 

26class Sample(BaseModel): 

27 seed: int 

28 size: int 

29 test_fraction: float 

30 max_pairs: int | None = Field(default=None, description="Units with more pairs than this were not eligible.") 

31 ignore_types: list[str] = Field(default_factory=list) 

32 eligible_count: int = Field(description="Number of units the sample was drawn from.") 

33 created: str 

34 source: str = Field(description="Name of the TEI file the sample was drawn from.") 

35 units: list[SampleUnit] = Field(description="The sampled units in document order.") 

36 

37 def role_of(self, unit_id:str) -> Role|None: 

38 for unit in self.units: 

39 if unit.id == unit_id: 

40 return unit.role 

41 return None 

42 

43 def ids(self, role:Role|None=None) -> list[str]: 

44 return [unit.id for unit in self.units if role is None or unit.role == role] 

45 

46 

47def default_sample_path(tei_path:Path|str) -> Path: 

48 tei_path = Path(tei_path) 

49 return tei_path.with_name(f"{tei_path.stem}.sample.yaml") 

50 

51 

52def draw( 

53 eligible_ids:list[str], 

54 size:int, 

55 seed:int, 

56 test_fraction:float=0.5, 

57 document_order:list[str]|None=None, 

58) -> list[SampleUnit]: 

59 """ 

60 Draws `size` units from `eligible_ids` and assigns round(size * test_fraction) of them to the test set. 

61 

62 The result depends only on the set of eligible ids, the size, the seed and the test fraction 

63 (not on the order of `eligible_ids`). Units are returned in document order if `document_order` is given. 

64 """ 

65 if size < 1: 

66 raise ValueError("The sample size must be at least 1.") 

67 if size > len(eligible_ids): 

68 raise ValueError(f"Cannot sample {size} units: only {len(eligible_ids)} are eligible.") 

69 if not 0.0 <= test_fraction <= 1.0: 

70 raise ValueError("test_fraction must be between 0 and 1.") 

71 

72 rng = random.Random(seed) 

73 chosen = rng.sample(sorted(eligible_ids), size) 

74 

75 shuffled = list(chosen) 

76 rng.shuffle(shuffled) 

77 test_count = round(size * test_fraction) 

78 test_ids = set(shuffled[:test_count]) 

79 

80 if document_order is not None: 

81 position = {unit_id: index for index, unit_id in enumerate(document_order)} 

82 chosen.sort(key=lambda unit_id: position.get(unit_id, len(position))) 

83 

84 return [SampleUnit(id=unit_id, role="test" if unit_id in test_ids else "example") for unit_id in chosen] 

85 

86 

87def load_sample(path:Path|str) -> Sample|None: 

88 path = Path(path) 

89 if not path.exists(): 

90 return None 

91 return Sample.model_validate(yaml.safe_load(path.read_text(encoding="utf-8"))) 

92 

93 

94def save_sample(sample:Sample, path:Path|str): 

95 path = Path(path) 

96 path.parent.mkdir(parents=True, exist_ok=True) 

97 fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp") 

98 try: 

99 with os.fdopen(fd, "w", encoding="utf-8") as f: 

100 yaml.safe_dump(sample.model_dump(), f, sort_keys=False, allow_unicode=True) 

101 os.replace(tmp, path) 

102 finally: 

103 if os.path.exists(tmp): 

104 os.remove(tmp) 

105 

106 

107def now() -> str: 

108 return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")