K-Dense-AI/scientific-agent-skills / skills/ontology-term-resolution
ontology-term-resolution
VerifiedResolves free-text scientific labels to ontology term IDs and validates existing CURIEs against the EBI Ontology Lookup Service (OLS4). Also looks up prefixes in Bioregistry, resolves compact identifiers via Identifiers.org, maps lab shorthand with ZOOMA, and builds Ontobee term pages. Use whenever an ontology identifier must be produced or checked - annotating tissue, cell type, disease, phenotype, assay, chemical, organism, sex, or developmental stage fields; preparing metadata for GEO, ENA, BioSamples, CELLxGENE, HCA, or ISA-Tab submission; auditing a metadata table of term IDs; checking whether a term is obsolete and what replaced it; or deciding HPO vs HP. Triggers include "ontology term", "ontology ID", "CURIE", "controlled vocabulary", "UBERON", "CL:", "MONDO", "HPO", "EFO", "ChEBI", "NCBITaxon", "GO term", "PATO", "Zooma", "Bioregistry", "Identifiers.org", "Ontobee", "annotate this tissue/cell type/disease", and any request to emit or verify an identifier shaped like PREFIX:0001234.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 14.3 KB |
| references/companion-apis.md | markdown | 9.4 KB |
| references/curation-rules.md | markdown | 5.9 KB |
| references/ols4-api.md | markdown | 7.5 KB |
| references/ontology-registry.md | markdown | 6.1 KB |
| scripts/id_client.py | script | 11.5 KB |
| scripts/lookup_prefix.py | script | 6.3 KB |
| scripts/map_terms.py | script | 7.3 KB |
| scripts/ols_client.py | script | 15.5 KB |
| scripts/resolve_terms.py | script | 8.3 KB |
| scripts/validate_terms.py | script | 10.7 KB |
| scripts/zooma_client.py | script | 5.2 KB |
scripts/zooma_client.py
View on GitHub#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""EBI ZOOMA annotate client.
ZOOMA maps free text to ontology IRIs using curated annotation history. It is
a fallback when OLS lexical search fails on lab shorthand (``PBMC``, ``WT``),
not a replacement for OLS.
Unfiltered annotate is unusable — ``propertyValue=liver`` returns FOODON,
XAO, BTO, and UBERON as equally HIGH hits. Always pass an ontology filter.
Standard library only. Reuses ``iri_to_curie`` from ``ols_client`` so IRI
shapes stay consistent with the rest of the skill.
"""
from __future__ import annotations
import json
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any
from ols_client import iri_to_curie
ZOOMA_ANNOTATE = "https://www.ebi.ac.uk/spot/zooma/v2/api/services/annotate"
USER_AGENT = "scientific-agent-skills-ontology-term-resolution/1.4"
TIMEOUT = 60
MAX_ATTEMPTS = 3
RETRY_STATUS = {429, 500, 502, 503, 504}
# Legacy output field ``safe`` means this confidence bucket only. Neither HIGH
# nor GOOD proves semantic equivalence, curation, currency or correct context.
SAFE_CONFIDENCE = {"HIGH", "GOOD"}
class ZoomaError(RuntimeError):
"""A request to ZOOMA failed in a way the caller cannot paper over."""
def ontology_filter(ontologies: list[str]) -> str:
"""Build the ``filter`` query value ZOOMA requires.
Empty required sources permit all curated sources. Ontology ids are
lowercase OLS ids (``uberon``, ``cl``); defining_only excludes imports.
"""
ids = ",".join(item.strip().lower() for item in ontologies if item.strip())
if not ids:
raise ZoomaError("ZOOMA annotate requires at least one ontology id")
if "none" in ids.split(","):
raise ZoomaError("'none' removes the server's ontology restriction; use a real ontology id")
if any(not item or not all(c.isalnum() or c in "_.-" for c in item) for item in ids.split(",")):
raise ZoomaError("invalid OLS ontology id")
return f"ontologies:[{ids}],defining_only:[true]"
def annotate(
text: str,
*,
ontologies: list[str],
property_type: str | None = None,
) -> list[dict]:
"""Call ``/annotate`` and return the raw hit list.
``ontologies`` is required. Calling this without a filter is how you get
``FOODON:03309772`` for ``liver``.
"""
params: dict[str, Any] = {
"propertyValue": text,
"filter": ontology_filter(ontologies),
}
if property_type:
params["propertyType"] = property_type
url = f"{ZOOMA_ANNOTATE}?{urllib.parse.urlencode(params)}"
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
last: Exception | None = None
for attempt in range(MAX_ATTEMPTS):
try:
with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
payload = json.load(response)
if not isinstance(payload, list):
raise ZoomaError(f"ZOOMA returned a non-list body for {text!r}")
return payload
except urllib.error.HTTPError as exc:
last = exc
if exc.code not in RETRY_STATUS:
raise ZoomaError(f"ZOOMA HTTP {exc.code} for {text!r}") from exc
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
last = exc
if attempt < MAX_ATTEMPTS - 1:
time.sleep(1.5 * (attempt + 1))
raise ZoomaError(f"ZOOMA request failed after {MAX_ATTEMPTS} attempts: {url} ({last})")
def flatten_hit(hit: dict) -> list[dict]:
"""Turn one ZOOMA annotation into one row per semantic tag."""
confidence = (hit.get("confidence") or "").upper()
prop = hit.get("annotatedProperty") or {}
chain = []
origin = hit
while isinstance(origin, dict):
if origin.get("provenance"):
chain.append(origin["provenance"])
origin = origin.get("derivedFrom")
# The v2 compatibility wrapper always says INFERRED_FROM_CURATED, even for
# lexical or embedding hits. Report the underlying source's evidence.
provenance = chain[-1] if chain else {}
source = provenance.get("source") or {}
rows = []
tags = hit.get("semanticTags") or []
if not tags:
return [
{
"iri": "",
"curie": "",
"confidence": confidence or "UNKNOWN",
"safe": False,
"evidence": provenance.get("evidence") or "",
"source": source.get("name") or "",
"property_type": prop.get("propertyType") or "",
"property_value": prop.get("propertyValue") or "",
"provenance_chain": chain,
}
]
for iri in tags:
iri = str(iri)
rows.append(
{
"iri": iri,
"curie": iri_to_curie(iri) or "",
"confidence": confidence or "UNKNOWN",
"safe": confidence in SAFE_CONFIDENCE,
"evidence": provenance.get("evidence") or "",
"source": source.get("name") or "",
"property_type": prop.get("propertyType") or "",
"property_value": prop.get("propertyValue") or "",
"provenance_chain": chain,
}
)
return rows
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |