""" TempBench — Temporal KG Indexer =================================== Implements the dual-index structure (entity index + interval tree temporal index) described in the TempBench paper. Usage: from indexer import TemporalKGIndexer indexer = TemporalKGIndexer() indexer.load_tkgl_smallpedia("path/to/tkgl-smallpedia.csv") # or from a list of quadruples: indexer.build(quadruples) # Query: all triples valid at a given timestamp valid_triples = indexer.query_valid_at(entity="Q1234", t=2015.5) # Query: temporally-filtered 1-hop neighbourhood for an anchor entity neighbourhood = indexer.neighbourhood(entity="Q1234", t_query=2015.5) """ from __future__ import annotations import csv import json import math from collections import defaultdict from dataclasses import dataclass, field from typing import Iterator, List, Optional, Tuple # --------------------------------------------------------------------------- # Data structures # --------------------------------------------------------------------------- @dataclass(frozen=True) class Triple: """A single timestamped KG quadruple.""" subject: str relation: str obj: str t_start: float # year as float, e.g. 2015.0 or 2015.583 (Aug) t_end: float # math.inf for currently-valid facts def valid_at(self, t: float) -> bool: return self.t_start <= t <= self.t_end def to_dict(self) -> dict: return { "s": self.subject, "r": self.relation, "o": self.obj, "t_start": self.t_start, "t_end": self.t_end if not math.isinf(self.t_end) else None, } @dataclass class ValidityWindow: t_start: float t_end: float def intersect(self, other: "ValidityWindow", t_query: float) -> Optional["ValidityWindow"]: """ Validity-window intersection clamped to (-inf, t_query], or None if empty. This is a building block used by benchmark construction; it is NOT the forward-propagating composability operator (that is defined in the TempBench paper). """ new_start = max(self.t_start, other.t_start) new_end = min(self.t_end, other.t_end, t_query) if new_start <= new_end: return ValidityWindow(new_start, new_end) return None @classmethod def full(cls) -> "ValidityWindow": return cls(t_start=-math.inf, t_end=math.inf) def is_empty(self) -> bool: return self.t_start > self.t_end # --------------------------------------------------------------------------- # Interval tree node (simple augmented BST) # --------------------------------------------------------------------------- class _IntervalNode: """Node in an augmented interval tree for O(log n) stabbing queries.""" def __init__(self, triple: Triple): self.triple = triple self.max_end = triple.t_end self.left: Optional[_IntervalNode] = None self.right: Optional[_IntervalNode] = None def update_max(self): self.max_end = self.triple.t_end if self.left: self.max_end = max(self.max_end, self.left.max_end) if self.right: self.max_end = max(self.max_end, self.right.max_end) class IntervalTree: """ Temporal index over triple validity windows using a sorted flat array + bisect. Handles 500K+ records without recursion limits. For point-in-time TKGs (t_start == t_end, e.g. tkgl-smallpedia), uses a timestamp bucket dict for O(1) exact-match lookup. For interval TKGs, uses bisect over sorted t_start array + t_end filter. Stabbing query: 'all triples whose [t_start, t_end] contains t'. """ def __init__(self): self._triples: List[Triple] = [] # all triples, unsorted until finalised self._sorted_starts: List[float] = [] # sorted t_start values (parallel to _sorted) self._sorted: List[Triple] = [] # triples sorted by t_start self._buckets: defaultdict[float, List[Triple]] = defaultdict(list) # for point-in-time self._finalised = False self._size = 0 def __len__(self) -> int: return self._size def insert(self, triple: Triple) -> None: self._triples.append(triple) self._buckets[triple.t_start].append(triple) self._size += 1 self._finalised = False def _finalise(self) -> None: """Sort triples by t_start for bisect queries. Called lazily before first stab.""" self._sorted = sorted(self._triples, key=lambda t: t.t_start) self._sorted_starts = [t.t_start for t in self._sorted] self._finalised = True def stab(self, t: float) -> List[Triple]: """Return all triples valid at time t (i.e. t_start <= t <= t_end).""" if not self._finalised: self._finalise() import bisect # All triples with t_start <= t right_idx = bisect.bisect_right(self._sorted_starts, t) # Filter for t_end >= t return [tr for tr in self._sorted[:right_idx] if tr.t_end >= t] # --------------------------------------------------------------------------- # Main indexer # --------------------------------------------------------------------------- class TemporalKGIndexer: """ Dual-index structure over a temporal knowledge graph. Attributes ---------- entity_index : dict[str, list[Triple]] Maps each entity (subject or object) to all its triples. temporal_index : IntervalTree Interval tree over all triples for O(log n) temporal filtering. """ def __init__(self): self.entity_index: defaultdict[str, List[Triple]] = defaultdict(list) self.temporal_index: IntervalTree = IntervalTree() self._all_triples: List[Triple] = [] # ------------------------------------------------------------------ # Loading # ------------------------------------------------------------------ def build(self, quadruples: List[Tuple[str, str, str, float, float]]) -> None: """ Build index from a list of (subject, relation, object, t_start, t_end) tuples. t_end = None or math.inf means currently valid. """ for s, r, o, t_start, t_end in quadruples: t_end = t_end if (t_end is not None and not math.isnan(t_end)) else math.inf triple = Triple(subject=s, relation=r, obj=o, t_start=t_start, t_end=t_end) self._index_triple(triple) def load_tkgl_smallpedia(self, path: str, delimiter: str = ",") -> None: """ Load tkgl-smallpedia from TGB 2.0 edge file. Handles the actual TGB 2.0 format: ts,head,tail,relation_type where ts is a point-in-time year (event-based TKG). Each event is normalised to interval [ts, ts]. """ count = 0 with open(path, "r", encoding="utf-8") as f: reader = csv.DictReader(f, delimiter=delimiter) for row in reader: # TGB 2.0 tkgl-smallpedia format: ts, head, tail, relation_type if "ts" in row: t = float(row["ts"]) triple = Triple( subject=row["head"], relation=row["relation_type"], obj=row["tail"], t_start=t, t_end=t, # point-in-time event normalised to [t, t] ) # Fallback: generic interval format else: t_start = float(row.get("start_time", row.get("t_start", 0))) raw_end = row.get("end_time", row.get("t_end", None)) t_end = float(raw_end) if raw_end and raw_end.strip() not in ("", "None", "nan") else math.inf triple = Triple( subject=row.get("subject", row.get("head", "")), relation=row.get("relation", row.get("relation_type", "")), obj=row.get("object", row.get("tail", "")), t_start=t_start, t_end=t_end, ) self._index_triple(triple) count += 1 print(f"[Indexer] Loaded {count:,} triples from {path}") def load_from_json(self, path: str) -> None: """Load from a JSON list of {s, r, o, t_start, t_end?} dicts.""" with open(path, "r", encoding="utf-8") as f: data = json.load(f) for item in data: t_end = item.get("t_end", None) triple = Triple( subject=item["s"], relation=item["r"], obj=item["o"], t_start=float(item["t_start"]), t_end=float(t_end) if t_end is not None else math.inf, ) self._index_triple(triple) print(f"[Indexer] Loaded {len(self._all_triples):,} triples from {path}") def _index_triple(self, triple: Triple) -> None: self._all_triples.append(triple) self.entity_index[triple.subject].append(triple) self.entity_index[triple.obj].append(triple) self.temporal_index.insert(triple) # ------------------------------------------------------------------ # Event-based normalisation (ICEWS-style) # ------------------------------------------------------------------ @staticmethod def normalise_event(s: str, r: str, o: str, t: float) -> Triple: """Convert a point-in-time event (s, r, o, t) to interval form [t, t].""" return Triple(subject=s, relation=r, obj=o, t_start=t, t_end=t) # ------------------------------------------------------------------ # Query interface # ------------------------------------------------------------------ def neighbourhood(self, entity: str, t_query: float) -> List[Triple]: """ Return the temporally-filtered 1-hop neighbourhood of `entity` at `t_query`. i.e., all triples (entity, r, o, τ) or (s, r, entity, τ) where t_query ∈ τ. O(degree(entity)) — filtered from entity index. """ return [t for t in self.entity_index.get(entity, []) if t.valid_at(t_query)] def query_valid_at(self, t: float) -> List[Triple]: """ Return all triples in the graph valid at time t. Uses interval tree for O(log n + k) performance. """ return self.temporal_index.stab(t) def entities_for_query(self, t_query: float, mention: str) -> List[str]: """ Simple entity linking: return all entities containing `mention` as substring. Replace with a proper entity linker (e.g. ELQ, BLINK) in production. """ return [e for e in self.entity_index if mention.lower() in e.lower()] # ------------------------------------------------------------------ # Chain validity-window intersection (benchmark/SFT construction only) # ------------------------------------------------------------------ @staticmethod def compose(window: ValidityWindow, triple: Triple, t_query: float) -> Optional[ValidityWindow]: """ Extend `window` by `triple` via validity-window intersection clamped to t_query. Used only in benchmark/SFT-data construction, not at inference (the retriever uses the per-hop valid_at(t_q) filter via neighbourhood()). Returns None if the composed window is empty. """ hop_window = ValidityWindow(triple.t_start, triple.t_end) return window.intersect(hop_window, t_query) # ------------------------------------------------------------------ # Sinusoidal temporal encoding # ------------------------------------------------------------------ @staticmethod def temporal_encoding(t: float, dim: int = 64) -> List[float]: """ Sinusoidal temporal positional encoding (following POSTRA, N04). Encodes a year float into a `dim`-dimensional vector. """ encoding = [] for i in range(0, dim, 2): freq = 1.0 / (10000 ** (i / dim)) encoding.append(math.sin(t * freq)) encoding.append(math.cos(t * freq)) return encoding[:dim] # ------------------------------------------------------------------ # Statistics # ------------------------------------------------------------------ def stats(self) -> dict: n_triples = len(self._all_triples) n_entities = len(self.entity_index) n_relations = len({t.relation for t in self._all_triples}) n_open_ended = sum(1 for t in self._all_triples if math.isinf(t.t_end)) n_inferred = 0 # populated during annotation phase; update after tagger runs return { "n_triples": n_triples, "n_entities": n_entities, "n_relations": n_relations, "n_currently_valid": n_open_ended, "n_inferred_windows": n_inferred, "pct_timestamped": round(100 * (n_triples - n_inferred) / max(n_triples, 1), 1), } def __repr__(self) -> str: s = self.stats() return ( f"TemporalKGIndexer(" f"{s['n_triples']:,} triples, " f"{s['n_entities']:,} entities, " f"{s['n_relations']:,} relations, " f"{s['pct_timestamped']}% explicitly timestamped)" ) # --------------------------------------------------------------------------- # LLM timestamp tagger scaffold # --------------------------------------------------------------------------- class LLMTimestampTagger: """ Scaffold for the LLM-based temporal tagger used when KG metadata lacks explicit timestamps (validity-window annotation). Replace `_call_llm` with your actual LLM API call. """ PROMPT_TEMPLATE = """ You are a temporal fact extractor. Given a knowledge graph triple and its associated text, extract the validity period of the fact as a start year and end year. Triple: ({subject}, {relation}, {object}) Associated text: {text} Respond in JSON: {{"t_start": , "t_end": }} If no temporal information is available, respond with {{"t_start": null, "t_end": null}}. """.strip() def __init__(self, llm_client=None, default_window_width: float = 50.0): """ Args: llm_client: any object with a .complete(prompt: str) -> str method. default_window_width: fallback window width (years) for triples where the tagger returns null (low confidence). """ self.llm_client = llm_client self.default_window_width = default_window_width def infer_window(self, triple: Triple, associated_text: str = "") -> Tuple[float, float]: """ Infer a validity window for a triple lacking explicit timestamps. Returns (t_start, t_end); t_end = math.inf if currently valid. """ if self.llm_client is None: # Fallback: return a wide default window centred on 1990 return (1900.0, math.inf) prompt = self.PROMPT_TEMPLATE.format( subject=triple.subject, relation=triple.relation, object=triple.obj, text=associated_text, ) try: response = self._call_llm(prompt) data = json.loads(response) t_start = float(data["t_start"]) if data.get("t_start") is not None else 1900.0 t_end = float(data["t_end"]) if data.get("t_end") is not None else math.inf return (t_start, t_end) except Exception: return (1900.0, math.inf) def _call_llm(self, prompt: str) -> str: """Override this with your actual LLM API call.""" return self.llm_client.complete(prompt) # --------------------------------------------------------------------------- # Quick test # --------------------------------------------------------------------------- if __name__ == "__main__": # Smoke test with synthetic quadruples indexer = TemporalKGIndexer() indexer.build([ ("Deutsche_Bank", "has_CFO", "John_Cryan", 2015.0, 2018.0), ("Deutsche_Bank", "has_CFO", "Christian_Sewing", 2018.0, math.inf), ("Deutsche_Bank", "settled", "LIBOR_Case", 2015.25, 2015.25), ("John_Cryan", "member_of", "Deutsche_Bank", 2015.0, 2018.0), ("Christian_Sewing", "member_of", "Deutsche_Bank", 2018.0, math.inf), ]) print(indexer) print() # Test 1: neighbourhood at query time 2015 nbrs = indexer.neighbourhood("Deutsche_Bank", t_query=2015.5) print(f"Deutsche_Bank neighbourhood at 2015.5: {len(nbrs)} triples") for t in nbrs: print(f" ({t.subject}, {t.relation}, {t.obj}) [{t.t_start}–{t.t_end}]") print() # Test 2: composability operator w = ValidityWindow.full() for triple in nbrs[:2]: composed = TemporalKGIndexer.compose(w, triple, t_query=2015.5) if composed: print(f"Composed window after ({triple.relation}): [{composed.t_start}, {composed.t_end}]") w = composed else: print(f"Chain broken at ({triple.relation}) — temporally inconsistent") print() # Test 3: temporal encoding enc = TemporalKGIndexer.temporal_encoding(2015.5, dim=8) print(f"Temporal encoding for 2015.5 (dim=8): {[round(x, 4) for x in enc]}")