|
| 1 | +""" |
| 2 | +knowledgecomplex.parametric — Parametric sequences over knowledge complexes. |
| 3 | +
|
| 4 | +A ParametricSequence represents a single complex viewed through a |
| 5 | +parameterized filter. Each parameter value selects a subcomplex — |
| 6 | +the sequence of subcomplexes can grow, shrink, or change arbitrarily |
| 7 | +as the parameter varies. |
| 8 | +
|
| 9 | +Unlike :class:`~knowledgecomplex.filtration.Filtration`, which enforces |
| 10 | +monotone nesting, a ParametricSequence is observational — it computes |
| 11 | +slices lazily from a filter function. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | +from typing import Any, Callable, Iterator, TYPE_CHECKING |
| 16 | + |
| 17 | +if TYPE_CHECKING: |
| 18 | + from knowledgecomplex.graph import KnowledgeComplex, Element |
| 19 | + |
| 20 | + |
| 21 | +class ParametricSequence: |
| 22 | + """ |
| 23 | + A complex viewed through a parameterized filter. |
| 24 | +
|
| 25 | + One complex holds all elements. A filter function decides which |
| 26 | + elements are active at each parameter value. The result is a |
| 27 | + sequence of subcomplexes indexed by parameter values. |
| 28 | +
|
| 29 | + Parameters |
| 30 | + ---------- |
| 31 | + kc : KnowledgeComplex |
| 32 | + The complex containing all elements. |
| 33 | + values : list |
| 34 | + Ordered parameter values (e.g. ``["Q1", "Q2", "Q3", "Q4"]``). |
| 35 | + filter : Callable[[Element, value], bool] |
| 36 | + Returns True if the element is active at the given parameter value. |
| 37 | +
|
| 38 | + Example |
| 39 | + ------- |
| 40 | + >>> seq = ParametricSequence(kc, values=["1","2","3","4"], |
| 41 | + ... filter=lambda elem, t: elem.attrs.get("active_from","0") <= t) |
| 42 | + >>> seq[0] # element IDs active at "1" |
| 43 | + >>> seq.birth("carol") # first value where carol appears |
| 44 | + """ |
| 45 | + |
| 46 | + def __init__( |
| 47 | + self, |
| 48 | + kc: "KnowledgeComplex", |
| 49 | + values: list, |
| 50 | + filter: Callable[["Element", Any], bool], |
| 51 | + ) -> None: |
| 52 | + self._kc = kc |
| 53 | + self._values = list(values) |
| 54 | + self._filter = filter |
| 55 | + self._cache: dict[int, frozenset[str]] = {} |
| 56 | + |
| 57 | + def _compute(self, index: int) -> frozenset[str]: |
| 58 | + """Compute and cache the element set at a given index.""" |
| 59 | + if index not in self._cache: |
| 60 | + value = self._values[index] |
| 61 | + ids = frozenset( |
| 62 | + eid for eid in self._kc.element_ids() |
| 63 | + if self._filter(self._kc.element(eid), value) |
| 64 | + ) |
| 65 | + self._cache[index] = ids |
| 66 | + return self._cache[index] |
| 67 | + |
| 68 | + def __repr__(self) -> str: |
| 69 | + return f"ParametricSequence(steps={len(self._values)}, monotone={self.is_monotone})" |
| 70 | + |
| 71 | + # --- Indexing --- |
| 72 | + |
| 73 | + def __getitem__(self, key: int | Any) -> set[str]: |
| 74 | + if isinstance(key, int): |
| 75 | + return set(self._compute(key)) |
| 76 | + # Try to look up by parameter value |
| 77 | + try: |
| 78 | + index = self._values.index(key) |
| 79 | + except ValueError: |
| 80 | + raise KeyError(f"Parameter value {key!r} not in values list") |
| 81 | + return set(self._compute(index)) |
| 82 | + |
| 83 | + def __len__(self) -> int: |
| 84 | + return len(self._values) |
| 85 | + |
| 86 | + def __iter__(self) -> Iterator[tuple[Any, set[str]]]: |
| 87 | + for i, value in enumerate(self._values): |
| 88 | + yield value, set(self._compute(i)) |
| 89 | + |
| 90 | + # --- Properties --- |
| 91 | + |
| 92 | + @property |
| 93 | + def complex(self) -> "KnowledgeComplex": |
| 94 | + """The parent KnowledgeComplex.""" |
| 95 | + return self._kc |
| 96 | + |
| 97 | + @property |
| 98 | + def values(self) -> list: |
| 99 | + """The ordered parameter values.""" |
| 100 | + return list(self._values) |
| 101 | + |
| 102 | + @property |
| 103 | + def is_monotone(self) -> bool: |
| 104 | + """True if every step is a superset of the previous (filtration-like).""" |
| 105 | + for i in range(1, len(self._values)): |
| 106 | + if not (self._compute(i - 1) <= self._compute(i)): |
| 107 | + return False |
| 108 | + return True |
| 109 | + |
| 110 | + # --- Queries --- |
| 111 | + |
| 112 | + def birth(self, element_id: str) -> Any: |
| 113 | + """Return the first parameter value where the element appears. |
| 114 | +
|
| 115 | + Raises |
| 116 | + ------ |
| 117 | + ValueError |
| 118 | + If the element does not appear at any parameter value. |
| 119 | + """ |
| 120 | + for i, value in enumerate(self._values): |
| 121 | + if element_id in self._compute(i): |
| 122 | + return value |
| 123 | + raise ValueError(f"Element '{element_id}' not found at any parameter value") |
| 124 | + |
| 125 | + def death(self, element_id: str) -> Any | None: |
| 126 | + """Return the first parameter value where the element disappears. |
| 127 | +
|
| 128 | + Returns None if the element is present at all values after its birth, |
| 129 | + or if it never appears. |
| 130 | + """ |
| 131 | + appeared = False |
| 132 | + for i in range(len(self._values)): |
| 133 | + present = element_id in self._compute(i) |
| 134 | + if present: |
| 135 | + appeared = True |
| 136 | + elif appeared: |
| 137 | + return self._values[i] |
| 138 | + return None |
| 139 | + |
| 140 | + def active_at(self, element_id: str) -> list: |
| 141 | + """Return the list of parameter values where the element is present.""" |
| 142 | + return [ |
| 143 | + self._values[i] |
| 144 | + for i in range(len(self._values)) |
| 145 | + if element_id in self._compute(i) |
| 146 | + ] |
| 147 | + |
| 148 | + def new_at(self, index: int) -> set[str]: |
| 149 | + """Return elements appearing at step index that were not in step index-1.""" |
| 150 | + current = self._compute(index) |
| 151 | + if index == 0: |
| 152 | + return set(current) |
| 153 | + previous = self._compute(index - 1) |
| 154 | + return set(current - previous) |
| 155 | + |
| 156 | + def removed_at(self, index: int) -> set[str]: |
| 157 | + """Return elements present at step index-1 that are absent at step index.""" |
| 158 | + if index == 0: |
| 159 | + return set() |
| 160 | + current = self._compute(index) |
| 161 | + previous = self._compute(index - 1) |
| 162 | + return set(previous - current) |
| 163 | + |
| 164 | + def subcomplex_at(self, index: int) -> bool: |
| 165 | + """Check if the slice at index is a valid subcomplex (closed under boundary).""" |
| 166 | + return self._kc.is_subcomplex(set(self._compute(index))) |
0 commit comments