File size: 4,199 Bytes
2eb3475
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""Stable persistence-diagram summary vectorisation (18 scalars).

Used by LGAP, RSCD, OWPS, GCLP, EAPT — every Phase-0..4 feature that
turns a small distance matrix into a Ripser persistence diagram and
needs a fixed-length, learnable summary.

Output (18 scalars, in order):
  H0:  count, sum_persistence, max_persistence, mean_persistence,
       std_persistence, entropy_of_persistence
  H1:  count, sum_persistence, max_persistence, mean_persistence,
       std_persistence, entropy_of_persistence
  cross: betti0_at_q25, betti0_at_q50, betti0_at_q75,
         betti1_at_q25, betti1_at_q50, betti1_at_q75
"""
from __future__ import annotations

from typing import List, Tuple

import numpy as np


def _safe_entropy(persistences: np.ndarray) -> float:
    if persistences.size == 0:
        return 0.0
    p = persistences / (persistences.sum() + 1e-12)
    p = np.clip(p, 1e-12, 1.0)
    return float(-(p * np.log(p)).sum())


def _persistence_stats(intervals: np.ndarray) -> List[float]:
    """intervals: (n, 2) array of [birth, death]. Returns 6 scalars."""
    if intervals.shape[0] == 0:
        return [0.0] * 6
    pers = intervals[:, 1] - intervals[:, 0]
    finite = pers[np.isfinite(pers)]
    if finite.size == 0:
        return [0.0] * 6
    return [
        float(finite.size),
        float(finite.sum()),
        float(finite.max()),
        float(finite.mean()),
        float(finite.std()),
        _safe_entropy(finite),
    ]


def _betti_counts(intervals: np.ndarray, thresholds: List[float]) -> List[float]:
    if intervals.shape[0] == 0:
        return [0.0] * len(thresholds)
    out = []
    for t in thresholds:
        born_before = intervals[:, 0] <= t
        die_after   = intervals[:, 1] >  t
        out.append(float((born_before & die_after).sum()))
    return out


def summarize_persistence(h0: np.ndarray, h1: np.ndarray,
                            quantiles=(0.25, 0.5, 0.75)) -> List[float]:
    """Return 18-dim summary of (H0, H1) persistence intervals."""
    feats = []
    feats.extend(_persistence_stats(h0))
    feats.extend(_persistence_stats(h1))

    # Pool intervals for threshold determination
    pooled = np.concatenate([h0, h1], axis=0) if (h0.size and h1.size) else (h0 if h0.size else h1)
    if pooled.shape[0] == 0:
        return feats + [0.0] * (2 * len(quantiles))
    finite_mask = np.isfinite(pooled).all(axis=1)
    pooled = pooled[finite_mask]
    if pooled.shape[0] == 0:
        return feats + [0.0] * (2 * len(quantiles))
    thresholds = list(np.quantile(pooled[:, 0], list(quantiles)))
    feats.extend(_betti_counts(h0, thresholds))
    feats.extend(_betti_counts(h1, thresholds))
    return feats


def column_names(prefix: str) -> List[str]:
    return [
        f"{prefix}_H0_count", f"{prefix}_H0_sum", f"{prefix}_H0_max",
        f"{prefix}_H0_mean", f"{prefix}_H0_std", f"{prefix}_H0_ent",
        f"{prefix}_H1_count", f"{prefix}_H1_sum", f"{prefix}_H1_max",
        f"{prefix}_H1_mean", f"{prefix}_H1_std", f"{prefix}_H1_ent",
        f"{prefix}_B0_q25", f"{prefix}_B0_q50", f"{prefix}_B0_q75",
        f"{prefix}_B1_q25", f"{prefix}_B1_q50", f"{prefix}_B1_q75",
    ]


def ripser_summary_from_distance(D: np.ndarray, maxdim: int = 1,
                                    prefix: str = "p") -> Tuple[List[float], List[str]]:
    """Run Ripser on a square distance matrix D and return an 18-scalar summary.

    Falls back to an all-zero feature vector if Ripser is unavailable or D is
    degenerate (one point, all-NaN, etc.).
    """
    try:
        from ripser import ripser
    except ImportError:
        return [0.0] * 18, column_names(prefix)

    if D.shape[0] < 2:
        return [0.0] * 18, column_names(prefix)
    D = np.nan_to_num(D, nan=0.0, posinf=1.0, neginf=0.0)
    # Symmetrise for Ripser
    D = 0.5 * (D + D.T)
    np.fill_diagonal(D, 0.0)
    try:
        res = ripser(D, distance_matrix=True, maxdim=maxdim)
        dgms = res["dgms"]
        h0 = dgms[0] if len(dgms) > 0 else np.zeros((0, 2))
        h1 = dgms[1] if len(dgms) > 1 else np.zeros((0, 2))
    except Exception:
        return [0.0] * 18, column_names(prefix)
    return summarize_persistence(h0, h1), column_names(prefix)