bioai-evidence-validator 0.5.0__py3-none-any.whl → 0.8.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.
- bioai_evidence_validator-0.8.0.dist-info/METADATA +313 -0
- bioai_evidence_validator-0.8.0.dist-info/RECORD +23 -0
- bioevidence_validator/__init__.py +1 -1
- bioevidence_validator/cli.py +131 -2
- bioevidence_validator/crosscheck.py +92 -0
- bioevidence_validator/definitions.py +124 -0
- bioevidence_validator/draft.py +9 -6
- bioevidence_validator/engine.py +61 -11
- bioevidence_validator/feedback.py +144 -0
- bioevidence_validator/grounding.py +104 -0
- bioevidence_validator/identifiers.py +395 -0
- bioevidence_validator/literature.py +387 -0
- bioevidence_validator/review.py +388 -0
- bioevidence_validator/schema/bioevidence_core.yaml +18 -4
- bioevidence_validator/semantic.py +66 -0
- bioevidence_validator/tables.py +118 -0
- bioai_evidence_validator-0.5.0.dist-info/METADATA +0 -299
- bioai_evidence_validator-0.5.0.dist-info/RECORD +0 -14
- {bioai_evidence_validator-0.5.0.dist-info → bioai_evidence_validator-0.8.0.dist-info}/WHEEL +0 -0
- {bioai_evidence_validator-0.5.0.dist-info → bioai_evidence_validator-0.8.0.dist-info}/entry_points.txt +0 -0
- {bioai_evidence_validator-0.5.0.dist-info → bioai_evidence_validator-0.8.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: bioai-evidence-validator
|
|
3
|
+
Version: 0.8.0
|
|
4
|
+
Summary: Standards-aligned evidence policy validation for AI-assisted biological curation
|
|
5
|
+
Project-URL: Homepage, https://github.com/NingyuSUN/bioai-evidence-validator
|
|
6
|
+
Project-URL: Documentation, https://ningyusun.github.io/bioai-evidence-validator/
|
|
7
|
+
Project-URL: Changelog, https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/CHANGELOG.md
|
|
8
|
+
Project-URL: Issues, https://github.com/NingyuSUN/bioai-evidence-validator/issues
|
|
9
|
+
Author: Ningyu Sun
|
|
10
|
+
License: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ai-safety,biocuration,bioinformatics,evidence,knowledge-graph,linkml,llm,ontology,provenance,validation
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Requires-Dist: jsonschema<5,>=4.23
|
|
26
|
+
Requires-Dist: linkml<2,>=1.8
|
|
27
|
+
Requires-Dist: pyyaml<7,>=6.0
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: mypy<3,>=2.3; extra == 'dev'
|
|
30
|
+
Requires-Dist: openpyxl<4,>=3.1; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest-cov<8,>=7; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest<9,>=8; extra == 'dev'
|
|
33
|
+
Requires-Dist: ruff<0.17,>=0.16; extra == 'dev'
|
|
34
|
+
Requires-Dist: types-jsonschema; extra == 'dev'
|
|
35
|
+
Requires-Dist: types-pyyaml; extra == 'dev'
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# BioAI Evidence Validator
|
|
39
|
+
|
|
40
|
+
[](https://github.com/NingyuSUN/bioai-evidence-validator/actions/workflows/ci.yml)
|
|
41
|
+
[](https://pypi.org/project/bioai-evidence-validator/)
|
|
42
|
+
[](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/pyproject.toml)
|
|
43
|
+
[](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/LICENSE)
|
|
44
|
+
[](https://colab.research.google.com/github/NingyuSUN/bioai-evidence-validator/blob/main/examples/quickstart.ipynb)
|
|
45
|
+
[](https://ningyusun.github.io/bioai-evidence-validator/)
|
|
46
|
+
|
|
47
|
+
**A validation layer for AI-assisted biological curation: let models do the routine work, and send
|
|
48
|
+
experts only the records that need them.**
|
|
49
|
+
|
|
50
|
+
LLMs and agents now extract claims from papers, cite the literature and annotate single-cell clusters.
|
|
51
|
+
Their output looks right, and it often is not. Some typical errors:
|
|
52
|
+
- a Cell Ontology ID that names a different cell type;
|
|
53
|
+
- a real PMID that belongs to an unrelated paper;
|
|
54
|
+
- a quote that appears nowhere in the paper.
|
|
55
|
+
|
|
56
|
+
Bioevidence checks every AI-produced record against pinned sources and reference releases, and decides,
|
|
57
|
+
for each intended use, whether it is **admitted**, needs **review**, or is **rejected**. Errors the model
|
|
58
|
+
can fix go back to it with the exact correction; findings that need judgment go to a person. Every claim
|
|
59
|
+
below is measured on real data with six models from Anthropic, OpenAI and Google.
|
|
60
|
+
|
|
61
|
+

|
|
62
|
+
|
|
63
|
+
## Results at a glance
|
|
64
|
+
|
|
65
|
+
| Experiment | The model alone | With bioevidence |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| **Single-cell cell-type annotation**: 6 models × 46 held-out clusters, protocol frozen before the run | 62 of 276 answers (22%) carry a Cell Ontology ID that does not match its label, e.g. "Paneth cell" filed under the ID of a pigment cell | No such answer admitted. In the feedback loop, answers compatible with the authors' term rise from **176 to 205**, wrong or invalid fall from 36% of answers to 20% of those admitted, and 8% go to a person |
|
|
68
|
+
| **Literature claims without a source**: 6 models × 18 CIViC claims | 38 of 50 answers cite an invalid paper or quote; 28 of 66 citations are real PMIDs of unrelated papers | 3 answers admitted, all with verified citations and the right decision |
|
|
69
|
+
| **Literature agent with PubMed tools**: 108 episodes | 8 of 77 first answers misquote their papers | 0 of 73 admitted answers carry an invalid citation; feedback rescues answers a plain gate would lose |
|
|
70
|
+
| **ClinVar germline classifications**: 5,026 variants, 2023 → 2026 | Schema-only checks admit 160 of 160 injected faults | 0 of 160 admitted; variants held back for a dissenting submission were 4–5× more likely to be reclassified three years later |
|
|
71
|
+
|
|
72
|
+
What it cannot do, also measured:
|
|
73
|
+
- **Semantic errors with valid identifiers and real evidence still get through.** Examples are a memory T
|
|
74
|
+
cell called naive, or an ILC3 called a Th17 cell: 20% of admitted single-cell annotations disagree with
|
|
75
|
+
the authors' term, part of it label noise.
|
|
76
|
+
- **One check failed external validation.** A check built from Cell Ontology marker definitions, with
|
|
77
|
+
thresholds set on development data, flagged errors no better than chance on six new studies. Fed back to
|
|
78
|
+
the models, it turned 15 correct answers into wrong ones. The check is kept as experimental, and the
|
|
79
|
+
cause (protein definitions that do not hold for transcripts) is documented.
|
|
80
|
+
|
|
81
|
+
Full protocols and numbers: [LLM benchmark](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/evaluation/llm_benchmark/README.md) ·
|
|
82
|
+
[single-cell case](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/examples/singlecell_celltype/README.md) ·
|
|
83
|
+
[ClinVar case](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/examples/clinvar_germline/README.md).
|
|
84
|
+
|
|
85
|
+
## End to end: LLM → tool calling → structured output → evaluation → failure handling
|
|
86
|
+
|
|
87
|
+
The [agent benchmark](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/evaluation/llm_benchmark/agent_loop.py)
|
|
88
|
+
runs the whole chain with every model:
|
|
89
|
+
- the harness, not the model's CLI, executes the tools, so each step is logged;
|
|
90
|
+
- each model reply must match a JSON Schema;
|
|
91
|
+
- each submission is validated by bioevidence before anything is admitted.
|
|
92
|
+
|
|
93
|
+
```mermaid
|
|
94
|
+
sequenceDiagram
|
|
95
|
+
participant H as Harness
|
|
96
|
+
participant M as Model (Claude / GPT / Gemini CLI)
|
|
97
|
+
participant T as Tools (PubMed, pinned papers)
|
|
98
|
+
participant B as bioevidence
|
|
99
|
+
H->>M: claim + tool list + JSON Schema for the reply
|
|
100
|
+
M-->>H: {"action": "search", "query": ...}
|
|
101
|
+
H->>T: esearch + efetch (cached, rate-limited)
|
|
102
|
+
T-->>H: up to 8 hits: PMID, title, abstract snippet
|
|
103
|
+
M-->>H: {"action": "read", "pmid": ...}
|
|
104
|
+
H->>T: resolve, pin full text or abstract by SHA-256
|
|
105
|
+
M-->>H: {"action": "submit", "decision": ..., "citations": [{pmid, title, quote, stance}]}
|
|
106
|
+
H->>B: record built from the submission, validated with grounders
|
|
107
|
+
alt admitted
|
|
108
|
+
B-->>H: admitted, report with hashes
|
|
109
|
+
else fixable finding
|
|
110
|
+
B-->>H: reasons (e.g. "citation 1: The quote does not appear in the cited paper.")
|
|
111
|
+
H->>M: the same task, with the reasons
|
|
112
|
+
else needs judgment
|
|
113
|
+
B-->>H: to a person (conflicting evidence, policy)
|
|
114
|
+
end
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
A real run from the committed results: Claude Haiku 4.5, asked whether VHL mutation predicts response to anti-VEGF
|
|
118
|
+
antibodies in renal cell carcinoma.
|
|
119
|
+
|
|
120
|
+
| Step | Model output (schema-validated JSON) | Harness and bioevidence |
|
|
121
|
+
|---|---|---|
|
|
122
|
+
| 1 | `search`: "VHL mutation renal cell carcinoma anti-VEGF response" | PubMed returns up to 8 hits with titles and abstract snippets |
|
|
123
|
+
| 2 | `read`: PMID 28103578 | The paper is resolved and pinned by SHA-256; its text is returned |
|
|
124
|
+
| 3 | `submit`: decision `does_not_support`, one citation with a 67-word quote | **Rejected.** BEV017: the quote does not appear in the cited paper. BEV020: no verified quote, as the profile requires. The reasons go back to the model |
|
|
125
|
+
| 4 | `submit`: the same decision with three shorter quotes from the same paper | All three are found in the pinned text, so the record is **admitted**. Its decision matches CIViC's |
|
|
126
|
+
|
|
127
|
+
The same loop corrects identifiers in single-cell annotation. Claude Haiku 4.5 labeled a pancreatic cluster
|
|
128
|
+
"pancreatic delta cell" but gave the ID `CL:0002335`, which is a brown preadipocyte. The feedback it received:
|
|
129
|
+
|
|
130
|
+
> object label: The label 'pancreatic delta cell' is not the name of CL:0002335 ('brown preadipocyte').
|
|
131
|
+
> 'pancreatic delta cell' is the name of CL:0000173 (pancreatic D cell).
|
|
132
|
+
|
|
133
|
+
Its second answer, `CL:0000173`, was admitted and is exactly the authors' annotation.
|
|
134
|
+
|
|
135
|
+
**Failure handling**, each in the code and exercised in the runs:
|
|
136
|
+
|
|
137
|
+
| Failure | Detected by | Handling |
|
|
138
|
+
|---|---|---|
|
|
139
|
+
| Malformed reply, or one that violates the schema | JSON Schema enforced by the CLI, then `check_step` / `check_answer` | One retry; then the step is logged as failed and the episode continues |
|
|
140
|
+
| The CLI uses its own tools (web, shell) | Tools are disabled where the CLI allows; otherwise tool events in its output stream | The answer is discarded and the call retried; the prompt also forbids tools |
|
|
141
|
+
| CLI error, timeout, no structured output | Subprocess timeout and output parsers | Logged per step and kept in the results (4 of 601 steps in the agent pilot) |
|
|
142
|
+
| PubMed rate limits, server errors | `Library.fetch` | Exponential backoff on 429 and 5xx, a response cache, a 100 MB download cap |
|
|
143
|
+
| Wrong paper, retracted paper, quote not in the paper | `LiteratureGrounder` (BEV016, BEV017, BEV019) | The reason goes back to the model; at most three submissions |
|
|
144
|
+
| ID of another term, obsolete term, gene alias | `OntologyGrounder`, `GeneGrounder` (BEV017, BEV023, BEV024) | The reason goes back, naming the correct identifier |
|
|
145
|
+
| The model's own evidence contradicts its answer | BEV004 | Sent to a person; not fed back, so the model is never asked to hide it |
|
|
146
|
+
| A revision drops evidence that was verified | `feedback.carry` | The verified evidence is carried into the revision |
|
|
147
|
+
| Still not admitted after the last round | `feedback.revise` | Sent to a person |
|
|
148
|
+
| A long batch is interrupted | One file per episode | A rerun skips finished episodes (used when a 486-episode run hit a time limit) |
|
|
149
|
+
|
|
150
|
+
## How it works
|
|
151
|
+
|
|
152
|
+
```mermaid
|
|
153
|
+
flowchart LR
|
|
154
|
+
A["AI output<br/>(LLM or agent)"] --> R["Evidence record<br/>claim + sources + evidence"]
|
|
155
|
+
R --> P["Profile rules<br/>per intended use"]
|
|
156
|
+
R --> G["Grounders<br/>check against pinned sources"]
|
|
157
|
+
P --> D{"Decision<br/>per use"}
|
|
158
|
+
G --> D
|
|
159
|
+
D -->|admitted| K["Knowledge base /<br/>training set"]
|
|
160
|
+
D -->|fixable error| F["Feedback to the model<br/>with the exact correction"]
|
|
161
|
+
F --> A
|
|
162
|
+
D -->|needs judgment| H["Expert review"]
|
|
163
|
+
D --> L["Audit report<br/>findings, versions, hashes"]
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
- **Records:** a claim (subject, predicate, object, scope) with the sources it rests on and typed evidence
|
|
167
|
+
items. They are validated against a LinkML schema.
|
|
168
|
+
- **Profiles:** each profile states, per use, which evidence a claim needs before it is admitted. For
|
|
169
|
+
example, LLM-extracted evidence may be enough for a research summary, while a knowledge base requires a
|
|
170
|
+
human's acceptance. Profiles are YAML, so a new domain needs no engine changes.
|
|
171
|
+
- **Grounders:** they recompute what a record only asserts from pinned, content-addressed snapshots:
|
|
172
|
+
|
|
173
|
+
| Grounder | Checks |
|
|
174
|
+
|---|---|
|
|
175
|
+
| Literature | PMID/DOI resolution, retraction, title, and every quote against open full text or the abstract |
|
|
176
|
+
| Ontology | the term exists, is current, matches its label and is of the right kind (e.g. a cell type) |
|
|
177
|
+
| Genes / variants | HGNC approved symbols, previous symbols and aliases; HGVS form, RefSeq version, genome build |
|
|
178
|
+
| Tables | a cited data row exists with the values claimed (e.g. a marker gene of this cluster) |
|
|
179
|
+
| Reference resources | a curated reference contradicts the claim (review only) |
|
|
180
|
+
| Ontology definitions | measurements contradict a marker the claimed term is defined by (experimental) |
|
|
181
|
+
|
|
182
|
+
- **Feedback loop:** `feedback.revise` wraps any model or agent.
|
|
183
|
+
- Fixable findings go back as precise reasons.
|
|
184
|
+
- Conflicts and policy decisions go to a person unchanged.
|
|
185
|
+
- Verified evidence cannot be withdrawn in a revision, so an agent cannot drop the evidence against
|
|
186
|
+
its own answer.
|
|
187
|
+
- **Audit:** every report records the input, schema and profile hashes and versions. There are 26
|
|
188
|
+
documented rule codes, each with a fixed severity.
|
|
189
|
+
|
|
190
|
+
## What this project demonstrates
|
|
191
|
+
|
|
192
|
+
- **Rigorous evaluation of LLMs and agents.**
|
|
193
|
+
- Six models from three vendors, called through their CLIs with structured output, plus a tool-using
|
|
194
|
+
agent with PubMed access.
|
|
195
|
+
- Protocols are designed on pilot data and committed to git before the held-out and external splits are
|
|
196
|
+
run.
|
|
197
|
+
- Scoring is ontology-aware, with Wilson intervals.
|
|
198
|
+
- Negative results are reported, including the run where a new check made things worse.
|
|
199
|
+
- **Biological data engineering.**
|
|
200
|
+
- Single-cell marker statistics computed from raw counts (CELLxGENE).
|
|
201
|
+
- The Cell Ontology, including its disjointness axioms and logical definitions, HGNC, NCBI assemblies,
|
|
202
|
+
ClinVar submissions, CIViC evidence and PMC JATS full text.
|
|
203
|
+
- All sources are pinned by SHA-256, with licences and attribution.
|
|
204
|
+
- **Production-quality software.**
|
|
205
|
+
- A typed Python package on PyPI, with CLI exit codes for pipelines and a GitHub Action for CI.
|
|
206
|
+
- Test coverage around 98%, with CI on Linux and Windows for Python 3.11–3.14.
|
|
207
|
+
- A documentation site, and byte-for-byte replay of every committed benchmark table.
|
|
208
|
+
- **Designing for trust, not only accuracy.**
|
|
209
|
+
- Decisions are made per intended use, with a measured trust boundary (controlled faults and forged
|
|
210
|
+
sources).
|
|
211
|
+
- Only facts are fed back to a model; anything that needs judgment goes to a person.
|
|
212
|
+
|
|
213
|
+
## Quickstart
|
|
214
|
+
|
|
215
|
+
```bash
|
|
216
|
+
pip install bioai-evidence-validator
|
|
217
|
+
bioevidence validate examples/literature_claim/llm_only.json --profile literature-claim # exit 2: review required
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
From version 0.8.0 the package also includes the literature, ontology, gene, variant, table and
|
|
221
|
+
reference grounders, and the feedback loop. For example, to check a cell-type annotation against a pinned
|
|
222
|
+
Cell Ontology release and the HGNC gene set:
|
|
223
|
+
|
|
224
|
+
```bash
|
|
225
|
+
bioevidence validate record.json --ontology cl.obo --term-root cell_type=CL:0000000 --genes hgnc_complete_set.txt
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
Wrap a model in the feedback loop:
|
|
229
|
+
|
|
230
|
+
```python
|
|
231
|
+
from pathlib import Path
|
|
232
|
+
|
|
233
|
+
from bioevidence_validator.engine import RecordValidator
|
|
234
|
+
from bioevidence_validator.feedback import revise
|
|
235
|
+
from bioevidence_validator.identifiers import GeneGrounder, Genes, Ontology, OntologyGrounder
|
|
236
|
+
|
|
237
|
+
validator = RecordValidator(profile="general", grounders=[
|
|
238
|
+
OntologyGrounder([Ontology.from_obo(Path("cl.obo").read_bytes())], roots={"cell_type": ["CL:0000000"]}),
|
|
239
|
+
GeneGrounder(Genes.from_hgnc(Path("hgnc_complete_set.txt").read_bytes())),
|
|
240
|
+
])
|
|
241
|
+
|
|
242
|
+
def propose(feedback: list[str]) -> dict | None:
|
|
243
|
+
"""Ask your model for a record; on later rounds, include the feedback in the prompt."""
|
|
244
|
+
...
|
|
245
|
+
|
|
246
|
+
attempts = revise(propose, validator, rounds=3)
|
|
247
|
+
print(attempts[-1].report["overall_status"]) # admitted, review_required or rejected
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
Exit codes: **0** admitted, **1** rejected, **2** review required, **3** input or configuration error.
|
|
251
|
+
|
|
252
|
+
To check records in a pull request, use the GitHub Action:
|
|
253
|
+
|
|
254
|
+
```yaml
|
|
255
|
+
- uses: NingyuSUN/bioai-evidence-validator@v0.8.0
|
|
256
|
+
with:
|
|
257
|
+
files: records/**/*.yaml
|
|
258
|
+
format: draft
|
|
259
|
+
profile: literature-claim
|
|
260
|
+
fail-on: review
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
More: [draft format](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/docs/DRAFTS.md) (state each fact once, build the full record) ·
|
|
264
|
+
[create a profile](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/docs/PROFILES.md) ·
|
|
265
|
+
[engineering contract and rule codes](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/docs/ENGINEERING.md) ·
|
|
266
|
+
[documentation site](https://ningyusun.github.io/bioai-evidence-validator/).
|
|
267
|
+
|
|
268
|
+
## Real-data cases
|
|
269
|
+
|
|
270
|
+
| Case | Data | What it shows |
|
|
271
|
+
|---|---|---|
|
|
272
|
+
| [Single-cell cell-type annotation](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/examples/singlecell_celltype/README.md) | 12 CELLxGENE datasets (151 clusters), Cell Ontology, HGNC, HuBMAP ASCT+B | Identifier hallucination caught for every model; a feedback loop that improves annotations; a pre-registered external test of a new check that failed |
|
|
273
|
+
| [LLM literature benchmark](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/evaluation/llm_benchmark/README.md) | CIViC claims, PMC open-access papers, six models | Invented citations blocked; an agent loop with stances and a "conflicting" outcome; semantic checks |
|
|
274
|
+
| [CIViC literature grounding](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/examples/civic_literature/README.md) | CC BY / CC0 full texts and retracted papers, pinned from PMC | Quotes, titles and retractions verified against pinned bytes |
|
|
275
|
+
| [ClinVar germline, three years later](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/examples/clinvar_germline/README.md) | 5,026 variants from the 2023-09 release, followed to 2026-09 | The profile reproduces NCBI's review status in 98–99% of decisions; held-back variants were less stable; a closed trust boundary |
|
|
276
|
+
| [VBO canine name mapping](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/examples/vbo_canine/README.md) | A pinned public ontology release | 0 of 160 controlled faults and 0 of 48 forged sources admitted |
|
|
277
|
+
|
|
278
|
+

|
|
279
|
+
|
|
280
|
+
## Limits
|
|
281
|
+
|
|
282
|
+
- **Admission is not truth.** It means the record meets the selected profile: its evidence exists in the
|
|
283
|
+
pinned sources and satisfies the use's rules. It does not mean the biological claim is true.
|
|
284
|
+
- **The references are curators' and authors' labels, not independent expert labels.** A blinded
|
|
285
|
+
[expert-review kit](https://github.com/NingyuSUN/bioai-evidence-validator/tree/main/evaluation/clinvar_review)
|
|
286
|
+
is ready (#23).
|
|
287
|
+
- **Sample sizes are small.** The literature benchmarks are pilot-scale (18 claims). Each single-cell split
|
|
288
|
+
was run once.
|
|
289
|
+
- **Not for clinical use.**
|
|
290
|
+
|
|
291
|
+
## Roadmap
|
|
292
|
+
|
|
293
|
+
Tracked in the [AI validation roadmap](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/docs/AI_VALIDATION_ROADMAP.md) (#26):
|
|
294
|
+
- expert review of the benchmark cases (#23);
|
|
295
|
+
- calibrated triage and audit sampling of admitted records, to measure what still gets through (#24);
|
|
296
|
+
- one-command reproduction of every benchmark, a funnel figure, and a validation dossier for release
|
|
297
|
+
0.8.0 (#25).
|
|
298
|
+
|
|
299
|
+
## Contributing and citing
|
|
300
|
+
|
|
301
|
+
Bug reports, domain profiles and new benchmarks are welcome. See
|
|
302
|
+
[CONTRIBUTING.md](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/CONTRIBUTING.md) and
|
|
303
|
+
issues labelled [`good first issue`](https://github.com/NingyuSUN/bioai-evidence-validator/labels/good%20first%20issue);
|
|
304
|
+
report security problems as described in [SECURITY.md](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/SECURITY.md).
|
|
305
|
+
To cite this toolkit, use [`CITATION.cff`](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/CITATION.cff)
|
|
306
|
+
(GitHub's "Cite this repository" button).
|
|
307
|
+
|
|
308
|
+
Author: Ningyu Sun ([@NingyuSUN](https://github.com/NingyuSUN)) ·
|
|
309
|
+
[Changelog](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/CHANGELOG.md) ·
|
|
310
|
+
[Standards alignment](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/docs/STANDARDS.md) ·
|
|
311
|
+
[Error taxonomy](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/docs/ERROR_TAXONOMY.md) ·
|
|
312
|
+
[Design case study](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/docs/CASE_STUDY.md) ·
|
|
313
|
+
[Apache-2.0](https://github.com/NingyuSUN/bioai-evidence-validator/blob/main/LICENSE)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
bioevidence_validator/__init__.py,sha256=ySYhSIndHmprgYmGFhUkKdwPKjjqa2bIQe02tE9XsTs,312
|
|
2
|
+
bioevidence_validator/cli.py,sha256=CT3ENJzhAsLhIEKuq3NIDOu72FD8RjLggTDh0gLWDhg,13827
|
|
3
|
+
bioevidence_validator/config.py,sha256=Ahc9eRPNR_ArqnbnJkdZsPFq9yERTYied0oGwUkANYI,1110
|
|
4
|
+
bioevidence_validator/crosscheck.py,sha256=1a50ydC3Ts9ug6IiUQYyVa295m4u8Q0FUwc7t6bhmFc,5550
|
|
5
|
+
bioevidence_validator/definitions.py,sha256=M4j7-diD09ZcebktOnKvhxYBFL8VE2NMMgD4-f2cewk,7298
|
|
6
|
+
bioevidence_validator/draft.py,sha256=2ge9l1BA44e-_ukO_Nnz9UZAV_RS8yqj3Ujr86eFxtY,13631
|
|
7
|
+
bioevidence_validator/engine.py,sha256=lBK6oobvpWL0oeSu_-VnYOM9xGaA8R4WLbPtjakPEiM,18386
|
|
8
|
+
bioevidence_validator/feedback.py,sha256=xIPMKpd6_o0FSe7ARGxovtGDa1hZVDgoYQWhYIABhxk,7131
|
|
9
|
+
bioevidence_validator/grounding.py,sha256=6_4Jb-bUCqepkerARhJS4BU2TvNS5QcZkSrdwI-S6RU,5087
|
|
10
|
+
bioevidence_validator/identifiers.py,sha256=zx9rX5L5Eq76XYwEdaAtw8AZ_BhU1C9w2UqSxywtf9I,20334
|
|
11
|
+
bioevidence_validator/literature.py,sha256=FT7Db04pMcRC-2XzHrEGtQw555g5mb-o9VyiES-qv5w,20205
|
|
12
|
+
bioevidence_validator/review.py,sha256=yp9DI2TafTiZqZmNTejtUb9oHeeXPEjZHXx3fe2qCGI,20293
|
|
13
|
+
bioevidence_validator/semantic.py,sha256=yrT4xtbUhnnfso_6_PlLfj1tNpULJTlz_YkT0Ve3GKE,3899
|
|
14
|
+
bioevidence_validator/tables.py,sha256=kzpWd1fgex4NedAy-fcaa8Q8B22WkiWvSG4_EK_S3nw,5755
|
|
15
|
+
bioevidence_validator/profiles/dataset-label.yaml,sha256=4utz9YcFFF2UnaLjIb0ATb-27hF8Smw7zmv0sBTaQdM,843
|
|
16
|
+
bioevidence_validator/profiles/general.yaml,sha256=i9fJCWovJZ2e2d4rbn0Bx7mrhumNb2zjS9TOarkBWZw,778
|
|
17
|
+
bioevidence_validator/profiles/literature-claim.yaml,sha256=7l82gX3oGGyYFq9B29-1qGXeL4LRcMhJi8Y9fieVE0c,612
|
|
18
|
+
bioevidence_validator/schema/bioevidence_core.yaml,sha256=c2YIBOhuT6v7j4MDsMScImdyLZCMy-3X--ExCB_IYu8,7514
|
|
19
|
+
bioai_evidence_validator-0.8.0.dist-info/METADATA,sha256=XS5JdGEGY4NDEb7P_nhLolRat7Utp_OOAauhC3FysUI,20605
|
|
20
|
+
bioai_evidence_validator-0.8.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
21
|
+
bioai_evidence_validator-0.8.0.dist-info/entry_points.txt,sha256=6oufzT2x1nIhTqM5B6y4aWubExKAoFb_wXXTdz3mBQQ,63
|
|
22
|
+
bioai_evidence_validator-0.8.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
23
|
+
bioai_evidence_validator-0.8.0.dist-info/RECORD,,
|
bioevidence_validator/cli.py
CHANGED
|
@@ -9,8 +9,12 @@ from pathlib import Path
|
|
|
9
9
|
|
|
10
10
|
import yaml
|
|
11
11
|
|
|
12
|
+
from . import review as review_module
|
|
12
13
|
from .draft import build_record, draft_json_schema, load_draft
|
|
13
|
-
from .engine import default_schema_path, generate_json_schema,
|
|
14
|
+
from .engine import default_schema_path, generate_json_schema, list_profiles, profile_path, validate_record
|
|
15
|
+
from .grounding import SnapshotStore, SourceBytesGrounder
|
|
16
|
+
from .identifiers import Assemblies, GeneGrounder, Genes, Ontology, OntologyGrounder, VariantGrounder
|
|
17
|
+
from .literature import CATALOG, LiteratureGrounder, ground_record, http_fetch
|
|
14
18
|
|
|
15
19
|
|
|
16
20
|
def parser() -> argparse.ArgumentParser:
|
|
@@ -21,6 +25,26 @@ def parser() -> argparse.ArgumentParser:
|
|
|
21
25
|
validate.add_argument("--output", type=Path)
|
|
22
26
|
validate.add_argument("--schema", type=Path, default=default_schema_path())
|
|
23
27
|
validate.add_argument("--profile", default="general", help="Built-in profile name or YAML file path")
|
|
28
|
+
validate.add_argument("--snapshot-dir", type=Path,
|
|
29
|
+
help="Directory of source snapshots named by SHA-256; recompute source hashes from them, "
|
|
30
|
+
"and check cited publications if it holds a literature.json from `ground`")
|
|
31
|
+
validate.add_argument("--ontology", type=Path, action="append", default=[],
|
|
32
|
+
help="A pinned OBO release; check the ontology terms the record cites (repeatable)")
|
|
33
|
+
validate.add_argument("--term-root", action="append", default=[], metavar="KIND=CURIE",
|
|
34
|
+
help="Terms for this entity type or locator key must descend from CURIE, e.g. "
|
|
35
|
+
"cell_type=CL:0000000 (repeatable)")
|
|
36
|
+
validate.add_argument("--genes", type=Path, help="A pinned HGNC complete set (TSV); check human gene symbols")
|
|
37
|
+
validate.add_argument("--assembly-report", type=Path, action="append", default=[],
|
|
38
|
+
help="A pinned NCBI assembly report; check HGVS variants and genome builds (repeatable)")
|
|
39
|
+
ground = commands.add_parser("ground", help="Resolve cited publications and pin their metadata and open-access "
|
|
40
|
+
"full text (uses the network)")
|
|
41
|
+
ground.add_argument("input", type=Path)
|
|
42
|
+
ground.add_argument("--snapshot-dir", type=Path, required=True)
|
|
43
|
+
ground.add_argument("--output", type=Path, required=True, help="The record with source hashes pinned")
|
|
44
|
+
ground.add_argument("--email", help="Contact address for the resolvers' User-Agent (polite use)")
|
|
45
|
+
ground.add_argument("--refresh", action="store_true", help="Resolve again even if already in the catalog")
|
|
46
|
+
ground.add_argument("--resolver", choices=["europepmc", "ncbi"], default="europepmc",
|
|
47
|
+
help="Europe PMC (with Crossref for DOIs) or NCBI E-utilities")
|
|
24
48
|
build = commands.add_parser("build", help="Expand a compact YAML/JSON draft into a full record")
|
|
25
49
|
build.add_argument("draft", type=Path)
|
|
26
50
|
build.add_argument("--output", type=Path)
|
|
@@ -31,6 +55,36 @@ def parser() -> argparse.ArgumentParser:
|
|
|
31
55
|
generate.add_argument("--output", type=Path, required=True)
|
|
32
56
|
generate.add_argument("--schema", type=Path, default=default_schema_path())
|
|
33
57
|
commands.add_parser("profiles", help="List built-in profiles and their use contracts")
|
|
58
|
+
|
|
59
|
+
review = commands.add_parser("review", help="Independent human review: agreement, adjudication, scoring")
|
|
60
|
+
steps = review.add_subparsers(dest="step", required=True)
|
|
61
|
+
check = steps.add_parser("check", help="Check annotations (and adjudications) against the protocol format")
|
|
62
|
+
check.add_argument("annotations", type=Path)
|
|
63
|
+
check.add_argument("--adjudications", type=Path)
|
|
64
|
+
agree = steps.add_parser("agreement", help="Inter-reviewer agreement per use, before adjudication")
|
|
65
|
+
agree.add_argument("annotations", type=Path)
|
|
66
|
+
agree.add_argument("--output", type=Path)
|
|
67
|
+
sheet = steps.add_parser("adjudication-sheet", help="Blank adjudication rows for every disagreement")
|
|
68
|
+
sheet.add_argument("annotations", type=Path)
|
|
69
|
+
sheet.add_argument("--output", type=Path, required=True)
|
|
70
|
+
sheet.add_argument("--min-reviewers", type=int, default=2)
|
|
71
|
+
scoring = steps.add_parser("score", help="Compare predictions with the resolved reference labels")
|
|
72
|
+
scoring.add_argument("--annotations", type=Path, required=True)
|
|
73
|
+
scoring.add_argument("--adjudications", type=Path, required=True)
|
|
74
|
+
scoring.add_argument("--predictions", type=Path, required=True)
|
|
75
|
+
scoring.add_argument("--split", default="test", choices=sorted(review_module.SPLITS))
|
|
76
|
+
scoring.add_argument("--min-reviewers", type=int, default=2)
|
|
77
|
+
scoring.add_argument("--output", type=Path)
|
|
78
|
+
frozen = steps.add_parser("freeze", help="Write a frozen manifest for a completed reference set")
|
|
79
|
+
frozen.add_argument("--manifest", type=Path, required=True, help="Draft manifest to complete")
|
|
80
|
+
frozen.add_argument("--annotations", type=Path, required=True)
|
|
81
|
+
frozen.add_argument("--adjudications", type=Path, required=True)
|
|
82
|
+
frozen.add_argument("--file", type=Path, action="append", default=[], help="Extra file to hash (repeatable)")
|
|
83
|
+
frozen.add_argument("--dataset-id", required=True)
|
|
84
|
+
frozen.add_argument("--version", required=True)
|
|
85
|
+
frozen.add_argument("--frozen-at", required=True, help="ISO 8601 time of the freeze")
|
|
86
|
+
frozen.add_argument("--min-reviewers", type=int, default=2)
|
|
87
|
+
frozen.add_argument("--output", type=Path, required=True)
|
|
34
88
|
return result
|
|
35
89
|
|
|
36
90
|
|
|
@@ -88,6 +142,9 @@ def _run(args) -> int:
|
|
|
88
142
|
print(json.dumps(list_profiles(), indent=2))
|
|
89
143
|
return 0
|
|
90
144
|
|
|
145
|
+
if args.command == "review":
|
|
146
|
+
return _review(args)
|
|
147
|
+
|
|
91
148
|
if args.command in {"build", "draft-schema"}:
|
|
92
149
|
if args.command == "build":
|
|
93
150
|
if args.output and args.output.resolve() == args.draft.resolve():
|
|
@@ -103,6 +160,18 @@ def _run(args) -> int:
|
|
|
103
160
|
print(json.dumps(result, indent=2))
|
|
104
161
|
return 0
|
|
105
162
|
|
|
163
|
+
if args.command == "ground":
|
|
164
|
+
if args.output.resolve() == args.input.resolve():
|
|
165
|
+
raise ValueError("Output must not overwrite the input record")
|
|
166
|
+
record = json.loads(args.input.read_text(encoding="utf-8"),
|
|
167
|
+
object_pairs_hook=_unique_object, parse_constant=_invalid_constant)
|
|
168
|
+
_check_depth(record)
|
|
169
|
+
grounded, catalog = ground_record(record, args.snapshot_dir, http_fetch(args.email), refresh=args.refresh,
|
|
170
|
+
resolver=args.resolver)
|
|
171
|
+
_write_json(args.output, grounded)
|
|
172
|
+
print(f"{len(catalog['works'])} publication(s) in {args.snapshot_dir / CATALOG}")
|
|
173
|
+
return 0
|
|
174
|
+
|
|
106
175
|
selected_profile = profile_path(args.profile)
|
|
107
176
|
protected = [args.input, args.schema, selected_profile, default_schema_path()]
|
|
108
177
|
if args.output and args.output.resolve() in {p.resolve() for p in protected}:
|
|
@@ -110,7 +179,25 @@ def _run(args) -> int:
|
|
|
110
179
|
record = json.loads(args.input.read_text(encoding="utf-8"),
|
|
111
180
|
object_pairs_hook=_unique_object, parse_constant=_invalid_constant)
|
|
112
181
|
_check_depth(record)
|
|
113
|
-
|
|
182
|
+
grounders: list = []
|
|
183
|
+
if args.snapshot_dir:
|
|
184
|
+
grounders.append(SourceBytesGrounder(SnapshotStore.from_directory(args.snapshot_dir)))
|
|
185
|
+
if (args.snapshot_dir / CATALOG).exists():
|
|
186
|
+
grounders.append(LiteratureGrounder.from_directory(args.snapshot_dir))
|
|
187
|
+
if args.ontology:
|
|
188
|
+
roots: dict[str, list[str]] = {}
|
|
189
|
+
for rule in args.term_root:
|
|
190
|
+
kind, _, curie = rule.partition("=")
|
|
191
|
+
if not kind or not curie:
|
|
192
|
+
raise ValueError(f"--term-root must be KIND=CURIE, not {rule!r}")
|
|
193
|
+
roots.setdefault(kind, []).append(curie)
|
|
194
|
+
grounders.append(OntologyGrounder([Ontology.from_obo(path.read_bytes()) for path in args.ontology], roots,
|
|
195
|
+
locator_keys=list(roots)))
|
|
196
|
+
if args.genes:
|
|
197
|
+
grounders.append(GeneGrounder(Genes.from_hgnc(args.genes.read_bytes(), args.genes.name)))
|
|
198
|
+
if args.assembly_report:
|
|
199
|
+
grounders.append(VariantGrounder(Assemblies.from_reports(path.read_bytes() for path in args.assembly_report)))
|
|
200
|
+
report = validate_record(record, schema_path=args.schema, profile=args.profile, grounders=grounders)
|
|
114
201
|
rendered = json.dumps(report, indent=2) + "\n"
|
|
115
202
|
if args.output:
|
|
116
203
|
_write_json(args.output, report)
|
|
@@ -123,6 +210,48 @@ def _run(args) -> int:
|
|
|
123
210
|
return 0
|
|
124
211
|
|
|
125
212
|
|
|
213
|
+
def _review(args) -> int:
|
|
214
|
+
rv = review_module
|
|
215
|
+
annotations = rv.load_annotations(args.annotations)
|
|
216
|
+
if args.step == "check":
|
|
217
|
+
adjudications = rv.load_adjudications(args.adjudications, annotations) if args.adjudications else []
|
|
218
|
+
units = {(a["case_id"], a["requested_use"]) for a in annotations}
|
|
219
|
+
print(f"OK: {len(annotations)} annotations, {len(units)} case-use units, "
|
|
220
|
+
f"{len({a['reviewer_id'] for a in annotations})} reviewers, {len(adjudications)} adjudications")
|
|
221
|
+
return 0
|
|
222
|
+
if args.step == "agreement":
|
|
223
|
+
report = rv.agreement(annotations)
|
|
224
|
+
if args.output:
|
|
225
|
+
_write_json(args.output, report)
|
|
226
|
+
print(rv.render_agreement(report), end="")
|
|
227
|
+
return 0
|
|
228
|
+
if args.step == "adjudication-sheet":
|
|
229
|
+
if args.output.exists():
|
|
230
|
+
raise ValueError(f"{args.output} exists; refusing to overwrite adjudication work")
|
|
231
|
+
rows, incomplete = rv.adjudication_sheet(annotations, min_reviewers=args.min_reviewers)
|
|
232
|
+
rv.write_csv(args.output, rows, rv.ADJUDICATION_COLUMNS)
|
|
233
|
+
print(f"{len(rows)} disagreement(s) to adjudicate; {len(incomplete)} unit(s) with too few reviews")
|
|
234
|
+
return 0
|
|
235
|
+
adjudications = rv.load_adjudications(args.adjudications, annotations)
|
|
236
|
+
final = rv.resolve(annotations, adjudications, min_reviewers=args.min_reviewers)
|
|
237
|
+
if args.step == "score":
|
|
238
|
+
report = rv.score(final, rv.load_predictions(args.predictions), split=args.split)
|
|
239
|
+
if args.output:
|
|
240
|
+
_write_json(args.output, report)
|
|
241
|
+
print(rv.render_score(report), end="")
|
|
242
|
+
return 0
|
|
243
|
+
manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
|
|
244
|
+
files = [args.annotations, args.adjudications, *args.file]
|
|
245
|
+
if args.output.resolve() in {f.resolve() for f in [args.manifest, *files]}:
|
|
246
|
+
raise ValueError("Output must not overwrite an input")
|
|
247
|
+
frozen = rv.freeze(manifest, final, annotations, files, dataset_id=args.dataset_id,
|
|
248
|
+
version=args.version, frozen_at=args.frozen_at)
|
|
249
|
+
_write_json(args.output, frozen)
|
|
250
|
+
print(f"Frozen {frozen['reviewed_case_use_count']} case-use labels from "
|
|
251
|
+
f"{frozen['independent_human_reviewer_count']} reviewers ({frozen['reference_type']})")
|
|
252
|
+
return 0
|
|
253
|
+
|
|
254
|
+
|
|
126
255
|
def main(argv: list[str] | None = None) -> int:
|
|
127
256
|
args = parser().parse_args(argv)
|
|
128
257
|
try:
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Cross-check against a pinned reference resource: what a curated reference contradicts goes to an expert.
|
|
2
|
+
|
|
3
|
+
Grounding checks a record against the sources it cites. A reference resource is a second, independent
|
|
4
|
+
source the record does not cite: a knowledge base of curated assertions. Where it disagrees, the record is
|
|
5
|
+
not wrong on that ground alone (the reference can be out of date, and its coverage is partial), so the
|
|
6
|
+
finding sends the record to review (BEV025) and never rejects it. Silence of the reference is not support.
|
|
7
|
+
|
|
8
|
+
Assertions are rows with `subject`, `predicate` and `object` (optionally `subject_label`, `object_label`),
|
|
9
|
+
e.g. a CIViC-style `BRAF V600E | does_not_support_sensitivity | vemurafenib in X`, or a marker table
|
|
10
|
+
`CD19 | marker_of | CL:0000236`. Two checks:
|
|
11
|
+
|
|
12
|
+
- statement: the reference asserts the opposite predicate for the same subject and object (`opposites`
|
|
13
|
+
maps each predicate to its opposite);
|
|
14
|
+
- evidence: supporting evidence names an entity in its locator (`evidence_key`, e.g. `gene=CD19`) that the
|
|
15
|
+
reference relates (`relation`, e.g. `marker_of`) only to objects that conflict with the statement's object.
|
|
16
|
+
With `conflict="unrelated"` (the default), an object conflicts unless it is the same term or, with an
|
|
17
|
+
ontology, an ancestor or descendant of it (a B cell marker supports "naive B cell"). With
|
|
18
|
+
`conflict="disjoint"`, an object conflicts only when the ontology declares the two disjoint (`disjoint_from`
|
|
19
|
+
on them or their ancestors, e.g. T cell and B cell): a marker the reference lists for a sibling type is not a
|
|
20
|
+
conflict, and where the ontology declares nothing, nothing is reported.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import csv
|
|
25
|
+
import io
|
|
26
|
+
from collections.abc import Iterable
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from .engine import Finding
|
|
30
|
+
from .grounding import finding
|
|
31
|
+
from .identifiers import Ontology, pairs
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ReferenceGrounder:
|
|
35
|
+
def __init__(self, assertions: Iterable[dict[str, str]], *, label: str, opposites: dict[str, str] | None = None,
|
|
36
|
+
evidence_key: str | None = None, relation: str | None = None, ontology: Ontology | None = None,
|
|
37
|
+
conflict: str = "unrelated"):
|
|
38
|
+
if conflict not in ("unrelated", "disjoint") or (conflict == "disjoint" and ontology is None):
|
|
39
|
+
raise ValueError("conflict must be 'unrelated', or 'disjoint' with an ontology")
|
|
40
|
+
self.conflict = conflict
|
|
41
|
+
self.assertions = list(assertions)
|
|
42
|
+
self.label, self.ontology = label, ontology
|
|
43
|
+
self.opposites = dict(opposites or {})
|
|
44
|
+
self.opposites.update({v: k for k, v in self.opposites.items()})
|
|
45
|
+
self.key, self.relation = evidence_key, relation
|
|
46
|
+
self.name = f"reference:{label}"
|
|
47
|
+
self._pairs: dict[tuple[str, str], list[dict[str, str]]] = {}
|
|
48
|
+
self._objects: dict[str, list[dict[str, str]]] = {}
|
|
49
|
+
for row in self.assertions:
|
|
50
|
+
self._pairs.setdefault((row["subject"], row["object"]), []).append(row)
|
|
51
|
+
if row["predicate"] == relation:
|
|
52
|
+
self._objects.setdefault(row["subject"], []).append(row)
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def from_table(cls, data: bytes, **options: Any) -> ReferenceGrounder:
|
|
56
|
+
text = data.decode("utf-8")
|
|
57
|
+
delimiter = "\t" if "\t" in text.partition("\n")[0] else ","
|
|
58
|
+
return cls(csv.DictReader(io.StringIO(text), delimiter=delimiter), **options)
|
|
59
|
+
|
|
60
|
+
def _conflicts(self, a: str, b: str) -> bool:
|
|
61
|
+
if self.conflict == "disjoint":
|
|
62
|
+
return bool(self.ontology and self.ontology.disjoint(a, b))
|
|
63
|
+
return not (a == b or bool(self.ontology and self.ontology.related(a, b)))
|
|
64
|
+
|
|
65
|
+
def _name(self, row: dict[str, str]) -> str:
|
|
66
|
+
return f"{row['object']} ({row['object_label']})" if row.get("object_label") else row["object"]
|
|
67
|
+
|
|
68
|
+
def check(self, record: dict[str, Any]) -> list[Finding]:
|
|
69
|
+
statement = record["statement"]
|
|
70
|
+
subject, predicate, target = statement["subject"]["id"], statement["predicate"], statement["object"]["id"]
|
|
71
|
+
out = []
|
|
72
|
+
for row in self._pairs.get((subject, target), []):
|
|
73
|
+
if self.opposites.get(row["predicate"]) == predicate:
|
|
74
|
+
out.append(finding(record, "BEV025", f"The {self.label} reference records {subject} {row['predicate']} "
|
|
75
|
+
f"{target}, the opposite of this claim.", "$.statement.predicate"))
|
|
76
|
+
if not self.key:
|
|
77
|
+
return out
|
|
78
|
+
supporting = {i for line in statement["evidence_lines"] if line["direction"] == "supports"
|
|
79
|
+
for i in line["evidence_item_ids"]}
|
|
80
|
+
for index, item in enumerate(record["evidence_items"]):
|
|
81
|
+
entity = pairs(item["locator"]).get(self.key)
|
|
82
|
+
rows = self._objects.get(entity or "", [])
|
|
83
|
+
if item["id"] not in supporting or not rows or not all(self._conflicts(r["object"], target) for r in rows):
|
|
84
|
+
continue
|
|
85
|
+
names = sorted({self._name(r) for r in rows})
|
|
86
|
+
more = f" and {len(names) - 3} more" if len(names) > 3 else ""
|
|
87
|
+
out.append(finding(record, "BEV025", f"The {self.label} reference lists {entity} as a {(self.relation or '').replace('_', ' ')} "
|
|
88
|
+
f"{'; '.join(names[:3])}{more}, "
|
|
89
|
+
+ (f"cell types disjoint from {target}." if self.conflict == "disjoint"
|
|
90
|
+
else f"not of {target} or a related term."),
|
|
91
|
+
f"$.evidence_items[{index}].locator"))
|
|
92
|
+
return out
|