Skip to content

ontometer_corpus.steps.abstractness_growth

Abstractness as the corpus grows: G(t).

The specialisation network of ontologies is a function of time. An ontology that nothing specialises is terminal — a leaf of the network. When a later ontology specialises one of its classes it becomes a branch, and in the network sense it has become more abstract. This script reconstructs G(t) and measures that process.

Reconstruction. The network is the one measured at capture: child → parent when a class homed in child is asserted, by child, under a class homed in parent (own-foreign edges, ontometer-corpus entity-network). Each ontology is placed in time by its first-evidence date (ontometer-corpus dates). A specialisation pair (child, parent) is placed at the first release of the child that asserts it when the child's releases are in the release panel (ontometer-corpus panel, used only if $ONTOMETER_STORE/cache/panel_releases.parquet exists), and otherwise at the child's first evidence — an assumption the panel measures (the share of pairs already asserted in a family's first panel release). It never predates its parent. Two birth variants are measured:

  • bounded (primary): the first-evidence date, further bounded by the rule that a class exists before anything specialises it, so an ontology is born no later than the first observed specialisation of one of its classes — the first panel release asserting it, or the captured release that does (bound_births); an undated parent with a dated observation becomes dated.
  • first_evidence: the first-evidence date alone.

Measured, per variant:

  • dating consistency — the share of specialisations whose child is born no earlier than its parent, against a permutation of the dates;
  • leaf survival — time from birth to the first specialiser (Kaplan–Meier, censored at capture). Ontologies already specialised when first attested are counted apart: the data cannot say when they stopped being leaves;
  • the corpus over calendar time — how many ontologies exist, the share that are branches, normalised network generality log(1 + specialisers) / log N(t) and height (longest chain of specialisers beneath), for all ontologies, for the measured ontologies (subject), and for fixed cohorts, so that change within existing ontologies is separated from the arrival of new, terminal ones;
  • attachment — whether specialisations spread over existing ontologies or concentrate: the number of leaves that became branches against the same arrivals re-targeted uniformly and preferentially (attachment_null);
  • who becomes a branch — content abstractness (A_local) of ontologies specialised within five years of birth against those that were not, net of ontology size;
  • terms — home classes gaining a first foreign specialiser, over time;
  • sense C over time — for terms used by other ontologies, whether later users use them as classes more than earlier users do.
$ONTOMETER_STORE/cache/entity_{ontologies,terms,edges,docs}.parquet,

<corpus>/ontology_abstractness.parquet, <corpus>/ontology_dates.parquet, and, when $ONTOMETER_STORE/cache/panel_releases.parquet exists, the panel releases' sidecars under $ONTOMETER_STORE/cache/structure/v<N>/.

Runs after: ontometer-corpus abstractness and ontometer-corpus dates; optionally ontometer-corpus panel select. Needs --store (or $ONTOMETER_STORE).

Usage

ontometer-corpus growth --store /path/to/ontologies --out /path/to/out

Attributes

BASE_YEARS = (2010, 2015, 2020) module-attribute

Classes

GrowthInputs dataclass

The ontology specialisation network at capture, placed in time.

dep holds one row per (child, parent) pair with n_terms, the number of term-level specialisations behind it. eps is each pair's arrival time (first panel release asserting it, else the child's first evidence); b_obs and b_bnd are first-evidence and bounded births, in days since the epoch, indexed by ontology.

Source code in ontometer_corpus/steps/abstractness_growth.py
@dataclass
class GrowthInputs:
    """The ontology specialisation network at capture, placed in time.

    ``dep`` holds one row per (child, parent) pair with ``n_terms``, the
    number of term-level specialisations behind it. ``eps`` is each pair's
    arrival time (first panel release asserting it, else the child's first
    evidence); ``b_obs`` and ``b_bnd`` are first-evidence and bounded births,
    in days since the epoch, indexed by ontology.
    """

    onts: pd.DataFrame
    onto: pd.DataFrame
    terms: pd.DataFrame
    edges: pd.DataFrame
    dates: pd.DataFrame
    dep: pd.DataFrame
    b_obs: np.ndarray
    b_bnd: np.ndarray
    eps: np.ndarray
    by_panel: np.ndarray
    panel_check: dict
    as_of: float

    @property
    def term_home(self) -> np.ndarray:
        return self.terms.home.to_numpy()

    @property
    def pair_time(self) -> dict[tuple[int, int], float]:
        return {
            (int(c), int(p)): float(e)
            for c, p, e in zip(self.dep.child, self.dep.parent, self.eps)
            if not np.isnan(e)
        }

