Coverage for src/scixplorer/evaluate.py: 99%

154 statements  

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

1"""Evaluate expressions in Python against objects. 

2 

3Used for models held in memory (journals, affiliations, libraries). The 

4semantics follow Solr where that makes sense: logic is two-valued, and a 

5missing (``None``) value never satisfies a positive predicate, so its negation 

6is true. Multivalued values (lists/tuples, flattened recursively) satisfy a 

7predicate if any element does. A per-record condition (``Document.authors.any(...)``) 

8is evaluated over the records built from the object's arrays, which is also 

9how document searches check such conditions client-side. 

10""" 

11 

12from __future__ import annotations 

13 

14import re 

15from collections.abc import Callable, Iterable, Iterator 

16from datetime import date, datetime 

17from typing import Any, TypeVar 

18 

19from .exceptions import NotLocallyEvaluable 

20from .expr import ( 

21 And, 

22 Constant, 

23 Expr, 

24 Func, 

25 In, 

26 InLibrary, 

27 Like, 

28 Match, 

29 Not, 

30 Or, 

31 Order, 

32 Quantified, 

33 Range, 

34 Raw, 

35 Related, 

36 SolrLiteral, 

37 Wildcard, 

38 parse_pattern, 

39) 

40from .fields import DateField, DateTimeField, Field, as_utc 

41 

42__all__ = ["matches", "predicate", "sort_rows"] 

43 

44T = TypeVar("T") 

45Predicate = Callable[[Any], bool] 

46 

47_WORD = re.compile(r"\w+") 

48 

49 

50def matches(expr: Expr, obj: Any) -> bool: 

51 """Whether ``obj`` satisfies ``expr``. 

52 

53 Raises :class:`~scixplorer.exceptions.NotLocallyEvaluable` if any part of ``expr`` 

54 can only be evaluated by ADS. 

55 """ 

56 return predicate(expr)(obj) 

57 

58 

59def predicate(expr: Expr) -> Predicate: 

60 """Compile ``expr`` once into a function ``obj -> bool``. 

61 

62 The whole expression is checked up front, so ``NotLocallyEvaluable`` is 

63 raised here rather than depending on which objects are tested. 

64 """ 

65 if isinstance(expr, And): 

66 parts = [predicate(op) for op in expr.operands] 

67 return lambda obj: all(part(obj) for part in parts) 

68 if isinstance(expr, Or): 

69 parts = [predicate(op) for op in expr.operands] 

70 return lambda obj: any(part(obj) for part in parts) 

71 if isinstance(expr, Not): 

72 inner = predicate(expr.operand) 

73 return lambda obj: not inner(obj) 

74 if isinstance(expr, Constant): 

75 value = expr.value 

76 return lambda obj: value 

77 if isinstance(expr, Related): 

78 return _related(expr) 

79 if isinstance(expr, Quantified): 

80 return _quantified(expr) 

81 if isinstance(expr, (Match, In, Like, Range)): 

82 field = expr.field 

83 if not field.stored: 

84 raise NotLocallyEvaluable(f"{field!r} is search-only, so {expr!r} needs ADS") 

85 test = _value_test(expr) 

86 name = field.name 

87 return lambda obj: any(test(value) for value in _flatten(getattr(obj, name))) 

88 if isinstance(expr, (Func, Raw, InLibrary)): 

89 raise NotLocallyEvaluable(f"{expr!r} can only be evaluated by ADS") 

90 raise TypeError(f"Cannot evaluate {expr!r}") 

91 

92 

93def _flatten(value: Any) -> Iterator[Any]: 

94 """Yield the non-``None`` scalar values in ``value``, flattening lists and tuples.""" 

95 if isinstance(value, (list, tuple)): 

96 for item in value: 

97 yield from _flatten(item) 

98 elif value is not None: 

99 yield value 

100 

101 

102def _related(expr: Related) -> Predicate: 

103 inner = predicate(expr.predicate) 

104 name = expr.relation.name 

105 return lambda obj: any(inner(related) for related in _flatten(getattr(obj, name))) 

106 

107 

108def _quantified(expr: Quantified) -> Predicate: 

109 """True if any (or every, and at least one) selected record of the object satisfies the predicate. 

110 

111 Records are built from the object's arrays, reading only the fields the 

112 predicate needs (an object of the right model is required). 

113 """ 

114 inner = predicate(expr.predicate) 

115 collection, every = expr.collection, expr.quantifier == "all" 

116 names = collection.fields_read(expr.predicate) 

117 start, end = (1, None) if expr.positions is None else expr.positions 

118 

119 def test(obj: Any) -> bool: 

120 records = collection.records(obj, names)[start - 1 : end] 

121 if every: 

122 return bool(records) and all(inner(record) for record in records) 

123 return any(inner(record) for record in records) 

124 

125 return test 

126 

127 

128def _value_test(expr: Match | In | Like | Range) -> Predicate: 

129 """Return a test of a single (non-``None``, non-list) value of ``expr.field``.""" 

130 field = expr.field 

131 if isinstance(expr, Match): 

132 return _match_test(field, expr.value, expr.exact) 

133 if isinstance(expr, In): 

134 tests = [_match_test(field, value, expr.exact) for value in expr.values] 

135 return lambda value: any(test(value) for test in tests) 

136 if isinstance(expr, Like): 

137 regex = _pattern_regex(expr.pattern) 

138 return lambda value: regex.fullmatch(str(value)) is not None 

