papertrail/lib/kg/linkPredict.ts
caelum0x 174222bcaa feat: Builder-Track named-user tools, bio + evidence-intelligence platform, Apache-2.0
Builds PaperTrail from the base skeleton into a full evidence-verification platform
for the "Built with Claude: Life Sciences" hackathon (Builder Track).

New named-user features (Build Beyond the Bench):
- Lab Notebook Companion — rough bench notes -> structured, searchable, grounded
  experiment records (lib/labNotebook, /console/lab-notebook, migration 0059)
- Clinical Trial Matcher — de-identified patient notes -> ranked eligible
  ClinicalTrials.gov trials with per-criterion inclusion/exclusion reasoning
  (lib/trialMatcher, /console/trial-matcher, migrations 0060)

Platform:
- Deterministic verification moat (biostats recompute, exact-span grounding)
- 11 biomedical evidence engines (FAERS, GWAS, Open Targets, ChEMBL, ClinVar,
  PharmGKB, PubTator, DDI, repurposing, biomarker, unified verifier)
- Evidence Intelligence (KG, dossier, provenance/export, RWE) + enterprise
  governance (RBAC, /api/v1 gateway, metering, audit chain, retention)
- 17 OSS projects assimilated into native TypeScript on our stack (backend/engines
  retained + credited in NOTICE)
- Multi-format upload (PDF/DOCX/XLSX/CSV/MD/TXT), logo, marketing site
- Next.js 16 upgrade, benchmark harness (honest smoke-test caveat)

Licensing: Apache-2.0 (LICENSE + NOTICE).
2026-07-10 16:23:13 +03:00

