gtfeng 0.1.0__py3-none-any.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.
Potentially problematic release.
This version of gtfeng might be problematic. Click here for more details.
- gtfeng/__init__.py +27 -0
- gtfeng/baseline.py +95 -0
- gtfeng/core.py +169 -0
- gtfeng/references.py +75 -0
- gtfeng/report.py +83 -0
- gtfeng/rules.py +91 -0
- gtfeng/values.py +45 -0
- gtfeng-0.1.0.dist-info/METADATA +155 -0
- gtfeng-0.1.0.dist-info/RECORD +13 -0
- gtfeng-0.1.0.dist-info/WHEEL +5 -0
- gtfeng-0.1.0.dist-info/licenses/LICENSE +202 -0
- gtfeng-0.1.0.dist-info/licenses/NOTICE +7 -0
- gtfeng-0.1.0.dist-info/top_level.txt +1 -0
gtfeng/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Jiayu Feng
|
|
3
|
+
"""GT-FENG: General Theory of Factual Evaluation and Normative Grounding.
|
|
4
|
+
|
|
5
|
+
import gtfeng
|
|
6
|
+
result = gtfeng.evaluate(answers, references, groups=["model"])
|
|
7
|
+
result.report(families={"cross_jurisdiction": ["J", "JD"]})
|
|
8
|
+
result.feng_value(["J", "JD"]) # Rule 7 and the FENG value
|
|
9
|
+
print(gtfeng.cite()) # BibTeX for the GT-FENG paper
|
|
10
|
+
|
|
11
|
+
Modules, in the order of the paper:
|
|
12
|
+
values how an answer and a gold value are compared
|
|
13
|
+
references the reference set R of documented rules
|
|
14
|
+
rules Rules 1-6, one function each
|
|
15
|
+
core evaluate(): runs the rules on every stable item
|
|
16
|
+
baseline Rule 7 (local perturbation baseline) and the FENG value
|
|
17
|
+
report the standard report and citation helpers
|
|
18
|
+
"""
|
|
19
|
+
from .baseline import DEFAULT_INCREMENTS
|
|
20
|
+
from .core import DEFAULT_COORDINATES, Result, evaluate
|
|
21
|
+
from .report import VERSION, cite
|
|
22
|
+
from .rules import AMBIGUOUS, CORRECT, UNMATCHED
|
|
23
|
+
from .values import normalize
|
|
24
|
+
|
|
25
|
+
__version__ = VERSION
|
|
26
|
+
__all__ = ["evaluate", "cite", "Result", "normalize", "DEFAULT_COORDINATES", "CORRECT", "UNMATCHED", "AMBIGUOUS",
|
|
27
|
+
"DEFAULT_INCREMENTS", "__version__"]
|
gtfeng/baseline.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Jiayu Feng
|
|
3
|
+
"""Rule 7 (local perturbation baseline) and the FENG value.
|
|
4
|
+
|
|
5
|
+
For a family F (a set of shifts, e.g. {"J", "JD"} for another jurisdiction):
|
|
6
|
+
|
|
7
|
+
W wrong items at a reference level
|
|
8
|
+
O wrong items grounded in F: they have matches, and every shift in M belongs to F
|
|
9
|
+
N the number of grounded items that nearby values produce. Each wrong answer A is replaced by A + i for every
|
|
10
|
+
increment i in I; increments that reach the correct value are dropped for that item. N is the sum over wrong
|
|
11
|
+
items of the share of nearby values that are grounded in F.
|
|
12
|
+
E = O - N, the excess over the baseline
|
|
13
|
+
p the share of random perturbations (one increment per item, drawn independently) whose grounded count
|
|
14
|
+
reaches O
|
|
15
|
+
|
|
16
|
+
FENG value = (O - N) / (W - N)
|
|
17
|
+
|
|
18
|
+
The FENG value is 0 when wrong answers are grounded in F as often as nearby values are, 1 when every wrong answer
|
|
19
|
+
is grounded in F, and negative when they are grounded less often than nearby values. It has the chance-corrected
|
|
20
|
+
form of Cohen's kappa; the match event and the local baseline come from GT-FENG.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from typing import Iterable, Sequence
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
import pandas as pd
|
|
28
|
+
|
|
29
|
+
from .rules import CORRECT, find_matches
|
|
30
|
+
|
|
31
|
+
# Increments must leave out any known definition shift. The Medicaid instance leaves out 5 (the 5% disregard).
|
|
32
|
+
DEFAULT_INCREMENTS = (-4, -3, -2, -1, 1, 2, 3, 4)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _grounded(shifts: Iterable[str], family: frozenset) -> bool:
|
|
36
|
+
shifts = set(shifts)
|
|
37
|
+
return bool(shifts) and shifts <= family
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def feng_values(result, family: Iterable[str], *, increments: Sequence[float] = DEFAULT_INCREMENTS,
|
|
41
|
+
permutations: int = 10000, seed: int = 0) -> pd.DataFrame:
|
|
42
|
+
"""Rule 7 and the FENG value, one row per group and reference level. Numeric answers only."""
|
|
43
|
+
context = result._context
|
|
44
|
+
if context is None:
|
|
45
|
+
raise ValueError("this Result was not produced by gtfeng.evaluate")
|
|
46
|
+
family = frozenset(family)
|
|
47
|
+
increments = [i for i in increments if i != 0]
|
|
48
|
+
if not increments:
|
|
49
|
+
raise ValueError("increments must contain at least one nonzero value")
|
|
50
|
+
references = context["references"]
|
|
51
|
+
coordinates = context["coordinates"]
|
|
52
|
+
item_columns = list(result.groups) + coordinates
|
|
53
|
+
rng = np.random.default_rng(seed)
|
|
54
|
+
|
|
55
|
+
# Nearby values of each wrong item, with their matches (computed once, then filtered by level).
|
|
56
|
+
nearby = {}
|
|
57
|
+
wrong_rows = result.items[result.items.label != CORRECT]
|
|
58
|
+
for row in wrong_rows.drop_duplicates(item_columns).to_dict("records"):
|
|
59
|
+
answer = row["answer"]
|
|
60
|
+
if isinstance(answer, bool) or not isinstance(answer, (int, float, np.integer, np.floating)):
|
|
61
|
+
raise ValueError(f"Rule 7 needs numeric answers; got {answer!r} for {row}")
|
|
62
|
+
item = {c: row[c] for c in item_columns}
|
|
63
|
+
asked_index = tuple(row[c] for c in coordinates)
|
|
64
|
+
gold = references.gold(asked_index)
|
|
65
|
+
values = []
|
|
66
|
+
for i in increments:
|
|
67
|
+
key = context["compare"](float(answer) + i)
|
|
68
|
+
if key == gold: # an increment that reaches the correct value is dropped for this item
|
|
69
|
+
continue
|
|
70
|
+
values.append(find_matches(key, item, asked_index, references, coordinates,
|
|
71
|
+
context["initials"], context["level_by_shift"]))
|
|
72
|
+
nearby[tuple(item.values())] = values
|
|
73
|
+
|
|
74
|
+
rows = []
|
|
75
|
+
keys = list(result.groups) + ["level"]
|
|
76
|
+
for key_values, group in result.items.groupby(keys, sort=True):
|
|
77
|
+
key_values = key_values if isinstance(key_values, tuple) else (key_values,)
|
|
78
|
+
level = key_values[-1]
|
|
79
|
+
wrong = group[group.label != CORRECT]
|
|
80
|
+
observed = int(sum(_grounded(s, family) for s in wrong.shifts))
|
|
81
|
+
hits = []
|
|
82
|
+
for row in wrong[item_columns].itertuples(index=False, name=None):
|
|
83
|
+
hits.append(np.array([_grounded({m.shift for m in ms if m.level <= level}, family)
|
|
84
|
+
for ms in nearby[tuple(row)]], dtype=float))
|
|
85
|
+
null = float(sum(h.mean() for h in hits if len(h)))
|
|
86
|
+
draws = np.zeros(permutations)
|
|
87
|
+
for h in hits:
|
|
88
|
+
if len(h):
|
|
89
|
+
draws += h[rng.integers(len(h), size=permutations)]
|
|
90
|
+
n_wrong = len(wrong)
|
|
91
|
+
rows.append({**dict(zip(keys, key_values)),
|
|
92
|
+
"W": n_wrong, "O": observed, "N": round(null, 2), "E": round(observed - null, 2),
|
|
93
|
+
"feng_value": round((observed - null) / (n_wrong - null), 3) if n_wrong > null else float("nan"),
|
|
94
|
+
"p": float((draws >= observed).mean())})
|
|
95
|
+
return pd.DataFrame(rows)
|
gtfeng/core.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Jiayu Feng
|
|
3
|
+
"""GT-FENG evaluation: the entry point `evaluate` and its `Result`.
|
|
4
|
+
|
|
5
|
+
The steps follow the paper:
|
|
6
|
+
1. keep stable items (every repeat gives the same answer);
|
|
7
|
+
2. Rule 1: is the answer correct? A correct answer is labeled "correct" at every level;
|
|
8
|
+
3. for a wrong answer, Rules 2 and 4: find the documented rules that set the same value, and their shifts;
|
|
9
|
+
4. for a wrong answer, Rules 3, 5 and 6: label it at each reference level.
|
|
10
|
+
Rule 7 and the FENG value run on the result: Result.feng_value (see baseline.py).
|
|
11
|
+
|
|
12
|
+
Glossary
|
|
13
|
+
item one group (e.g. one model) x one asked index; a dict of group and coordinate values
|
|
14
|
+
level level k means the reference set R_k; a documented rule or match belongs to R_k when its level <= k
|
|
15
|
+
source documented rules with equal coordinates except time (plus scope columns) form one source
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import math
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from typing import Callable, Iterable, Mapping, Sequence
|
|
22
|
+
|
|
23
|
+
import pandas as pd
|
|
24
|
+
|
|
25
|
+
from .baseline import DEFAULT_INCREMENTS, feng_values
|
|
26
|
+
from .references import ReferenceSet
|
|
27
|
+
from .report import standard_report, to_markdown
|
|
28
|
+
from .rules import CORRECT, coordinate_initials, count_sources, find_matches, is_correct, label
|
|
29
|
+
from .values import normalize
|
|
30
|
+
|
|
31
|
+
DEFAULT_COORDINATES = ("quantity", "jurisdiction", "time", "definition")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class Result:
|
|
36
|
+
"""Output of `evaluate`.
|
|
37
|
+
|
|
38
|
+
items one row per stable item and reference level: label, shifts, number of sources, matched indices.
|
|
39
|
+
unstable items left out because their repeats disagree or their answer is missing.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
items: pd.DataFrame
|
|
43
|
+
unstable: pd.DataFrame
|
|
44
|
+
groups: tuple = field(default_factory=tuple)
|
|
45
|
+
_context: dict | None = field(default=None, repr=False)
|
|
46
|
+
|
|
47
|
+
def report(self, families: Mapping[str, Iterable[str]] | None = None) -> pd.DataFrame:
|
|
48
|
+
"""The standard report; `families` maps a name to a set of shifts, e.g. {"cross": ["J", "JD"]}."""
|
|
49
|
+
return standard_report(self.items, self.groups, families)
|
|
50
|
+
|
|
51
|
+
def report_markdown(self, families: Mapping[str, Iterable[str]] | None = None) -> str:
|
|
52
|
+
"""The standard report as a signed Markdown table."""
|
|
53
|
+
return to_markdown(self.report(families))
|
|
54
|
+
|
|
55
|
+
def feng_value(self, family: Iterable[str], *, increments: Sequence[float] = DEFAULT_INCREMENTS,
|
|
56
|
+
permutations: int = 10000, seed: int = 0) -> pd.DataFrame:
|
|
57
|
+
"""Rule 7 and the FENG value for a family, e.g. ["J", "JD"]; one row per group and level.
|
|
58
|
+
|
|
59
|
+
Columns: W (wrong items), O (grounded in the family), N (local perturbation baseline), E = O - N,
|
|
60
|
+
feng_value = (O - N) / (W - N), and p. Numeric answers only; see gtfeng.baseline.
|
|
61
|
+
"""
|
|
62
|
+
return feng_values(self, family, increments=increments, permutations=permutations, seed=seed)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def evaluate(answers: pd.DataFrame, references: pd.DataFrame, *,
|
|
66
|
+
coordinates: Sequence[str] = DEFAULT_COORDINATES,
|
|
67
|
+
time_coordinate: str | None = "time",
|
|
68
|
+
answer: str = "answer",
|
|
69
|
+
value: str = "value",
|
|
70
|
+
level: str | None = "level",
|
|
71
|
+
level_by_shift: Mapping[str, float] | None = None,
|
|
72
|
+
scope: Mapping[str, str] | None = None,
|
|
73
|
+
groups: Sequence[str] = (),
|
|
74
|
+
decimals: int | None = None,
|
|
75
|
+
compare: Callable | None = None) -> Result:
|
|
76
|
+
"""Evaluate model answers against documented rules (GT-FENG Rules 1-6).
|
|
77
|
+
|
|
78
|
+
answers one row per response: the coordinate columns, `answer`, and any `groups` columns
|
|
79
|
+
(e.g. "model"). Repeated responses to the same question are allowed.
|
|
80
|
+
references one row per documented rule: the coordinate columns and `value`. Optional: a `level`
|
|
81
|
+
column (the first reference level that contains the rule, default 1) and `scope` columns.
|
|
82
|
+
time_coordinate the coordinate that holds time; documented rules that differ only in it share a source.
|
|
83
|
+
level_by_shift extension: the earliest level at which a shift may enter. math.inf leaves a shift out.
|
|
84
|
+
Example: {"D": 2, "T": 2, "TD": 2} holds the asked jurisdiction's own other values back
|
|
85
|
+
until level 2.
|
|
86
|
+
scope extension: {references column: answers coordinate}. A documented rule with a value in that
|
|
87
|
+
column applies only to items whose coordinate equals it.
|
|
88
|
+
decimals round numbers to this many places before comparing.
|
|
89
|
+
compare a custom function that turns a value into a comparison key (replaces values.normalize).
|
|
90
|
+
"""
|
|
91
|
+
coordinates = list(coordinates)
|
|
92
|
+
groups = tuple(groups)
|
|
93
|
+
level_by_shift = dict(level_by_shift or {})
|
|
94
|
+
scope = dict(scope or {})
|
|
95
|
+
compare = compare or (lambda v: normalize(v, decimals))
|
|
96
|
+
# Checked first: a setup error, not a data error.
|
|
97
|
+
initials = coordinate_initials(coordinates)
|
|
98
|
+
_check_columns(answers, coordinates + [answer], "answers")
|
|
99
|
+
_check_columns(references, coordinates + [value] + list(scope), "references")
|
|
100
|
+
|
|
101
|
+
coordinate_order = [initials[c] for c in coordinates]
|
|
102
|
+
reference_set = ReferenceSet(references, coordinates=coordinates, value=value, level=level,
|
|
103
|
+
time_coordinate=time_coordinate, scope=scope, compare=compare)
|
|
104
|
+
levels = _reference_levels(reference_set, level_by_shift)
|
|
105
|
+
|
|
106
|
+
stable, unstable = _split_by_stability(answers, list(groups) + coordinates, answer, compare)
|
|
107
|
+
rows = []
|
|
108
|
+
for item, raw_answer, answer_key in stable:
|
|
109
|
+
asked_index = tuple(item[c] for c in coordinates)
|
|
110
|
+
|
|
111
|
+
# Rule 1
|
|
112
|
+
correct = is_correct(answer_key, asked_index, reference_set)
|
|
113
|
+
|
|
114
|
+
# Rules 2 and 4 (each match carries its shift and its level)
|
|
115
|
+
matches = [] if correct else find_matches(answer_key, item, asked_index, reference_set,
|
|
116
|
+
coordinates, initials, level_by_shift)
|
|
117
|
+
|
|
118
|
+
# Rule 6: label the answer once per reference level
|
|
119
|
+
for current_level in levels:
|
|
120
|
+
if correct:
|
|
121
|
+
answer_label, shifts, in_level = CORRECT, (), []
|
|
122
|
+
else:
|
|
123
|
+
in_level = [m for m in matches if m.level <= current_level]
|
|
124
|
+
# Rules 3 and 5
|
|
125
|
+
answer_label, shifts = label(in_level, coordinate_order)
|
|
126
|
+
rows.append({**item,
|
|
127
|
+
"answer": raw_answer,
|
|
128
|
+
"level": _tidy_level(current_level),
|
|
129
|
+
"label": answer_label,
|
|
130
|
+
"shifts": shifts,
|
|
131
|
+
"n_shifts": len(shifts),
|
|
132
|
+
"n_sources": count_sources(in_level),
|
|
133
|
+
"matches": tuple(m.rule.index for m in in_level)})
|
|
134
|
+
context = {"references": reference_set, "coordinates": coordinates, "initials": initials,
|
|
135
|
+
"level_by_shift": level_by_shift, "compare": compare}
|
|
136
|
+
return Result(items=pd.DataFrame(rows), unstable=pd.DataFrame(unstable), groups=groups, _context=context)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _check_columns(table: pd.DataFrame, required: Sequence[str], name: str) -> None:
|
|
140
|
+
for column in required:
|
|
141
|
+
if column not in table.columns:
|
|
142
|
+
raise KeyError(f"{name} lacks column {column!r}")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _split_by_stability(answers: pd.DataFrame, item_columns: list, answer: str, compare: Callable):
|
|
146
|
+
"""An item is stable when every repeat gives the same, non-missing answer.
|
|
147
|
+
|
|
148
|
+
Returns (stable, unstable): stable is a list of (item, first raw answer, comparison key).
|
|
149
|
+
"""
|
|
150
|
+
stable, unstable = [], []
|
|
151
|
+
for key_values, responses in answers.groupby(item_columns, sort=False, dropna=False):
|
|
152
|
+
item = dict(zip(item_columns, key_values))
|
|
153
|
+
keys = [compare(v) for v in responses[answer]]
|
|
154
|
+
if None in keys or len(set(keys)) != 1:
|
|
155
|
+
unstable.append({**item, "answers": list(responses[answer])})
|
|
156
|
+
else:
|
|
157
|
+
stable.append((item, responses[answer].iloc[0], keys[0]))
|
|
158
|
+
return stable, unstable
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _reference_levels(reference_set: ReferenceSet, level_by_shift: Mapping[str, float]) -> list[float]:
|
|
162
|
+
"""Every level at which some documented rule or shift enters: the k of R1, R2, ..."""
|
|
163
|
+
levels = set(reference_set.levels()) | {v for v in level_by_shift.values() if v != math.inf}
|
|
164
|
+
return sorted(levels) or [1.0]
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _tidy_level(level: float):
|
|
168
|
+
"""Show level 2.0 as 2 in the output."""
|
|
169
|
+
return int(level) if float(level).is_integer() else level
|
gtfeng/references.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Jiayu Feng
|
|
3
|
+
"""The reference set R: every documented rule, indexed by its coordinates.
|
|
4
|
+
|
|
5
|
+
A documented rule sets one value at one index, for example (quantity="pregnancy", jurisdiction="Iowa",
|
|
6
|
+
time=2025, definition="canon") -> 205. The gold value G of a question is the value of the documented rule at the
|
|
7
|
+
question's index.
|
|
8
|
+
|
|
9
|
+
Naming: a "documented rule" is a row of the references table. The paper's "Rules 1-6" are the evaluation steps in
|
|
10
|
+
rules.py.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Callable, Mapping, Sequence
|
|
16
|
+
|
|
17
|
+
import pandas as pd
|
|
18
|
+
|
|
19
|
+
from .values import is_missing
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class DocumentedRule:
|
|
24
|
+
"""One row of the references table."""
|
|
25
|
+
|
|
26
|
+
index: tuple # coordinate values, in the order of `coordinates`
|
|
27
|
+
value_key: object # comparison key of the rule's value (see values.normalize)
|
|
28
|
+
level: float # the first reference level that contains this rule (level k means R_k)
|
|
29
|
+
source: tuple # all coordinates except time, plus the scope columns: equal sources = one source
|
|
30
|
+
scope: dict # {answers coordinate: required value}; empty when the rule applies to every item
|
|
31
|
+
|
|
32
|
+
def applies_to(self, item: Mapping) -> bool:
|
|
33
|
+
"""A scoped rule applies only to items whose coordinates equal its scope values."""
|
|
34
|
+
return all(item[coordinate] == required for coordinate, required in self.scope.items())
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ReferenceSet:
|
|
38
|
+
"""All documented rules, with lookup by index (for the gold value) and by value (for matches)."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, table: pd.DataFrame, *, coordinates: Sequence[str], value: str, level: str | None,
|
|
41
|
+
time_coordinate: str | None, scope: Mapping[str, str], compare: Callable):
|
|
42
|
+
source_columns = [c for c in coordinates if c != time_coordinate] + list(scope)
|
|
43
|
+
self.rules: list[DocumentedRule] = []
|
|
44
|
+
for row in table.to_dict("records"):
|
|
45
|
+
value_key = compare(row[value])
|
|
46
|
+
if value_key is None: # a rule without a value cannot be gold and cannot match anything
|
|
47
|
+
continue
|
|
48
|
+
self.rules.append(DocumentedRule(
|
|
49
|
+
index=tuple(row[c] for c in coordinates),
|
|
50
|
+
value_key=value_key,
|
|
51
|
+
level=float(row[level]) if level and level in row else 1.0,
|
|
52
|
+
source=tuple(None if is_missing(row[c]) else row[c] for c in source_columns),
|
|
53
|
+
scope={item_column: row[ref_column] for ref_column, item_column in scope.items()
|
|
54
|
+
if not is_missing(row[ref_column])},
|
|
55
|
+
))
|
|
56
|
+
self._gold: dict[tuple, object] = {}
|
|
57
|
+
self._by_value: dict[object, list[DocumentedRule]] = {}
|
|
58
|
+
for rule in self.rules:
|
|
59
|
+
self._gold.setdefault(rule.index, rule.value_key) # if an index appears twice, the first row is gold
|
|
60
|
+
self._by_value.setdefault(rule.value_key, []).append(rule)
|
|
61
|
+
|
|
62
|
+
def gold(self, index: tuple):
|
|
63
|
+
"""G at an index: the value of the documented rule at that index."""
|
|
64
|
+
if index not in self._gold:
|
|
65
|
+
raise KeyError(f"no documented rule with a value at the asked index {index}; "
|
|
66
|
+
"every question needs a gold value in the references table")
|
|
67
|
+
return self._gold[index]
|
|
68
|
+
|
|
69
|
+
def rules_with_value(self, value_key) -> list[DocumentedRule]:
|
|
70
|
+
"""Every documented rule whose value equals `value_key`."""
|
|
71
|
+
return self._by_value.get(value_key, [])
|
|
72
|
+
|
|
73
|
+
def levels(self) -> list[float]:
|
|
74
|
+
"""The levels that occur in the references table, in increasing order."""
|
|
75
|
+
return sorted({rule.level for rule in self.rules})
|
gtfeng/report.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Jiayu Feng
|
|
3
|
+
"""The GT-FENG standard report and the citation helpers."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from typing import Iterable, Mapping, Sequence
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from .rules import CORRECT, UNMATCHED
|
|
11
|
+
|
|
12
|
+
VERSION = "0.1.0"
|
|
13
|
+
SIGNATURE = f"Evaluated with GT-FENG v{VERSION} (Feng, 2026)."
|
|
14
|
+
BIBTEX = """@article{feng2026gtfeng,
|
|
15
|
+
title = {GT-FENG: General Theory of Factual Evaluation and Normative Grounding in Language Models},
|
|
16
|
+
author = {Feng, Jiayu},
|
|
17
|
+
journal = {arXiv preprint arXiv:2611.18279},
|
|
18
|
+
year = {2026},
|
|
19
|
+
url = {https://arxiv.org/abs/2611.18279}
|
|
20
|
+
}"""
|
|
21
|
+
TEXT = "Feng, J. (2026). GT-FENG: General Theory of Factual Evaluation and Normative Grounding in Language Models. arXiv:2611.18279."
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def cite(style: str = "bibtex") -> str:
|
|
25
|
+
"""Citation for GT-FENG: style "bibtex" (default) or "text"."""
|
|
26
|
+
if style not in ("bibtex", "text"):
|
|
27
|
+
raise ValueError('style must be "bibtex" or "text"')
|
|
28
|
+
return BIBTEX if style == "bibtex" else TEXT
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def standard_report(items: pd.DataFrame, groups: Sequence[str],
|
|
32
|
+
families: Mapping[str, Iterable[str]] | None = None) -> pd.DataFrame:
|
|
33
|
+
"""One row per group and reference level, with the seven quantities of the standard report:
|
|
34
|
+
|
|
35
|
+
1. correct items whose answer is correct
|
|
36
|
+
2. U wrong items with no match
|
|
37
|
+
3. shift_X wrong items labeled with the single shift X
|
|
38
|
+
4. shift_ambiguous wrong items whose matches carry two or more shifts
|
|
39
|
+
5. source_ambiguous wrong items whose matches come from two or more sources
|
|
40
|
+
6. mean_sources mean number of sources per matched item
|
|
41
|
+
7. O_<family> wrong items grounded in the family (every shift in M belongs to it)
|
|
42
|
+
"""
|
|
43
|
+
families = {name: frozenset(shifts) for name, shifts in (families or {}).items()}
|
|
44
|
+
keys = list(groups) + ["level"]
|
|
45
|
+
rows = []
|
|
46
|
+
for key_values, group in items.groupby(keys, sort=True):
|
|
47
|
+
key_values = key_values if isinstance(key_values, tuple) else (key_values,)
|
|
48
|
+
wrong = group[group.label != CORRECT]
|
|
49
|
+
matched = wrong[wrong.label != UNMATCHED]
|
|
50
|
+
single_shift = matched[matched.n_shifts == 1]
|
|
51
|
+
|
|
52
|
+
row = dict(zip(keys, key_values))
|
|
53
|
+
row["items"] = len(group)
|
|
54
|
+
row["correct"] = int((group.label == CORRECT).sum())
|
|
55
|
+
row["wrong"] = len(wrong)
|
|
56
|
+
row["U"] = int((wrong.label == UNMATCHED).sum())
|
|
57
|
+
for shift, count in single_shift.label.value_counts().items():
|
|
58
|
+
row[f"shift_{shift}"] = int(count)
|
|
59
|
+
row["shift_ambiguous"] = int((matched.n_shifts >= 2).sum())
|
|
60
|
+
row["source_ambiguous"] = int((matched.n_sources >= 2).sum())
|
|
61
|
+
row["mean_sources"] = round(float(matched.n_sources.mean()), 2) if len(matched) else float("nan")
|
|
62
|
+
for name, family in families.items():
|
|
63
|
+
# an item is grounded in a family when every shift in its M belongs to the family
|
|
64
|
+
grounded = matched.shifts.map(lambda shifts, family=family: set(shifts) <= family)
|
|
65
|
+
row[f"O_{name}"] = int(grounded.sum())
|
|
66
|
+
rows.append(row)
|
|
67
|
+
|
|
68
|
+
report = pd.DataFrame(rows)
|
|
69
|
+
shift_columns = sorted(c for c in report.columns if c.startswith("shift_") and c != "shift_ambiguous")
|
|
70
|
+
report[shift_columns] = report[shift_columns].fillna(0).astype(int)
|
|
71
|
+
columns = (keys + ["items", "correct", "wrong", "U"] + shift_columns
|
|
72
|
+
+ ["shift_ambiguous", "source_ambiguous", "mean_sources"] + [f"O_{name}" for name in families])
|
|
73
|
+
report = report[columns]
|
|
74
|
+
report.attrs["generated_by"] = SIGNATURE
|
|
75
|
+
return report
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def to_markdown(report: pd.DataFrame) -> str:
|
|
79
|
+
"""A report as a Markdown table, signed with the GT-FENG version."""
|
|
80
|
+
header = "| " + " | ".join(report.columns) + " |"
|
|
81
|
+
divider = "|" + "---|" * len(report.columns)
|
|
82
|
+
body = ["| " + " | ".join(str(v) for v in row) + " |" for row in report.itertuples(index=False)]
|
|
83
|
+
return "\n".join([header, divider, *body]) + "\n\n" + SIGNATURE + "\n"
|
gtfeng/rules.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Jiayu Feng
|
|
3
|
+
"""GT-FENG Rules 1-6, one function per rule, in the order of the paper.
|
|
4
|
+
|
|
5
|
+
Rule 1 Correct the answer equals the gold value at the asked index.
|
|
6
|
+
Rule 2 Matches otherwise, M = every other documented rule whose value equals the answer.
|
|
7
|
+
Rule 3 Unmatched if M is empty, the answer is labeled U.
|
|
8
|
+
Rule 4 Shift the coordinates in which a match differs from the asked index, as initials (J, T, JD, ...).
|
|
9
|
+
Rule 5 Label one shift -> that shift; two or more shifts -> "ambiguous {...}".
|
|
10
|
+
Rule 6 Levels nested reference sets R1 ⊆ R2 ⊆ ...; a match belongs to R_k when its level is at most k.
|
|
11
|
+
|
|
12
|
+
Two package extensions, not in the paper's rules: `scope` limits a documented rule to some items, and
|
|
13
|
+
`level_by_shift` sets the earliest level at which a shift may enter (a short way to define R1, R2, ...).
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import math
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from typing import Mapping, Sequence
|
|
20
|
+
|
|
21
|
+
from .references import DocumentedRule, ReferenceSet
|
|
22
|
+
|
|
23
|
+
CORRECT = "correct"
|
|
24
|
+
UNMATCHED = "U"
|
|
25
|
+
# The label "ambiguous" marks shift ambiguity (Rule 5). Source ambiguity is reported separately, as n_sources >= 2.
|
|
26
|
+
AMBIGUOUS = "ambiguous"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Match:
|
|
31
|
+
"""A documented rule that sets the same value as a wrong answer."""
|
|
32
|
+
|
|
33
|
+
rule: DocumentedRule
|
|
34
|
+
shift: str # Rule 4
|
|
35
|
+
level: float # Rule 6: the first reference level that contains this match
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def coordinate_initials(coordinates: Sequence[str]) -> dict[str, str]:
|
|
39
|
+
"""Each coordinate is named by its initial in shifts: quantity -> Q, jurisdiction -> J, and so on."""
|
|
40
|
+
initials = {c: c.strip()[0].upper() for c in coordinates}
|
|
41
|
+
if len(set(initials.values())) != len(initials):
|
|
42
|
+
raise ValueError(f"coordinate initials must be unique, got {initials}; rename a coordinate")
|
|
43
|
+
return initials
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def is_correct(answer_key, asked_index: tuple, references: ReferenceSet) -> bool:
|
|
47
|
+
"""Rule 1."""
|
|
48
|
+
return answer_key == references.gold(asked_index)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def shift(rule_index: tuple, asked_index: tuple, coordinates: Sequence[str], initials: Mapping[str, str]) -> str:
|
|
52
|
+
"""Rule 4: the initials of the coordinates in which a documented rule differs from the asked index."""
|
|
53
|
+
return "".join(initials[c] for c, theirs, asked in zip(coordinates, rule_index, asked_index) if theirs != asked)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def find_matches(answer_key, item: Mapping, asked_index: tuple, references: ReferenceSet,
|
|
57
|
+
coordinates: Sequence[str], initials: Mapping[str, str],
|
|
58
|
+
level_by_shift: Mapping[str, float]) -> list[Match]:
|
|
59
|
+
"""Rule 2: every other documented rule that sets the answer's value, with its shift (Rule 4) and level (Rule 6).
|
|
60
|
+
|
|
61
|
+
Package extensions: a rule whose scope excludes this item is skipped, and `level_by_shift` can delay a match
|
|
62
|
+
to a later level (math.inf leaves it out of every level).
|
|
63
|
+
"""
|
|
64
|
+
matches = []
|
|
65
|
+
for rule in references.rules_with_value(answer_key):
|
|
66
|
+
if rule.index == asked_index: # the asked index itself is the gold, not a match
|
|
67
|
+
continue
|
|
68
|
+
if not rule.applies_to(item): # scope extension
|
|
69
|
+
continue
|
|
70
|
+
rule_shift = shift(rule.index, asked_index, coordinates, initials)
|
|
71
|
+
level = max(rule.level, level_by_shift.get(rule_shift, 1.0))
|
|
72
|
+
if level != math.inf:
|
|
73
|
+
matches.append(Match(rule=rule, shift=rule_shift, level=level))
|
|
74
|
+
return matches
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def label(matches: Sequence[Match], coordinate_order: Sequence[str]) -> tuple[str, tuple[str, ...]]:
|
|
78
|
+
"""Rules 3 and 5 for a wrong answer: return (label, shifts present in M)."""
|
|
79
|
+
# Sort shifts by coordinate order, so the label reads {J, JD, T} and never {T, J, DJ}.
|
|
80
|
+
position = {initial: i for i, initial in enumerate(coordinate_order)}
|
|
81
|
+
shifts = tuple(sorted({m.shift for m in matches}, key=lambda s: [position[letter] for letter in s]))
|
|
82
|
+
if not matches:
|
|
83
|
+
return UNMATCHED, shifts
|
|
84
|
+
if len(shifts) == 1:
|
|
85
|
+
return shifts[0], shifts
|
|
86
|
+
return f"{AMBIGUOUS} {{{', '.join(shifts)}}}", shifts
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def count_sources(matches: Sequence[Match]) -> int:
|
|
90
|
+
"""Distinct sources in M. Two documented rules share a source when they differ only in time."""
|
|
91
|
+
return len({m.rule.source for m in matches})
|
gtfeng/values.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2026 Jiayu Feng
|
|
3
|
+
"""How two values are compared.
|
|
4
|
+
|
|
5
|
+
GT-FENG asks whether an answer A equals a documented rule's gold value G. Values can be numbers, Booleans,
|
|
6
|
+
strings, or sets, so each value is first turned into a comparison key, and two values are equal when their keys
|
|
7
|
+
are equal.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import pandas as pd
|
|
12
|
+
|
|
13
|
+
COLLECTIONS = (list, tuple, set, frozenset)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def is_missing(value) -> bool:
|
|
17
|
+
"""True for an empty cell: None, NaN, pd.NA, or NaT. Collections are never missing as a whole."""
|
|
18
|
+
if isinstance(value, COLLECTIONS):
|
|
19
|
+
return False
|
|
20
|
+
try:
|
|
21
|
+
return bool(pd.isna(value))
|
|
22
|
+
except (TypeError, ValueError):
|
|
23
|
+
return False
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def normalize(value, decimals: int | None = None):
|
|
27
|
+
"""Return the comparison key of a value, or None when the value is missing.
|
|
28
|
+
|
|
29
|
+
- Booleans are compared exactly (True is not the number 1).
|
|
30
|
+
- Numbers are compared as floats, rounded to `decimals` places when given (so 205 equals 205.0).
|
|
31
|
+
- Lists, tuples, and sets are compared as sets (order and repeats do not matter). A collection with a
|
|
32
|
+
missing member counts as missing.
|
|
33
|
+
- Anything else is compared as text.
|
|
34
|
+
"""
|
|
35
|
+
if is_missing(value):
|
|
36
|
+
return None
|
|
37
|
+
if isinstance(value, bool):
|
|
38
|
+
return ("bool", value)
|
|
39
|
+
if isinstance(value, (int, float)):
|
|
40
|
+
number = float(value)
|
|
41
|
+
return ("number", round(number, decimals) if decimals is not None else number)
|
|
42
|
+
if isinstance(value, COLLECTIONS):
|
|
43
|
+
members = [normalize(item, decimals) for item in value]
|
|
44
|
+
return None if None in members else ("set", frozenset(members))
|
|
45
|
+
return ("text", str(value))
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gtfeng
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: GT-FENG (General Theory of Factual Evaluation and Normative Grounding): evaluate language-model answers about rule-governed facts
|
|
5
|
+
Author: Jiayu Feng
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/VonFlair/gtfeng
|
|
8
|
+
Project-URL: Paper, https://arxiv.org/abs/2611.18279
|
|
9
|
+
Project-URL: Medicaid study, https://arxiv.org/abs/2610.09458
|
|
10
|
+
Keywords: language models,evaluation,factuality,law,policy,temporal,jurisdiction
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
License-File: NOTICE
|
|
18
|
+
Requires-Dist: pandas>=1.5
|
|
19
|
+
Requires-Dist: numpy
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# gtfeng
|
|
23
|
+
|
|
24
|
+
**GT-FENG (General Theory of Factual Evaluation and Normative Grounding)** evaluates language-model answers about facts whose correct value is set by a rule: an income limit, a filing deadline, a legal duty. The same answer can be right under one jurisdiction, date, or definition and wrong under another. `gtfeng` scores each answer against the rule that applies and lists every documented rule that matches a wrong answer. Paper: [arXiv:2611.18279](https://arxiv.org/abs/2611.18279).
|
|
25
|
+
|
|
26
|
+
Use it when you evaluate model answers about numbers, dates, or yes/no facts set by law or policy, and you want to know whether a wrong answer is the correct value for another state, another year, or another definition.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install gtfeng # from PyPI
|
|
32
|
+
pip install . # from a clone of this repository
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Requires Python 3.9+ and pandas.
|
|
36
|
+
|
|
37
|
+
## Quick start
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import pandas as pd
|
|
41
|
+
import gtfeng
|
|
42
|
+
|
|
43
|
+
references = pd.DataFrame(
|
|
44
|
+
[("limit", "A", 2025, "x", 50), ("limit", "A", 2018, "x", 40), ("limit", "B", 2025, "x", 40)],
|
|
45
|
+
columns=["quantity", "jurisdiction", "time", "definition", "value"])
|
|
46
|
+
answers = pd.DataFrame(
|
|
47
|
+
[{"model": "m", "quantity": "limit", "jurisdiction": "A", "time": 2025, "definition": "x", "answer": 40}])
|
|
48
|
+
|
|
49
|
+
result = gtfeng.evaluate(answers, references, groups=["model"])
|
|
50
|
+
result.items[["jurisdiction", "answer", "label", "n_sources"]]
|
|
51
|
+
# jurisdiction answer label n_sources
|
|
52
|
+
# A 40 ambiguous {J, T} 2
|
|
53
|
+
result.report(families={"cross_jurisdiction": ["J", "JD"]})
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The answer 40 is wrong for A in 2025. It matches B's current rule (shift **J**, another jurisdiction) and A's 2018 rule (shift **T**, another time), so GT-FENG labels it ambiguous and reports both sources.
|
|
57
|
+
|
|
58
|
+
## Key terms
|
|
59
|
+
|
|
60
|
+
| Term | Meaning | Example (quick start) |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| match | a documented rule, other than the one asked about, that gives the same value as a wrong answer | 40 matches B's 2025 rule and A's 2018 rule |
|
|
63
|
+
| U | a wrong answer with no match | an answer of 45 |
|
|
64
|
+
| shift | the coordinates in which a match differs from the question, written as their initials | B 2025 has shift J (another jurisdiction); A 2018 has shift T (another time) |
|
|
65
|
+
| source | where a match comes from; matches that differ only in year count as one source | A's 2018 and A's 2021 rules would be one source |
|
|
66
|
+
| reference level | how many documented rules a wrong answer is checked against; R1 is the smallest set, and each later level adds rules. Set with the `level` column or `level_by_shift` (default: everything at R1) | in the Medicaid example, R1 holds other states' current limits and R2 adds the asked state's earlier ones |
|
|
67
|
+
| ambiguous | the matches have two or more different shifts (shift ambiguity); matches from two or more sources are source ambiguity | 40 is `ambiguous {J, T}` |
|
|
68
|
+
| family | a set of shifts treated as one kind of error | {J, JD}: the value belongs to another jurisdiction |
|
|
69
|
+
| grounded in a family | every match of the wrong answer has a shift in the family | 40 is not grounded in {J, JD}, because its match A 2018 has shift T |
|
|
70
|
+
|
|
71
|
+
## Inputs
|
|
72
|
+
|
|
73
|
+
| Table | Required columns | Optional columns |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| `references` | the coordinates (default `quantity`, `jurisdiction`, `time`, `definition`) and `value` | `level` (reference level, default 1); scope columns |
|
|
76
|
+
| `answers` | the coordinates and `answer` | group columns such as `model`; repeated rows for repeated responses |
|
|
77
|
+
|
|
78
|
+
Coordinates are configurable (`coordinates=[...]`); each must have a distinct initial, which names its shift. Values can be numbers, Booleans, strings, or lists compared as sets.
|
|
79
|
+
|
|
80
|
+
## What it computes
|
|
81
|
+
|
|
82
|
+
Rule numbers follow the [GT-FENG paper](https://arxiv.org/abs/2611.18279).
|
|
83
|
+
|
|
84
|
+
| Paper | `gtfeng` |
|
|
85
|
+
|---|---|
|
|
86
|
+
| Stability | an item enters only when all repeats give the same answer (`result.unstable` lists the rest) |
|
|
87
|
+
| Rule 1, correct | `label == "correct"` |
|
|
88
|
+
| Rules 2–3, matches and U | `matches`; `label == "U"` when nothing matches |
|
|
89
|
+
| Rule 4, shift | `shifts`, e.g. `J`, `T`, `JD`, `JT` |
|
|
90
|
+
| Rule 5, label and ambiguity | single shift, or `ambiguous {...}` (shift ambiguity); `n_sources` counts distinct sources, so source ambiguity is `n_sources >= 2` (documented rules that differ only in time are one source) |
|
|
91
|
+
| Rule 6, reference levels | `level` column (level k means R_k); extension `level_by_shift`, e.g. `{"T": 2}` holds matches with shift T back until level 2 |
|
|
92
|
+
| Rule 7, local perturbation baseline | `result.feng_value(family)`: O, N, E, the FENG value, and p |
|
|
93
|
+
| Standard report | `result.report(families=...)`: correct, U, single-shift labels, shift-ambiguous, source-ambiguous, mean sources per matched item, and O for each family |
|
|
94
|
+
|
|
95
|
+
Extension `scope={"ref_column": "answer_coordinate"}` restricts a documented rule to items whose coordinate equals the rule's value in that column.
|
|
96
|
+
|
|
97
|
+
## Rule 7 and the FENG value
|
|
98
|
+
|
|
99
|
+
For a family of shifts F, `result.feng_value(F)` compares how often wrong answers are grounded in F with how often nearby values are:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
result.feng_value(["J", "JD"]) # one row per group and reference level
|
|
103
|
+
# W O N E feng_value p
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
| Column | Meaning |
|
|
107
|
+
|---|---|
|
|
108
|
+
| `W` | wrong items |
|
|
109
|
+
| `O` | wrong items grounded in F (they have matches, and every match has a shift in F) |
|
|
110
|
+
| `N` | local perturbation baseline: each wrong answer A is replaced by A + i for every increment i (default ±1 to ±4; increments that reach the correct value are dropped), and N sums each item's share of nearby values grounded in F |
|
|
111
|
+
| `E` | O − N |
|
|
112
|
+
| `feng_value` | (O − N) / (W − N); NaN when N ≥ W |
|
|
113
|
+
| `p` | share of random perturbations (one increment per item) whose grounded count reaches O |
|
|
114
|
+
|
|
115
|
+
The FENG value is 0 when wrong answers are grounded in F as often as nearby values, 1 when every wrong answer is grounded in F, and negative when nearby values are grounded more often. It has the chance-corrected form of Cohen's kappa; the match event and the local baseline come from GT-FENG. Rule 7 needs numeric answers, and the increments must leave out any known definition shift (the Medicaid example leaves out 5).
|
|
116
|
+
|
|
117
|
+
Report the FENG value next to accuracy: it describes the structure of wrong answers and does not rank models.
|
|
118
|
+
|
|
119
|
+
## Example: Medicaid income limits
|
|
120
|
+
|
|
121
|
+
[`examples/medicaid/`](https://github.com/VonFlair/gtfeng/tree/main/examples/medicaid) (in the GitHub repository) reproduces the paper's Medicaid instance (two models, 51 jurisdictions, three quantities). Its four reference levels follow the paper's Table 2:
|
|
122
|
+
|
|
123
|
+
| Level | A wrong answer is also checked against |
|
|
124
|
+
|---|---|
|
|
125
|
+
| R1 | other states' July 2025 limits, with and without the 5-point income disregard |
|
|
126
|
+
| R2 | the asked state's own limit under the other definition, three earlier editions, and the federal anchors 100, 133 and 138 (percent of the federal poverty level) |
|
|
127
|
+
| R3 | every edition of the asked state's limits, 2018–2024 |
|
|
128
|
+
| R4 | every other number in the asked state's rows of the MACStats data book, 2018–2025 |
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
cd examples/medicaid
|
|
132
|
+
python run_example.py
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
The input tables are included (`build_tables.py` rebuilds them from the original paper's supplementary materials), and `run_example.py` shows how to set reference levels with `level_by_shift` and limit rules with `scope`. The test suite checks that the output equals the paper's Table 3 and that Rule 7 reproduces the local perturbation baseline of the Medicaid instance.
|
|
136
|
+
|
|
137
|
+
## Citation
|
|
138
|
+
|
|
139
|
+
`gtfeng.cite()` returns the BibTeX entry (`gtfeng.cite("text")` a plain reference), and `result.report_markdown()` signs every report with "Evaluated with GT-FENG v0.1.0 (Feng, 2026)." If you use GT-FENG, please cite:
|
|
140
|
+
|
|
141
|
+
```bibtex
|
|
142
|
+
@article{feng2026gtfeng,
|
|
143
|
+
title = {GT-FENG: General Theory of Factual Evaluation and Normative Grounding in Language Models},
|
|
144
|
+
author = {Feng, Jiayu},
|
|
145
|
+
journal = {arXiv preprint arXiv:2611.18279},
|
|
146
|
+
year = {2026},
|
|
147
|
+
url = {https://arxiv.org/abs/2611.18279}
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## License
|
|
152
|
+
|
|
153
|
+
The code is licensed under the [Apache License 2.0](https://github.com/VonFlair/gtfeng/blob/main/LICENSE). Anyone who redistributes it, modified or not, must keep the `LICENSE` and `NOTICE` files, which carry the GT-FENG name and its author. The license grants no right to use the name GT-FENG for other products.
|
|
154
|
+
|
|
155
|
+
The example data in `examples/medicaid/` are licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). The gold values are derived from MACPAC MACStats Exhibits 35–36.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
gtfeng/__init__.py,sha256=tHRH1JhMbz6ED6jGvbR00mY_tKMyQfCvD2zY08O9NXw,1204
|
|
2
|
+
gtfeng/baseline.py,sha256=N3vUzcXn8RKS4771W1YAT_PqYNtATTwSZtxfpfplBJc,4676
|
|
3
|
+
gtfeng/core.py,sha256=b7BMXfGBwPaazuahoC1Wr05YHjyXchgngNhvsxNn1hw,8516
|
|
4
|
+
gtfeng/references.py,sha256=kAAsJyrxrt3y1siMGXzwx83RKJY8vSU4oHH5r8UacFc,3687
|
|
5
|
+
gtfeng/report.py,sha256=nNKrOisS0UL5HVcsMP5trvSN1w7akKKwCLakY2gapMI,3984
|
|
6
|
+
gtfeng/rules.py,sha256=XBzwwxG4hHlrKqr7G1ncvih_PPAXIWjVLQvvAYlWp8s,4305
|
|
7
|
+
gtfeng/values.py,sha256=3gKPy0qeMTU9osBaOzI5P7SEad9KkPQvLy0iT5hKLzk,1698
|
|
8
|
+
gtfeng-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
9
|
+
gtfeng-0.1.0.dist-info/licenses/NOTICE,sha256=kdN4JQ2d6w4tbYHjt13XhXw_y2UDOp7nZ0sKVEjLSo8,377
|
|
10
|
+
gtfeng-0.1.0.dist-info/METADATA,sha256=WTP8Kr-KbIwc-pyiR7XlrRIDzNFoTYAhrQvuNQps69Q,9339
|
|
11
|
+
gtfeng-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
gtfeng-0.1.0.dist-info/top_level.txt,sha256=sVZP7HaiGRUhgU6bb--_fmpctu4pQIcOKGhkt20SSS8,7
|
|
13
|
+
gtfeng-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
GT-FENG (General Theory of Factual Evaluation and Normative Grounding)
|
|
2
|
+
Copyright 2026 Jiayu Feng
|
|
3
|
+
|
|
4
|
+
This product includes software developed by Jiayu Feng as part of GT-FENG.
|
|
5
|
+
|
|
6
|
+
If you use GT-FENG in research, please cite:
|
|
7
|
+
Feng, J. (2026). GT-FENG: General Theory of Factual Evaluation and Normative Grounding in Language Models. arXiv:2611.18279. https://arxiv.org/abs/2611.18279
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gtfeng
|