Attributes

onts instance-attribute
onto instance-attribute
terms instance-attribute
edges instance-attribute
dates instance-attribute
dep instance-attribute
b_obs instance-attribute
b_bnd instance-attribute
eps instance-attribute
by_panel instance-attribute
panel_check instance-attribute
as_of instance-attribute
term_home property
pair_time property

Methods:

__init__(onts, onto, terms, edges, dates, dep, b_obs, b_bnd, eps, by_panel, panel_check, as_of)

Functions:

load_timed_network(paths)

Load the entity network and date its ontologies and specialisation pairs.

Source code in ontometer_corpus/steps/abstractness_growth.py
def load_timed_network(paths: CorpusPaths) -> GrowthInputs:
    """Load the entity network and date its ontologies and specialisation pairs."""
    d = paths.cache_dir
    onts = pd.read_parquet(d / "entity_ontologies.parquet")
    oa = pd.read_parquet(paths.ontology_abstractness_path)
    dates = pd.read_parquet(paths.ontology_dates_path)
    terms = pd.read_parquet(d / "entity_terms.parquet", columns=["term", "iri", "home"])
    edges = pd.read_parquet(d / "entity_edges.parquet")
    term_home = terms.home.to_numpy()

    base = onts[["onto", "family", "registry", "source_id", "release_date"]].merge(
        oa[["onto", "subject", "A_local", "n_home_classes", "community"]], on="onto"
    )

    of = edges[edges.kind == EDGE_OWN_FOREIGN]
    ph = term_home[of.parent.to_numpy()]
    dep = (
        pd.DataFrame({"child": of.onto.to_numpy()[ph != EXTERNAL], "parent": ph[ph != EXTERNAL]})
        .value_counts()
        .rename("n_terms")
        .reset_index()
        .sort_values(["child", "parent"])
    )
    dep = dep[dep.child != dep.parent].reset_index(drop=True)

    # The first panel release asserting each pair, where the child's releases
    # are in the panel. Written with the pairs as a small table in the data
    # directory, from which G(t) can be rebuilt without the object store.
    panel_times, panel_check = _panel_pair_times(paths, terms, dep)
    pairs = list(zip(dep.child.to_numpy(), dep.parent.to_numpy()))
    by_panel = np.array([pair in panel_times for pair in pairs])
    first_days = pd.Series([panel_times.get(pair, np.nan) for pair in pairs], dtype=float)
    family = base.set_index("onto").family
    spec = dep.assign(
        child_family=family.reindex(dep.child).to_numpy(),
        parent_family=family.reindex(dep.parent).to_numpy(),
        panel_first=(EPOCH + pd.to_timedelta(first_days, unit="D")).dt.strftime("%Y-%m-%d"),
    )
    spec.to_parquet(paths.ontology_specialisations_path, index=False)

    net = assemble(base, spec, dates)
    onto = net.onto.merge(dates[["family", "birth_source", "as_of"]], on="family", how="left")
    b_obs, b_bnd, eps, as_of = net.b_obs, net.b_bnd, net.eps, net.as_of
    return GrowthInputs(
        onts=onts,
        onto=onto,
        terms=terms,
        edges=edges,
        dates=dates,
        dep=dep,
        b_obs=b_obs,
        b_bnd=b_bnd,
        eps=eps,
        by_panel=by_panel,
        panel_check=panel_check,
        as_of=as_of,
    )

build(paths, out, reps, seed)

