robustrep 0.1.0__tar.gz
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.
- robustrep-0.1.0/LICENSE +202 -0
- robustrep-0.1.0/PKG-INFO +34 -0
- robustrep-0.1.0/README.md +9 -0
- robustrep-0.1.0/pyproject.toml +45 -0
- robustrep-0.1.0/robustrep/__init__.py +6 -0
- robustrep-0.1.0/robustrep/aggregate.py +262 -0
- robustrep-0.1.0/robustrep/cli.py +469 -0
- robustrep-0.1.0/robustrep/config.py +58 -0
- robustrep-0.1.0/robustrep/evidence.py +69 -0
- robustrep-0.1.0/robustrep/explain.py +112 -0
- robustrep-0.1.0/robustrep/normalize.py +73 -0
- robustrep-0.1.0/robustrep/pipeline.py +195 -0
- robustrep-0.1.0/robustrep/report/__init__.py +0 -0
- robustrep-0.1.0/robustrep/report/adversarial.py +245 -0
- robustrep-0.1.0/robustrep/report/export.py +52 -0
- robustrep-0.1.0/robustrep/report/figures.py +140 -0
- robustrep-0.1.0/robustrep/report/render.py +249 -0
- robustrep-0.1.0/robustrep/report/sensitivity.py +188 -0
- robustrep-0.1.0/robustrep/schema.py +109 -0
- robustrep-0.1.0/robustrep/sources/__init__.py +0 -0
- robustrep-0.1.0/robustrep/sources/base_erc8004.py +390 -0
- robustrep-0.1.0/robustrep/sources/evidence_fetch.py +395 -0
- robustrep-0.1.0/robustrep/sources/rater_profile.py +272 -0
- robustrep-0.1.0/robustrep/sources/rpc.py +286 -0
- robustrep-0.1.0/robustrep/store.py +305 -0
- robustrep-0.1.0/robustrep/sybil.py +260 -0
- robustrep-0.1.0/robustrep.egg-info/PKG-INFO +34 -0
- robustrep-0.1.0/robustrep.egg-info/SOURCES.txt +31 -0
- robustrep-0.1.0/robustrep.egg-info/dependency_links.txt +1 -0
- robustrep-0.1.0/robustrep.egg-info/entry_points.txt +2 -0
- robustrep-0.1.0/robustrep.egg-info/requires.txt +15 -0
- robustrep-0.1.0/robustrep.egg-info/top_level.txt +1 -0
- robustrep-0.1.0/setup.cfg +4 -0
robustrep-0.1.0/LICENSE
ADDED
|
@@ -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 2026 Dong Wang
|
|
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.
|
robustrep-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: robustrep
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Robust, transport-agnostic reputation scoring for AI agents
|
|
5
|
+
Author: Dong Wang
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: pandas<4,>=2.0
|
|
11
|
+
Requires-Dist: numpy>=1.24
|
|
12
|
+
Requires-Dist: eth-abi>=5.0
|
|
13
|
+
Requires-Dist: eth-hash[pycryptodome]>=0.5
|
|
14
|
+
Requires-Dist: requests>=2.31
|
|
15
|
+
Requires-Dist: urllib3>=2
|
|
16
|
+
Requires-Dist: tabulate>=0.9
|
|
17
|
+
Requires-Dist: matplotlib>=3.7
|
|
18
|
+
Requires-Dist: typer>=0.12
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
21
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
22
|
+
Requires-Dist: build; extra == "dev"
|
|
23
|
+
Requires-Dist: twine; extra == "dev"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# robustrep
|
|
27
|
+
|
|
28
|
+
Robust, transport-agnostic reputation scoring for AI agents.
|
|
29
|
+
|
|
30
|
+
Feed it any table of `(rater, ratee, value, scale, tag, ts, evidence_uri, source)` and it returns a
|
|
31
|
+
robust score per ratee that resists Sybil raters and evidence-free ratings. Ships with a Base-chain
|
|
32
|
+
ERC-8004 adapter and a reproducible report.
|
|
33
|
+
|
|
34
|
+
Status: v0.1 in development. See `docs/` in the parent repo for the design.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# robustrep
|
|
2
|
+
|
|
3
|
+
Robust, transport-agnostic reputation scoring for AI agents.
|
|
4
|
+
|
|
5
|
+
Feed it any table of `(rater, ratee, value, scale, tag, ts, evidence_uri, source)` and it returns a
|
|
6
|
+
robust score per ratee that resists Sybil raters and evidence-free ratings. Ships with a Base-chain
|
|
7
|
+
ERC-8004 adapter and a reproducible report.
|
|
8
|
+
|
|
9
|
+
Status: v0.1 in development. See `docs/` in the parent repo for the design.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "robustrep"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Robust, transport-agnostic reputation scoring for AI agents"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "Apache-2.0" }
|
|
11
|
+
authors = [{ name = "Dong Wang" }]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = [
|
|
14
|
+
"pandas>=2.0,<4",
|
|
15
|
+
"numpy>=1.24",
|
|
16
|
+
"eth-abi>=5.0",
|
|
17
|
+
"eth-hash[pycryptodome]>=0.5",
|
|
18
|
+
"requests>=2.31",
|
|
19
|
+
"urllib3>=2",
|
|
20
|
+
"tabulate>=0.9",
|
|
21
|
+
"matplotlib>=3.7",
|
|
22
|
+
"typer>=0.12",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
dev = ["pytest>=8", "pytest-cov>=5", "build", "twine"]
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
robustrep = "robustrep.cli:app"
|
|
30
|
+
|
|
31
|
+
[tool.setuptools.packages.find]
|
|
32
|
+
include = ["robustrep*"]
|
|
33
|
+
|
|
34
|
+
[tool.pytest.ini_options]
|
|
35
|
+
testpaths = ["tests"]
|
|
36
|
+
markers = ["live: needs network; run weekly, not on every push"]
|
|
37
|
+
addopts = "-m 'not live'"
|
|
38
|
+
filterwarnings = ["error"]
|
|
39
|
+
|
|
40
|
+
[tool.coverage.run]
|
|
41
|
+
source = ["robustrep"]
|
|
42
|
+
|
|
43
|
+
[tool.coverage.report]
|
|
44
|
+
fail_under = 80
|
|
45
|
+
show_missing = true
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""Aggregators turn (values, weights) into (score, ci_low, ci_high).
|
|
2
|
+
|
|
3
|
+
The arithmetic mean has breakdown point zero: a single extreme rating can move
|
|
4
|
+
it arbitrarily far. The weighted median has breakdown point ~0.5 (roughly half
|
|
5
|
+
the total weight must be adversarial to move it), so it is the default
|
|
6
|
+
aggregator here. `Aggregator` is an abstract base so Bayesian and graph-based
|
|
7
|
+
aggregators can be added later behind the same interface.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from abc import ABC, abstractmethod
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from .config import Config
|
|
16
|
+
|
|
17
|
+
# Half-weight threshold is nudged down by this relative fraction so that
|
|
18
|
+
# float64 cumsum drift at an exact tie doesn't step one element too far
|
|
19
|
+
# (which would break scale invariance and bias the result upward).
|
|
20
|
+
_TIE_EPS = 1e-9
|
|
21
|
+
|
|
22
|
+
# Minimum fraction of bootstrap resamples that must carry non-zero total
|
|
23
|
+
# weight for the CI to be considered meaningful.
|
|
24
|
+
MIN_VALID_BOOT_FRACTION = 0.1
|
|
25
|
+
|
|
26
|
+
# Cap on the number of (resample x vote) float64 cells materialized at once
|
|
27
|
+
# by `bootstrap_ci`'s chunked multinomial draw, so peak memory stays bounded
|
|
28
|
+
# even for a ratee with thousands of votes: a chunk holds at most this many
|
|
29
|
+
# cells regardless of how large `n_boot` is.
|
|
30
|
+
_MAX_BOOT_CHUNK_CELLS = 2_000_000
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _validate(values: np.ndarray, weights: np.ndarray, name: str) -> tuple[np.ndarray, np.ndarray]:
|
|
34
|
+
"""Shared input validation for `weighted_median` and `bootstrap_ci`.
|
|
35
|
+
|
|
36
|
+
Coerces both to 1-D float64 arrays and validates: 1-D, non-empty, equal
|
|
37
|
+
length, all-finite (no NaN/+/-inf), weights non-negative, and weights
|
|
38
|
+
summing to > 0. Returns the coerced `(values, weights)`. Raises
|
|
39
|
+
ValueError (messages prefixed with `name`, the caller's own name) on any
|
|
40
|
+
violation.
|
|
41
|
+
"""
|
|
42
|
+
values = np.asarray(values, dtype=float)
|
|
43
|
+
weights = np.asarray(weights, dtype=float)
|
|
44
|
+
if values.ndim != 1 or weights.ndim != 1:
|
|
45
|
+
raise ValueError(f"{name}: values/weights must be 1-D")
|
|
46
|
+
if values.shape[0] == 0:
|
|
47
|
+
raise ValueError(f"{name}: values/weights must not be empty")
|
|
48
|
+
if values.shape != weights.shape:
|
|
49
|
+
raise ValueError(f"{name}: values and weights must have the same length")
|
|
50
|
+
if not np.isfinite(values).all() or not np.isfinite(weights).all():
|
|
51
|
+
raise ValueError(f"{name}: values/weights must not contain non-finite entries (NaN/inf)")
|
|
52
|
+
if (weights < 0).any():
|
|
53
|
+
raise ValueError(f"{name}: weights must be non-negative")
|
|
54
|
+
if weights.sum() <= 0:
|
|
55
|
+
raise ValueError(f"{name}: weights must sum to > 0")
|
|
56
|
+
return values, weights
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _weighted_median_pos(cum: np.ndarray) -> int:
|
|
60
|
+
"""Position in an ascending cumulative-weight array selected by the lower-weighted-
|
|
61
|
+
median convention: the first index at which cumulative weight reaches >= half the
|
|
62
|
+
total (`np.searchsorted(..., side="left")`), with the half-weight threshold nudged
|
|
63
|
+
down by `_TIE_EPS` to absorb float64 cumsum drift at exact ties. Shared by
|
|
64
|
+
`_weighted_median_sorted` and `weighted_median_index` so this tie-tolerance logic
|
|
65
|
+
lives in exactly one place. `cum` must be non-empty and non-decreasing (a cumsum).
|
|
66
|
+
"""
|
|
67
|
+
half = 0.5 * cum[-1]
|
|
68
|
+
return int(np.searchsorted(cum, half * (1 - _TIE_EPS), side="left"))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _weighted_median_sorted(v: np.ndarray, w: np.ndarray) -> float:
|
|
72
|
+
"""Weighted median of already-sorted, already-validated inputs.
|
|
73
|
+
|
|
74
|
+
Assumes `v` is sorted ascending and `w` is finite, non-negative, and sums
|
|
75
|
+
to > 0. Not for external use (no validation) — see `weighted_median`.
|
|
76
|
+
"""
|
|
77
|
+
return float(v[_weighted_median_pos(np.cumsum(w))])
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def weighted_median(values: np.ndarray, weights: np.ndarray) -> float:
|
|
81
|
+
"""Return the weighted median of `values` under `weights`.
|
|
82
|
+
|
|
83
|
+
Tie/even-count convention: this is the *lower* weighted median. Sorting
|
|
84
|
+
values ascending and walking cumulative weight, the returned value is the
|
|
85
|
+
first one at which cumulative weight reaches >= half the total weight
|
|
86
|
+
(`np.searchsorted(..., side="left")`, with the half-weight threshold
|
|
87
|
+
nudged down by a small epsilon to absorb float64 cumsum drift at exact
|
|
88
|
+
ties). For an even count with equal weights this picks the smaller of the
|
|
89
|
+
two middle values (e.g. [0.2, 0.8] with equal weights returns 0.2),
|
|
90
|
+
matching a robust, deterministic, order-independent convention rather
|
|
91
|
+
than numpy's mean-of-two-middles.
|
|
92
|
+
|
|
93
|
+
Raises ValueError if `values`/`weights` are not 1-D, are empty,
|
|
94
|
+
mismatched in length, contain NaN or +/-inf, or if any weight is
|
|
95
|
+
negative or all weights are zero (see `_validate`).
|
|
96
|
+
"""
|
|
97
|
+
values, weights = _validate(values, weights, "weighted_median")
|
|
98
|
+
order = np.argsort(values, kind="stable")
|
|
99
|
+
return _weighted_median_sorted(values[order], weights[order])
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def weighted_median_index(values: np.ndarray, weights: np.ndarray) -> int:
|
|
103
|
+
"""Return the *original* index of the element `weighted_median` would return.
|
|
104
|
+
|
|
105
|
+
Same validation, stable sort, and tie tolerance as `weighted_median` (see
|
|
106
|
+
`_validate` and `_weighted_median_sorted`) -- `values[weighted_median_index(values,
|
|
107
|
+
weights)] == weighted_median(values, weights)` always holds. Useful when a caller
|
|
108
|
+
needs to know *which* input element was selected (e.g. `explain()` marking the
|
|
109
|
+
vote/tag chosen by the weighted-median chain), not just its value.
|
|
110
|
+
"""
|
|
111
|
+
values, weights = _validate(values, weights, "weighted_median_index")
|
|
112
|
+
order = np.argsort(values, kind="stable")
|
|
113
|
+
cum = np.cumsum(weights[order])
|
|
114
|
+
return int(order[_weighted_median_pos(cum)])
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _bootstrap_draws(
|
|
118
|
+
v_sorted: np.ndarray,
|
|
119
|
+
w_sorted: np.ndarray,
|
|
120
|
+
n_boot: int,
|
|
121
|
+
rng: np.random.Generator,
|
|
122
|
+
chunk_size: int,
|
|
123
|
+
) -> np.ndarray:
|
|
124
|
+
"""The array of valid weighted-median bootstrap draws (length <= n_boot).
|
|
125
|
+
|
|
126
|
+
`v_sorted`/`w_sorted` must already be sorted ascending by value. Draws
|
|
127
|
+
are generated `chunk_size` resamples at a time via
|
|
128
|
+
`rng.multinomial(n, [1/n]*n, size=chunk_size)` (see `bootstrap_ci` for
|
|
129
|
+
why a multinomial count draw is equivalent to classic index resampling
|
|
130
|
+
with replacement) and accumulated, so peak memory is bounded by
|
|
131
|
+
`chunk_size * n` regardless of `n_boot`. A resample whose weights sum to
|
|
132
|
+
zero has an undefined weighted median and is dropped from the result
|
|
133
|
+
rather than counted.
|
|
134
|
+
"""
|
|
135
|
+
n = len(v_sorted)
|
|
136
|
+
pvals = np.full(n, 1.0 / n)
|
|
137
|
+
boots = []
|
|
138
|
+
remaining = n_boot
|
|
139
|
+
while remaining > 0:
|
|
140
|
+
take = min(chunk_size, remaining)
|
|
141
|
+
remaining -= take
|
|
142
|
+
counts = rng.multinomial(n, pvals, size=take)
|
|
143
|
+
cum = np.cumsum(counts * w_sorted, axis=1)
|
|
144
|
+
valid = cum[:, -1] > 0
|
|
145
|
+
cum_valid = cum[valid]
|
|
146
|
+
half = 0.5 * cum_valid[:, -1:]
|
|
147
|
+
idx = (cum_valid >= half * (1 - _TIE_EPS)).argmax(axis=1)
|
|
148
|
+
boots.append(v_sorted[idx])
|
|
149
|
+
return np.concatenate(boots) if boots else np.array([], dtype=float)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def bootstrap_ci(
|
|
153
|
+
values: np.ndarray,
|
|
154
|
+
weights: np.ndarray,
|
|
155
|
+
n_boot: int,
|
|
156
|
+
rng: np.random.Generator,
|
|
157
|
+
ci_level: float,
|
|
158
|
+
) -> tuple[float, float]:
|
|
159
|
+
"""Vectorized bootstrap (lo, hi) quantiles of the weighted median.
|
|
160
|
+
|
|
161
|
+
Equivalent to resampling n `(value, weight)` pairs with replacement
|
|
162
|
+
`n_boot` times and taking the weighted median of each resample, but
|
|
163
|
+
without a Python-level loop over resamples. A resample's weighted
|
|
164
|
+
median depends only on how many times each *position* was drawn (its
|
|
165
|
+
resample count), not on the order of the draws, so after sorting
|
|
166
|
+
`values` once (stable), `rng.multinomial(n, [1/n]*n, size=chunk)`
|
|
167
|
+
produces a batch of resamples' per-position counts in a single call --
|
|
168
|
+
equivalent to drawing n indices with replacement, once per resample --
|
|
169
|
+
and the cumulative sum of `counts * sorted_weights` along each row gives
|
|
170
|
+
every resample's weighted median in one vectorized pass (see
|
|
171
|
+
`_bootstrap_draws`). Processed in chunks of at most
|
|
172
|
+
`max(1, 2_000_000 // n)` resamples so peak memory stays bounded even for
|
|
173
|
+
a ratee with thousands of votes; this is what keeps the per-ratee
|
|
174
|
+
bootstrap affordable at ~28k ratees.
|
|
175
|
+
|
|
176
|
+
Inputs are validated exactly like `weighted_median` (see `_validate`).
|
|
177
|
+
A resample whose weights sum to zero has an undefined weighted median
|
|
178
|
+
and is skipped rather than counted. If fewer than `max(2, n_boot // 10)`
|
|
179
|
+
resamples remain valid, raises ValueError instead of silently reporting
|
|
180
|
+
a CI built from too few (or zero) samples. Skipping all-zero resamples
|
|
181
|
+
conditions the CI on non-zero weight; unreachable in-pipeline since
|
|
182
|
+
Config forbids zero weights.
|
|
183
|
+
"""
|
|
184
|
+
values, weights = _validate(values, weights, "bootstrap_ci")
|
|
185
|
+
n = len(values)
|
|
186
|
+
order = np.argsort(values, kind="stable")
|
|
187
|
+
v_sorted, w_sorted = values[order], weights[order]
|
|
188
|
+
|
|
189
|
+
chunk_size = max(1, _MAX_BOOT_CHUNK_CELLS // n)
|
|
190
|
+
boots = _bootstrap_draws(v_sorted, w_sorted, n_boot, rng, chunk_size)
|
|
191
|
+
|
|
192
|
+
min_valid = max(2, int(n_boot * MIN_VALID_BOOT_FRACTION))
|
|
193
|
+
if boots.size < min_valid:
|
|
194
|
+
raise ValueError("bootstrap degenerate: too many zero-weight resamples")
|
|
195
|
+
|
|
196
|
+
alpha = (1 - ci_level) / 2
|
|
197
|
+
lo, hi = np.quantile(boots, [alpha, 1 - alpha])
|
|
198
|
+
return float(lo), float(hi)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _bootstrap_ci(
|
|
202
|
+
values: np.ndarray,
|
|
203
|
+
weights: np.ndarray,
|
|
204
|
+
n_boot: int,
|
|
205
|
+
seed: int,
|
|
206
|
+
ci_level: float,
|
|
207
|
+
) -> tuple[float, float]:
|
|
208
|
+
"""Bootstrap (lo, hi) quantiles of the weighted median, seeded by a plain
|
|
209
|
+
integer `seed`. Thin wrapper around `bootstrap_ci` (the one bootstrap
|
|
210
|
+
implementation) for callers that don't manage their own
|
|
211
|
+
`numpy.random.Generator`.
|
|
212
|
+
"""
|
|
213
|
+
return bootstrap_ci(values, weights, n_boot, np.random.default_rng(seed), ci_level)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class Aggregator(ABC):
|
|
217
|
+
"""Abstract base for turning per-ratee (values, weights) into a score with a CI.
|
|
218
|
+
|
|
219
|
+
Concrete implementations (e.g. `WeightedMedian`, and future Bayesian or
|
|
220
|
+
graph-based aggregators) all expose the same `aggregate` interface so the
|
|
221
|
+
pipeline can swap aggregation strategies without changing callers.
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
@abstractmethod
|
|
225
|
+
def aggregate(self, values: np.ndarray, weights: np.ndarray) -> tuple[float, float, float]:
|
|
226
|
+
"""Return (score, ci_low, ci_high)."""
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class WeightedMedian(Aggregator):
|
|
230
|
+
"""Weighted-median aggregator with a bootstrap confidence interval.
|
|
231
|
+
|
|
232
|
+
`aggregate` resamples (values, weights) pairs with replacement `n_boot`
|
|
233
|
+
times, computes the weighted median of each resample, and reports the
|
|
234
|
+
`ci_level` central interval of the bootstrap distribution (widened if
|
|
235
|
+
needed so it always contains the point estimate). Note: with tied or
|
|
236
|
+
coarse-grained values the percentile bootstrap can legitimately return a
|
|
237
|
+
zero-width interval (every resample lands on the same value) — consumers
|
|
238
|
+
should read the CI together with the underlying vote count rather than
|
|
239
|
+
treating a narrow interval alone as high confidence.
|
|
240
|
+
"""
|
|
241
|
+
|
|
242
|
+
def __init__(self, n_boot: int = 1000, seed: int = 0, ci_level: float = 0.95):
|
|
243
|
+
if n_boot < 0:
|
|
244
|
+
raise ValueError("WeightedMedian: n_boot must be >= 0")
|
|
245
|
+
if not 0 < ci_level < 1:
|
|
246
|
+
raise ValueError("WeightedMedian: ci_level must be in (0, 1)")
|
|
247
|
+
self.n_boot, self.seed, self.ci_level = n_boot, seed, ci_level
|
|
248
|
+
|
|
249
|
+
@classmethod
|
|
250
|
+
def from_config(cls, cfg: Config) -> "WeightedMedian":
|
|
251
|
+
"""Build a WeightedMedian aggregator from a pipeline Config."""
|
|
252
|
+
return cls(n_boot=cfg.bootstrap_n, seed=cfg.bootstrap_seed, ci_level=cfg.ci_level)
|
|
253
|
+
|
|
254
|
+
def aggregate(self, values: np.ndarray, weights: np.ndarray) -> tuple[float, float, float]:
|
|
255
|
+
values = np.asarray(values, dtype=float)
|
|
256
|
+
weights = np.asarray(weights, dtype=float)
|
|
257
|
+
point = weighted_median(values, weights)
|
|
258
|
+
if len(values) == 1 or self.n_boot == 0:
|
|
259
|
+
return point, point, point
|
|
260
|
+
lo, hi = _bootstrap_ci(values, weights, self.n_boot, self.seed, self.ci_level)
|
|
261
|
+
# defensive; not expected to fire
|
|
262
|
+
return point, float(min(lo, point)), float(max(hi, point))
|