File size: 7,313 Bytes
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, Iterable, List, Tuple

from libs.adaptive.scheduler import AdaptiveScheduler


@dataclass(frozen=True)
class AdaptivePolicyVariant:
    name: str
    stop_mode: str  # hard | soft | none
    cluster_bootstrap_rounds: int = 0
    min_cluster_coverage: float = 0.0
    min_hypercluster_coverage: float = 0.0
    soft_recovery_batches: int = 0
    soft_threshold_relax: float = 0.0
    soft_model_weight_cap: float = 1.0
    soft_exploration_boost: float = 0.0
    pre_floor_model_weight_cap: float = 1.0
    max_soft_recoveries: int = 1
    epsilon_quality: float = 0.10
    acceptable_regret: float = 0.10
    min_budget: int = 250
    max_budget: int = 10000
    regret_patience_rounds: int = 6
    regret_uncertainty_multiplier: float = 0.5
    regret_min_cluster_coverage: float = 0.20
    regret_min_hypercluster_coverage: float = 0.20


@dataclass
class PolicyRuntimeState:
    soft_recovery_remaining: int = 0
    soft_recoveries_used: int = 0


def default_policy_variants() -> Dict[str, AdaptivePolicyVariant]:
    return {
        "adaptive_hard_stop": AdaptivePolicyVariant(
            name="adaptive_hard_stop",
            stop_mode="hard",
        ),
        "adaptive_soft_stop": AdaptivePolicyVariant(
            name="adaptive_soft_stop",
            stop_mode="soft",
            soft_recovery_batches=16,
            soft_threshold_relax=0.35,
            soft_model_weight_cap=0.45,
            soft_exploration_boost=0.25,
            pre_floor_model_weight_cap=1.0,
            max_soft_recoveries=1,
        ),
        "adaptive_no_stop": AdaptivePolicyVariant(
            name="adaptive_no_stop",
            stop_mode="none",
        ),
        "adaptive_cluster_bootstrap": AdaptivePolicyVariant(
            name="adaptive_cluster_bootstrap",
            stop_mode="hard",
            cluster_bootstrap_rounds=24,
        ),
        "adaptive_soft_stop_cluster_floor": AdaptivePolicyVariant(
            name="adaptive_soft_stop_cluster_floor",
            stop_mode="soft",
            cluster_bootstrap_rounds=20,
            min_cluster_coverage=0.60,
            min_hypercluster_coverage=0.55,
            soft_recovery_batches=20,
            soft_threshold_relax=0.40,
            soft_model_weight_cap=0.40,
            soft_exploration_boost=0.30,
            pre_floor_model_weight_cap=0.35,
            max_soft_recoveries=2,
        ),
    }


def regret_stop_variant(
    *,
    name: str = "adaptive_budgeted_regret_stop",
    epsilon_quality: float = 0.10,
    acceptable_regret: float = 0.10,
    min_budget: int = 250,
    max_budget: int = 10000,
    regret_patience_rounds: int = 6,
    regret_uncertainty_multiplier: float = 0.50,
    regret_min_cluster_coverage: float = 0.20,
    regret_min_hypercluster_coverage: float = 0.20,
) -> AdaptivePolicyVariant:
    return AdaptivePolicyVariant(
        name=name,
        stop_mode="regret",
        epsilon_quality=float(epsilon_quality),
        acceptable_regret=float(acceptable_regret),
        min_budget=int(min_budget),
        max_budget=int(max_budget),
        regret_patience_rounds=int(regret_patience_rounds),
        regret_uncertainty_multiplier=float(regret_uncertainty_multiplier),
        regret_min_cluster_coverage=float(regret_min_cluster_coverage),
        regret_min_hypercluster_coverage=float(regret_min_hypercluster_coverage),
    )


def coverage_fraction(sampled: Iterable[int], total: int) -> float:
    if total <= 0:
        return 0.0
    return float(len(set(sampled)) / float(total))


def coverage_floor_reached(
    variant: AdaptivePolicyVariant,
    *,
    cluster_coverage: float,
    hypercluster_coverage: float,
) -> bool:
    return bool(
        cluster_coverage >= float(variant.min_cluster_coverage)
        and hypercluster_coverage >= float(variant.min_hypercluster_coverage)
    )


def select_cluster_bootstrap_batch(
    scheduler: AdaptiveScheduler,
    *,
    sampled_clusters: set[int],
    batch_size: int,
) -> List[str]:
    active = scheduler.queue_manager.ordered_active()
    if not active:
        return []
    selected: List[str] = []
    # First pass: one candidate from unsampled clusters.
    for item in active:
        if item.cluster_id in sampled_clusters:
            continue
        if item.ligand_id in selected:
            continue
        selected.append(item.ligand_id)
        if len(selected) >= batch_size:
            break
    # Fill remaining by priority order.
    if len(selected) < batch_size:
        for item in active:
            if item.ligand_id in selected:
                continue
            selected.append(item.ligand_id)
            if len(selected) >= batch_size:
                break
    for ligand_id in selected:
        scheduler.queue_manager.items[ligand_id].times_selected += 1
    return selected


def effective_controls(
    variant: AdaptivePolicyVariant,
    state: PolicyRuntimeState,
    *,
    coverage_floor_active: bool,
) -> Tuple[float, float, float]:
    # Returns (model_weight_cap, exploration_boost, threshold_relax).
    model_cap = 1.0
    exploration_boost = 0.0
    threshold_relax = 0.0
    if coverage_floor_active:
        model_cap = min(model_cap, float(variant.pre_floor_model_weight_cap))
    if state.soft_recovery_remaining > 0:
        model_cap = min(model_cap, float(variant.soft_model_weight_cap))
        exploration_boost = max(exploration_boost, float(variant.soft_exploration_boost))
        threshold_relax = max(threshold_relax, float(variant.soft_threshold_relax))
    return float(model_cap), float(exploration_boost), float(threshold_relax)


def apply_stop_policy(
    variant: AdaptivePolicyVariant,
    state: PolicyRuntimeState,
    *,
    stop_signal: bool,
    stop_reason: str,
    coverage_floor_active: bool,
) -> Tuple[bool, str, PolicyRuntimeState]:
    mode = str(variant.stop_mode).strip().lower()
    # Coverage floor blocks stop decisions in floor-enforced variants.
    if coverage_floor_active and stop_signal:
        return False, "coverage_floor_blocked_stop", state

    if mode == "none":
        return False, "no_stop_policy", state

    if mode == "hard":
        return bool(stop_signal), (stop_reason if stop_signal else "continue"), state

    if mode == "regret":
        return bool(stop_signal), (stop_reason if stop_signal else "continue"), state

    # soft mode
    if state.soft_recovery_remaining > 0:
        state.soft_recovery_remaining -= 1
        if state.soft_recovery_remaining <= 0 and stop_signal:
            if state.soft_recoveries_used >= int(variant.max_soft_recoveries):
                return True, "soft_recovery_exhausted", state
            state.soft_recovery_remaining = int(variant.soft_recovery_batches)
            state.soft_recoveries_used += 1
            return False, "soft_recovery_restarted", state
        return False, "soft_recovery_active", state

    if not stop_signal:
        return False, "continue", state

    if state.soft_recoveries_used >= int(variant.max_soft_recoveries):
        return True, "soft_recovery_limit_reached", state

    state.soft_recovery_remaining = int(variant.soft_recovery_batches)
    state.soft_recoveries_used += 1
    return False, "soft_recovery_started", state