251 lines
9.8 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// NATIVE graph LINK PREDICTION over the persisted evidence knowledge graph.
//
// Ported from PyKEEN (backend/engines/pykeen) — but NOT its trained-embedding models
// (TransE/DistMult/ComplEx need a torch training loop we deliberately don't run here).
// We port PyKEEN's OWN non-parametric BASELINE family (`models/baseline/*.py`): the
// idea that you can rank candidate links from GRAPH TOPOLOGY ALONE, no learned
// parameters, no GPU. PyKEEN's baselines build a normalized sparse adjacency and score
// candidates by shared structure; we implement the four classic topology link-
// predictors from the same lineage (used across the link-prediction literature
// PyKEEN's baselines draw on):
//
// common-neighbors (CN) : |Γ(u) ∩ Γ(v)|
// Adamic-Adar (AA) : Σ_{w ∈ Γ(u)∩Γ(v)} 1 / log|Γ(w)|
// resource-allocation (RA) : Σ_{w ∈ Γ(u)∩Γ(v)} 1 / |Γ(w)|
// preferential-attachment(PA): |Γ(u)| · |Γ(v)|
//
// where Γ(x) is the neighbor set of x. A high score on (u, v) means u and v are
// structurally close in the evidence graph WITHOUT a direct edge — i.e. a NOVEL
// repurposing / association HYPOTHESIS worth surfacing to a researcher.
//
// The graph is read ONLY through lib/kg/repository (neighbors), so this stays offline-
// testable against the same in-memory pool fake the rest of the KG uses. All math is
// pure, deterministic, and immutable — there is NO LLM anywhere in a score.
import { neighbors, type KgNeighbor, type KgPool } from "./repository";
import type { KgNode, KgPredicate } from "./schemas";
// ---------------------------------------------------------------------------
// Local undirected subgraph.
//
// The repository primitive `neighbors(nodeId)` returns OUTBOUND edges only. To score
// topology we need each node's neighbor SET; we treat every discovered edge as
// UNDIRECTED (both endpoints gain each other as a neighbor), which is the standard
// convention for these structural predictors. We BFS-expand from a seed set up to a
// bounded radius so scoring works over the neighborhood of interest without loading the
// whole table — mirroring PyKEEN baselines operating on a fixed adjacency, but built
// lazily and immutably from the repository.
// ---------------------------------------------------------------------------
export interface Subgraph {
// nodeId -> the KgNode (identity + Biolink-typeable metadata)
readonly nodes: ReadonlyMap<string, KgNode>;
// nodeId -> undirected neighbor ids (a Set, so membership + degree are O(1))
readonly adjacency: ReadonlyMap<string, ReadonlySet<string>>;
// "subjectId->objectId" of every DIRECTED edge seen, so we never propose a link that
// already exists, and can carry the predicate a proposed link would take.
readonly directedEdges: ReadonlySet<string>;
}
const DEFAULT_RADIUS = 2;
const MAX_RADIUS = 4;
const MAX_NODES = 5_000; // defence against a runaway expansion on a dense hub
function directedKey(subjectId: string, objectId: string): string {
return `${subjectId}${objectId}`;
}
// Build the local undirected subgraph reachable from `seedIds` within `radius` hops,
// reading ONLY via repository.neighbors. Pure with respect to its inputs (the pool is
// a read-only data source); returns fresh immutable structures.
export async function buildSubgraph(
pool: KgPool,
seedIds: readonly string[],
radius: number = DEFAULT_RADIUS
): Promise<Subgraph> {
const hopBudget = Math.max(1, Math.min(Math.trunc(radius), MAX_RADIUS));
const nodes = new Map<string, KgNode>();
const adjacency = new Map<string, Set<string>>();
const directedEdges = new Set<string>();
const ensureAdj = (id: string): Set<string> => {
let set = adjacency.get(id);
if (!set) {
set = new Set<string>();
adjacency.set(id, set);
}
return set;
};
const link = (a: string, b: string): void => {
ensureAdj(a).add(b);
ensureAdj(b).add(a);
};
const expanded = new Set<string>();
let frontier: string[] = [];
for (const id of seedIds) {
if (!expanded.has(id)) frontier.push(id);
}
for (let hop = 0; hop < hopBudget; hop++) {
const next: string[] = [];
for (const nodeId of frontier) {
if (expanded.has(nodeId)) continue;
expanded.add(nodeId);
if (nodes.size > MAX_NODES) break;
const outs: KgNeighbor[] = await neighbors(pool, nodeId);
for (const { edge, node } of outs) {
nodes.set(node.id, node);
directedEdges.add(directedKey(edge.subjectId, edge.objectId));
link(nodeId, node.id);
if (!expanded.has(node.id)) next.push(node.id);
}
}
frontier = next;
if (frontier.length === 0) break;
}
// Ensure seed nodes always have an adjacency entry (possibly empty) so degree lookups
// are total.
for (const id of seedIds) ensureAdj(id);
return { nodes, adjacency, directedEdges };
}
// ---------------------------------------------------------------------------
// The four topology scorers — pure functions of two neighbor sets (and, for AA/RA, the
// degree of each shared neighbor). Ported directly from the standard definitions the
// PyKEEN baseline family builds on. Each is O(min(|Γ(u)|, |Γ(v)|)).
// ---------------------------------------------------------------------------
export type ScorerName =
| "common_neighbors"
| "adamic_adar"
| "resource_allocation"
| "preferential_attachment";
function neighborsOf(sub: Subgraph, id: string): ReadonlySet<string> {
return sub.adjacency.get(id) ?? new Set<string>();
}
function sharedNeighbors(sub: Subgraph, u: string, v: string): string[] {
const gu = neighborsOf(sub, u);
const gv = neighborsOf(sub, v);
// iterate the smaller set for the intersection
const [small, large] = gu.size <= gv.size ? [gu, gv] : [gv, gu];
const shared: string[] = [];
for (const w of small) {
// a node is not its own bridging neighbor
if (w === u || w === v) continue;
if (large.has(w)) shared.push(w);
}
return shared;
}
export function commonNeighbors(sub: Subgraph, u: string, v: string): number {
return sharedNeighbors(sub, u, v).length;
}
export function adamicAdar(sub: Subgraph, u: string, v: string): number {
let score = 0;
for (const w of sharedNeighbors(sub, u, v)) {
const deg = neighborsOf(sub, w).size;
// log(1) = 0 would divide by zero; a degree-1 shared neighbor cannot bridge two
// distinct endpoints, so it is skipped (standard AA guard).
if (deg > 1) score += 1 / Math.log(deg);
}
return score;
}
export function resourceAllocation(sub: Subgraph, u: string, v: string): number {
let score = 0;
for (const w of sharedNeighbors(sub, u, v)) {
const deg = neighborsOf(sub, w).size;
if (deg > 0) score += 1 / deg;
}
return score;
}
export function preferentialAttachment(sub: Subgraph, u: string, v: string): number {
return neighborsOf(sub, u).size * neighborsOf(sub, v).size;
}
const SCORERS: Readonly<Record<ScorerName, (s: Subgraph, u: string, v: string) => number>> = {
common_neighbors: commonNeighbors,
adamic_adar: adamicAdar,
resource_allocation: resourceAllocation,
preferential_attachment: preferentialAttachment,
};
// ---------------------------------------------------------------------------
// Ranked prediction — the public entry point.
//
// Given a `from` node (and optionally a target `predicate`), score every candidate
// object node in the local subgraph that is NOT already directly linked from `from`,
// and return them ranked by the chosen topology scorer. Each prediction is a
// well-formed (subject, predicate, object) hypothesis with a numeric score.
// ---------------------------------------------------------------------------
export interface PredictedLink {
readonly subject: KgNode;
readonly predicate: KgPredicate;
readonly object: KgNode;
readonly scorer: ScorerName;
readonly score: number;
}
export interface PredictOptions {
readonly scorer?: ScorerName;
readonly predicate?: KgPredicate;
readonly radius?: number;
readonly limit?: number;
// Optional structural filter: keep a candidate only if this returns true for the
// (subjectType, objectType) pair. Used by the API to enforce Biolink well-typing.
readonly accept?: (subjectType: string, objectType: string) => boolean;
}
const DEFAULT_LIMIT = 25;
const MAX_LIMIT = 200;
// Score candidate objects for a single source node. Immutable: returns a fresh sorted
// array, sorted by descending score then by object id for a stable, deterministic order
// (ties never depend on Map iteration order).
export async function predictLinks(
pool: KgPool,
fromNode: KgNode,
options: PredictOptions = {}
): Promise<PredictedLink[]> {
const scorer = options.scorer ?? "adamic_adar";
const predicate: KgPredicate = options.predicate ?? "associates_with";
const limit = Math.max(1, Math.min(Math.trunc(options.limit ?? DEFAULT_LIMIT), MAX_LIMIT));
const scoreFn = SCORERS[scorer];
const sub = await buildSubgraph(pool, [fromNode.id], options.radius);
const existingDirect = new Set<string>();
for (const objId of neighborsOf(sub, fromNode.id)) {
if (sub.directedEdges.has(directedKey(fromNode.id, objId))) existingDirect.add(objId);
}
const predictions: PredictedLink[] = [];
for (const [candidateId, candidate] of sub.nodes) {
if (candidateId === fromNode.id) continue; // no self-link
if (existingDirect.has(candidateId)) continue; // link already exists — not novel
if (options.accept && !options.accept(fromNode.entityType, candidate.entityType)) {
continue;
}
const score = scoreFn(sub, fromNode.id, candidateId);
if (score <= 0) continue; // no structural support — honest omission over a 0-score
predictions.push({ subject: fromNode, predicate, object: candidate, scorer, score });
}
predictions.sort((a, b) =>
b.score !== a.score ? b.score - a.score : a.object.id < b.object.id ? -1 : 1
);
return predictions.slice(0, limit);
}