Skip to content

ontometer_corpus.steps.ontology_dates

First-evidence dates: when each ontology in the entity network is first attested.

Per release family (ontometer_corpus.versions), the earliest date any of these sources attests to:

  • d_registry — the earliest release date recorded for the family, or for any corpus row, in any registry, declaring the same ontology IRI;
  • d_archive — the Internet Archive's first capture of the ontology IRI (CDX API; ontometer_corpus.dating.archive_candidates); Ontohub rows without an IRI use their repository page;
  • d_wikidata — inception (P571) or publication date (P577) of the Wikidata item that Open Knowledge Graphs links to.

Every source is an upper bound on the birth date (see ontometer_corpus.dating); birth is their minimum and birth_source names the source that set it. The network sources are queried once and cached in <corpus>/dating_cache.jsonl, which is tracked: the archive and Wikidata can change their answers, so the cache is the record that makes the table reproducible. With it, --offline rebuilds the same table without the network.

Reads: <corpus>/corpus.db and $ONTOMETER_STORE/cache/entity_ontologies.parquet. Writes: <corpus>/ontology_dates.parquet, one row per release family, and appends new lookups to <corpus>/dating_cache.jsonl. Runs after: ontometer-corpus entity-network. Needs --store (or $ONTOMETER_STORE).

Usage

ontometer-corpus dates --store /path/to/ontologies ontometer-corpus dates --store /path/to/ontologies --offline

An online run that cannot finish its lookups writes nothing and exits 75; rerun to resume. --offline --allow-uncached builds from the cache alone and marks families with absent lookups lookups_complete = False.

Attributes

CDX_URL = 'https://web.archive.org/cdx/search/cdx' module-attribute

WIKIDATA_SPARQL = 'https://query.wikidata.org/sparql' module-attribute

USER_AGENT = 'ontometer-corpus (+https://github.com/growgraph/ontometer-corpus)' module-attribute

EXIT_INCOMPLETE = 75 module-attribute

Classes

Functions:

build(paths, offline, workers, delay, allow_uncached=False)

Write ontology_dates.parquet; False when archive lookups are incomplete.