139 return _range_test(expr) 

140 

141 

142def _match_test(field: Field[Any, Any], target: Any, exact: bool) -> Predicate: 

143 """Test one value against ``target`` according to the field's match kind.""" 

144 _require_local(target) 

145 if field.match_kind == "text": 

146 if exact: 

147 wanted = _normalise_space(target) 

148 return lambda value: _normalise_space(value) == wanted 

149 needle = _tokens(target) 

150 return lambda value: _contains_run(_tokens(value), needle) 

151 if field.match_kind == "name": 

152 name = _parse_name(target) 

153 if exact: 

154 return lambda value: _parse_name(value) == name 

155 return lambda value: _names_match(name, _parse_name(value)) 

156 key = _comparable(field, target) 

157 return lambda value: _comparable(field, value) == key 

158 

159 

160def _range_test(expr: Range) -> Predicate: 

161 field = expr.field 

162 _require_local(expr.lo) 

163 _require_local(expr.hi) 

164 lo = None if expr.lo is None else _comparable(field, expr.lo) 

165 hi = None if expr.hi is None else _comparable(field, expr.hi) 

166 

167 def test(value: Any) -> bool: 

168 value = _comparable(field, value) 

169 if lo is not None and (value < lo if expr.include_lo else value <= lo): 

170 return False 

171 if hi is not None and (value > hi if expr.include_hi else value >= hi): 

172 return False 

173 return True 

174 

175 return test 

176 

177 

178def _require_local(value: Any) -> None: 

179 if isinstance(value, SolrLiteral): 

180 raise NotLocallyEvaluable(f"{value!r} is evaluated by Solr and cannot be compared locally") 

181 

182 

183def _comparable(field: Field[Any, Any], value: Any) -> Any: 

184 """Normalise a value of a date field for comparison; other values pass through. 

185 

186 ``DateTimeField`` values become aware UTC datetimes (dates are midnight UTC); 

187 ``DateField`` values become ``(year, month)``, matching its month precision. 

188 """ 

189 if isinstance(field, DateTimeField) and isinstance(value, date): 

190 return as_utc(value) 

191 if isinstance(field, DateField): 

192 if isinstance(value, datetime): 

193 value = as_utc(value) 

194 if isinstance(value, date): 

195 return (value.year, value.month) 

196 if isinstance(value, str): 196 ↛ 199line 196 didn't jump to line 199 because the condition on line 196 was always true

197 parsed = field._to_python(value) 

198 return (parsed.year, parsed.month) 

199 return value 

200 

201 

202def _tokens(text: str) -> list[str]: 

203 return [token.casefold() for token in _WORD.findall(str(text))] 

204 

205 

206def _contains_run(haystack: list[str], needle: list[str]) -> bool: 

207 if not needle: 

208 return False 

209 width = len(needle) 

210 return any(haystack[i : i + width] == needle for i in range(len(haystack) - width + 1)) 

211 

212 

213def _normalise_space(text: str) -> str: 

214 return " ".join(str(text).split()).casefold() 

215 

216 

217def _parse_name(name: Any) -> tuple[str, tuple[str, ...]]: 

218 """Split ``"Last, Given1 Given2"`` into a last name and given-name tokens. 

219 

220 Case is folded, periods are read as spaces (so ``"S.S."`` is two initials) 

221 and whitespace is collapsed. A name without a comma is all last name. 

222 """ 

223 last, _, given = str(name).casefold().replace(".", " ").partition(",") 

224 return " ".join(last.split()), tuple(given.split()) 

225 

226 

227def _names_match(query: tuple[str, tuple[str, ...]], record: tuple[str, tuple[str, ...]]) -> bool: 

228 """ADS's default author matching, with name variants. 

229 

230 The last names must be equal. Given names are compared in order for as 

231 many positions as both have; a pair is compatible if equal, or if either is 

232 an initial and both start with the same letter. Extra given names on 

233 either side are ignored. 

234 """ 

235 if query[0] != record[0]: 

236 return False 

237 return all( 

238 a == b or ((len(a) == 1 or len(b) == 1) and a[0] == b[0]) for a, b in zip(query[1], record[1], strict=False) 

239 ) 

240 

241 

242def _pattern_regex(pattern: str) -> re.Pattern[str]: 

243 parts = [] 

244 for token in parse_pattern(pattern): 

245 if token is Wildcard.ANY: 

246 parts.append(".*") 

247 elif token is Wildcard.ONE: 

248 parts.append(".") 

249 else: 

250 parts.append(re.escape(token)) 

251 return re.compile("".join(parts), re.IGNORECASE | re.DOTALL) 

252 

253 

254def sort_rows(rows: Iterable[T], orders: Iterable[Order]) -> list[T]: 

255 """Sort ``rows`` by ``orders`` (first key most significant). 

256 

257 Each key has its own direction, ``None`` values always sort last, and rows 

258 with equal keys keep their input order. 

259 """ 

260 result = list(rows) 

261 for order in reversed(list(orders)): 

262 field = order.field 

263 if not field.stored: 

264 raise NotLocallyEvaluable(f"Cannot sort by search-only field {field!r} locally") 

265 name = field.name 

266 present = [row for row in result if getattr(row, name) is not None] 

267 missing = [row for row in result if getattr(row, name) is None] 

268 present.sort(key=lambda row: _comparable(field, getattr(row, name)), reverse=order.descending) 

269 result = present + missing 

270 return result