File size: 13,884 Bytes
0161e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
"""
CellBandit: FOCUS-inspired multi-armed bandit for cell prompt selection.

Adapted from FOCUS (Frame-Optimistic Confidence Upper-bound Selection).
Removes all temporal/video concepts; keeps the Bernstein UCB formula
and coarse-fine-select three-stage structure.
"""

import math
from typing import Callable, Dict, List, Optional, Tuple

import numpy as np


class CellBandit:
    """
    Multi-armed bandit for selecting optimal cells from a candidate pool.

    Each arm is a (cell_type, cluster_id) group. The algorithm:
      1. Coarse: sample a few cells per arm, score via similarity_fn
      2. UCB: rank arms by mean + confidence bound (Bernstein)
      3. Fine: sample more cells from top arms
      4. Select: top_ratio direct picks + softmax-weighted sampling
    """

    def __init__(
        self,
        similarity_fn: Callable[[np.ndarray, List[int]], List[float]],
        zoom_ratio: float = 0.25,
        min_zoom_arms: int = 2,
        coarse_samples_per_arm: int = 10,
        coarse_ratio: float = 0.2,
        extra_fine_samples_per_arm: int = 10,
        min_variance_threshold: float = 1e-6,
        exploration_weight: float = 1.0,
        top_ratio: float = 0.2,
        temperature: float = 0.06,
    ):
        """
        Args:
            similarity_fn: fn(query_embedding, cell_indices) -> List[float]
            zoom_ratio: Fraction of arms to zoom into for fine sampling.
            min_zoom_arms: Minimum number of arms to zoom into.
            coarse_samples_per_arm: Minimum coarse samples per arm.
            coarse_ratio: Minimum fraction of each arm to sample in coarse phase.
            extra_fine_samples_per_arm: Extra samples per arm in fine phase.
            min_variance_threshold: Floor for variance in UCB.
            exploration_weight: Scales the exploration bonus (lower = more exploitation).
            top_ratio: Fraction of k selected directly from top scores.
            temperature: Softmax temperature for within-arm sampling.
        """
        self.similarity_fn = similarity_fn
        self.zoom_ratio = zoom_ratio
        self.min_zoom_arms = min_zoom_arms
        self.coarse_samples_per_arm = coarse_samples_per_arm
        self.coarse_ratio = coarse_ratio
        self.extra_fine_samples_per_arm = extra_fine_samples_per_arm
        self.min_variance_threshold = min_variance_threshold
        self.exploration_weight = exploration_weight
        self.top_ratio = top_ratio
        self.temperature = temperature

    def select_cells(
        self,
        query_embedding: np.ndarray,
        arms: List[Dict],
        k: int,
        rng: Optional[np.random.Generator] = None,
    ) -> Tuple[List[int], Dict]:
        """
        Select k cells from the pool using FOCUS-style bandit.

        Args:
            query_embedding: Mean embedding of query cells.
            arms: List of arm dicts, each with 'cell_indices' and metadata.
            k: Number of cells to select.
            rng: Random number generator.

        Returns:
            (selected_indices, details) where selected_indices are pool indices.
        """
        if rng is None:
            rng = np.random.default_rng()

        # Reset arm statistics
        for arm in arms:
            arm["samples"] = 0
            arm["mean_sim"] = 0.0
            arm["variance"] = 0.0
            arm["focus_score"] = 0.0
            arm["sampled_indices"] = []
            arm["sampled_scores"] = []

        # Stage 1: Coarse sampling
        coarse_indices = self._coarse_sampling(arms, rng)
        if coarse_indices:
            coarse_scores = self.similarity_fn(query_embedding, coarse_indices)
            self._update_arms_with_scores(arms, coarse_indices, coarse_scores)
            self._update_focus_scores(arms)

        for arm in arms:
            arm["focus_after_coarse"] = float(arm["focus_score"])

        # Stage 2: Choose promising arms
        selected_arms = self._choose_promising_arms(arms)

        # Stage 3: Fine sampling in promising arms
        coarse_set = set(coarse_indices)
        fine_indices = self._fine_sampling(selected_arms, coarse_set, rng)
        if fine_indices:
            fine_scores = self.similarity_fn(query_embedding, fine_indices)
            self._update_arms_with_scores(arms, fine_indices, fine_scores)
            self._update_focus_scores(arms)

        for arm in arms:
            arm["focus_after_fine"] = float(arm["focus_score"])

        # Merge all scores
        all_scores: Dict[int, float] = {}
        for arm in arms:
            for idx, score in arm["sampled_scores"]:
                all_scores[idx] = score

        # Stage 4a: Top picks
        selected = self._select_top_cells(all_scores, k)

        # Stage 4b: Remaining via softmax within top arms
        remaining = k - len(selected)
        if remaining > 0:
            additional = self._select_remaining_cells(
                arms, remaining, all_scores, set(selected), rng
            )
            selected.extend(additional)

        selected = selected[:k]

        details = self._prepare_details(arms, selected, coarse_indices, fine_indices)
        return selected, details

    # ------------------------------------------------------------------
    # Internal stages
    # ------------------------------------------------------------------

    def _coarse_sampling(self, arms: List[Dict], rng: np.random.Generator) -> List[int]:
        """Sample cells from each arm. Uses max(coarse_samples_per_arm, coarse_ratio * arm_size)."""
        all_indices: List[int] = []
        for arm in arms:
            cell_indices = arm["cell_indices"]
            # Adaptive: sample at least coarse_ratio of each arm
            n_from_ratio = max(1, int(np.ceil(len(cell_indices) * self.coarse_ratio)))
            n_sample = min(max(self.coarse_samples_per_arm, n_from_ratio), len(cell_indices))
            if n_sample == 0:
                continue
            sampled = rng.choice(cell_indices, size=n_sample, replace=False).tolist()
            arm["sampled_indices"] = sampled
            all_indices.extend(sampled)
        return all_indices

    def _update_arms_with_scores(
        self, arms: List[Dict], indices: List[int], scores: List[float]
    ) -> None:
        """Update arms with new scores and recompute statistics."""
        idx_to_score = dict(zip(indices, scores))

        for arm in arms:
            existing_idx_set = {idx for idx, _ in arm["sampled_scores"]}
            for idx in arm["sampled_indices"]:
                if idx in idx_to_score and idx not in existing_idx_set:
                    arm["sampled_scores"].append((idx, idx_to_score[idx]))
                    existing_idx_set.add(idx)

            if arm["sampled_scores"]:
                all_arm_scores = [s for _, s in arm["sampled_scores"]]
                arm["samples"] = len(all_arm_scores)
                arm["mean_sim"] = float(np.mean(all_arm_scores))
                arm["variance"] = (
                    float(np.var(all_arm_scores)) if len(all_arm_scores) > 1 else 0.0
                )

    def _update_focus_scores(self, arms: List[Dict]) -> None:
        """Compute FOCUS UCB scores (Bernstein confidence bound).

        Formula: mean + w * [sqrt(2*log(N)*var/n) + 3*log(N)/n]
        Based on FOCUS focus.py:424-453, with exploration_weight (w) scaling.
        """
        total_samples = sum(arm["samples"] for arm in arms)
        w = self.exploration_weight

        for arm in arms:
            n_i = arm["samples"]
            mean = arm["mean_sim"]
            var = max(arm["variance"], self.min_variance_threshold)

            focus_score = mean
            if total_samples > 1 and n_i > 0:
                focus_score += w * math.sqrt(
                    max(0.0, 2 * math.log(total_samples) * var / n_i)
                )
                focus_score += w * 3 * math.log(total_samples) / n_i
            arm["focus_score"] = focus_score

    def _choose_promising_arms(self, arms: List[Dict]) -> List[Dict]:
        """Select top zoom_ratio fraction of arms by FOCUS score."""
        arms_sorted = sorted(arms, key=lambda x: x["focus_score"], reverse=True)
        n_select = max(self.min_zoom_arms, int(np.ceil(len(arms) * self.zoom_ratio)))
        n_select = min(n_select, len(arms))
        return arms_sorted[:n_select]

    def _fine_sampling(
        self,
        selected_arms: List[Dict],
        coarse_set: set,
        rng: np.random.Generator,
    ) -> List[int]:
        """Sample extra cells from promising arms."""
        fine: List[int] = []
        for arm in selected_arms:
            available = [i for i in arm["cell_indices"] if i not in coarse_set]
            n_sample = min(self.extra_fine_samples_per_arm, len(available))
            if n_sample > 0:
                sampled = rng.choice(available, size=n_sample, replace=False).tolist()
                arm["sampled_indices"].extend(sampled)
                fine.extend(sampled)
        return fine

    def _select_top_cells(
        self, all_scores: Dict[int, float], k: int
    ) -> List[int]:
        """Select top_ratio * k cells with highest scores."""
        if not all_scores or k <= 0:
            return []
        k_top = int(round(self.top_ratio * min(k, len(all_scores))))
        sorted_scores = sorted(all_scores.items(), key=lambda x: x[1], reverse=True)
        return [idx for idx, _ in sorted_scores[:k_top]]

    def _select_remaining_cells(
        self,
        arms: List[Dict],
        count: int,
        all_scores: Dict[int, float],
        selected_set: set,
        rng: np.random.Generator,
    ) -> List[int]:
        """Softmax-weighted sampling within top arms (no temporal gap).

        Final selection ranks arms by mean_sim (exploitation-focused),
        not focus_score, since we want the best cells, not exploration.
        """
        if count <= 0 or not arms:
            return []

        total_arms = len(arms)
        S = int(np.ceil(total_arms * max(0.0, min(1.0, self.zoom_ratio))))
        S = max(self.min_zoom_arms, S)
        S = min(S, total_arms)

        # Use mean_sim for final arm ranking (exploitation)
        arms_sorted = sorted(
            enumerate(arms), key=lambda x: x[1]["mean_sim"], reverse=True
        )
        top_arm_entries = arms_sorted[:S]

        # Even allocation across top arms
        base_alloc = count // S
        rem = count % S
        per_arm_need = [base_alloc + (1 if i < rem else 0) for i in range(S)]

        new_cells: List[int] = []
        current_selected = set(selected_set)

        for rank, (_, arm) in enumerate(top_arm_entries):
            needed = per_arm_need[rank]
            if needed == 0:
                continue

            available = [i for i in arm["cell_indices"] if i not in current_selected]
            if not available:
                continue

            # Collect scores for available candidates
            scored = [(c, all_scores[c]) for c in available if c in all_scores]
            unscored = [c for c in available if c not in all_scores]

            if scored:
                candidates, scores_arr = zip(*scored)
                candidates = list(candidates)
                scores_arr = np.array(scores_arr, dtype=np.float64)

                # Normalize to [0, 1]
                if scores_arr.max() > scores_arr.min():
                    scores_arr = (scores_arr - scores_arr.min()) / (
                        scores_arr.max() - scores_arr.min()
                    )
                else:
                    scores_arr = np.ones_like(scores_arr)

                # Softmax with temperature
                logits = scores_arr / max(1e-12, self.temperature)
                logits = logits - logits.max()
                probs = np.exp(logits)
                probs = probs / probs.sum()

                actual = min(needed, len(candidates))
                if actual > 0:
                    chosen_pos = rng.choice(
                        len(candidates), size=actual, p=probs, replace=False
                    )
                    for pos in chosen_pos:
                        idx = candidates[pos]
                        new_cells.append(idx)
                        current_selected.add(idx)
                    needed -= actual

            # Fill remaining from unscored candidates randomly
            if needed > 0 and unscored:
                actual = min(needed, len(unscored))
                chosen = rng.choice(unscored, size=actual, replace=False).tolist()
                new_cells.extend(chosen)
                for c in chosen:
                    current_selected.add(c)

        return new_cells

    def _prepare_details(
        self,
        arms: List[Dict],
        selected: List[int],
        coarse_indices: List[int],
        fine_indices: List[int],
    ) -> Dict:
        """Prepare sampling details for analysis."""
        arms_info = []
        for arm in arms:
            arms_info.append(
                {
                    "arm_id": arm["arm_id"],
                    "cell_type": arm.get("cell_type", ""),
                    "cluster_id": arm.get("cluster_id", -1),
                    "n_cells_in_arm": len(arm["cell_indices"]),
                    "focus_score": float(arm["focus_score"]),
                    "focus_after_coarse": arm.get("focus_after_coarse"),
                    "focus_after_fine": arm.get("focus_after_fine"),
                    "mean_similarity": float(arm["mean_sim"]),
                    "variance": float(arm["variance"]),
                    "samples_count": int(arm["samples"]),
                }
            )

        return {
            "n_coarse_samples": len(coarse_indices),
            "n_fine_samples": len(fine_indices),
            "n_selected": len(selected),
            "arms_info": arms_info,
            "selected_indices": selected,
        }