Skip to content

ontometer_corpus.steps.term_coupling

Term-level coupling per ontology, from a re-parse of each file.

The parse phase keeps, per ontology, only the set of namespaces it references (referenced_namespaces / own_namespaces); it discards the individual terms to stay memory-bounded on very large files. A dependency ratio computed from those sets is therefore a namespace-breadth measure: FOAF counts once whether an ontology borrows one term from it or five hundred.

The term-level coupling ratio asks the finer question — of the domain terms an ontology actually uses, what fraction are borrowed from other vocabularies rather than its own — which is only answerable by re-reading each file. This script does that re-parse once and writes the per-ontology term tallies; consumers load that small table instead of re-parsing the corpus.

<corpus>/corpus.db (latest-version, parsed rows with their

namespace claims and parse_format), structural sidecars, and the raw files under $ONTOMETER_STORE/objects/.

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

Keyed by raw-byte file_hash (the same key the structural sidecars use), so files with the same coarse class/property signature remain independently measured; join the result back to latest-version rows on file_hash.

Method, per ontology: - Collect every distinct referenced term (URIRef) via the same parse path that succeeded for this file in the parse phase (parse_format says which): obo -> flat-file scan of logical-axiom lines turtle / json-ld / nt -> rdflib xml / stream_xml_cvt -> rdflib (RDF/XML) owl_xml / owlready2 -> owlready2 (via the pipeline's try_owlready2) - Bucket each term by namespace with ontometer_corpus.namespaces.iri_namespace (OBO-prefix-aware: .../obo/GO_ , not the bare .../obo/), so buckets line up exactly with the stored own_namespaces. - A term is "external" if its namespace resolves to another ontology (or outside the corpus) under the shared pick_home ownership rule; "domain" if reference_kind does not identify its namespace as a representation language, metadata/identifier, or malformed. The headline coupling ratio is external-domain / total-domain, so language terms and citation metadata are excluded from both sides. - Each term is also classified by how the file uses it (logical, annotation, declaration only; ontometer_corpus.usage). n_terms_logical and n_ext_logical restrict the domain tallies to terms used logically, so a vocabulary used only for metadata (Dublin Core on the header) does not count as coupling while the same vocabulary used for modelling does.

Large files: a file above the 50 MB in-memory guard that the parse phase streamed (parse_format stream_xml_cvt / stream_nt_cvt) is converted to N-Triples with the same pyoxigraph reader and read line by line, so it gets the same measurements. --only-failed re-reads just the files the existing tables record as failed and splices them in.

OBO caveat: OBO cannot be converted to RDF by any tool available here (pyoxigraph does not read OBO; owlready2 fails on these files), so OBO term capture is limited to IDs appearing in logical-axiom lines (is_a, relationship, intersection_of, union_of, disjoint_from, equivalent_to) plus the ontology's own id: stanzas — it does not see IRIs buried in annotation values the way the rdflib path does. OBO rows also leave n_logical_statements empty, so they fall outside that comparison.

Usage

ontometer-corpus term-coupling --store /path/to/ontologies ontometer-corpus term-coupling --store /path/to/ontologies --limit 50 ontometer-corpus term-coupling --store /path/to/ontologies --only-failed --workers 3

Attributes

Classes

Functions:

build(paths, limit=None, workers=8, only_failed=False, timeout=_PER_FILE_TIMEOUT_S)

Re-read every latest parsed file, or with only_failed just those the existing term_coupling.parquet records as failed, replacing their rows in both output tables.

Source code in ontometer_corpus/steps/term_coupling.py
def build(
    paths: CorpusPaths,
    limit: int | None = None,
    workers: int = 8,
    only_failed: bool = False,
    timeout: int = _PER_FILE_TIMEOUT_S,
) -> None:
    """Re-read every latest parsed file, or with *only_failed* just those the
    existing ``term_coupling.parquet`` records as failed, replacing their rows
    in both output tables."""
    import multiprocessing as mp
    import time

    # The streamed path spills to the parse phase's scratch dir; forked
    # workers inherit this.
    configure_paths(paths)
    conn = sqlite3.connect(str(paths.db_path))
    conn.row_factory = sqlite3.Row
    ownership_rows = conn.execute(
        """
        SELECT id, ontology_iri, source_registry, file_hash, triple_count,
               own_namespaces, shared_iri, skos_concept_count
        FROM corpus_registry
        WHERE is_latest_version = 1 AND parse_status = 'ok' AND file_hash IS NOT NULL
        """
    ).fetchall()
    owners = resolve_namespace_owners(_owner_record(paths, row) for row in ownership_rows)
    resolved_own_by_row: dict[int, set[str]] = {}
    for namespace, owner in owners.items():
        resolved_own_by_row.setdefault(owner, set()).add(namespace)

    # One representative row per exact raw file among latest parsed rows.
    rows = conn.execute(
        """
        SELECT id, file_hash, content_hash, retrieved_file, parse_format
        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
        )
        """
    ).fetchall()
    conn.close()
    previous_records: list[dict] = []
    previous_usage: list[dict] = []
    if only_failed:
        import pyarrow.parquet as pq

        previous = pq.read_table(paths.term_coupling_path).to_pylist()
        failed = {r["file_hash"] for r in previous if not r["ok"]}
        previous_records = [r for r in previous if r["file_hash"] not in failed]
        previous_usage = [
            r
            for r in pq.read_table(paths.namespace_usage_path).to_pylist()
            if r["file_hash"] not in failed
        ]
        rows = [r for r in rows if r["file_hash"] in failed]
        print(f"Re-reading {len(rows)} previously failed files")
    if limit:
        rows = rows[:limit]

    from collections import deque

    # Stored paths are relative to the object store, so they are resolved here
    # in the parent and the workers receive something absolute.
    tasks = deque(
        (
            r["file_hash"],
            r["content_hash"],
            str(paths.resolve_object(r["retrieved_file"])),
            json.dumps(sorted(resolved_own_by_row.get(r["id"], set()))),
            r["parse_format"],
            False,
        )
        for r in rows
    )
    total = len(tasks)

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

    def _spawn(task):
        parent_conn, child_conn = ctx.Pipe(duplex=False)
        p = ctx.Process(target=_subprocess_target, args=(task, child_conn))
        p.start()
        child_conn.close()  # only the child needs its end open
        if p.pid is None:
            raise RuntimeError("term-coupling worker did not receive a PID")
        running[p.pid] = [p, parent_conn, task, time.monotonic()]

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

        for pid, (p, pconn, task, start) in list(running.items()):
            budget = _STREAM_TIMEOUT_S if _is_streamed(task[4]) else timeout
            timed_out = time.monotonic() - start > budget
            if pconn.poll(0.2):
                try:
                    rec = pconn.recv()
                except EOFError:
                    rec = _empty_rec(
                        task[0], task[1], task[4], "EOFError: worker died without a result"
                    )
                p.join(2)
            elif timed_out:
                p.terminate()
                p.join(3)
                if p.is_alive():
                    p.kill()
                    p.join(3)
                if task[4] in ("owl_xml", "owlready2") and not task[5]:
                    # owlready2 can hang inside C code on some OWL/XML files;
                    # retry once with the direct OWL/XML reader.
                    pconn.close()
                    del running[pid]
                    tasks.append((*task[:5], True))
                    continue
                rec = _empty_rec(
                    task[0],
                    task[1],
                    task[4],
                    f"HardTimeout: exceeded {budget}s wall clock",
                )
            else:
                continue  # still running, within budget

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

    import pyarrow as pa
    import pyarrow.parquet as pq

    usage_rows = [
        {
            "file_hash": rec["file_hash"],
            "namespace": ns,
            "n_logical_terms": n_log,
            "n_annotation_terms": n_ann,
            "n_declared_terms": n_decl,
        }
        for rec in records
        for ns, n_log, n_ann, n_decl in rec.pop("namespace_usage")
    ]
    records = previous_records + records
    usage_rows = previous_usage + usage_rows
    n_ok = sum(1 for r in records if r["ok"])
    n_fail = len(records) - n_ok
    out_path = paths.term_coupling_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})")
    pq.write_table(pa.Table.from_pylist(usage_rows), paths.namespace_usage_path)
    print(f"Wrote {len(usage_rows)} rows to {paths.namespace_usage_path}")

main(limit, workers, only_failed, timeout, paths)

Term-level coupling per ontology. Needs the object store.

Source code in ontometer_corpus/steps/term_coupling.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(
    "--only-failed",
    is_flag=True,
    help="Re-read only the files the existing tables record as failed.",
)
@click.option(
    "--timeout",
    type=int,
    default=_PER_FILE_TIMEOUT_S,
    show_default=True,
    help="Per-file wall-clock budget in seconds (streamed files get longer).",
)
@corpus_paths
def main(
    limit: int | None, workers: int, only_failed: bool, timeout: int, paths: CorpusPaths
) -> None:
    """Term-level coupling per ontology. Needs the object store."""
    paths.require_store_dir()
    build(paths, limit=limit, workers=workers, only_failed=only_failed, timeout=timeout)