Skip to content

ontometer_corpus.steps.structural_metrics

Per-ontology hierarchy metrics from the structural sidecars.

Taxonomic depth, branching factor and the depth-distribution shape all need the full subsumption hierarchy, which lives in the per-ontology structural sidecars ($ONTOMETER_STORE/cache/structure/v<N>/<hh>/<file_hash>.parquet, the subclass_edge and entity records written by the parse phase). Some hierarchies are very large, so this script computes the metrics once, in parallel, and writes a compact per-ontology table; consumers load that small table instead of re-reading sidecars.

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

sidecars under $ONTOMETER_STORE/cache/structure/v<N>/; never the raw files.

Runs after: ontometer-corpus process (parse and dedup phases). Needs --store (or $ONTOMETER_STORE).

Keyed by raw-byte file_hash (matching the sidecar store and term_coupling.parquet), so distinct files cannot inherit one another's hierarchy merely because they declare the same class/property IRIs.

Depth model
  • The hierarchy is a DAG (multiple inheritance is real). A node's parents are the targets of its subclass_edges; a "local root" is a node that never appears as a child within this ontology's own edges (its parent is external/imported or owl:Thing — depth 0).
  • An explicit rdfs:subClassOf owl:Thing is not an edge, and owl:Thing is not a class: whether a file writes that line depends on the tool that saved it, not on the hierarchy, so keeping it would give the same hierarchy different depth, size and branching. The line still counts as an asserted parent for multiple inheritance, as OQuaRE's TMOnto does.
  • Depth is computed by Kahn topological relaxation from the roots, which is exact for both the longest path (max over parents + 1) and the shortest path (min over parents + 1); both are kept, as separate columns. Nodes trapped in a cycle never reach in-degree 0; they are counted (n_cyclic) and excluded from the depth statistics rather than looping forever.

Metrics per ontology (all over the subclass-edge node set): n_nodes, n_roots, n_cyclic; n_classes, n_multiple_inheritance, multiple_inheritance_rate; n_orphans, orphan_rate; mean/max/std of longest-path depth, mean/std of shortest-path depth; branching = mean distinct-children fan-out over non-leaf nodes; depth_hist = node counts per longest-path depth level (list; index = depth), from which the shape of the depth distribution can be read.

Usage

ontometer-corpus structural-metrics --store /path/to/ontologies ontometer-corpus structural-metrics --store /path/to/ontologies --limit 50

Classes

Functions:

build(paths, limit=None, workers=8)

Source code in ontometer_corpus/steps/structural_metrics.py
def build(
    paths: CorpusPaths,
    limit: int | None = None,
    workers: int = 8,
) -> None:
    import multiprocessing as mp
    import time
    from collections import deque

    global _PATHS
    _PATHS = paths

    conn = sqlite3.connect(str(paths.db_path))
    hashes = deque(
        r[0]
        for r in conn.execute(
            """
        SELECT DISTINCT file_hash FROM corpus_registry
        WHERE is_latest_version = 1 AND parse_status = 'ok'
              AND file_hash IS NOT NULL
        """
        ).fetchall()
    )
    conn.close()
    if limit:
        hashes = deque(list(hashes)[:limit])
    total = len(hashes)

    ctx = mp.get_context("fork")
    running: dict[int, list] = {}  # pid -> [process, conn, file_hash, start_time]
    records = []
    n_ok = n_fail = 0

    def _spawn(file_hash):
        parent_conn, child_conn = ctx.Pipe(duplex=False)
        p = ctx.Process(target=_subprocess_target, args=(file_hash, child_conn))
        p.start()
        child_conn.close()
        if p.pid is None:
            raise RuntimeError("structural-metrics worker did not receive a PID")
        running[p.pid] = [p, parent_conn, file_hash, time.monotonic()]

    while hashes or running:
        while len(running) < workers and hashes:
            _spawn(hashes.popleft())

        for pid, (p, pconn, file_hash, start) in list(running.items()):
            timed_out = time.monotonic() - start > _PER_FILE_TIMEOUT_S
            if pconn.poll(0.2):
                try:
                    rec = pconn.recv()
                except EOFError:
                    rec = {
                        "file_hash": file_hash,
                        "ok": False,
                        "error": "EOFError: worker died without a result",
                        **_EMPTY,
                    }
                p.join(2)
            elif timed_out:
                p.terminate()
                p.join(3)
                if p.is_alive():
                    p.kill()
                    p.join(3)
                rec = {
                    "file_hash": file_hash,
                    "ok": False,
                    "error": f"HardTimeout: exceeded {_PER_FILE_TIMEOUT_S}s wall clock",
                    **_EMPTY,
                }
            else:
                continue

            pconn.close()
            records.append(rec)
            n_ok += int(bool(rec["ok"]))
            n_fail += int(not bool(rec["ok"]))
            del running[pid]
            if len(records) % 200 == 0 or len(records) == total:
                print(f"  {len(records)}/{total} done  (ok={n_ok} fail={n_fail})", flush=True)

    import pyarrow as pa
    import pyarrow.parquet as pq

    out_path = paths.structural_metrics_path
    out_path.parent.mkdir(parents=True, exist_ok=True)
    pq.write_table(pa.Table.from_pylist(records), out_path)
    print(f"Wrote {len(records)} rows to {out_path}  (ok={n_ok} fail={n_fail})")

main(limit, workers, paths)

Per-ontology hierarchy metrics from the structural sidecars. Needs the object store.

Source code in ontometer_corpus/steps/structural_metrics.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."
)
@corpus_paths
def main(limit: int | None, workers: int, paths: CorpusPaths) -> None:
    """Per-ontology hierarchy metrics from the structural sidecars. Needs the object store."""
    paths.require_store_dir()
    build(paths, limit=limit, workers=workers)