Skip to content

ontometer_corpus.steps.entity_roles

Per-term class/instance roles and labels (abstractness, sense C).

The structural sidecars record declarations and subclass edges, which is enough for taxonomic generality but not for class-likeness: whether a term is used as a class (it types something, it fills a restriction) or as an instance (it is typed, it takes part in facts) needs the rest of the file. This pass re-reads each canonical latest-version file once.

<corpus>/corpus.db (latest-version, parsed rows) and the raw

files under $ONTOMETER_STORE/objects/; with --panel, the releases listed in $ONTOMETER_STORE/cache/panel_releases.parquet instead.

Writes, per ontology,

$ONTOMETER_STORE/cache/roles/v<N>/<hh>/<file_hash>.parquet
    record_type='role'  → (subject=term IRI, object=role name)
    record_type='label' → (subject=term IRI, object=preferred label)

plus a per-ontology coverage table, $ONTOMETER_STORE/cache/roles_summary.parquet (roles_summary_panel.parquet with --panel). Ontologies already done are skipped unless --force. Runs after: ontometer-corpus process; with --panel, after ontometer-corpus panel select. Needs --store (or $ONTOMETER_STORE).

Role names and the fact definition are documented in ontometer_corpus.roles.

Files are loaded exactly as the parse phase loads them — archive decompression, the tolerant rdflib dispatch with syntax repairs, the owlready2 fallback — so the role pass sees the same graph the sidecar came from. Files larger than the size guard once decompressed are skipped here; their declaration and subclass roles still come from the sidecar downstream, so they lose only the richer usage roles and labels.

Usage

ontometer-corpus entity-roles --store /path/to/ontologies --limit 50 ontometer-corpus entity-roles --store /path/to/ontologies --workers 10 ontometer-corpus entity-roles --store /path/to/ontologies --panel

Classes

Functions:

build(paths, limit, workers, force, panel)

Source code in ontometer_corpus/steps/entity_roles.py
def build(paths: CorpusPaths, limit: int | None, workers: int, force: bool, panel: bool) -> None:
    global _PATHS
    _PATHS = paths
    refresh_skos: set[str] = set()
    if panel:
        import pandas as pd

        sel = pd.read_parquet(paths.cache_dir / "panel_releases.parquet")
        sel = sel.drop_duplicates("file_hash").sort_values("file_hash")
        rows = list(zip(sel.file_hash, sel.retrieved_file, sel.parse_format))
    else:
        conn = sqlite3.connect(str(paths.db_path))
        db_rows = conn.execute(
            """
            SELECT file_hash, retrieved_file, parse_format, skos_concept_count
            FROM corpus_registry
            WHERE id IN (
                SELECT MIN(id) FROM corpus_registry
                WHERE is_latest_version = 1 AND parse_status = 'ok' AND file_hash IS NOT NULL
                GROUP BY file_hash)
            ORDER BY file_hash
            """
        ).fetchall()
        conn.close()
        refresh_skos = {
            file_hash
            for file_hash, _, _, n_skos in db_rows
            if (n_skos or 0) > 0
            and not _has_skos_concept_sidecar(paths.sidecar_path(file_hash))
            and not _has_skos_concept_roles(paths.roles_path(file_hash))
        }
        rows = [
            (file_hash, retrieved_file, parse_format)
            for file_hash, retrieved_file, parse_format, _ in db_rows
        ]
    if limit:
        rows = rows[:limit]

    summary_path = paths.cache_dir / (
        "roles_summary_panel.parquet" if panel else "roles_summary.parquet"
    )
    previous: dict[str, dict] = {}
    if summary_path.exists() and not force:
        import pandas as pd

        old = pd.read_parquet(summary_path)
        if "file_hash" in old:
            for rec in old.to_dict("records"):
                if (
                    rec["ok"]
                    and rec["file_hash"] not in refresh_skos
                    and paths.roles_path(rec["file_hash"]).exists()
                ):
                    previous[rec["file_hash"]] = rec

    tasks = [(h, str(paths.resolve_object(f)), fmt) for h, f, fmt in rows if h not in previous]
    print(f"{len(rows)} ontologies; {len(previous)} already done; {len(tasks)} to process")
    records = run_supervised(
        tasks,
        _process,
        _empty,
        timeout_s=_PER_FILE_TIMEOUT_S,
        workers=workers,
        progress_every=100,
        label="parsed",
    )
    records += list(previous.values())

    import pyarrow as pa
    import pyarrow.parquet as pq

    summary_path.parent.mkdir(parents=True, exist_ok=True)
    pq.write_table(pa.Table.from_pylist(records), summary_path)
    n_ok = sum(1 for r in records if r["ok"])
    print(f"Wrote {summary_path}  ({n_ok}/{len(records)} ok)")

main(limit, workers, force, panel, paths)

Per-term class/instance roles and labels. Needs the object store.

Source code in ontometer_corpus/steps/entity_roles.py
@click.command()
@click.option("--limit", type=int, default=None, help="Process at most N ontologies.")
@click.option(
    "--workers", type=int, default=8, show_default=True, help="Concurrent worker processes."
)
@click.option("--force", is_flag=True, help="Recompute ontologies already done.")
@click.option(
    "--panel", is_flag=True, help="Process the releases chosen by `ontometer-corpus panel select`."
)
@corpus_paths
def main(limit: int | None, workers: int, force: bool, panel: bool, paths: CorpusPaths) -> None:
    """Per-term class/instance roles and labels. Needs the object store."""
    paths.require_store_dir()
    build(paths, limit=limit, workers=workers, force=force, panel=panel)