bioconverge 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.4
2
+ Name: bioconverge
3
+ Version: 0.1.0
4
+ Requires-Python: >=3.8
5
+ Requires-Dist: numpy
6
+ Requires-Dist: pandas
7
+ Requires-Dist: scipy
8
+ Requires-Dist: scikit-learn
9
+ Requires-Dist: matplotlib
10
+ Requires-Dist: seaborn
11
+ Requires-Dist: lifelines
12
+ Requires-Dist: umap-learn
13
+ Requires-Dist: hdbscan
14
+ Requires-Dist: requests
15
+ Requires-Dist: plotly
16
+ Requires-Dist: nbformat
17
+ Dynamic: requires-dist
18
+ Dynamic: requires-python
@@ -0,0 +1,86 @@
1
+ # bioconverge
2
+
3
+ Multi-layer biological score integration and hypothesis validation tool for cancer research.
4
+
5
+ ## What it does
6
+
7
+ bioconverge takes multiple biological scores per patient (transcriptomic, genomic, imaging, clinical) and runs them through four layers:
8
+
9
+ - **Layer 1** — finds which scores agree and which conflict per patient, assigns convergence strata and discordance archetypes
10
+ - **Layer 2** — computes per-patient biological fragility using model gradient perturbation
11
+ - **Layer 3** — generates ranked hypotheses for each archetype by querying Reactome, Enrichr, STRING, GWAS Catalog, and PubMed
12
+ - **Layer 4** — validates each hypothesis across four independent sources (survival, replication cohort, known-biology benchmark, literature) and assigns Tier A / B / C confidence
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install bioconverge
18
+ ```
19
+
20
+ ## Quick start
21
+
22
+ ```python
23
+ import bioconverge as bc
24
+
25
+ result = bc.integrate(
26
+ scores="my_scores.csv",
27
+ patient_col="patient_id",
28
+ score_metadata={
29
+ "immune_score": {"process": "T-cell exhaustion", "modality": "transcriptomic", "genes": ["CD8A", "CD8B", "GZMA", "PRF1"]},
30
+ "genomic_score": {"process": "DNA repair instability", "modality": "genomic", "genes": ["BRCA1", "BRCA2", "ATM"]}
31
+ },
32
+ outcome="survival.csv",
33
+ time_col="OS_days",
34
+ event_col="OS_event"
35
+ )
36
+
37
+ result.concordance()
38
+ result.hypotheses()
39
+ result.report("output/")
40
+ ```
41
+
42
+ ## TNBC demonstration
43
+
44
+ The full demonstration on 116 TCGA-BRCA triple-negative breast cancer patients is in `notebooks/01_TNBC_demo.ipynb`.
45
+
46
+ Datasets required:
47
+
48
+ | Dataset | Source |
49
+ |---|---|
50
+ | TCGA-BRCA clinical | https://portal.gdc.cancer.gov/projects/TCGA-BRCA |
51
+ | TCGA-BRCA mutations | http://gdac.broadinstitute.org |
52
+ | TCGA-BRCA RNA-seq | http://gdac.broadinstitute.org |
53
+ | METABRIC clinical | https://www.cbioportal.org/study/summary?id=brca_metabric |
54
+ | Lehmann subtypes | https://www.cbioportal.org/study/summary?id=brca_tcga |
55
+ | MSigDB Hallmark | https://www.gsea-msigdb.org/gsea/msigdb |
56
+
57
+ ## Output
58
+
59
+ Running `result.report("output/")` produces:
60
+
61
+ - `summary.html` — interactive concordance matrix and patient strata
62
+ - `per_patient_scores.csv` — convergence index, archetype, fragility per patient
63
+ - `hypotheses_ranked.csv` — full hypothesis table with Tier A/B/C labels
64
+ - `reproducibility_log.txt` — all API queries with timestamps
65
+ - `kaplan_meier/` — survival plots per archetype
66
+ - `fragility_topology.png` — UMAP of patient fragility clusters
67
+
68
+ ## Confidence tiers
69
+
70
+ | Tier | Meaning | Validation sources passed |
71
+ |---|---|---|
72
+ | A | finding | 3 or 4 |
73
+ | B | supported hypothesis | 2 |
74
+ | C | exploratory | 0 or 1 |
75
+
76
+ ## Requirements
77
+
78
+ ```
79
+ numpy, pandas, scipy, scikit-learn, matplotlib, seaborn,
80
+ lifelines, umap-learn, hdbscan, requests, plotly, torch,
81
+ tensorflow, jupyter
82
+ ```
83
+
84
+ ## License
85
+
86
+ MIT
@@ -0,0 +1,138 @@
1
+ import os
2
+
3
+ import pandas as pd
4
+
5
+ from .layer1 import ConcordanceAnalyzer
6
+ from .layer2 import FragilityAnalyzer
7
+ from .layer3 import HypothesisGenerator
8
+ from .layer4 import ValidationEngine
9
+ from .report import BioConvergeResult
10
+ from .utils import parse_gmt
11
+
12
+
13
+ def integrate(
14
+ scores,
15
+ patient_col="patient_id",
16
+ score_metadata=None,
17
+ models=None,
18
+ feature_matrix=None,
19
+ pathway_constraints=None,
20
+ outcome=None,
21
+ time_col="OS_days",
22
+ event_col="OS_event",
23
+ dataset_dir=None,
24
+ n_archetypes=3,
25
+ n_bootstrap=1000,
26
+ random_state=42,
27
+ output_dir="output",
28
+ ):
29
+ skipped = []
30
+ print("bioconverge starting")
31
+
32
+ # load scores
33
+ if isinstance(scores, str):
34
+ if not os.path.exists(scores):
35
+ raise FileNotFoundError(f"scores file not found: {scores}")
36
+ score_df = pd.read_csv(scores)
37
+ else:
38
+ score_df = scores.copy()
39
+
40
+ score_cols = [c for c in score_df.columns if c != patient_col]
41
+ if len(score_cols) == 0:
42
+ raise ValueError("no score columns found")
43
+
44
+ # layer 1
45
+ print("layer1")
46
+ l1 = ConcordanceAnalyzer(score_df, patient_col)
47
+ l1.fit(n_archetypes=n_archetypes, n_bootstrap=n_bootstrap, random_state=random_state)
48
+
49
+ # layer 2
50
+ l2 = None
51
+ if models is not None and feature_matrix is not None:
52
+ print("layer2")
53
+ gene_sets = None
54
+ if pathway_constraints is not None:
55
+ if isinstance(pathway_constraints, str) and os.path.exists(pathway_constraints):
56
+ gene_sets = parse_gmt(pathway_constraints)
57
+ elif pathway_constraints == "hallmark" and dataset_dir:
58
+ gmt_path = os.path.join(dataset_dir, "h.all.v2023.2.Hs.symbols.gmt")
59
+ if os.path.exists(gmt_path):
60
+ gene_sets = parse_gmt(gmt_path)
61
+ import numpy as np
62
+ X = np.array(feature_matrix)
63
+ patient_ids = score_df[patient_col].values
64
+ feat_names = None
65
+ if hasattr(feature_matrix, "columns"):
66
+ feat_names = list(feature_matrix.columns)
67
+ l2 = FragilityAnalyzer(
68
+ models=models,
69
+ X=X,
70
+ patient_ids=patient_ids,
71
+ feature_names=feat_names,
72
+ gene_sets=gene_sets,
73
+ )
74
+ l2.fit(output_dir=output_dir)
75
+ else:
76
+ skipped.append("layer2")
77
+ print("layer2 skipped")
78
+
79
+ # layer 3
80
+ l3 = None
81
+ if score_metadata is not None:
82
+ print("layer3")
83
+ archetypes_df = l1.archetypes()
84
+ frag_df = l2.fragility() if l2 is not None else None
85
+ l3 = HypothesisGenerator(score_metadata, archetypes_df, fragility_df=frag_df)
86
+ l3.generate()
87
+ else:
88
+ skipped.append("layer3")
89
+ print("layer3 skipped")
90
+
91
+ # layer 4
92
+ l4 = None
93
+ if l3 is not None:
94
+ print("layer4")
95
+ clinical_tar = None
96
+ mut_tar = None
97
+ metabric_path = None
98
+ tcga_brca_path = None
99
+ if dataset_dir:
100
+ for fname in os.listdir(dataset_dir):
101
+ fpath = os.path.join(dataset_dir, fname)
102
+ if "clinical" in fname and fname.endswith(".tar.gz"):
103
+ clinical_tar = fpath
104
+ elif "Mutation_Packager" in fname and fname.endswith(".tar.gz"):
105
+ mut_tar = fpath
106
+ elif "metabric" in fname and fname.endswith(".tsv"):
107
+ metabric_path = fpath
108
+ elif "brca_tcga" in fname and fname.endswith(".tsv"):
109
+ tcga_brca_path = fpath
110
+ l4 = ValidationEngine(
111
+ clinical_tar_path=clinical_tar,
112
+ mut_tar_path=mut_tar,
113
+ metabric_path=metabric_path,
114
+ tcga_brca_path=tcga_brca_path,
115
+ dataset_dir=dataset_dir,
116
+ )
117
+ km_dir = os.path.join(output_dir, "kaplan_meier")
118
+ l4.validate(
119
+ hypotheses_df=l3.hypotheses(),
120
+ archetypes_df=l1.archetypes(),
121
+ score_df=score_df,
122
+ patient_col=patient_col,
123
+ score_metadata=score_metadata,
124
+ km_output_dir=km_dir,
125
+ )
126
+ hyp = l3.hypotheses()
127
+ if hyp is not None and not hyp.empty:
128
+ l4.compute_replication_rate(hyp)
129
+ else:
130
+ skipped.append("layer4")
131
+ print("layer4 skipped")
132
+
133
+ if skipped:
134
+ print(f"skipped: {', '.join(skipped)}")
135
+
136
+ result = BioConvergeResult(l1=l1, l2=l2, l3=l3, l4=l4, skipped=skipped)
137
+ print("done")
138
+ return result
@@ -0,0 +1,168 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ from scipy.stats import spearmanr
4
+ from sklearn.cluster import KMeans
5
+ from sklearn.metrics import adjusted_rand_score
6
+ from sklearn.preprocessing import StandardScaler
7
+
8
+
9
+ class ConcordanceAnalyzer:
10
+ def __init__(self, df, patient_col):
11
+ self.patient_col = patient_col
12
+ self.patients = df[patient_col].values
13
+ self.score_cols = [c for c in df.columns if c != patient_col]
14
+ self.X = df[self.score_cols].apply(pd.to_numeric, errors="coerce").values
15
+ self._concordance_df = None
16
+ self._convergence_df = None
17
+ self._archetypes_df = None
18
+ self._stability_dict = None
19
+ self._km_model = None
20
+ self._scaler = None
21
+
22
+ def fit(self, n_archetypes=3, n_bootstrap=1000, random_state=42):
23
+ print("fitting concordance")
24
+ self._compute_concordance(n_bootstrap, random_state)
25
+ self._compute_convergence()
26
+ self._compute_archetypes(n_archetypes, random_state)
27
+ self._compute_stability(n_archetypes, n_bootstrap, random_state)
28
+ print("layer1 done")
29
+ return self
30
+
31
+ def _compute_concordance(self, n_bootstrap, random_state):
32
+ rng = np.random.default_rng(random_state)
33
+ n = len(self.score_cols)
34
+ rows = []
35
+ for i in range(n):
36
+ for j in range(i + 1, n):
37
+ x = self.X[:, i]
38
+ y = self.X[:, j]
39
+ mask = ~(np.isnan(x) | np.isnan(y))
40
+ if mask.sum() < 5:
41
+ rows.append({
42
+ "score_a": self.score_cols[i],
43
+ "score_b": self.score_cols[j],
44
+ "spearman_rho": np.nan,
45
+ "ci_lo": np.nan,
46
+ "ci_hi": np.nan,
47
+ "n_patients": int(mask.sum()),
48
+ })
49
+ continue
50
+ rho, _ = spearmanr(x[mask], y[mask])
51
+ xm, ym = x[mask], y[mask]
52
+ boot = []
53
+ for _ in range(n_bootstrap):
54
+ idx = rng.integers(0, len(xm), size=len(xm))
55
+ try:
56
+ rb, _ = spearmanr(xm[idx], ym[idx])
57
+ boot.append(rb)
58
+ except Exception:
59
+ pass
60
+ ci_lo = float(np.percentile(boot, 2.5)) if boot else np.nan
61
+ ci_hi = float(np.percentile(boot, 97.5)) if boot else np.nan
62
+ rows.append({
63
+ "score_a": self.score_cols[i],
64
+ "score_b": self.score_cols[j],
65
+ "spearman_rho": float(rho),
66
+ "ci_lo": ci_lo,
67
+ "ci_hi": ci_hi,
68
+ "n_patients": int(mask.sum()),
69
+ })
70
+ self._concordance_df = pd.DataFrame(rows)
71
+
72
+ def _compute_convergence(self):
73
+ global_means = np.nanmean(self.X, axis=0)
74
+ global_stds = np.nanstd(self.X, axis=0)
75
+ global_stds[global_stds == 0] = 1.0
76
+ patient_conv = []
77
+ for p_idx in range(len(self.patients)):
78
+ vals = self.X[p_idx]
79
+ valid = ~np.isnan(vals)
80
+ if valid.sum() < 2:
81
+ patient_conv.append(np.nan)
82
+ continue
83
+ z = (vals[valid] - global_means[valid]) / global_stds[valid]
84
+ mean_z = np.mean(z)
85
+ std_z = np.std(z)
86
+ conv = 1.0 - std_z / (abs(mean_z) + 1e-8)
87
+ patient_conv.append(float(conv))
88
+ conv_series = pd.Series(patient_conv)
89
+ t33 = conv_series.quantile(0.33)
90
+ t67 = conv_series.quantile(0.67)
91
+
92
+ def _stratum(v):
93
+ if pd.isna(v):
94
+ return "unknown"
95
+ if v >= t67:
96
+ return "convergent_high"
97
+ if v >= t33:
98
+ return "convergent_mid"
99
+ return "convergent_low"
100
+
101
+ self._convergence_df = pd.DataFrame({
102
+ "patient_id": self.patients,
103
+ "convergence_index": patient_conv,
104
+ "stratum": [_stratum(v) for v in patient_conv],
105
+ })
106
+
107
+ def _fill_X(self):
108
+ X_filled = self.X.copy()
109
+ for j in range(X_filled.shape[1]):
110
+ col = X_filled[:, j]
111
+ med = np.nanmedian(col)
112
+ col[np.isnan(col)] = med if not np.isnan(med) else 0.0
113
+ return X_filled
114
+
115
+ def _compute_archetypes(self, n_archetypes, random_state):
116
+ X_filled = self._fill_X()
117
+ scaler = StandardScaler()
118
+ X_scaled = scaler.fit_transform(X_filled)
119
+ km = KMeans(n_clusters=n_archetypes, random_state=random_state, n_init=10)
120
+ labels = km.fit_predict(X_scaled)
121
+ self._km_model = km
122
+ self._scaler = scaler
123
+ self._archetypes_df = pd.DataFrame({
124
+ "patient_id": self.patients,
125
+ "archetype": labels,
126
+ })
127
+
128
+ def _compute_stability(self, n_archetypes, n_bootstrap, random_state):
129
+ rng = np.random.default_rng(random_state)
130
+ X_filled = self._fill_X()
131
+ scaler = StandardScaler()
132
+ X_scaled = scaler.fit_transform(X_filled)
133
+ base_labels = self._archetypes_df["archetype"].values
134
+ n_iters = min(n_bootstrap, 200)
135
+ aris = []
136
+ for _ in range(n_iters):
137
+ idx = rng.integers(0, len(X_scaled), size=len(X_scaled))
138
+ try:
139
+ km2 = KMeans(n_clusters=n_archetypes, random_state=None, n_init=3, max_iter=100)
140
+ km2.fit(X_scaled[idx])
141
+ pred = km2.predict(X_scaled)
142
+ aris.append(adjusted_rand_score(base_labels, pred))
143
+ except Exception:
144
+ pass
145
+ self._stability_dict = {
146
+ "mean_ari": float(np.mean(aris)) if aris else np.nan,
147
+ "std_ari": float(np.std(aris)) if aris else np.nan,
148
+ "n_bootstrap": len(aris),
149
+ "interpretation": "stable" if (aris and np.mean(aris) > 0.6) else "unstable",
150
+ }
151
+
152
+ def concordance(self):
153
+ return self._concordance_df
154
+
155
+ def convergence(self):
156
+ return self._convergence_df
157
+
158
+ def discordance(self):
159
+ if self._archetypes_df is None or self._convergence_df is None:
160
+ return None
161
+ merged = self._archetypes_df.merge(self._convergence_df, on="patient_id")
162
+ return merged[merged["stratum"] == "convergent_low"].copy().reset_index(drop=True)
163
+
164
+ def archetypes(self):
165
+ return self._archetypes_df
166
+
167
+ def stability(self):
168
+ return self._stability_dict
@@ -0,0 +1,269 @@
1
+ import os
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ import matplotlib
6
+ matplotlib.use("Agg")
7
+ import matplotlib.pyplot as plt
8
+
9
+
10
+ def _predict_proba_sklearn(model, X):
11
+ if hasattr(model, "predict_proba"):
12
+ return model.predict_proba(X)[:, 1]
13
+ return model.predict(X).ravel()
14
+
15
+
16
+ def _finite_diff_gradient(model, X, eps=1e-4, backend="sklearn"):
17
+ n, d = X.shape
18
+ grads = np.zeros((n, d))
19
+ base = _get_predictions(model, X, backend)
20
+ for j in range(d):
21
+ Xp = X.copy()
22
+ Xp[:, j] += eps
23
+ pred_p = _get_predictions(model, Xp, backend)
24
+ grads[:, j] = (pred_p - base) / eps
25
+ return grads
26
+
27
+
28
+ def _get_predictions(model, X, backend):
29
+ if backend == "sklearn":
30
+ if hasattr(model, "predict_proba"):
31
+ return model.predict_proba(X)[:, 1]
32
+ return model.predict(X).ravel()
33
+ if backend == "torch":
34
+ import torch
35
+ model.eval()
36
+ with torch.no_grad():
37
+ t = torch.tensor(X, dtype=torch.float32)
38
+ out = model(t)
39
+ if out.dim() > 1 and out.shape[1] > 1:
40
+ out = torch.softmax(out, dim=1)[:, 1]
41
+ return out.numpy().ravel()
42
+ if backend == "tensorflow":
43
+ import tensorflow as tf
44
+ t = tf.constant(X, dtype=tf.float32)
45
+ out = model(t)
46
+ return out.numpy().ravel()
47
+ raise ValueError(f"unknown backend: {backend}")
48
+
49
+
50
+ def _torch_gradient(model, X):
51
+ import torch
52
+ model.eval()
53
+ t = torch.tensor(X, dtype=torch.float32, requires_grad=True)
54
+ out = model(t)
55
+ if out.dim() > 1 and out.shape[1] > 1:
56
+ out = torch.softmax(out, dim=1)[:, 1]
57
+ loss = out.sum()
58
+ loss.backward()
59
+ return t.grad.detach().numpy()
60
+
61
+
62
+ def _tf_gradient(model, X):
63
+ import tensorflow as tf
64
+ t = tf.constant(X, dtype=tf.float32)
65
+ with tf.GradientTape() as tape:
66
+ tape.watch(t)
67
+ out = model(t)
68
+ if len(out.shape) > 1 and out.shape[1] > 1:
69
+ out = tf.nn.softmax(out)[:, 1]
70
+ loss = tf.reduce_sum(out)
71
+ return tape.gradient(loss, t).numpy()
72
+
73
+
74
+ def _detect_backend(model):
75
+ cls = type(model).__module__
76
+ if "sklearn" in cls:
77
+ return "sklearn"
78
+ try:
79
+ import torch
80
+ if isinstance(model, torch.nn.Module):
81
+ return "torch"
82
+ except ImportError:
83
+ pass
84
+ try:
85
+ import tensorflow as tf
86
+ if isinstance(model, tf.Module):
87
+ return "tensorflow"
88
+ except ImportError:
89
+ pass
90
+ return "sklearn"
91
+
92
+
93
+ class FragilityAnalyzer:
94
+ def __init__(self, models, X, patient_ids=None, feature_names=None, gene_sets=None):
95
+ if isinstance(models, dict):
96
+ self.models = models
97
+ else:
98
+ self.models = {"model": models}
99
+ self.X = np.array(X, dtype=float)
100
+ self.patient_ids = patient_ids if patient_ids is not None else np.arange(len(self.X))
101
+ self.feature_names = feature_names if feature_names is not None else [f"f{i}" for i in range(self.X.shape[1])]
102
+ self.gene_sets = gene_sets
103
+ self._fragility_df = None
104
+ self._pathway_df = None
105
+ self._trajectory_df = None
106
+ self._topology_df = None
107
+ self._consistency_dict = None
108
+
109
+ def fit(self, output_dir=None):
110
+ print("fitting fragility")
111
+ self._compute_fragility()
112
+ if self.gene_sets:
113
+ self._compute_pathway_fragility()
114
+ self._compute_trajectory()
115
+ self._compute_topology(output_dir=output_dir)
116
+ if len(self.models) >= 2:
117
+ self._compute_consistency()
118
+ print("layer2 done")
119
+ return self
120
+
121
+ def _compute_gradients_single(self, model):
122
+ backend = _detect_backend(model)
123
+ if backend == "torch":
124
+ try:
125
+ return _torch_gradient(model, self.X)
126
+ except Exception:
127
+ return _finite_diff_gradient(model, self.X, backend=backend)
128
+ if backend == "tensorflow":
129
+ try:
130
+ return _tf_gradient(model, self.X)
131
+ except Exception:
132
+ return _finite_diff_gradient(model, self.X, backend=backend)
133
+ return _finite_diff_gradient(model, self.X, backend=backend)
134
+
135
+ def _compute_fragility(self):
136
+ all_grads = {}
137
+ for name, model in self.models.items():
138
+ grads = self._compute_gradients_single(model)
139
+ all_grads[name] = grads
140
+ mean_grad = np.mean([g for g in all_grads.values()], axis=0)
141
+ fragility_scores = np.linalg.norm(mean_grad, axis=1)
142
+ self._all_grads = all_grads
143
+ self._mean_grad = mean_grad
144
+ self._fragility_df = pd.DataFrame({
145
+ "patient_id": self.patient_ids,
146
+ "fragility_score": fragility_scores,
147
+ })
148
+ for name, grads in all_grads.items():
149
+ self._fragility_df[f"fragility_{name}"] = np.linalg.norm(grads, axis=1)
150
+
151
+ def _compute_pathway_fragility(self):
152
+ rows = []
153
+ feat_set = set(self.feature_names)
154
+ for pathway, genes in self.gene_sets.items():
155
+ idxs = [i for i, f in enumerate(self.feature_names) if f in genes]
156
+ if not idxs:
157
+ continue
158
+ pathway_grads = self._mean_grad[:, idxs]
159
+ pathway_fragility = np.linalg.norm(pathway_grads, axis=1)
160
+ rows.append({
161
+ "pathway": pathway,
162
+ "mean_fragility": float(np.mean(pathway_fragility)),
163
+ "max_fragility": float(np.max(pathway_fragility)),
164
+ "n_features": len(idxs),
165
+ })
166
+ if rows:
167
+ self._pathway_df = pd.DataFrame(rows).sort_values("mean_fragility", ascending=False).reset_index(drop=True)
168
+ else:
169
+ self._pathway_df = pd.DataFrame(columns=["pathway", "mean_fragility", "max_fragility", "n_features"])
170
+
171
+ def _compute_trajectory(self):
172
+ directions = self._mean_grad.copy()
173
+ norms = np.linalg.norm(directions, axis=1, keepdims=True)
174
+ norms[norms == 0] = 1.0
175
+ unit_dirs = directions / norms
176
+ rows = []
177
+ for i, pid in enumerate(self.patient_ids):
178
+ top_idx = np.argsort(np.abs(unit_dirs[i]))[::-1][:5]
179
+ top_feats = [self.feature_names[j] for j in top_idx]
180
+ top_vals = [float(unit_dirs[i, j]) for j in top_idx]
181
+ rows.append({
182
+ "patient_id": pid,
183
+ "top_features": top_feats,
184
+ "top_directions": top_vals,
185
+ "trajectory_norm": float(norms[i, 0]),
186
+ })
187
+ self._trajectory_df = pd.DataFrame(rows)
188
+
189
+ def _compute_topology(self, output_dir=None):
190
+ try:
191
+ import umap
192
+ import hdbscan
193
+ except ImportError:
194
+ self._topology_df = pd.DataFrame({
195
+ "patient_id": self.patient_ids,
196
+ "umap_x": np.nan,
197
+ "umap_y": np.nan,
198
+ "fragility_cluster": -1,
199
+ })
200
+ return
201
+ fragility_mat = self._mean_grad.copy()
202
+ norms = np.linalg.norm(fragility_mat, axis=1, keepdims=True)
203
+ norms[norms == 0] = 1.0
204
+ fragility_norm = fragility_mat / norms
205
+ n_samples = len(fragility_norm)
206
+ n_neighbors = min(15, n_samples - 1)
207
+ try:
208
+ reducer = umap.UMAP(n_neighbors=n_neighbors, n_components=2, random_state=42)
209
+ embedding = reducer.fit_transform(fragility_norm)
210
+ min_cluster = max(2, n_samples // 20)
211
+ clusterer = hdbscan.HDBSCAN(min_cluster_size=min_cluster)
212
+ labels = clusterer.fit_predict(embedding)
213
+ except Exception as e:
214
+ print(f"topology fallback: {e}")
215
+ embedding = np.zeros((n_samples, 2))
216
+ labels = np.zeros(n_samples, dtype=int)
217
+ self._topology_df = pd.DataFrame({
218
+ "patient_id": self.patient_ids,
219
+ "umap_x": embedding[:, 0],
220
+ "umap_y": embedding[:, 1],
221
+ "fragility_cluster": labels,
222
+ })
223
+ if output_dir:
224
+ os.makedirs(output_dir, exist_ok=True)
225
+ fig, ax = plt.subplots(figsize=(8, 6))
226
+ scatter = ax.scatter(embedding[:, 0], embedding[:, 1], c=labels, cmap="tab10", s=20, alpha=0.8)
227
+ ax.set_xlabel("UMAP 1")
228
+ ax.set_ylabel("UMAP 2")
229
+ ax.set_title("fragility topology")
230
+ plt.colorbar(scatter, ax=ax, label="cluster")
231
+ fig.savefig(os.path.join(output_dir, "fragility_topology.png"), dpi=150, bbox_inches="tight")
232
+ plt.close(fig)
233
+ print("saved topology")
234
+
235
+ def _compute_consistency(self):
236
+ model_names = list(self.models.keys())
237
+ scores = {}
238
+ for name in model_names:
239
+ scores[name] = np.linalg.norm(self._all_grads[name], axis=1)
240
+ from scipy.stats import spearmanr
241
+ pairs = []
242
+ for i in range(len(model_names)):
243
+ for j in range(i + 1, len(model_names)):
244
+ na, nb = model_names[i], model_names[j]
245
+ rho, pval = spearmanr(scores[na], scores[nb])
246
+ pairs.append({"model_a": na, "model_b": nb, "spearman_rho": float(rho), "pvalue": float(pval)})
247
+ mean_rho = np.mean([p["spearman_rho"] for p in pairs]) if pairs else np.nan
248
+ self._consistency_dict = {
249
+ "pairwise": pairs,
250
+ "mean_rho": float(mean_rho),
251
+ "consistent": bool(mean_rho > 0.5) if not np.isnan(mean_rho) else False,
252
+ }
253
+
254
+ def fragility(self):
255
+ return self._fragility_df
256
+
257
+ def fragility_pathways(self):
258
+ return self._pathway_df
259
+
260
+ def trajectory(self):
261
+ return self._trajectory_df
262
+
263
+ def topology(self):
264
+ return self._topology_df
265
+
266
+ def consistency(self):
267
+ if self._consistency_dict is None:
268
+ return {"message": "single model provided, no consistency check"}
269
+ return self._consistency_dict