evalsuite-python 0.6.0__cp39-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. evalsuite/__init__.py +268 -0
  2. evalsuite/__main__.py +5 -0
  3. evalsuite/_bench_metrics.py +2080 -0
  4. evalsuite/_core.pyd +0 -0
  5. evalsuite/_lazy.py +32 -0
  6. evalsuite/_native.py +60 -0
  7. evalsuite/api.py +275 -0
  8. evalsuite/benchmarks.py +946 -0
  9. evalsuite/calibration.py +392 -0
  10. evalsuite/classification/__init__.py +51 -0
  11. evalsuite/classification/_common.py +111 -0
  12. evalsuite/classification/metrics.py +945 -0
  13. evalsuite/cli/__init__.py +5 -0
  14. evalsuite/cli/main.py +606 -0
  15. evalsuite/clinical/__init__.py +18 -0
  16. evalsuite/clinical/metrics.py +342 -0
  17. evalsuite/clinical/report.py +366 -0
  18. evalsuite/core/__init__.py +1 -0
  19. evalsuite/core/context.py +199 -0
  20. evalsuite/core/exceptions.py +52 -0
  21. evalsuite/core/export.py +100 -0
  22. evalsuite/core/registry.py +90 -0
  23. evalsuite/core/result.py +379 -0
  24. evalsuite/core/types.py +23 -0
  25. evalsuite/core/validation.py +256 -0
  26. evalsuite/llmsys/__init__.py +189 -0
  27. evalsuite/llmsys/_common.py +215 -0
  28. evalsuite/llmsys/agents.py +384 -0
  29. evalsuite/llmsys/code.py +923 -0
  30. evalsuite/llmsys/efficiency.py +346 -0
  31. evalsuite/llmsys/longcontext.py +361 -0
  32. evalsuite/llmsys/multilingual.py +339 -0
  33. evalsuite/llmsys/robustness.py +504 -0
  34. evalsuite/llmsys/safety.py +509 -0
  35. evalsuite/llmsys/uncertainty.py +229 -0
  36. evalsuite/plot.py +651 -0
  37. evalsuite/py.typed +0 -0
  38. evalsuite/regression/__init__.py +41 -0
  39. evalsuite/regression/metrics.py +629 -0
  40. evalsuite/reporting.py +241 -0
  41. evalsuite/stats/__init__.py +46 -0
  42. evalsuite/stats/_resolve.py +229 -0
  43. evalsuite/stats/compare.py +420 -0
  44. evalsuite/stats/effect.py +159 -0
  45. evalsuite/stats/hypothesis.py +593 -0
  46. evalsuite/stats/intervals.py +338 -0
  47. evalsuite/stats/paired.py +214 -0
  48. evalsuite/stats/results.py +129 -0
  49. evalsuite/text/__init__.py +154 -0
  50. evalsuite/text/_common.py +97 -0
  51. evalsuite/text/factuality.py +469 -0
  52. evalsuite/text/generation.py +1346 -0
  53. evalsuite/text/judge.py +556 -0
  54. evalsuite/text/qa.py +108 -0
  55. evalsuite/text/rag.py +235 -0
  56. evalsuite/text/reasoning.py +215 -0
  57. evalsuite/text/report.py +158 -0
  58. evalsuite/text/retrieval.py +238 -0
  59. evalsuite/text/semantic.py +499 -0
  60. evalsuite/text/spice.py +162 -0
  61. evalsuite/text/structured.py +793 -0
  62. evalsuite/version.py +3 -0
  63. evalsuite/vision/__init__.py +47 -0
  64. evalsuite/vision/detection.py +696 -0
  65. evalsuite/vision/segmentation.py +1028 -0
  66. evalsuite_python-0.6.0.dist-info/METADATA +509 -0
  67. evalsuite_python-0.6.0.dist-info/RECORD +72 -0
  68. evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
  69. evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
  70. evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
  71. evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
  72. evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