Source code in ontometer_corpus/steps/ontology_dates.py
def build(
    paths: CorpusPaths,
    offline: bool,
    workers: int,
    delay: float,
    allow_uncached: bool = False,
) -> bool:
    """Write ``ontology_dates.parquet``; False when archive lookups are incomplete."""
    conn = sqlite3.connect(str(paths.db_path))
    # The latest plausible date is the corpus capture date, not the day the
    # script runs, so the same corpus and cache always give the same table.
    today = conn.execute(
        "SELECT substr(MAX(retrieval_date), 1, 10) FROM corpus_registry"
    ).fetchone()[0]
    rows = pd.read_sql(
        "SELECT source_id, source_registry, ontology_iri, source_registry_metadata, shared_iri "
        "FROM corpus_registry",
        conn,
    )
    conn.close()
    rows["family"] = rows.source_id.map(family_key)
    # An IRI shared by distinct ontologies (dedup's shared_iri) links none of
    # them to the others' releases.
    rows["iri_n"] = rows.ontology_iri.where(rows.shared_iri.fillna(0) == 0).map(iri_match_key)
    rows["d"] = [plausible(release_date(m), today) for m in rows.source_registry_metadata]

    onts = pd.read_parquet(paths.cache_dir / "entity_ontologies.parquet")
    fam_rows = rows[rows.family.isin(set(onts.family))]

    # Registry: the family's own releases, and every row sharing one of its IRIs.
    by_iri = rows.dropna(subset=["iri_n", "d"]).groupby("iri_n").d.min()
    fam_iris = fam_rows.dropna(subset=["iri_n"]).groupby("family").iri_n.agg(set)
    fam_min = fam_rows.dropna(subset=["d"]).groupby("family").d.min()
    d_registry = {
        f: earliest([fam_min.get(f), *(by_iri.get(i) for i in fam_iris.get(f, ()))])
        for f in onts.family
    }

    # Archive candidates: every IRI of the family; Ontohub repository pages.
    targets: dict[str, list[str]] = {}
    for f in onts.family:
        urls = [u for i in sorted(fam_iris.get(f, ())) for u in archive_candidates(i)]
        if not urls and f.startswith("ontohub:"):
            repo = f.split(":", 1)[1].split("/", 1)[0]
            urls = [f"ontohub.org/{repo}"]
        targets[f] = urls
    qids = {
        f: q
        for f, q in (
            (r.family, _qid(r.source_id, r.source_registry_metadata)) for r in fam_rows.itertuples()
        )
        if q
    }

    paths.cache_dir.mkdir(parents=True, exist_ok=True)
    cache = _Cache(paths.corpus_dir / _CACHE_FILE)
    complete = True
    uncached: set[str] = set()
    if offline:
        if allow_uncached:
            uncached = _uncached_families(targets, qids, cache)
            print(
                f"offline: {len(uncached)} families have lookups absent from the cache "
                "(no evidence from those sources)"
            )
        else:
            _require_cached(
                cache,
                [f"cdx:{u}" for urls in targets.values() for u in urls]
                + [f"wd:{q}" for q in qids.values()],
            )
        d_archive = {
            f: earliest(plausible(cache.get(f"cdx:{u}")[1], today) for u in urls)
            for f, urls in targets.items()
        }
        d_wiki = {f: plausible(cache.get(f"wd:{q}")[1], today) for f, q in qids.items()}
    else:
        d_wiki = _wikidata_dates(qids, cache, today)
        undated = {f for f, d in d_registry.items() if d is None}
        complete, d_archive = _archive_dates(targets, cache, workers, delay, today, first=undated)
    if not complete:
        # A partial table would silently replace the last complete one; the
        # lookups made so far are cached, so the next run resumes.
        print(f"Not writing {paths.ontology_dates_path}: archive lookups incomplete")
        return False

    out = onts[["family", "registry", "ontology_iri"]].drop_duplicates("family").copy()
    out["d_registry"] = out.family.map(d_registry)
    out["d_archive"] = out.family.map(d_archive)
    out["d_wikidata"] = out.family.map(d_wiki)
    sources = ["d_registry", "d_archive", "d_wikidata"]
    out["birth"] = [earliest(vals) for vals in out[sources].itertuples(index=False)]
    first = out[sources].fillna("9999-12-31").to_numpy().argmin(axis=1)
    out["birth_source"] = pd.Series([sources[i][2:] for i in first], index=out.index).where(
        out.birth.notna()
    )
    out["n_sources"] = out[sources].notna().sum(axis=1)
    out["as_of"] = today  # the capture date the dates are bounded by
    # False where a lookup was absent from the cache (--offline --allow-uncached).
    out["lookups_complete"] = ~out.family.isin(uncached)
    target = paths.ontology_dates_path
    out.to_parquet(target, index=False)
    print(f"Wrote {target}  ({out.birth.notna().sum()}/{len(out)} families dated)")
    print(out.groupby("registry").birth.apply(lambda s: f"{s.notna().mean():.0%}").to_string())
    print(out.birth_source.value_counts().to_string())
    return True

main(offline, workers, delay, allow_uncached, paths)

First-evidence date of each ontology family.

Source code in ontometer_corpus/steps/ontology_dates.py
@click.command()
@click.option("--offline", is_flag=True, help="Use cached network lookups only.")
@click.option(
    "--workers", type=int, default=1, show_default=True, help="Concurrent archive queries."
)
@click.option(
    "--delay",
    type=float,
    default=4.0,
    show_default=True,
    help="Seconds each worker waits between queries.",
)
@click.option(
    "--allow-uncached",
    is_flag=True,
    help="With --offline: treat lookups absent from the cache as no evidence instead of failing.",
)
@corpus_paths
def main(
    offline: bool, workers: int, delay: float, allow_uncached: bool, paths: CorpusPaths
) -> None:
    """First-evidence date of each ontology family."""
    if allow_uncached and not offline:
        raise click.UsageError("--allow-uncached needs --offline")
    paths.require_store_dir()
    if not build(
        paths, offline=offline, workers=workers, delay=delay, allow_uncached=allow_uncached
    ):
        sys.exit(EXIT_INCOMPLETE)