sieve-probe 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.
- sieve_probe/__init__.py +5 -0
- sieve_probe/__main__.py +8 -0
- sieve_probe/cli.py +212 -0
- sieve_probe/data/public-1.json +53 -0
- sieve_probe/engine.py +179 -0
- sieve_probe/fixedmath.py +69 -0
- sieve_probe/inputs.py +224 -0
- sieve_probe/normalize.py +31 -0
- sieve_probe/publicdata.py +14 -0
- sieve_probe-0.1.0.dist-info/METADATA +150 -0
- sieve_probe-0.1.0.dist-info/RECORD +15 -0
- sieve_probe-0.1.0.dist-info/WHEEL +5 -0
- sieve_probe-0.1.0.dist-info/entry_points.txt +2 -0
- sieve_probe-0.1.0.dist-info/licenses/LICENSE +21 -0
- sieve_probe-0.1.0.dist-info/top_level.txt +1 -0
sieve_probe/__init__.py
ADDED
sieve_probe/__main__.py
ADDED
sieve_probe/cli.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""The command line of sieve-probe: battery, validate and compare.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 = the observation sits within the allowance with the declared
|
|
4
|
+
reference nearest; 1 = any other observation result; 2 = a usage error, a
|
|
5
|
+
format error, or too few samples. The output carries counts, distances,
|
|
6
|
+
hashes and closed words only; no answer string is ever printed. Everything
|
|
7
|
+
is written as UTF-8 bytes, so the output does not depend on the locale.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from . import __version__
|
|
17
|
+
from .engine import compare
|
|
18
|
+
from .fixedmath import format6
|
|
19
|
+
from .inputs import (FormatError, build_battery, load_observation,
|
|
20
|
+
validate_file)
|
|
21
|
+
from .publicdata import BATTERY_NAME, bundled_battery_bytes
|
|
22
|
+
|
|
23
|
+
MIN_SAMPLES = 20
|
|
24
|
+
MIN_CELLS = 8
|
|
25
|
+
OBSERVATION_NAME = "observation"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class UsageError(Exception):
|
|
29
|
+
"""A usage problem, carrying exactly one closed usage word."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, word):
|
|
32
|
+
super().__init__(word)
|
|
33
|
+
self.word = word
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def emit(text):
|
|
37
|
+
sys.stdout.buffer.write(text.encode("utf-8"))
|
|
38
|
+
sys.stdout.buffer.flush()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def command_battery(format_name):
|
|
42
|
+
raw = bundled_battery_bytes()
|
|
43
|
+
if format_name == "json":
|
|
44
|
+
emit(raw.decode("utf-8"))
|
|
45
|
+
return 0
|
|
46
|
+
battery = build_battery(json.loads(raw.decode("utf-8")))
|
|
47
|
+
lines = ["battery %s" % BATTERY_NAME]
|
|
48
|
+
for cell_id, prompt in battery:
|
|
49
|
+
lines.append("%s %s" % (cell_id, prompt))
|
|
50
|
+
emit("\n".join(lines) + "\n")
|
|
51
|
+
return 0
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def command_validate(path):
|
|
55
|
+
kind, cells, samples = validate_file(path)
|
|
56
|
+
if kind == "observation":
|
|
57
|
+
emit("format_ok: observation (%d cells, %d samples)\n"
|
|
58
|
+
% (cells, samples))
|
|
59
|
+
else:
|
|
60
|
+
emit("format_ok: battery (%d cells)\n" % cells)
|
|
61
|
+
return 0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def parse_references(specs):
|
|
65
|
+
"""NAME=FILE pairs, in order, with the closed usage words."""
|
|
66
|
+
names = []
|
|
67
|
+
paths = {}
|
|
68
|
+
for spec in specs:
|
|
69
|
+
name, separator, value = spec.partition("=")
|
|
70
|
+
if not separator or not name or not value:
|
|
71
|
+
raise UsageError("invalid_reference_spec")
|
|
72
|
+
if name in names:
|
|
73
|
+
raise UsageError("duplicate_reference_name")
|
|
74
|
+
names.append(name)
|
|
75
|
+
paths[name] = value
|
|
76
|
+
if not names:
|
|
77
|
+
raise UsageError("missing_reference")
|
|
78
|
+
return names, paths
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def input_entry(path, name, role):
|
|
82
|
+
data = Path(path).read_bytes()
|
|
83
|
+
return {"role": role, "name": name, "file": Path(path).name,
|
|
84
|
+
"sha256": hashlib.sha256(data).hexdigest()}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def compare_text(result):
|
|
88
|
+
lines = ["common cells: %d" % len(result["cells"])]
|
|
89
|
+
if result["status"] == "too_few_samples":
|
|
90
|
+
lines.append("status: too_few_samples")
|
|
91
|
+
lines.append("nearest: too_few_samples")
|
|
92
|
+
return "\n".join(lines) + "\n"
|
|
93
|
+
lines.append("s_obs: %s" % format6(result["s_obs"]))
|
|
94
|
+
for entry in result["references"]:
|
|
95
|
+
lines.append("reference %s: distance %s s_ref %s rank %d"
|
|
96
|
+
% (entry["name"], format6(entry["distance"]),
|
|
97
|
+
format6(entry["noise"]), entry["rank"]))
|
|
98
|
+
lines.append("status: %s" % result["status"])
|
|
99
|
+
lines.append("nearest: %s" % result["nearest"])
|
|
100
|
+
return "\n".join(lines) + "\n"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def compare_json(result, inputs):
|
|
104
|
+
document = {
|
|
105
|
+
"probe_version": 1,
|
|
106
|
+
"inputs": inputs,
|
|
107
|
+
"min_samples": result["min_samples"],
|
|
108
|
+
"min_cells": result["min_cells"],
|
|
109
|
+
"common_cells": len(result["cells"]),
|
|
110
|
+
"status": result["status"],
|
|
111
|
+
"nearest": result["nearest"],
|
|
112
|
+
}
|
|
113
|
+
if result["status"] != "too_few_samples":
|
|
114
|
+
document["s_obs"] = format6(result["s_obs"])
|
|
115
|
+
document["references"] = [
|
|
116
|
+
{"name": entry["name"],
|
|
117
|
+
"distance": format6(entry["distance"]),
|
|
118
|
+
"s_ref": format6(entry["noise"]),
|
|
119
|
+
"rank": entry["rank"]}
|
|
120
|
+
for entry in result["references"]
|
|
121
|
+
]
|
|
122
|
+
document["per_cell"] = [
|
|
123
|
+
{"cell": cell,
|
|
124
|
+
"distances": {entry["name"]: format6(entry["per_cell"][cell])
|
|
125
|
+
for entry in result["references"]}}
|
|
126
|
+
for cell in result["cells"]
|
|
127
|
+
]
|
|
128
|
+
return json.dumps(document, ensure_ascii=True, indent=2,
|
|
129
|
+
sort_keys=True) + "\n"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def command_compare(args):
|
|
133
|
+
names, paths = parse_references(args.reference)
|
|
134
|
+
if args.declare not in names:
|
|
135
|
+
raise UsageError("declared_not_in_references")
|
|
136
|
+
if args.min_samples < 1 or args.min_cells < 1:
|
|
137
|
+
raise UsageError("invalid_threshold")
|
|
138
|
+
observation = load_observation(args.observation)
|
|
139
|
+
references = []
|
|
140
|
+
for name in names:
|
|
141
|
+
reference = load_observation(paths[name])
|
|
142
|
+
reference.name = name
|
|
143
|
+
references.append(reference)
|
|
144
|
+
result = compare(observation, references, args.declare,
|
|
145
|
+
args.min_samples, args.min_cells)
|
|
146
|
+
inputs = [input_entry(args.observation, OBSERVATION_NAME, "observation")]
|
|
147
|
+
for name in names:
|
|
148
|
+
inputs.append(input_entry(paths[name], name, "reference"))
|
|
149
|
+
if args.format == "json":
|
|
150
|
+
emit(compare_json(result, inputs))
|
|
151
|
+
else:
|
|
152
|
+
emit(compare_text(result))
|
|
153
|
+
if result["status"] == "too_few_samples":
|
|
154
|
+
return 2
|
|
155
|
+
if (result["status"] == "within_noise_allowance"
|
|
156
|
+
and result["nearest"] == "nearest_is_declared"):
|
|
157
|
+
return 0
|
|
158
|
+
return 1
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def build_parser():
|
|
162
|
+
parser = argparse.ArgumentParser(
|
|
163
|
+
prog="sieve-probe",
|
|
164
|
+
description="Measure how close a distribution of one-word answers "
|
|
165
|
+
"stays to declared reference distributions. Collects "
|
|
166
|
+
"nothing: no network, no keys, no dependencies.")
|
|
167
|
+
parser.add_argument("--version", action="version",
|
|
168
|
+
version="sieve-probe %s" % __version__)
|
|
169
|
+
commands = parser.add_subparsers(dest="command", metavar="command",
|
|
170
|
+
required=True)
|
|
171
|
+
battery = commands.add_parser(
|
|
172
|
+
"battery", help="print the bundled battery public-1")
|
|
173
|
+
battery.add_argument("--format", choices=["text", "json"],
|
|
174
|
+
default="text")
|
|
175
|
+
validate = commands.add_parser(
|
|
176
|
+
"validate", help="check one observation or battery file")
|
|
177
|
+
validate.add_argument("file")
|
|
178
|
+
compare_parser = commands.add_parser(
|
|
179
|
+
"compare",
|
|
180
|
+
help="compare one recording with one or more references")
|
|
181
|
+
compare_parser.add_argument("observation")
|
|
182
|
+
compare_parser.add_argument("--reference", action="append", default=[],
|
|
183
|
+
metavar="NAME=FILE")
|
|
184
|
+
compare_parser.add_argument("--declare", required=True, metavar="NAME")
|
|
185
|
+
compare_parser.add_argument("--min-samples", type=int,
|
|
186
|
+
default=MIN_SAMPLES, metavar="N")
|
|
187
|
+
compare_parser.add_argument("--min-cells", type=int, default=MIN_CELLS,
|
|
188
|
+
metavar="N")
|
|
189
|
+
compare_parser.add_argument("--format", choices=["text", "json"],
|
|
190
|
+
default="text")
|
|
191
|
+
return parser
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def main(argv=None):
|
|
195
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
196
|
+
args = build_parser().parse_args(argv)
|
|
197
|
+
try:
|
|
198
|
+
if args.command == "battery":
|
|
199
|
+
return command_battery(args.format)
|
|
200
|
+
if args.command == "validate":
|
|
201
|
+
return command_validate(args.file)
|
|
202
|
+
return command_compare(args)
|
|
203
|
+
except FormatError as error:
|
|
204
|
+
emit("format_error: %s\n" % error.word)
|
|
205
|
+
return 2
|
|
206
|
+
except UsageError as error:
|
|
207
|
+
sys.stderr.write("usage_error: %s\n" % error.word)
|
|
208
|
+
return 2
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
if __name__ == "__main__":
|
|
212
|
+
sys.exit(main())
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"probe_battery_version": 1,
|
|
3
|
+
"cells": [
|
|
4
|
+
{
|
|
5
|
+
"id": "p01",
|
|
6
|
+
"prompt": "Pick a whole number between 1 and 10. Answer with one word only."
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
"id": "p02",
|
|
10
|
+
"prompt": "Name a color. Answer with one word only."
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
"id": "p03",
|
|
14
|
+
"prompt": "Name a fruit. Answer with one word only."
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
"id": "p04",
|
|
18
|
+
"prompt": "Name an animal. Answer with one word only."
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"id": "p05",
|
|
22
|
+
"prompt": "Pick a letter of the English alphabet. Answer with one word only."
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"id": "p06",
|
|
26
|
+
"prompt": "Name a country. Answer with one word only."
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
"id": "p07",
|
|
30
|
+
"prompt": "Name a day of the week. Answer with one word only."
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"id": "p08",
|
|
34
|
+
"prompt": "Name a month. Answer with one word only."
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"id": "p09",
|
|
38
|
+
"prompt": "Name a planet. Answer with one word only."
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
"id": "p10",
|
|
42
|
+
"prompt": "Name a musical instrument. Answer with one word only."
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
"id": "p11",
|
|
46
|
+
"prompt": "Name a programming language. Answer with one word only."
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
"id": "p12",
|
|
50
|
+
"prompt": "Name a city. Answer with one word only."
|
|
51
|
+
}
|
|
52
|
+
]
|
|
53
|
+
}
|
sieve_probe/engine.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""The distance engine: distributions, the Jensen-Shannon distance, the
|
|
2
|
+
parity noise, the ranks and the closed status words.
|
|
3
|
+
|
|
4
|
+
All arithmetic is exact fraction arithmetic on top of the fixed-point
|
|
5
|
+
logarithm, so the same recording gives the same numbers on every operating
|
|
6
|
+
system. No answer string ever reaches the output from here: the engine
|
|
7
|
+
returns counts, fractions and closed words only.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from fractions import Fraction
|
|
11
|
+
|
|
12
|
+
from .fixedmath import TIE, lg
|
|
13
|
+
|
|
14
|
+
WITHIN = "within_noise_allowance"
|
|
15
|
+
BEYOND = "beyond_noise_allowance"
|
|
16
|
+
NEAREST_DECLARED = "nearest_is_declared"
|
|
17
|
+
NEAREST_OTHER = "nearest_is_other"
|
|
18
|
+
TOO_FEW = "too_few_samples"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def distribution(counts, total):
|
|
22
|
+
"""Exact probabilities from {answer: count} and the cell total.
|
|
23
|
+
|
|
24
|
+
An empty cell (no samples in this half of a parity split) gives an empty
|
|
25
|
+
distribution, which the distance below treats as all-zero.
|
|
26
|
+
"""
|
|
27
|
+
if not total:
|
|
28
|
+
return {}
|
|
29
|
+
return {answer: Fraction(count, total)
|
|
30
|
+
for answer, count in counts.items()}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def jsd_cell(p_side, q_side):
|
|
34
|
+
"""The Jensen-Shannon distance of two distributions of one cell.
|
|
35
|
+
|
|
36
|
+
Base 2, no square root, so the value stays between 0 and 1. A missing
|
|
37
|
+
answer carries probability zero and contributes nothing.
|
|
38
|
+
"""
|
|
39
|
+
answers = set(p_side) | set(q_side)
|
|
40
|
+
total = Fraction(0)
|
|
41
|
+
for answer in answers:
|
|
42
|
+
p_value = p_side.get(answer, Fraction(0))
|
|
43
|
+
q_value = q_side.get(answer, Fraction(0))
|
|
44
|
+
middle = (p_value + q_value) / 2
|
|
45
|
+
if p_value:
|
|
46
|
+
total += p_value * lg(p_value / middle) / 2
|
|
47
|
+
if q_value:
|
|
48
|
+
total += q_value * lg(q_value / middle) / 2
|
|
49
|
+
return total
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def average_distance(sides_a, sides_b, cells):
|
|
53
|
+
"""The mean cell distance over the given cells."""
|
|
54
|
+
total = Fraction(0)
|
|
55
|
+
for cell in cells:
|
|
56
|
+
total += jsd_cell(sides_a[cell], sides_b[cell])
|
|
57
|
+
return total / len(cells)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parity_noise(cells_data, cells):
|
|
61
|
+
"""The noise of one recording: split every cell into the even-index and
|
|
62
|
+
the odd-index samples, measure their distance, and average it over the
|
|
63
|
+
shared cells."""
|
|
64
|
+
total = Fraction(0)
|
|
65
|
+
for cell in cells:
|
|
66
|
+
data = cells_data[cell]
|
|
67
|
+
even = distribution(data.even_counts, data.even_total)
|
|
68
|
+
odd = distribution(data.odd_counts, data.odd_total)
|
|
69
|
+
total += jsd_cell(even, odd)
|
|
70
|
+
return total / len(cells)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def common_cells(observation, references, min_samples):
|
|
74
|
+
"""The shared cells: present in the observation and in every reference,
|
|
75
|
+
with a total of at least min_samples samples across all inputs, sorted
|
|
76
|
+
by cell id."""
|
|
77
|
+
shared = set(observation.cells)
|
|
78
|
+
for reference in references:
|
|
79
|
+
shared &= set(reference.cells)
|
|
80
|
+
selected = []
|
|
81
|
+
for cell in sorted(shared):
|
|
82
|
+
total = observation.cells[cell].total
|
|
83
|
+
for reference in references:
|
|
84
|
+
total += reference.cells[cell].total
|
|
85
|
+
if total >= min_samples:
|
|
86
|
+
selected.append(cell)
|
|
87
|
+
return selected
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def allowance_word(distance, s_obs, s_ref):
|
|
91
|
+
"""The closed word for the allowance rule d <= s_obs + s_ref."""
|
|
92
|
+
if distance <= s_obs + s_ref:
|
|
93
|
+
return WITHIN
|
|
94
|
+
return BEYOND
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def ranks_and_nearest(names, distances):
|
|
98
|
+
"""Ranks on the shared cells.
|
|
99
|
+
|
|
100
|
+
The references are sorted by distance (equal distances by name). A
|
|
101
|
+
reference joins the rank of the group it lands in: a new group starts
|
|
102
|
+
when the distance moves away from the distance that opened the group by
|
|
103
|
+
1e-9 or more. The nearest set is the first group (everything within
|
|
104
|
+
1e-9 of the smallest distance).
|
|
105
|
+
"""
|
|
106
|
+
order = sorted(range(len(names)),
|
|
107
|
+
key=lambda index: (distances[index], names[index]))
|
|
108
|
+
ranks = [0] * len(names)
|
|
109
|
+
group_distance = None
|
|
110
|
+
group_rank = 0
|
|
111
|
+
for position, index in enumerate(order, 1):
|
|
112
|
+
if (group_distance is None
|
|
113
|
+
or distances[index] - group_distance >= TIE):
|
|
114
|
+
group_rank = position
|
|
115
|
+
group_distance = distances[index]
|
|
116
|
+
ranks[index] = group_rank
|
|
117
|
+
nearest = {names[index] for index in order
|
|
118
|
+
if distances[index] - distances[order[0]] < TIE}
|
|
119
|
+
return ranks, nearest
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def compare(observation, references, declared_name, min_samples, min_cells):
|
|
123
|
+
"""The full comparison of one observation against its references.
|
|
124
|
+
|
|
125
|
+
Returns a dict with exact fractions and closed words. When the shared
|
|
126
|
+
cells stay below min_cells, the status and the nearest word are both
|
|
127
|
+
too_few_samples and no distances are computed.
|
|
128
|
+
"""
|
|
129
|
+
cells = common_cells(observation, references, min_samples)
|
|
130
|
+
result = {
|
|
131
|
+
"cells": cells,
|
|
132
|
+
"min_samples": min_samples,
|
|
133
|
+
"min_cells": min_cells,
|
|
134
|
+
}
|
|
135
|
+
if len(cells) < min_cells:
|
|
136
|
+
result["status"] = TOO_FEW
|
|
137
|
+
result["nearest"] = TOO_FEW
|
|
138
|
+
return result
|
|
139
|
+
|
|
140
|
+
observed = {}
|
|
141
|
+
for cell in cells:
|
|
142
|
+
data = observation.cells[cell]
|
|
143
|
+
observed[cell] = distribution(data.counts, data.total)
|
|
144
|
+
distances = {}
|
|
145
|
+
noises = {}
|
|
146
|
+
per_cell = {}
|
|
147
|
+
for reference in references:
|
|
148
|
+
side = {}
|
|
149
|
+
for cell in cells:
|
|
150
|
+
data = reference.cells[cell]
|
|
151
|
+
side[cell] = distribution(data.counts, data.total)
|
|
152
|
+
distances[reference.name] = average_distance(observed, side, cells)
|
|
153
|
+
noises[reference.name] = parity_noise(reference.cells, cells)
|
|
154
|
+
per_cell[reference.name] = {
|
|
155
|
+
cell: jsd_cell(observed[cell], side[cell]) for cell in cells
|
|
156
|
+
}
|
|
157
|
+
s_obs = parity_noise(observation.cells, cells)
|
|
158
|
+
|
|
159
|
+
names = [reference.name for reference in references]
|
|
160
|
+
ranks, nearest = ranks_and_nearest(
|
|
161
|
+
names, [distances[name] for name in names])
|
|
162
|
+
|
|
163
|
+
result["s_obs"] = s_obs
|
|
164
|
+
result["references"] = [
|
|
165
|
+
{
|
|
166
|
+
"name": reference.name,
|
|
167
|
+
"distance": distances[reference.name],
|
|
168
|
+
"noise": noises[reference.name],
|
|
169
|
+
"rank": ranks[position],
|
|
170
|
+
"per_cell": per_cell[reference.name],
|
|
171
|
+
}
|
|
172
|
+
for position, reference in enumerate(references)
|
|
173
|
+
]
|
|
174
|
+
declared_distance = distances[declared_name]
|
|
175
|
+
result["status"] = allowance_word(
|
|
176
|
+
declared_distance, s_obs, noises[declared_name])
|
|
177
|
+
result["nearest"] = (NEAREST_DECLARED
|
|
178
|
+
if declared_name in nearest else NEAREST_OTHER)
|
|
179
|
+
return result
|
sieve_probe/fixedmath.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Deterministic arithmetic for the distances.
|
|
2
|
+
|
|
3
|
+
The engine never uses floating point. Every probability is an exact
|
|
4
|
+
fraction, and the base-2 logarithm of a fraction comes from its own atanh
|
|
5
|
+
series carried out in exact fraction arithmetic, kept as a fixed-point
|
|
6
|
+
integer with a scale of 2^64. The same code path runs on every operating
|
|
7
|
+
system, so identical inputs give identical output bytes. Rounding to six
|
|
8
|
+
decimals happens once, right before the output, half-up, on integers.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from fractions import Fraction
|
|
12
|
+
|
|
13
|
+
SCALE = 2 ** 64
|
|
14
|
+
SERIES_TERMS = 40
|
|
15
|
+
TIE = Fraction(1, 10 ** 9) # distances closer than this share a rank
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _atanh_series(value):
|
|
19
|
+
"""atanh(value) = sum of value^(2k+1) / (2k+1), exact fractions.
|
|
20
|
+
|
|
21
|
+
The engine only calls this for values below one third, where the series
|
|
22
|
+
converges geometrically; the fixed number of terms keeps the error far
|
|
23
|
+
below the fixed-point scale.
|
|
24
|
+
"""
|
|
25
|
+
total = Fraction(0)
|
|
26
|
+
power = value
|
|
27
|
+
for term in range(SERIES_TERMS):
|
|
28
|
+
total += power / (2 * term + 1)
|
|
29
|
+
power *= value * value
|
|
30
|
+
return total
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
_HALF_LN2 = _atanh_series(Fraction(1, 3)) # ln(2) = 2 * atanh(1/3)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def log2_fixed(value):
|
|
37
|
+
"""floor(log2(value) * SCALE) for an exact fraction value > 0."""
|
|
38
|
+
if value <= 0:
|
|
39
|
+
raise ValueError("log2 needs a positive fraction")
|
|
40
|
+
shift = value.numerator.bit_length() - value.denominator.bit_length()
|
|
41
|
+
unit = None
|
|
42
|
+
for candidate in range(shift - 2, shift + 2):
|
|
43
|
+
reduced = value / (Fraction(2) ** candidate)
|
|
44
|
+
if 1 <= reduced < 2:
|
|
45
|
+
unit = reduced
|
|
46
|
+
break
|
|
47
|
+
if unit is None:
|
|
48
|
+
raise ValueError("the normalization window failed")
|
|
49
|
+
ratio = (unit - 1) / (unit + 1)
|
|
50
|
+
total = _atanh_series(ratio)
|
|
51
|
+
return candidate * SCALE + (total * SCALE) // _HALF_LN2
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def lg(value):
|
|
55
|
+
"""The fixed-point logarithm as an exact fraction (scale 2^-64)."""
|
|
56
|
+
return Fraction(log2_fixed(value), SCALE)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def format6(value):
|
|
60
|
+
"""Six decimals, round half up, computed on integers only.
|
|
61
|
+
|
|
62
|
+
`value` is an exact fraction; the only place where anything is rounded
|
|
63
|
+
is this function, and it runs just before the output is written.
|
|
64
|
+
"""
|
|
65
|
+
scaled = value * 10 ** 6
|
|
66
|
+
whole, rest = divmod(scaled.numerator, scaled.denominator)
|
|
67
|
+
if 2 * rest >= scaled.denominator:
|
|
68
|
+
whole += 1
|
|
69
|
+
return "%d.%06d" % divmod(whole, 10 ** 6)
|
sieve_probe/inputs.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Loading and validation of observation and battery files.
|
|
2
|
+
|
|
3
|
+
Every format problem is reported as exactly one closed reason word; the
|
|
4
|
+
words are constants here so that the tests, the docs and the command line
|
|
5
|
+
pin the same list.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .normalize import normalize_answer
|
|
12
|
+
|
|
13
|
+
OBSERVATION_VERSION_KEY = "probe_obs_version"
|
|
14
|
+
BATTERY_VERSION_KEY = "probe_battery_version"
|
|
15
|
+
VERSION = 1
|
|
16
|
+
|
|
17
|
+
# the closed reason words
|
|
18
|
+
UNREADABLE_FILE = "unreadable_file"
|
|
19
|
+
NOT_JSON = "not_json"
|
|
20
|
+
NOT_OBJECT = "not_object"
|
|
21
|
+
PROBE_VERSION_MISMATCH = "probe_version_mismatch"
|
|
22
|
+
UNKNOWN_TOP_KEY = "unknown_top_key"
|
|
23
|
+
MISSING_TOP_KEY = "missing_top_key"
|
|
24
|
+
META_NOT_OBJECT = "meta_not_object"
|
|
25
|
+
UNKNOWN_META_KEY = "unknown_meta_key"
|
|
26
|
+
META_VALUE_NOT_STRING = "meta_value_not_string"
|
|
27
|
+
SAMPLES_NOT_LIST = "samples_not_list"
|
|
28
|
+
SAMPLE_ENTRY_NOT_OBJECT = "sample_entry_not_object"
|
|
29
|
+
UNKNOWN_SAMPLE_KEY = "unknown_sample_key"
|
|
30
|
+
CELL_NOT_STRING = "cell_not_string"
|
|
31
|
+
ANSWER_NOT_STRING = "answer_not_string"
|
|
32
|
+
SAMPLE_NOT_INTEGER = "sample_not_integer"
|
|
33
|
+
SAMPLE_SEQUENCE_GAP = "sample_sequence_gap"
|
|
34
|
+
SAMPLE_SEQUENCE_DUPLICATE = "sample_sequence_duplicate"
|
|
35
|
+
CELLS_NOT_LIST = "cells_not_list"
|
|
36
|
+
CELL_ENTRY_NOT_OBJECT = "cell_entry_not_object"
|
|
37
|
+
UNKNOWN_CELL_KEY = "unknown_cell_key"
|
|
38
|
+
CELL_ID_NOT_STRING = "cell_id_not_string"
|
|
39
|
+
PROMPT_NOT_STRING = "prompt_not_string"
|
|
40
|
+
DUPLICATE_CELL_ID = "duplicate_cell_id"
|
|
41
|
+
|
|
42
|
+
OBSERVATION_TOP_KEYS = frozenset(
|
|
43
|
+
[OBSERVATION_VERSION_KEY, "meta", "samples"])
|
|
44
|
+
META_KEYS = frozenset(["label", "collected_on", "setting"])
|
|
45
|
+
SAMPLE_KEYS = frozenset(["cell", "sample", "answer"])
|
|
46
|
+
BATTERY_TOP_KEYS = frozenset([BATTERY_VERSION_KEY, "cells"])
|
|
47
|
+
BATTERY_CELL_KEYS = frozenset(["id", "prompt"])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class FormatError(Exception):
|
|
51
|
+
"""A format problem, carrying exactly one closed reason word."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, word):
|
|
54
|
+
super().__init__(word)
|
|
55
|
+
self.word = word
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class CellData(object):
|
|
59
|
+
"""The samples of one cell: total counts and the parity split."""
|
|
60
|
+
|
|
61
|
+
__slots__ = ("counts", "total", "even_counts", "even_total",
|
|
62
|
+
"odd_counts", "odd_total")
|
|
63
|
+
|
|
64
|
+
def __init__(self):
|
|
65
|
+
self.counts = {}
|
|
66
|
+
self.total = 0
|
|
67
|
+
self.even_counts = {}
|
|
68
|
+
self.even_total = 0
|
|
69
|
+
self.odd_counts = {}
|
|
70
|
+
self.odd_total = 0
|
|
71
|
+
|
|
72
|
+
def add(self, index, answer):
|
|
73
|
+
self.counts[answer] = self.counts.get(answer, 0) + 1
|
|
74
|
+
self.total += 1
|
|
75
|
+
if index % 2 == 0:
|
|
76
|
+
self.even_counts[answer] = self.even_counts.get(answer, 0) + 1
|
|
77
|
+
self.even_total += 1
|
|
78
|
+
else:
|
|
79
|
+
self.odd_counts[answer] = self.odd_counts.get(answer, 0) + 1
|
|
80
|
+
self.odd_total += 1
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Observation(object):
|
|
84
|
+
"""One recording: cells and their samples (answers are normalized)."""
|
|
85
|
+
|
|
86
|
+
def __init__(self):
|
|
87
|
+
self.cells = {}
|
|
88
|
+
self.name = ""
|
|
89
|
+
|
|
90
|
+
def add_sample(self, cell, index, answer):
|
|
91
|
+
data = self.cells.setdefault(cell, CellData())
|
|
92
|
+
data.add(index, answer)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def read_bytes(path):
|
|
96
|
+
try:
|
|
97
|
+
return Path(path).read_bytes()
|
|
98
|
+
except OSError:
|
|
99
|
+
raise FormatError(UNREADABLE_FILE)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def parse_json(raw):
|
|
103
|
+
try:
|
|
104
|
+
return json.loads(raw.decode("utf-8"))
|
|
105
|
+
except (ValueError, UnicodeDecodeError):
|
|
106
|
+
raise FormatError(NOT_JSON)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _version_is_one(document, key):
|
|
110
|
+
value = document.get(key)
|
|
111
|
+
return (isinstance(value, int) and not isinstance(value, bool)
|
|
112
|
+
and value == VERSION)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def build_observation(document):
|
|
116
|
+
"""Validate one observation document and return an Observation."""
|
|
117
|
+
if not isinstance(document, dict):
|
|
118
|
+
raise FormatError(NOT_OBJECT)
|
|
119
|
+
if not _version_is_one(document, OBSERVATION_VERSION_KEY):
|
|
120
|
+
raise FormatError(PROBE_VERSION_MISMATCH)
|
|
121
|
+
for key in document:
|
|
122
|
+
if key not in OBSERVATION_TOP_KEYS:
|
|
123
|
+
raise FormatError(UNKNOWN_TOP_KEY)
|
|
124
|
+
if "samples" not in document:
|
|
125
|
+
raise FormatError(MISSING_TOP_KEY)
|
|
126
|
+
meta = document.get("meta")
|
|
127
|
+
if meta is not None:
|
|
128
|
+
if not isinstance(meta, dict):
|
|
129
|
+
raise FormatError(META_NOT_OBJECT)
|
|
130
|
+
for key, value in meta.items():
|
|
131
|
+
if key not in META_KEYS:
|
|
132
|
+
raise FormatError(UNKNOWN_META_KEY)
|
|
133
|
+
if not isinstance(value, str):
|
|
134
|
+
raise FormatError(META_VALUE_NOT_STRING)
|
|
135
|
+
samples = document["samples"]
|
|
136
|
+
if not isinstance(samples, list):
|
|
137
|
+
raise FormatError(SAMPLES_NOT_LIST)
|
|
138
|
+
record = Observation()
|
|
139
|
+
indices = {}
|
|
140
|
+
for entry in samples:
|
|
141
|
+
if not isinstance(entry, dict):
|
|
142
|
+
raise FormatError(SAMPLE_ENTRY_NOT_OBJECT)
|
|
143
|
+
for key in entry:
|
|
144
|
+
if key not in SAMPLE_KEYS:
|
|
145
|
+
raise FormatError(UNKNOWN_SAMPLE_KEY)
|
|
146
|
+
cell = entry.get("cell")
|
|
147
|
+
if not isinstance(cell, str):
|
|
148
|
+
raise FormatError(CELL_NOT_STRING)
|
|
149
|
+
index = entry.get("sample")
|
|
150
|
+
if not isinstance(index, int) or isinstance(index, bool):
|
|
151
|
+
raise FormatError(SAMPLE_NOT_INTEGER)
|
|
152
|
+
answer = entry.get("answer")
|
|
153
|
+
if not isinstance(answer, str):
|
|
154
|
+
raise FormatError(ANSWER_NOT_STRING)
|
|
155
|
+
indices.setdefault(cell, []).append(index)
|
|
156
|
+
record.add_sample(cell, index, normalize_answer(answer))
|
|
157
|
+
for cell, seen in indices.items():
|
|
158
|
+
if len(set(seen)) != len(seen):
|
|
159
|
+
raise FormatError(SAMPLE_SEQUENCE_DUPLICATE)
|
|
160
|
+
if sorted(seen) != list(range(len(seen))):
|
|
161
|
+
raise FormatError(SAMPLE_SEQUENCE_GAP)
|
|
162
|
+
return record
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def build_battery(document):
|
|
166
|
+
"""Validate one battery document and return its list of cells."""
|
|
167
|
+
if not isinstance(document, dict):
|
|
168
|
+
raise FormatError(NOT_OBJECT)
|
|
169
|
+
if not _version_is_one(document, BATTERY_VERSION_KEY):
|
|
170
|
+
raise FormatError(PROBE_VERSION_MISMATCH)
|
|
171
|
+
for key in document:
|
|
172
|
+
if key not in BATTERY_TOP_KEYS:
|
|
173
|
+
raise FormatError(UNKNOWN_TOP_KEY)
|
|
174
|
+
if "cells" not in document:
|
|
175
|
+
raise FormatError(MISSING_TOP_KEY)
|
|
176
|
+
cells = document["cells"]
|
|
177
|
+
if not isinstance(cells, list):
|
|
178
|
+
raise FormatError(CELLS_NOT_LIST)
|
|
179
|
+
battery = []
|
|
180
|
+
seen = set()
|
|
181
|
+
for entry in cells:
|
|
182
|
+
if not isinstance(entry, dict):
|
|
183
|
+
raise FormatError(CELL_ENTRY_NOT_OBJECT)
|
|
184
|
+
for key in entry:
|
|
185
|
+
if key not in BATTERY_CELL_KEYS:
|
|
186
|
+
raise FormatError(UNKNOWN_CELL_KEY)
|
|
187
|
+
cell_id = entry.get("id")
|
|
188
|
+
if not isinstance(cell_id, str):
|
|
189
|
+
raise FormatError(CELL_ID_NOT_STRING)
|
|
190
|
+
prompt = entry.get("prompt")
|
|
191
|
+
if not isinstance(prompt, str):
|
|
192
|
+
raise FormatError(PROMPT_NOT_STRING)
|
|
193
|
+
if cell_id in seen:
|
|
194
|
+
raise FormatError(DUPLICATE_CELL_ID)
|
|
195
|
+
seen.add(cell_id)
|
|
196
|
+
battery.append((cell_id, prompt))
|
|
197
|
+
return battery
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def validate_document(document):
|
|
201
|
+
"""Classify a document (observation or battery), validate it and return
|
|
202
|
+
(kind, cells, samples)."""
|
|
203
|
+
if not isinstance(document, dict):
|
|
204
|
+
raise FormatError(NOT_OBJECT)
|
|
205
|
+
has_observation = OBSERVATION_VERSION_KEY in document
|
|
206
|
+
has_battery = BATTERY_VERSION_KEY in document
|
|
207
|
+
if has_observation == has_battery:
|
|
208
|
+
raise FormatError(PROBE_VERSION_MISMATCH)
|
|
209
|
+
if has_observation:
|
|
210
|
+
record = build_observation(document)
|
|
211
|
+
samples = sum(data.total for data in record.cells.values())
|
|
212
|
+
return "observation", len(record.cells), samples
|
|
213
|
+
battery = build_battery(document)
|
|
214
|
+
return "battery", len(battery), None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def load_observation(path):
|
|
218
|
+
"""Read, parse and validate an observation or reference file."""
|
|
219
|
+
return build_observation(parse_json(read_bytes(path)))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def validate_file(path):
|
|
223
|
+
"""Validate the file at `path`; returns (kind, cells, samples)."""
|
|
224
|
+
return validate_document(parse_json(read_bytes(path)))
|
sieve_probe/normalize.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""The closed normalization rules for one-word answers.
|
|
2
|
+
|
|
3
|
+
The rules, in order: Unicode NFKC, lower case, then strip the closed sets
|
|
4
|
+
of whitespace and punctuation at both ends only. An answer that normalizes
|
|
5
|
+
to nothing counts as the one empty value, represented here as None; it is
|
|
6
|
+
never printed. Inner punctuation stays where it is. The rules and the
|
|
7
|
+
examples are documented in docs/normalization.md.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import unicodedata
|
|
11
|
+
|
|
12
|
+
WHITESPACE = " \t\n\r\v\f"
|
|
13
|
+
# After NFKC the fullwidth forms of . , ; : ! ? " ( ) are already ASCII, so
|
|
14
|
+
# the closed set below carries the ASCII forms plus the marks NFKC keeps.
|
|
15
|
+
PUNCTUATION = (
|
|
16
|
+
".,;:!?\"'`()"
|
|
17
|
+
"“”‘’"
|
|
18
|
+
"「」『』、。"
|
|
19
|
+
"・…"
|
|
20
|
+
"―–—-"
|
|
21
|
+
)
|
|
22
|
+
STRIP_CHARS = WHITESPACE + PUNCTUATION
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def normalize_answer(text):
|
|
26
|
+
"""The normalized value of one answer, or None when nothing is left."""
|
|
27
|
+
if not isinstance(text, str):
|
|
28
|
+
raise TypeError("an answer must be a string")
|
|
29
|
+
value = unicodedata.normalize("NFKC", text).lower()
|
|
30
|
+
value = value.strip(STRIP_CHARS)
|
|
31
|
+
return value or None
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""The bundled battery: the public-1 prompts shipped inside the package."""
|
|
2
|
+
|
|
3
|
+
import importlib.resources
|
|
4
|
+
|
|
5
|
+
BATTERY_NAME = "public-1"
|
|
6
|
+
DATA_PATH = ("data", "public-1.json")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def bundled_battery_bytes():
|
|
10
|
+
"""The exact bytes of the bundled battery file."""
|
|
11
|
+
resource = importlib.resources.files("sieve_probe")
|
|
12
|
+
for part in DATA_PATH:
|
|
13
|
+
resource = resource / part
|
|
14
|
+
return resource.read_bytes()
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sieve-probe
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Measure how close a distribution of one-word answers stays to declared reference distributions, with exact numbers and closed words
|
|
5
|
+
Author: Kai IWASAKI
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/neguseatama/sieve-probe
|
|
8
|
+
Project-URL: Repository, https://github.com/neguseatama/sieve-probe.git
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# Sieve Probe v0.1.0
|
|
22
|
+
|
|
23
|
+
Measure how close a distribution of one-word answers stays to the reference
|
|
24
|
+
distributions you declare. The output is a set of reproducible numbers and
|
|
25
|
+
closed words, computed on recordings you collected yourself. The tool
|
|
26
|
+
collects nothing: no network access, no keys, no dependencies beyond the
|
|
27
|
+
standard library. Python 3.10 or later.
|
|
28
|
+
|
|
29
|
+
The subject of this tool is the distribution of answers. It does not
|
|
30
|
+
identify models, vendors or versions; the reading of the numbers is yours.
|
|
31
|
+
|
|
32
|
+
## The five steps
|
|
33
|
+
|
|
34
|
+
1. Print the bundled public battery: `sieve-probe battery` (twelve one-word
|
|
35
|
+
prompts, battery `public-1`).
|
|
36
|
+
2. Collect one answer per sample with your own means. The tool never
|
|
37
|
+
collects anything.
|
|
38
|
+
3. Record the answers as an observation file (JSON, the shape is below).
|
|
39
|
+
Record the reference recordings in the same shape.
|
|
40
|
+
4. Compare: `sieve-probe compare OBS --reference NAME=FILE --declare NAME`.
|
|
41
|
+
5. Read the distances, the noise values, the ranks and the status words.
|
|
42
|
+
The exit code carries the same meaning.
|
|
43
|
+
|
|
44
|
+
## Commands
|
|
45
|
+
|
|
46
|
+
- `sieve-probe battery [--format text|json]` — print the bundled battery,
|
|
47
|
+
so answers can be collected against it. The battery is a starting point,
|
|
48
|
+
not a claimed-best set; new questions arrive with a version bump.
|
|
49
|
+
- `sieve-probe validate FILE` — check an observation or battery file; a
|
|
50
|
+
format problem is reported as exactly one closed reason word.
|
|
51
|
+
- `sieve-probe compare OBS --reference NAME=FILE [--reference ...]
|
|
52
|
+
--declare NAME [--min-samples N] [--min-cells N] [--format text|json]` —
|
|
53
|
+
the comparison on the shared cells.
|
|
54
|
+
- `sieve-probe --version`.
|
|
55
|
+
|
|
56
|
+
## The distance and the noise
|
|
57
|
+
|
|
58
|
+
- The distance is the Jensen-Shannon divergence (base 2, values from 0 to
|
|
59
|
+
1, no square root), computed per cell and averaged over the shared cells.
|
|
60
|
+
- The shared cells are the cells present in the observation and in every
|
|
61
|
+
reference whose total number of samples reaches `--min-samples` (default
|
|
62
|
+
20). Fewer than `--min-cells` (default 8) shared cells gives the status
|
|
63
|
+
`too_few_samples` and exit code 2.
|
|
64
|
+
- The noise of one recording splits every cell into even-index and
|
|
65
|
+
odd-index samples, measures the distance between the two halves, and
|
|
66
|
+
averages it over the shared cells (`s_obs` for the observation, `s_ref`
|
|
67
|
+
for a reference).
|
|
68
|
+
- The allowance: the distance to the declared reference is compared with
|
|
69
|
+
`s_obs + s_ref`. Within it, the status is `within_noise_allowance`;
|
|
70
|
+
above it, `beyond_noise_allowance`. The thresholds are fixed by design
|
|
71
|
+
and every number is printed, so the reading stays yours.
|
|
72
|
+
- The nearest reference is the one with the smallest distance; distances
|
|
73
|
+
within 0.000000001 of each other share a rank. The declared reference
|
|
74
|
+
inside that nearest group gives the status `nearest_is_declared`,
|
|
75
|
+
otherwise `nearest_is_other`.
|
|
76
|
+
|
|
77
|
+
## Exit codes
|
|
78
|
+
|
|
79
|
+
- `0` — the observation sits within the allowance and the declared
|
|
80
|
+
reference is nearest.
|
|
81
|
+
- `1` — any other observation result (`beyond_noise_allowance` or
|
|
82
|
+
`nearest_is_other`).
|
|
83
|
+
- `2` — a usage error, a format error, or `too_few_samples`.
|
|
84
|
+
|
|
85
|
+
## Closed words
|
|
86
|
+
|
|
87
|
+
Status words: `within_noise_allowance`, `beyond_noise_allowance`,
|
|
88
|
+
`nearest_is_declared`, `nearest_is_other`, `too_few_samples`.
|
|
89
|
+
|
|
90
|
+
Reason words (a format problem is reported as exactly one of these):
|
|
91
|
+
`unreadable_file`, `not_json`, `not_object`, `probe_version_mismatch`,
|
|
92
|
+
`unknown_top_key`, `missing_top_key`, `meta_not_object`, `unknown_meta_key`,
|
|
93
|
+
`meta_value_not_string`, `samples_not_list`, `sample_entry_not_object`,
|
|
94
|
+
`unknown_sample_key`, `cell_not_string`, `answer_not_string`,
|
|
95
|
+
`sample_not_integer`, `sample_sequence_gap`, `sample_sequence_duplicate`,
|
|
96
|
+
`cells_not_list`, `cell_entry_not_object`, `unknown_cell_key`,
|
|
97
|
+
`cell_id_not_string`, `prompt_not_string`, `duplicate_cell_id`.
|
|
98
|
+
|
|
99
|
+
Usage words: `missing_reference`, `duplicate_reference_name`,
|
|
100
|
+
`invalid_reference_spec`, `declared_not_in_references`, `invalid_threshold`.
|
|
101
|
+
|
|
102
|
+
## The shape of an observation file
|
|
103
|
+
|
|
104
|
+
```json
|
|
105
|
+
{
|
|
106
|
+
"probe_obs_version": 1,
|
|
107
|
+
"meta": {"label": "my-endpoint", "collected_on": "2026-11-29",
|
|
108
|
+
"setting": "temperature 1.0"},
|
|
109
|
+
"samples": [
|
|
110
|
+
{"cell": "p01", "sample": 0, "answer": "seven"},
|
|
111
|
+
{"cell": "p01", "sample": 1, "answer": "Seven."}
|
|
112
|
+
]
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
- The three `meta` keys are optional strings; no other `meta` key is
|
|
117
|
+
accepted.
|
|
118
|
+
- `sample` numbers run from 0 upward within a cell, without gaps or
|
|
119
|
+
duplicates.
|
|
120
|
+
- `answer` is a string. Answers are normalized before counting: Unicode
|
|
121
|
+
NFKC, lower case, then the closed sets of whitespace and punctuation are
|
|
122
|
+
stripped at both ends only. The rules and the examples are in
|
|
123
|
+
[docs/normalization.md](docs/normalization.md). An answer that normalizes
|
|
124
|
+
to nothing counts as one single empty value.
|
|
125
|
+
|
|
126
|
+
## The JSON output of compare
|
|
127
|
+
|
|
128
|
+
`"probe_version": 1`, the inputs with their base file names and `sha256`,
|
|
129
|
+
the number of shared cells, `s_obs`, per reference the `distance`, `s_ref`
|
|
130
|
+
and `rank`, the distance of every shared cell, and the status words. The
|
|
131
|
+
numbers carry six decimals. Answer strings are never part of any output.
|
|
132
|
+
|
|
133
|
+
## Determinism
|
|
134
|
+
|
|
135
|
+
The engine computes with exact fractions and a fixed-point logarithm; no
|
|
136
|
+
floating point is involved in a distance. Identical inputs give
|
|
137
|
+
byte-identical outputs on every operating system. Rounding to six decimals
|
|
138
|
+
happens once, right before the output (round half up).
|
|
139
|
+
|
|
140
|
+
## Development
|
|
141
|
+
|
|
142
|
+
```
|
|
143
|
+
python3 -m unittest discover -s tests
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## License
|
|
147
|
+
|
|
148
|
+
MIT License. See [LICENSE](https://github.com/neguseatama/sieve-probe/blob/main/LICENSE).
|
|
149
|
+
|
|
150
|
+
Copyright (c) 2026 Kai IWASAKI
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
sieve_probe/__init__.py,sha256=48j3hhR29A-jKuWDvTxpSVF3Scv7hftiI3bAYAJpZpw,230
|
|
2
|
+
sieve_probe/__main__.py,sha256=9qa-deKVxFTXF-2koFYz3nbV77fL7z7YUfkKKb-6lpY,161
|
|
3
|
+
sieve_probe/cli.py,sha256=ShA2eUQmB0hPLyOUF5_buU7A_cG79tkK59OORZDbwG8,7583
|
|
4
|
+
sieve_probe/engine.py,sha256=JGO87VbVjMB_d9U7KdMzIWuK2dBS97h9yJe8uETAXTg,6303
|
|
5
|
+
sieve_probe/fixedmath.py,sha256=FvRykZ0T7Tw0jyYV-3UE1v0RJxBEdebUnWfc8FPOJg8,2364
|
|
6
|
+
sieve_probe/inputs.py,sha256=t9ypJQdt0Ge4Yye8rAEv0sWXaB6T-8yJRiLDostcZ4E,7703
|
|
7
|
+
sieve_probe/normalize.py,sha256=lH3zXJkCrSsziZDeXJT83J9WoLNbeRWXuP-KKvA_SYs,1064
|
|
8
|
+
sieve_probe/publicdata.py,sha256=HQKMIg3S8MSTHRlwtLwoWRMIfSDI7K8gMviOzp8rWCA,406
|
|
9
|
+
sieve_probe/data/public-1.json,sha256=vdWwkHTLSGzwqGIK5LIO2OxytmtOc_DLIAyDUoJMB-c,1233
|
|
10
|
+
sieve_probe-0.1.0.dist-info/licenses/LICENSE,sha256=elLpPoGcCA_Tr2ln2abEvan7pEj_LoC4Q0-z5cudib8,1068
|
|
11
|
+
sieve_probe-0.1.0.dist-info/METADATA,sha256=riCQxOBblaCSqRmGMoPH2MWABYHnjaGNrmSswQtCVoE,6357
|
|
12
|
+
sieve_probe-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
sieve_probe-0.1.0.dist-info/entry_points.txt,sha256=6lvcBKn8pYtpvrrIOSMCWbqIokdOSzi_s-pLSZ1NANQ,53
|
|
14
|
+
sieve_probe-0.1.0.dist-info/top_level.txt,sha256=CEaVH6jFsREp4pj7SoyH1sGd4i9Kwv6AtFTEsD-Etv0,12
|
|
15
|
+
sieve_probe-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kai IWASAKI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sieve_probe
|