@@ -0,0 +1,923 @@
1
+ """Code generation and software engineering (v0.5.0).
2
+
3
+ EvalSuite never executes generated code: test outcomes, coverage, analyser findings and timings come from your
4
+ own sandboxed runner, and these functions aggregate them. Three measures are computed from source text directly,
5
+ with Python's standard library only: syntax validity (``compile``), CodeBLEU and cyclomatic complexity /
6
+ maintainability index (``ast``, the same counting rules as radon). Pass@k is the existing ``es.pass_at_k``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import io
13
+ import math
14
+ import tokenize
15
+ import warnings
16
+ from collections import Counter
17
+ from collections.abc import Sequence
18
+ from typing import Any, Callable, Optional
19
+
20
+ import numpy as np
21
+
22
+ from ..core.exceptions import InputValidationError
23
+ from ..core.registry import register
24
+ from ..core.result import MetricResult
25
+ from ._common import bools, floats, lists_of, rate, same_length, seq
26
+
27
+ __all__ = [
28
+ "PYTHON_KEYWORDS",
29
+ "code_complexity",
30
+ "codebleu",
31
+ "coverage_rate",
32
+ "execution_success_rate",
33
+ "patch_acceptance_rate",
34
+ "resolved_rate",
35
+ "runtime_efficiency",
36
+ "security_vulnerability_rate",
37
+ "static_analysis_violation_rate",
38
+ "syntax_validity_rate",
39
+ "unit_test_pass_rate",
40
+ ]
41
+
42
+ _C = "code"
43
+
44
+ # Errors CPython raises for source it cannot parse: syntax errors, null bytes (ValueError), and input nested
45
+ # too deeply for the parser (MemoryError "parser stack overflowed") or for the compiler (RecursionError).
46
+ _PARSE_ERRORS = (SyntaxError, ValueError, MemoryError, RecursionError)
47
+ _REF_HUMANEVAL = (
48
+ "Chen M, Tworek J, Jun H, et al. Evaluating large language models trained on code. arXiv:2107.03374. 2021."
49
+ )
50
+ _REF_CODEBLEU = (
51
+ "Ren S, Guo D, Lu S, et al. CodeBLEU: a method for automatic evaluation of code synthesis. arXiv:2009.10297. "
52
+ "2020."
53
+ )
54
+ _REF_SWEBENCH = (
55
+ "Jimenez CE, Yang J, Wettig A, et al. SWE-bench: can language models resolve real-world GitHub issues? ICLR. "
56
+ "2024."
57
+ )
58
+ _REF_MCCABE = "McCabe TJ. A complexity measure. IEEE Trans Softw Eng. 1976;SE-2(4):308-320."
59
+ _REF_MI = (
60
+ "Coleman D, Ash D, Lowther B, Oman P. Using metrics to evaluate software system maintainability. Computer. "
61
+ "1994;27(8):44-49."
62
+ )
63
+ _REF_PEARCE = (
64
+ "Pearce H, Ahmad B, Tan B, Dolan-Gavitt B, Karri R. Asleep at the keyboard? Assessing the security of GitHub "
65
+ "Copilot's code contributions. IEEE S&P. 2022:754-768."
66
+ )
67
+ _REF_EFFIBENCH = (
68
+ "Huang D, Zhang JM, Qing Y, Cui H. EffiBench: benchmarking the efficiency of automatically generated code. "
69
+ "NeurIPS Datasets and Benchmarks. 2024."
70
+ )
71
+ _REF_SWT = (
72
+ "Mündler N, Müller MN, He J, Vechev M. SWT-Bench: testing and validating real-world bug-fixes with code "
73
+ "agents. "
74
+ "NeurIPS. 2024."
75
+ )
76
+ _REF_MBPP = (
77
+ "Austin J, Odena A, Nye M, et al. Program synthesis with large language models. arXiv:2108.07732. 2021."
78
+ )
79
+ _REF_LINT = (
80
+ "Liu Y, Le-Cong T, Widyasari R, et al. Refining ChatGPT-generated code: characterizing and mitigating code "
81
+ "quality issues. ACM TOSEM. 2024;33(5):1-26."
82
+ )
83
+ _REF_COV = (
84
+ "Siddiq ML, Santos JCS, Tanvir RH, et al. Using large language models to generate JUnit tests: an empirical "
85
+ "study. EASE. 2024:313-322."
86
+ )
87
+
88
+
89
+ def _codes(x: Any, name: str) -> list[str]:
90
+ items = seq(x, name)
91
+ for i, c in enumerate(items):
92
+ if not isinstance(c, str):
93
+ raise InputValidationError(f"{name}[{i}] must be a string of source code.")
94
+ return items
95
+
96
+
97
+ # ---------------------------------------------------------------------------------------------- tests
98
+ @register(
99
+ category=_C,
100
+ task="code-generation",
101
+ name="Unit-test pass rate",
102
+ definition="Per problem, the share of its unit tests the generated solution passes, averaged over problems; "
103
+ "the strict rate (all tests pass) is reported alongside.",
104
+ formula="mean_p (passed_p / tests_p); strict = mean_p 1[all pass]",
105
+ range="[0, 1]",
106
+ input_requirements=("test_results",),
107
+ references=(_REF_HUMANEVAL, _REF_MBPP),
108
+ )
109
+ def unit_test_pass_rate(test_results: Any) -> MetricResult:
110
+ """``test_results``: per problem, one boolean per unit test."""
111
+ rows = lists_of(test_results, "test_results")
112
+ if any(not r for r in rows):
113
+ raise InputValidationError("Every problem needs at least one test result.")
114
+ frac = np.array([np.mean([bool(v) for v in r]) for r in rows])
115
+ strict = np.array([all(bool(v) for v in r) for r in rows])
116
+ return MetricResult(
117
+ "unit_test_pass_rate",
118
+ "Unit-test pass rate",
119
+ float(frac.mean()),
120
+ {"strict_pass_rate": float(strict.mean()), "n_problems": len(rows), "n_tests": sum(len(r) for r in rows)},
121
+ )
122
+
123
+
124
+ @register(
125
+ category=_C,
126
+ task="code-generation",
127
+ name="Compilation / syntax validity rate",
128
+ definition="Share of generated programs that parse (Python: compiled with ``compile`` in 'exec' mode, never "
129
+ "run). Other languages: pass a ``checker`` that returns True when the code compiles.",
130
+ formula="valid programs / programs",
131
+ range="[0, 1]",
132
+ input_requirements=("code",),
133
+ references=(_REF_HUMANEVAL,),
134
+ )
135
+ def syntax_validity_rate(
136
+ code: Any, *, language: str = "python", checker: Optional[Callable[[str], bool]] = None
137
+ ) -> MetricResult:
138
+ progs = _codes(code, "code")
139
+ if checker is None:
140
+ if language != "python":
141
+ raise InputValidationError("Only Python is checked built-in; pass checker= for other languages.")
142
+
143
+ def checker(src: str) -> bool:
144
+ try:
145
+ with warnings.catch_warnings():
146
+ warnings.simplefilter("ignore", SyntaxWarning)
147
+ compile(src, "<generated>", "exec", dont_inherit=True) # parses only; nothing runs
148
+ except _PARSE_ERRORS:
149
+ return False
150
+ return True
151
+
152
+ flags = np.array([bool(checker(p)) for p in progs])
153
+ return rate("syntax_validity_rate", "Syntax validity rate", flags, {"language": language})
154
+
155
+
156
+ @register(
157
+ category=_C,
158
+ task="code-quality",
159
+ name="Static-analysis violation rate",
160
+ definition="Linter / static-analyser findings in generated code: violations per 1,000 lines (the value) and "
161
+ "the share of programs with at least one finding, from counts your analyser (ruff, pylint, ESLint) reported.",
162
+ formula="1000 · Σ violations / Σ lines",
163
+ range="[0, ∞)",
164
+ input_requirements=("violations", "lines"),
165
+ references=(_REF_LINT,),
166
+ higher_is_better=False,
167
+ )
168
+ def static_analysis_violation_rate(violations: Any, lines: Any) -> MetricResult:
169
+ v = floats(violations, "violations", lo=0)
170
+ n = floats(lines, "lines", lo=0)
171
+ same_length(("violations", v), ("lines", n))
172
+ if n.sum() == 0:
173
+ raise InputValidationError("lines sums to zero.")
174
+ return MetricResult(
175
+ "static_analysis_violation_rate",
176
+ "Violations per KLOC",
177
+ float(1000 * v.sum() / n.sum()),
178
+ {"programs_with_violations": float((v > 0).mean()), "mean_per_program": float(v.mean())},
179
+ )
180
+
181
+
182
+ @register(
183
+ category=_C,
184
+ task="code-generation",
185
+ name="Code execution success / functional correctness",
186
+ definition="Share of generated programs that run to completion and give the expected result in your sandbox, "
187
+ "with the breakdown of failure kinds (runtime error, timeout, wrong answer, compile error).",
188
+ formula="#passed / #programs",
189
+ range="[0, 1]",
190
+ input_requirements=("outcomes",),
191
+ references=(_REF_HUMANEVAL, _REF_MBPP),
192
+ )
193
+ def execution_success_rate(outcomes: Any, *, success: Sequence[Any] = ("passed", "ok", True)) -> MetricResult:
194
+ """``outcomes``: one outcome per program, e.g. ``"passed"``, ``"wrong_answer"``, ``"runtime_error"``,
195
+ ``"timeout"``."""
196
+ items = seq(outcomes, "outcomes")
197
+ ok = set(success)
198
+ flags = np.array([o in ok for o in items])
199
+ fails = Counter(str(o) for o in items if o not in ok)
200
+ return rate(
201
+ "execution_success_rate",
202
+ "Execution success rate",
203
+ flags,
204
+ {"by_failure": {k: v / len(items) for k, v in sorted(fails.items())}},
205
+ )
206
+
207
+
208
+ @register(
209
+ category=_C,
210
+ task="testing",
211
+ name="Generated-code test coverage",
212
+ definition="Line (or branch) coverage achieved by generated tests, pooled over programs (covered / "
213
+ "coverable), "
214
+ "with the mean per-program coverage.",
215
+ formula="Σ covered / Σ coverable",
216
+ range="[0, 1]",
217
+ input_requirements=("covered", "total"),
218
+ references=(_REF_COV,),
219
+ )
220
+ def coverage_rate(covered: Any, total: Any) -> MetricResult:
221
+ c = floats(covered, "covered", lo=0)
222
+ t = floats(total, "total", lo=0)
223
+ same_length(("covered", c), ("total", t))
224
+ if np.any(c > t):
225
+ raise InputValidationError("covered cannot exceed total.")
226
+ if t.sum() == 0:
227
+ raise InputValidationError("total sums to zero.")
228
+ per = np.divide(c, t, out=np.ones_like(c), where=t > 0)
229
+ return MetricResult(
230
+ "coverage_rate", "Test coverage", float(c.sum()) / float(t.sum()), {"mean_per_program": float(per.mean())}
231
+ )
232
+
233
+
234
+ @register(
235
+ category=_C,
236
+ task="software-engineering",
237
+ name="Bug reproduction / patch acceptance rate",
238
+ definition="Share of attempts accepted: generated patches merged or approved by reviewers, or generated tests "
239
+ "that reproduce the reported bug (fail before the fix and pass after it, SWT-Bench).",
240
+ formula="accepted / attempts",
241
+ range="[0, 1]",
242
+ input_requirements=("accepted",),
243
+ references=(_REF_SWT, _REF_SWEBENCH),
244
+ )
245
+ def patch_acceptance_rate(
246
+ accepted: Any = None, *, fails_before: Any = None, passes_after: Any = None
247
+ ) -> MetricResult:
248
+ """Either ``accepted`` (one bool per patch), or ``fails_before`` and ``passes_after`` (one bool per generated
249
+ reproduction test) for the bug-reproduction rate."""
250
+ if accepted is not None:
251
+ return rate(
252
+ "patch_acceptance_rate", "Patch acceptance rate", bools(accepted, "accepted"), {"mode": "acceptance"}
253
+ )
254
+ if fails_before is None or passes_after is None:
255
+ raise InputValidationError("Pass accepted=, or both fails_before= and passes_after=.")
256
+ fb, pa = bools(fails_before, "fails_before"), bools(passes_after, "passes_after")
257
+ same_length(("fails_before", fb), ("passes_after", pa))
258
+ return rate("patch_acceptance_rate", "Bug reproduction rate", fb & pa, {"mode": "reproduction"})
259
+
260
+
261
+ @register(
262
+ category=_C,
263
+ task="software-engineering",
264
+ name="Repository task success / SWE-bench resolved rate",
265
+ definition="Share of task instances resolved: every FAIL_TO_PASS test now passes and every PASS_TO_PASS test "
266
+ "still passes after applying the generated patch (SWE-bench).",
267
+ formula="mean_i 1[all F2P pass ∧ all P2P pass]",
268
+ range="[0, 1]",
269
+ input_requirements=("fail_to_pass", "pass_to_pass"),
270
+ references=(_REF_SWEBENCH,),
271
+ )
272
+ def resolved_rate(fail_to_pass: Any, pass_to_pass: Any, *, applied: Any = None) -> MetricResult:
273
+ """Per instance, the post-patch results of its FAIL_TO_PASS and PASS_TO_PASS tests (lists of bools).
274
+ ``applied``: whether the patch applied at all (unapplied instances are unresolved)."""
275
+ f2p, p2p = lists_of(fail_to_pass, "fail_to_pass"), lists_of(pass_to_pass, "pass_to_pass")
276
+ same_length(("fail_to_pass", f2p), ("pass_to_pass", p2p))
277
+ if any(not f for f in f2p):
278
+ raise InputValidationError("Every instance needs at least one FAIL_TO_PASS test.")
279
+ ok = np.array([all(map(bool, f)) and all(map(bool, p)) for f, p in zip(f2p, p2p)])
280
+ extra: dict[str, Any] = {"f2p_only_rate": float(np.mean([all(map(bool, f)) for f in f2p]))}
281
+ if applied is not None:
282
+ a = bools(applied, "applied")
283
+ same_length(("fail_to_pass", f2p), ("applied", a))
284
+ ok &= a
285
+ extra["apply_rate"] = float(a.mean())
286
+ return rate("resolved_rate", "Resolved rate", ok, extra)
287
+
288
+
289
+ @register(
290
+ category=_C,
291
+ task="code-security",
292
+ name="Security vulnerability rate",
293
+ definition="Share of generated programs with at least one security finding at or above a severity level "
294
+ "(from Bandit, CodeQL, Semgrep), with findings per program by severity.",
295
+ formula="programs with a finding ≥ severity / programs",
296
+ range="[0, 1]",
297
+ input_requirements=("findings",),
298
+ references=(_REF_PEARCE,),
299
+ higher_is_better=False,
300
+ )
301
+ def security_vulnerability_rate(findings: Any, *, min_severity: str = "low") -> MetricResult:
302
+ """``findings``: per program, the list of finding severities (``"low"``, ``"medium"``, ``"high"``,
303
+ ``"critical"``)."""
304
+ order = {"low": 0, "medium": 1, "high": 2, "critical": 3}
305
+ if min_severity not in order:
306
+ raise InputValidationError(f"min_severity must be one of {list(order)}.")
307
+ rows = lists_of(findings, "findings")
308
+ counts: Counter[str] = Counter()
309
+ flags = []
310
+ for i, r in enumerate(rows):
311
+ sev = [str(s).lower() for s in r]
312
+ bad = [s for s in sev if s not in order]
313
+ if bad:
314
+ raise InputValidationError(f"findings[{i}] has unknown severities {bad}.")
315
+ counts.update(sev)
316
+ flags.append(any(order[s] >= order[min_severity] for s in sev))
317
+ n = len(rows)
318
+ return rate(
319
+ "security_vulnerability_rate",
320
+ "Security vulnerability rate",
321
+ np.array(flags),
322
+ {"min_severity": min_severity, "findings_per_program": {k: counts.get(k, 0) / n for k in order}},
323
+ )
324
+
325
+
326
+ @register(
327
+ category=_C,
328
+ task="code-efficiency",
329
+ name="Runtime efficiency / memory consumption",
330
+ definition="Execution time and peak memory of generated solutions relative to reference (canonical) "
331
+ "solutions on the same tests: normalised execution time NET and normalised memory usage NMU (EffiBench); "
332
+ "values above 1 mean the generated code is slower or uses more memory.",
333
+ formula="NET = mean_p t_gen / t_ref; NMU = mean_p m_gen / m_ref",
334
+ range="(0, ∞) (1 = as efficient as the reference)",
335
+ input_requirements=("times", "reference_times"),
336
+ references=(_REF_EFFIBENCH,),
337
+ higher_is_better=False,
338
+ )
339
+ def runtime_efficiency(
340
+ times: Any, reference_times: Any, *, memory: Any = None, reference_memory: Any = None
341
+ ) -> MetricResult:
342
+ t = floats(times, "times", lo=0)
343
+ r = floats(reference_times, "reference_times", lo=0)
344
+ same_length(("times", t), ("reference_times", r))
345
+ if np.any(r <= 0):
346
+ raise InputValidationError("reference_times must be positive.")
347
+ ratio = t / r
348
+ extra: dict[str, Any] = {
349
+ "median_time_ratio": float(np.median(ratio)),
350
+ "share_slower_than_2x": float((ratio > 2).mean()),
351
+ }
352
+ if memory is not None or reference_memory is not None:
353
+ m = floats(memory, "memory", lo=0)
354
+ rm = floats(reference_memory, "reference_memory", lo=0)
355
+ same_length(("times", t), ("memory", m), ("reference_memory", rm))
356
+ if np.any(rm <= 0):
357
+ raise InputValidationError("reference_memory must be positive.")
358
+ extra["nmu"] = float(np.mean(m / rm))
359
+ return MetricResult("runtime_efficiency", "Normalised execution time (NET)", float(ratio.mean()), extra)
360
+
361
+
362
+ # ---------------------------------------------------------------------------------------------- complexity
363
+ class _Complexity(ast.NodeVisitor):
364
+ """Cyclomatic complexity with radon's counting rules (``radon.visitors.ComplexityVisitor``)."""
365
+
366
+ def __init__(self, off: bool = True) -> None:
367
+ self.off = off
368
+ self.complexity = 1 if off else 0
369
+ self.functions: list[tuple[str, int]] = []
370
+ self.classes: list[int] = []
371
+
372
+ @classmethod
373
+ def run(cls, node: ast.AST, off: bool = True) -> _Complexity:
374
+ v = cls(off)
375
+ v.visit(node)
376
+ return v
377
+
378
+ def generic_visit(self, node: ast.AST) -> None:
379
+ name = type(node).__name__
380
+ if name in ("Try", "TryStar"):
381
+ self.complexity += len(node.handlers) + bool(node.orelse) # type: ignore[attr-defined]
382
+ elif name == "BoolOp":
383
+ self.complexity += len(node.values) - 1 # type: ignore[attr-defined]
384
+ elif name in ("If", "IfExp"):
385
+ self.complexity += 1
386
+ elif name == "Match":
387
+ cases = node.cases # type: ignore[attr-defined]
388
+ underscore = any(getattr(c.pattern, "pattern", False) is None for c in cases)
389
+ self.complexity += max(0, len(cases) - underscore)
390
+ elif name in ("For", "While", "AsyncFor"):
391
+ self.complexity += bool(node.orelse) + 1 # type: ignore[attr-defined]
392
+ elif name == "comprehension":
393
+ self.complexity += len(node.ifs) + 1 # type: ignore[attr-defined]
394
+ super().generic_visit(node)
395
+
396
+ def visit_Assert(self, node: ast.Assert) -> None:
397
+ self.complexity += 1
398
+
399
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
400
+ self._function(node)
401
+
402
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
403
+ self._function(node)
404
+
405
+ def _function(self, node: Any) -> None:
406
+ body = 1
407
+ for child in node.body:
408
+ body += _Complexity.run(child, off=False).complexity
409
+ self.functions.append((node.name, body))
410
+
411
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
412
+ body = 1
413
+ for child in node.body:
414
+ v = _Complexity.run(child, off=False)
415
+ body += v.complexity + sum(c for _, c in v.functions) - len(v.functions) + len(v.functions)
416
+ self.functions_methods = getattr(self, "functions_methods", [])
417
+ self.functions_methods += [(f"{node.name}.{n}", c) for n, c in v.functions]
418
+ self.classes.append(body)
419
+
420
+ @property
421
+ def total(self) -> int:
422
+ f = sum(c for _, c in self.functions) - len(self.functions)
423
+ k = sum(self.classes) - len(self.classes)
424
+ return self.complexity + f + k + (not self.off)
425
+
426
+ @property
427
+ def blocks(self) -> list[tuple[str, int]]:
428
+ return [*self.functions, *getattr(self, "functions_methods", [])]
429
+
430
+
431
+ def _halstead_volume(tree: ast.AST) -> float:
432
+ """Halstead volume N·log2(η) with radon's operator / operand rules (functions analysed in their own
433
+ context)."""
434
+ ops_seen: set[Any] = set()
435
+ opnds_seen: set[Any] = set()
436
+ counts = [0, 0]
437
+
438
+ def operand_key(node: ast.AST, ctx: Any) -> Any:
439
+ if isinstance(node, ast.Name):
440
+ return (ctx, node.id)
441
+ if isinstance(node, ast.Attribute):
442
+ return (ctx, node.attr)
443
+ if isinstance(node, ast.Constant):
444
+ return (ctx, node.value)
445
+ return (ctx, id(node)) # radon keys any other operand node by identity
446
+
447
+ def walk(node: ast.AST, ctx: Any) -> None:
448
+ for child in ast.iter_child_nodes(node):
449
+ visit(child, ctx)
450
+
451
+ def visit(node: ast.AST, ctx: Any) -> None:
452
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
453
+ for child in node.body:
454
+ visit(child, node.name)
455
+ return
456
+ rec: Optional[tuple[int, int, list[str], list[ast.AST]]] = None
457
+ if isinstance(node, ast.BinOp):
458
+ rec = (1, 2, [type(node.op).__name__], [node.left, node.right])
459
+ elif isinstance(node, ast.UnaryOp):
460
+ rec = (1, 1, [type(node.op).__name__], [node.operand])
461
+ elif isinstance(node, ast.BoolOp):
462
+ rec = (1, len(node.values), [type(node.op).__name__], list(node.values))
463
+ elif isinstance(node, ast.AugAssign):
464
+ rec = (1, 2, [type(node.op).__name__], [node.target, node.value])
465
+ elif isinstance(node, ast.Compare):
466
+ rec = (
467
+ len(node.ops),
468
+ len(node.comparators) + 1,
469
+ [type(o).__name__ for o in node.ops],
470
+ [*node.comparators, node.left],
471
+ )
472
+ if rec is not None:
473
+ counts[0] += rec[0]
474
+ counts[1] += rec[1]
475
+ ops_seen.update(rec[2])
476
+ opnds_seen.update(operand_key(o, ctx) for o in rec[3])
477
+ walk(node, ctx)
478
+
479
+ for child in ast.iter_child_nodes(tree):
480
+ visit(child, None)
481
+ n, eta = counts[0] + counts[1], len(ops_seen) + len(opnds_seen)
482
+ return n * math.log2(eta) if eta > 0 else 0.0
483
+
484
+
485
+ def _line_tokens(line: str, lines: Any) -> tuple[list[Any], list[str]]:
486
+ """Shortest tokenisable run of stripped lines starting at ``line`` (multi-line strings and statements)."""
487
+ buffer, used = line, [line]
488
+ while True:
489
+ try:
490
+ tokens = list(tokenize.generate_tokens(io.StringIO(buffer).readline))
491
+ except tokenize.TokenError:
492
+ pass
493
+ else:
494
+ if not any(t[0] == tokenize.ERRORTOKEN for t in tokens):
495
+ return tokens, used
496
+ nxt = next(lines)
497
+ buffer += "\n" + nxt
498
+ used.append(nxt)
499
+
500
+
501
+ def _logical_lines(tokens: list[Any]) -> int:
502
+ """Logical lines in one physical run: ``if x: return y`` counts 2 (radon's rule)."""
503
+ groups: list[list[Any]] = [[]]
504
+ for t in tokens:
505
+ if t[0] == tokenize.OP and t[1] == ";":
506
+ groups.append([])
507
+ else:
508
+ groups[-1].append(t)
509
+ total = 0
510
+ for g in groups:
511
+ kept = [t for t in g if t[0] not in (tokenize.COMMENT, tokenize.NL, tokenize.NEWLINE)]
512
+ colon = [i for i, t in enumerate(kept) if t[0] == tokenize.OP and t[1] == ":"]
513
+ if colon:
514
+ total += 2 - (colon[-1] == len(kept) - 2)
515
+ elif [t for t in kept if t[0] not in (tokenize.NL, tokenize.NEWLINE, tokenize.ENDMARKER)]:
516
+ total += 1
517
+ return total
518
+
519
+
520
+ def _raw(src: str) -> tuple[int, int, int]:
521
+ """(logical lines, source lines, comment + multi-line-string lines), counted line by line as radon's
522
+ ``raw.analyze`` does."""
523
+ lloc = comments = multi = sloc = 0
524
+ lines = (ln.strip() for ln in src.splitlines())
525
+ for line in lines:
526
+ try:
527
+ tokens, used = _line_tokens(line, lines)
528
+ except StopIteration: # pragma: no cover - the source already parsed
529
+ break
530
+ comments += sum(1 for t in tokens if t[0] == tokenize.COMMENT)
531
+ rest = [t[0] for t in tokens[1:]]
532
+ only = all(k in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE) for k in rest)
533
+ if tokens[0][0] == tokenize.COMMENT and only:
534
+ pass
535
+ elif tokens[0][0] == tokenize.STRING and only:
536
+ if tokens[0][3][0] != tokens[0][2][0]:
537
+ multi += sum(1 for ln in used if ln)
538
+ else:
539
+ sloc += sum(1 for ln in used if ln)
540
+ lloc += _logical_lines(tokens)
541
+ return lloc, sloc, comments + multi
542
+
543
+
544
+ @register(
545
+ category=_C,
546
+ task="code-quality",
547
+ name="Cyclomatic complexity / maintainability index",
548
+ definition="McCabe cyclomatic complexity of each function (decision points + 1, counted as radon does) and "
549
+ "the maintainability index MI = max(0, 100·(171 − 5.2 ln V − 0.23 G − 16.2 ln L + 50 sin √(2.46·rad(C))) / "
550
+ "171) from Halstead volume V, total complexity G, logical lines L and comment percentage C. Python source.",
551
+ formula="CC = 1 + decisions; MI as above",
552
+ range="CC ≥ 1; MI in [0, 100]",
553
+ input_requirements=("code",),
554
+ references=(_REF_MCCABE, _REF_MI),
555
+ higher_is_better=False,
556
+ )
557
+ def code_complexity(code: Any) -> MetricResult:
558
+ """Mean cyclomatic complexity per function over all programs (the value), with the maximum, the mean
559
+ maintainability index and per-program results. Programs that do not parse are rejected."""
560
+ progs = _codes(code, "code")
561
+ funcs: list[int] = []
562
+ mi: list[float] = []
563
+ per = []
564
+ for i, src in enumerate(progs):
565
+ try:
566
+ with warnings.catch_warnings():
567
+ warnings.simplefilter("ignore", SyntaxWarning)
568
+ tree = ast.parse(src)
569
+ visitor = _Complexity.run(tree)
570
+ v = _halstead_volume(tree)
571
+ except SyntaxError as exc:
572
+ raise InputValidationError(f"code[{i}] is not valid Python: {exc.msg} (line {exc.lineno}).") from exc
573
+ except _PARSE_ERRORS as exc:
574
+ raise InputValidationError(
575
+ f"code[{i}] is too deeply nested to analyse ({type(exc).__name__})."
576
+ ) from exc
577
+ blocks = visitor.blocks
578
+ funcs += [c for _, c in blocks]
579
+ g = visitor.total
580
+ lloc, sloc, comments = _raw(src)
581
+ c_pct = comments / sloc * 100 if sloc else 0.0
582
+ if v <= 0 or lloc <= 0:
583
+ m = 100.0
584
+ else:
585
+ nn = (
586
+ 171
587
+ - 5.2 * math.log(v)
588
+ - 0.23 * g
589
+ - 16.2 * math.log(lloc)
590
+ + 50 * math.sin(math.sqrt(2.46 * math.radians(c_pct)))
591
+ )
592
+ m = min(max(0.0, nn * 100 / 171.0), 100.0)
593
+ mi.append(m)
594
+ per.append({"functions": dict(blocks), "total_complexity": g, "maintainability_index": m})
595
+ value = float(np.mean(funcs)) if funcs else 1.0
596
+ return MetricResult(
597
+ "code_complexity",
598
+ "Mean cyclomatic complexity",
599
+ value,
600
+ {
601
+ "max_complexity": max(funcs) if funcs else 1,
602
+ "maintainability_index": float(np.mean(mi)),
603
+ "per_program": per,
604
+ },
605
+ )
606
+
607
+
608
+ # ---------------------------------------------------------------------------------------------- CodeBLEU
609
+ PYTHON_KEYWORDS = [
610
+ "False",
611
+ "None",
612
+ "True",
613
+ "and",
614
+ "as",
615
+ "assert",
616
+ "async",
617
+ "await",
618
+ "break",
619
+ "class",
620
+ "continue",
621
+ "def",
622
+ "del",
623
+ "elif",
624
+ "else",
625
+ "except",
626
+ "finally",
627
+ "for",
628
+ "from",
629
+ "global",
630
+ "if",
631
+ "import",
632
+ "in",
633
+ "is",
634
+ "lambda",
635
+ "nonlocal",
636
+ "not",
637
+ "or",
638
+ "pass",
639
+ "raise",
640
+ "return",
641
+ "try",
642
+ "while",
643
+ "with",
644
+ "yield",
645
+ "match",
646
+ "case",
647
+ "type",
648
+ ]
649
+
650
+
651
+ def _ngrams(tokens: Sequence[str], n: int) -> Counter[tuple[str, ...]]:
652
+ return Counter(tuple(tokens[i : i + n]) for i in range(len(tokens) - n + 1))
653
+
654
+
655
+ def _closest(ref_lens: Sequence[int], hyp_len: int) -> int:
656
+ return min(ref_lens, key=lambda r: (abs(r - hyp_len), r))
657
+
658
+
659
+ def _bp(r: int, c: int) -> float:
660
+ if c > r:
661
+ return 1.0
662
+ if c == 0:
663
+ return 0.0
664
+ return math.exp(1 - r / c)
665
+
666
+
667
+ def _corpus_bleu(refs: list[list[list[str]]], hyps: list[list[str]], weighted: Optional[set[str]]) -> float:
668
+ """BLEU-4 as in the CodeBLEU reference implementation (NLTK conventions, smoothing method 1, ε = 0.1).
669
+ ``weighted`` (the keyword set) switches to the keyword-weighted n-gram match, whose unigram term is a
670
+ recall over reference tokens weighted 1 for keywords and 0.2 otherwise."""
671
+ num: dict[int, float] = {n: 0.0 for n in range(1, 5)}
672
+ den: dict[int, float] = {n: 0.0 for n in range(1, 5)}
673
+ hyp_len = ref_len = 0
674
+ for rs, h in zip(refs, hyps):
675
+ for n in range(1, 5):
676
+ hc = _ngrams(h, n)
677
+ if weighted is None:
678
+ maxc: Counter[tuple[str, ...]] = Counter()
679
+ for r in rs:
680
+ maxc |= _ngrams(r, n)
681
+ num[n] += sum(min(c, maxc[g]) for g, c in hc.items())
682
+ den[n] += max(1, sum(hc.values()))
683
+ else:
684
+ for r in rs:
685
+ rc = _ngrams(r, n)
686
+ clipped = {g: min(c, hc[g]) for g, c in rc.items()}
687
+ if n == 1:
688
+ w = {t: 1.0 if t in weighted else 0.2 for t in r}
689
+ num[n] += sum(c * w.get(g[0], 1) for g, c in clipped.items())
690
+ den[n] += max(1, sum(c * w.get(g[0], 1) for g, c in rc.items()))
691
+ else:
692
+ num[n] += sum(clipped.values())
693
+ den[n] += max(1, sum(rc.values()))
694
+ hyp_len += len(h)
695
+ ref_len += _closest([len(r) for r in rs], len(h))
696
+ if num[1] == 0:
697
+ return 0.0
698
+ bp = _bp(ref_len, hyp_len)
699
+ logs = [math.log((num[n] if num[n] else 0.1) / den[n]) for n in range(1, 5)]
700
+ return bp * math.exp(math.fsum(0.25 * x for x in logs))
701
+
702
+
703
+ def _strip(src: str) -> str:
704
+ """Remove comments and docstrings (as the CodeBLEU reference does before parsing)."""
705
+ out, prev_type, last_line, last_col = [], tokenize.INDENT, -1, 0
706
+ try:
707
+ for tok in tokenize.generate_tokens(io.StringIO(src).readline):
708
+ ttype, text, (sl, sc), (el, ec), _ = tok
709
+ if sl > last_line:
710
+ last_col = 0
711
+ if sc > last_col:
712
+ out.append(" " * (sc - last_col))
713
+ if ttype == tokenize.COMMENT or (
714
+ ttype == tokenize.STRING and prev_type in (tokenize.INDENT, tokenize.NEWLINE)
715
+ ):
716
+ pass
717
+ else:
718
+ out.append(text)
719
+ prev_type = ttype
720
+ last_col, last_line = ec, el
721
+ except (tokenize.TokenError, IndentationError):
722
+ return src
723
+ return "\n".join(ln for ln in "".join(out).split("\n") if ln.strip())
724
+
725
+
726
+ def _parse(src: str) -> Optional[ast.AST]:
727
+ try:
728
+ with warnings.catch_warnings():
729
+ warnings.simplefilter("ignore", SyntaxWarning)
730
+ return ast.parse(_strip(src))
731
+ except _PARSE_ERRORS:
732
+ return None
733
+
734
+
735
+ _SKIP_NODES = (ast.expr_context, ast.operator, ast.unaryop, ast.boolop, ast.cmpop)
736
+
737
+
738
+ def _kids(node: ast.AST) -> list[ast.AST]:
739
+ return [c for c in ast.iter_child_nodes(node) if not isinstance(c, _SKIP_NODES)]
740
+
741
+
742
+ def _subtrees(tree: ast.AST, table: dict[tuple[Any, ...], int]) -> list[int]:
743
+ """Every subtree with children (and the root), as ids that are equal exactly when the subtrees are
744
+ structurally equal. Built bottom-up without recursion: ``table`` interns (node type, child ids), so the
745
+ cost is linear in the tree size (comparing serialised subtrees would be quadratic)."""
746
+ ids: dict[int, int] = {}
747
+ out: list[int] = []
748
+ stack: list[tuple[ast.AST, bool]] = [(tree, False)]
749
+ while stack:
750
+ node, ready = stack.pop()
751
+ kids = _kids(node)
752
+ if not ready:
753
+ stack.append((node, True))
754
+ stack.extend((k, False) for k in kids)
755
+ continue
756
+ tag = type(node).__name__
757
+ if isinstance(node, (ast.BinOp, ast.UnaryOp, ast.BoolOp, ast.AugAssign)):
758
+ tag += ":" + type(node.op).__name__
759
+ sid = table.setdefault((tag, tuple(ids[id(k)] for k in kids)), len(table))
760
+ ids[id(node)] = sid
761
+ if kids or node is tree:
762
+ out.append(sid)
763
+ return out
764
+
765
+
766
+ def _dataflow(tree: ast.AST) -> list[tuple[str, str, tuple[str, ...]]]:
767
+ """Def-use edges in source order: ``(var, 'computedFrom', sources)`` for assignments and
768
+ ``(var, 'comesFrom', (var,))`` for uses of an earlier definition, as in CodeBLEU's data-flow graph."""
769
+ edges: list[tuple[str, str, tuple[str, ...]]] = []
770
+ defined: set[str] = set()
771
+
772
+ def names(node: Optional[ast.AST]) -> list[str]:
773
+ if node is None:
774
+ return []
775
+ return [n.id for n in ast.walk(node) if isinstance(n, ast.Name)]
776
+
777
+ def targets(node: ast.AST) -> list[str]:
778
+ return [n.id for n in ast.walk(node) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)]
779
+
780
+ def uses(node: Optional[ast.AST]) -> None:
781
+ if node is None:
782
+ return
783
+ for n in ast.walk(node):
784
+ if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load) and n.id in defined:
785
+ edges.append((n.id, "comesFrom", (n.id,)))
786
+
787
+ def stmt(s: ast.AST) -> None:
788
+ if isinstance(s, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
789
+ value = s.value
790
+ uses(value)
791
+ src = tuple(sorted(set(names(value))))
792
+ tg = s.targets if isinstance(s, ast.Assign) else [s.target]
793
+ for t in tg:
794
+ for v in targets(t):
795
+ edges.append((v, "computedFrom", src + ((v,) if isinstance(s, ast.AugAssign) else ())))
796
+ defined.add(v)
797
+ elif isinstance(s, (ast.For, ast.AsyncFor)):
798
+ uses(s.iter)
799
+ for v in targets(s.target):
800
+ edges.append((v, "computedFrom", tuple(sorted(set(names(s.iter))))))
801
+ defined.add(v)
802
+ for b in s.body + s.orelse:
803
+ stmt(b)
804
+ elif isinstance(s, (ast.FunctionDef, ast.AsyncFunctionDef)):
805
+ for a in s.args.posonlyargs + s.args.args + s.args.kwonlyargs:
806
+ defined.add(a.arg)
807
+ for b in s.body:
808
+ stmt(b)
809
+ else:
810
+ body_fields = [
811
+ f for f in ("body", "orelse", "finalbody", "handlers") if isinstance(getattr(s, f, None), list)
812
+ ]
813
+ for f, v in ast.iter_fields(s):
814
+ if f not in body_fields and isinstance(v, ast.AST):
815
+ uses(v)
816
+ elif f not in body_fields and isinstance(v, list):
817
+ for x in v:
818
+ if isinstance(x, ast.AST):
819
+ uses(x)
820
+ for f in body_fields:
821
+ for b in getattr(s, f):
822
+ if isinstance(b, ast.ExceptHandler):
823
+ if b.name:
824
+ defined.add(b.name)
825
+ for x in b.body:
826
+ stmt(x)
827
+ elif isinstance(b, ast.stmt):
828
+ stmt(b)
829
+
830
+ for s in tree.body: # type: ignore[attr-defined]
831
+ stmt(s)
832
+ return edges
833
+
834
+
835
+ def _normalize_flow(flow: list[tuple[str, str, tuple[str, ...]]]) -> list[tuple[str, str, tuple[str, ...]]]:
836
+ names: dict[str, str] = {}
837
+ out = []
838
+ for var, rel, src in flow:
839
+ for s in src:
840
+ names.setdefault(s, f"var_{len(names)}")
841
+ names.setdefault(var, f"var_{len(names)}")
842
+ out.append((names[var], rel, tuple(names[s] for s in src)))
843
+ return out
844
+
845
+
846
+ @register(
847
+ category=_C,
848
+ task="code-generation",
849
+ name="CodeBLEU",
850
+ definition="Weighted sum of BLEU, keyword-weighted n-gram match, AST subtree match and data-flow match "
851
+ "between generated and reference code (Ren et al.). The two n-gram terms follow the reference "
852
+ "implementation exactly; the syntax and data-flow terms use Python's own ``ast`` instead of tree-sitter, so "
853
+ "they are defined for Python source.",
854
+ formula="CodeBLEU = α·BLEU + β·BLEU_weight + γ·Match_ast + δ·Match_df",
855
+ range="[0, 1]",
856
+ input_requirements=("references", "predictions"),
857
+ references=(_REF_CODEBLEU,),
858
+ )
859
+ def codebleu(
860
+ references: Any,
861
+ predictions: Any,
862
+ *,
863
+ weights: tuple[float, float, float, float] = (0.25, 0.25, 0.25, 0.25),
864
+ keywords: Optional[Sequence[str]] = None,
865
+ tokenizer: Optional[Callable[[str], list[str]]] = None,
866
+ ) -> MetricResult:
867
+ """``references``: one reference program (or a list of references) per prediction. Components are in
868
+ ``params``. When no reference has any data flow the data-flow term counts as 1, as in the reference
869
+ implementation."""
870
+ preds = _codes(predictions, "predictions")
871
+ refs_in = seq(references, "references")
872
+ same_length(("references", refs_in), ("predictions", preds))
873
+ refs = []
874
+ for i, r in enumerate(refs_in):
875
+ rs = [r] if isinstance(r, str) else list(r)
876
+ if not rs or not all(isinstance(x, str) for x in rs):
877
+ raise InputValidationError(f"references[{i}] must be a string or a list of strings.")
878
+ refs.append([x.strip() for x in rs])
879
+ preds = [p.strip() for p in preds]
880
+ if len(weights) != 4 or any(w < 0 for w in weights) or not math.isclose(sum(weights), 1.0):
881
+ raise InputValidationError("weights must be four non-negative numbers summing to 1.")
882
+ tok = tokenizer or str.split
883
+ kw = set(PYTHON_KEYWORDS if keywords is None else keywords)
884
+ t_refs = [[tok(x) for x in rs] for rs in refs]
885
+ t_hyps = [tok(p) for p in preds]
886
+ ngram = _corpus_bleu(t_refs, t_hyps, None)
887
+ weighted = _corpus_bleu(t_refs, t_hyps, kw)
888
+ match = total = df_match = df_total = 0
889
+ table: dict[tuple[Any, ...], int] = {}
890
+ for rs, p in zip(refs, preds):
891
+ cand = _parse(p)
892
+ cand_sub = set(_subtrees(cand, table)) if cand is not None else set()
893
+ cand_flow = _normalize_flow(_dataflow(cand)) if cand is not None else []
894
+ for r in rs:
895
+ ref = _parse(r)
896
+ if ref is None:
897
+ continue
898
+ ref_sub = _subtrees(ref, table)
899
+ match += sum(s in cand_sub for s in ref_sub)
900
+ total += len(ref_sub)
901
+ ref_flow = _normalize_flow(_dataflow(ref))
902
+ pool = list(cand_flow)
903
+ df_total += len(ref_flow)
904
+ for e in ref_flow:
905
+ if e in pool:
906
+ df_match += 1
907
+ pool.remove(e)
908
+ syntax = match / total if total else 0.0
909
+ dataflow = df_match / df_total if df_total else 0.0
910
+ a, b, g, d = weights
911
+ value = a * ngram + b * weighted + g * syntax + d * (dataflow or 1.0)
912
+ return MetricResult(
913
+ "codebleu",
914
+ "CodeBLEU",
915
+ value,
916
+ {
917
+ "ngram_match": ngram,
918
+ "weighted_ngram_match": weighted,
919
+ "syntax_match": syntax,
920
+ "dataflow_match": dataflow,
921
+ "weights": tuple(weights),
922
+ },
923
+ )