Source code in ontometer_corpus/steps/abstractness_growth.py
def build(paths: CorpusPaths, out: Path, reps: int, seed: int) -> None:
    import matplotlib

    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    out.mkdir(parents=True, exist_ok=True)
    net = load_timed_network(paths)
    onto, dep, dates, edges = net.onto, net.dep, net.dates, net.edges
    b_obs, b_bnd, eps, as_of = net.b_obs, net.b_bnd, net.eps, net.as_of
    term_home, pair_time = net.term_home, net.pair_time
    by_panel, panel_check = net.by_panel, net.panel_check
    d = paths.cache_dir

    summary: dict = {
        "as_of": str(dates.as_of.iloc[0]),
        "n_ontologies": len(onto),
        "n_specialisation_pairs": len(dep),
        "edge_timing": {**panel_check, "pairs_timed_by_panel_in_network": int(by_panel.sum())},
        "dating": {
            "dated_first_evidence": int((~np.isnan(b_obs)).sum()),
            "dated_bounded": int((~np.isnan(b_bnd)).sum()),
            "moved_earlier_by_bound": int((b_bnd < b_obs).sum()),
            "by_source": onto.birth_source.value_counts().to_dict(),
            "by_registry": onto.assign(d=~np.isnan(b_obs))
            .groupby("registry")
            .d.mean()
            .round(3)
            .to_dict(),
            "consistency_first_evidence": _consistency(
                dating_consistency(b_obs, dep.child.to_numpy(), dep.parent.to_numpy(), seed=seed)
            ),
        },
    }
    print("edge timing", summary["edge_timing"])
    print(json.dumps(summary["dating"], indent=1, default=str))

    per_onto = onto[["onto", "family", "registry", "subject"]].copy()
    yearly_all, km_all, coh_all, null_all = [], [], [], []
    for name, b in (("bounded", b_bnd), ("first_evidence", b_obs)):
        res, po, yearly, km, coh, null = _variant(name, b, eps, dep, onto, as_of, reps, seed)
        summary[name] = res
        per_onto = pd.concat([per_onto, po], axis=1)
        yearly_all.append(yearly)
        km_all.append(km)
        coh_all.append(coh)
        null_all.append(null)
        print(name, json.dumps(res, default=str)[:2500])

    summary["terms"], term_years = _term_growth(edges, term_home, b_bnd, b_obs, pair_time, onto)
    print("terms", summary["terms"])
    docs = pd.read_parquet(d / "entity_docs.parquet")
    summary["sense_c"], lag = _sense_c(docs, term_home, b_obs, b_bnd, reps, seed)
    print("sense C", summary["sense_c"])
    del docs

    per_onto.to_parquet(paths.corpus_dir / "abstractness_growth.parquet", index=False)
    yearly = pd.concat(yearly_all, ignore_index=True)
    km = pd.concat(km_all, ignore_index=True)
    coh = pd.concat(coh_all, ignore_index=True)
    null = pd.concat(null_all, ignore_index=True)
    yearly.to_csv(out / "growth_yearly.csv", index=False)
    coh.to_csv(out / "growth_cohorts.csv", index=False)
    km.to_csv(out / "growth_leaf_survival.csv", index=False)
    null.to_csv(out / "growth_attachment_null.csv", index=False)
    term_years.to_csv(out / "growth_terms_per_year.csv", index=False)
    lag.to_csv(out / "growth_sense_c_by_lag.csv", index=False)
    (out / "growth_summary.json").write_text(json.dumps(summary, indent=1, default=str))

    # --- figures -----------------------------------------------------------------
    v = "bounded"
    fig, axes = plt.subplots(1, 2, figsize=(10, 3.9), dpi=150, facecolor=SURFACE)
    ax = axes[0]
    _style(ax)
    ys = yearly[(yearly.variant == v) & (yearly.population == "all") & (yearly.year >= 2008)]
    ax.plot(ys.year, ys.branch_share, color=INK2, linewidth=2.2, label="whole corpus at t")
    for (lab, g), col in zip(
        coh[coh.variant == v].groupby("cohort", sort=False), (BLUE, ORANGE, AQUA)
    ):
        ax.plot(g.year, g.branch_share, color=col, linewidth=1.6, label=f"born {lab}")
    ax.set_ylabel("share specialised by some ontology", color=INK, fontsize=10)
    ax.set_xlabel("year", color=INK, fontsize=10)
    ax.set_ylim(0, None)
    ax.legend(frameon=False, fontsize=8, labelcolor=INK2)
    ax.set_title(
        "Share of ontologies that are branches in G(t)", color=INK, fontsize=10, loc="left"
    )
    ax = axes[1]
    _style(ax)
    ax2 = ax.twinx()
    ax.bar(ys.year, ys.n, color=GRID, width=0.8, label="ontologies in G(t)")
    ax2.plot(ys.year, ys.mean_height, color=BLUE, linewidth=2, label="mean height")
    ax2.plot(ys.year, ys.max_height, color=ORANGE, linewidth=1.6, label="max height")
    ax.set_ylabel("ontologies in G(t)", color=INK, fontsize=10)
    ax2.set_ylabel("specialisers beneath (chain length)", color=INK, fontsize=10)
    ax2.tick_params(colors=INK2, labelsize=9)
    for s in ("top",):
        ax2.spines[s].set_visible(False)
    ax.set_xlabel("year", color=INK, fontsize=10)
    ax2.legend(frameon=False, fontsize=8, labelcolor=INK2, loc="upper left")
    ax.set_title("Size and height of G(t)", color=INK, fontsize=10, loc="left")
    fig.tight_layout()
    fig.savefig(out / "growth_branch_share.png", facecolor=SURFACE)
    plt.close(fig)

    fig, ax = plt.subplots(figsize=(6.4, 4.0), dpi=150, facecolor=SURFACE)
    _style(ax)
    for (lab, g), col in zip(km[km.variant == v].groupby("population", sort=False), (BLUE, ORANGE)):
        ax.step(
            np.r_[0, g.years],
            np.r_[1, g.survival],
            where="post",
            color=col,
            linewidth=1.8,
            label=lab,
        )
    ax.set_xlim(0, 15)
    ax.set_ylim(0, 1.02)
    ax.set_xlabel("years since first evidence", color=INK, fontsize=10)
    ax.set_ylabel("P(still terminal)", color=INK, fontsize=10)
    ax.legend(frameon=False, fontsize=9, labelcolor=INK2)
    ax.set_title(
        "Time from first evidence to first specialiser", color=INK, fontsize=10, loc="left"
    )
    fig.tight_layout()
    fig.savefig(out / "growth_leaf_survival.png", facecolor=SURFACE)
    plt.close(fig)

    fig, ax = plt.subplots(figsize=(6.4, 3.8), dpi=150, facecolor=SURFACE)
    _style(ax)
    nv = null[null.variant == v]
    for (lab, g), col in zip(nv.groupby("model", sort=False), (BLUE, AQUA)):
        ax.hist(
            g.branches, bins=25, color=col, alpha=0.75, label=f"{lab} attachment", edgecolor=SURFACE
        )
    ax.axvline(
        summary[v]["attachment"]["observed_branches"], color=ORANGE, linewidth=2.2, label="observed"
    )
    ax.set_xlabel("ontologies ever specialised (leaves turned branches)", color=INK, fontsize=10)
    ax.set_ylabel("replicates", color=INK, fontsize=10)
    ax.legend(frameon=False, fontsize=8, labelcolor=INK2)
    ax.set_title(
        "Leaves turned branches: observed against re-targeted arrivals",
        color=INK,
        fontsize=10,
        loc="left",
    )
    fig.tight_layout()
    fig.savefig(out / "growth_attachment_null.png", facecolor=SURFACE)
    plt.close(fig)
    print(f"Wrote {out}")

main(out, reps, seed, paths)

Abstractness as the corpus grows: G(t).

Source code in ontometer_corpus/steps/abstractness_growth.py
@click.command()
@click.option(
    "--out",
    type=click.Path(file_okay=False, path_type=Path),
    required=True,
    help="Directory for tables and figures.",
)
@click.option("--reps", type=int, default=200, show_default=True, help="Null-model replicates.")
@click.option(
    "--seed", type=int, default=0, show_default=True, help="Random seed of the null models."
)
@corpus_paths
def main(out: Path, reps: int, seed: int, paths: CorpusPaths) -> None:
    """Abstractness as the corpus grows: G(t)."""
    paths.require_store_dir()
    build(paths, out, reps, seed)