Download libs/adaptive/scheduler.py from QPromaQ/Docking_project: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/libs/adaptive/scheduler.py
- Command line
-
hf download hf://datasets/QPromaQ/Docking_project/libs/adaptive/scheduler.py
-
curl -L -o scheduler.py https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/libs/adaptive/scheduler.py
10.9 kB
| from __future__ import annotations | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| from typing import Dict, List | |
| import numpy as np | |
| import pandas as pd | |
| from .metrics import score_metrics | |
| from .policies import PrioritizationPolicy | |
| from .prioritization import cluster_bonus, compute_priority | |
| from .queue_manager import QueueManager | |
| from .state import QueueItem, SchedulerState | |
| from .surrogate_model import SurrogateConfig, SurrogateModel | |
| from .weight_schedule import WeightScheduleConfig, compute_model_weight | |
| class SchedulerConfig: | |
| batch_size: int = 8 | |
| init_coverage_fraction: float = 0.25 | |
| conservative_deprioritize: bool = True | |
| state_path: str = "results/state.json" | |
| weight_schedule: WeightScheduleConfig = field(default_factory=WeightScheduleConfig) | |
| class AdaptiveScheduler: | |
| """Adaptive batch scheduler with queue state and online masked surrogate updates.""" | |
| def __init__( | |
| self, | |
| config: SchedulerConfig | None = None, | |
| policy: PrioritizationPolicy | None = None, | |
| surrogate_config: SurrogateConfig | None = None, | |
| ) -> None: | |
| self.config = config or SchedulerConfig() | |
| self.policy = policy or PrioritizationPolicy() | |
| self.surrogate = SurrogateModel(surrogate_config) | |
| self.state = SchedulerState() | |
| self.queue_manager = QueueManager.from_items([]) | |
| self.last_model_weight: float = 0.0 | |
| def initialize( | |
| self, | |
| ligands_df: pd.DataFrame, | |
| cluster_map: Dict[str, int], | |
| hypercluster_for_cluster: Dict[int, int], | |
| ) -> None: | |
| items: List[QueueItem] = [] | |
| cluster_load: Dict[int, int] = {} | |
| for row in ligands_df.itertuples(index=False): | |
| ligand_id = str(row.ligand_id) | |
| cluster_id = int(cluster_map.get(ligand_id, -1)) | |
| hypercluster_id = int(hypercluster_for_cluster.get(cluster_id, -1)) | |
| bonus = cluster_bonus(cluster_load, cluster_id) | |
| priority = compute_priority( | |
| predicted_utility=0.0, | |
| uncertainty=1.0, | |
| diversity_gain=bonus, | |
| cluster_bonus=bonus, | |
| policy=self.policy, | |
| ) | |
| items.append( | |
| QueueItem( | |
| ligand_id=ligand_id, | |
| status="active", | |
| priority=float(priority), | |
| cluster_id=cluster_id, | |
| hypercluster_id=hypercluster_id, | |
| ) | |
| ) | |
| cluster_load[cluster_id] = cluster_load.get(cluster_id, 0) + 1 | |
| self.state = SchedulerState(queue=items, batch_history=[], round_idx=0) | |
| self.queue_manager = QueueManager.from_items(items) | |
| def select_batch(self) -> List[str]: | |
| active = self.queue_manager.ordered_active() | |
| if not active: | |
| # If conservative deprioritization exhausted active queue, reactivate | |
| # deprioritized candidates to continue spending the docking budget. | |
| deprioritized = sorted( | |
| [item for item in self.queue_manager.items.values() if item.status == "deprioritized"], | |
| key=lambda item: item.priority, | |
| reverse=True, | |
| ) | |
| if not deprioritized: | |
| return [] | |
| for item in deprioritized: | |
| item.status = "active" | |
| active = deprioritized | |
| coverage_count = max(1, int(self.config.batch_size * self.config.init_coverage_fraction)) | |
| by_hypercluster: Dict[int, List[QueueItem]] = {} | |
| for item in active: | |
| by_hypercluster.setdefault(item.hypercluster_id, []).append(item) | |
| selected: List[str] = [] | |
| # Broad initial coverage. | |
| for _h_id, items in sorted(by_hypercluster.items(), key=lambda x: len(x[1]), reverse=True): | |
| if len(selected) >= coverage_count: | |
| break | |
| selected.append(items[0].ligand_id) | |
| # Fill remaining slots by priority. | |
| for item in active: | |
| if len(selected) >= self.config.batch_size: | |
| break | |
| if item.ligand_id not in selected: | |
| selected.append(item.ligand_id) | |
| for ligand_id in selected: | |
| self.queue_manager.items[ligand_id].times_selected += 1 | |
| return selected | |
| def _mean_or_default(values: list[float], default: float = 0.0) -> float: | |
| if not values: | |
| return float(default) | |
| return float(np.mean(np.asarray(values, dtype=float))) | |
| def update_from_batch( | |
| self, | |
| evaluated_df: pd.DataFrame, | |
| feature_values_df: pd.DataFrame, | |
| feature_masks_df: pd.DataFrame, | |
| ) -> Dict[str, float]: | |
| # Mark completed ligands and store latest score. | |
| score_map = dict(zip(evaluated_df["ligand_id"].astype(str), evaluated_df["docking_score"].astype(float))) | |
| for ligand_id, score in score_map.items(): | |
| if ligand_id in self.queue_manager.items: | |
| item = self.queue_manager.items[ligand_id] | |
| item.status = "completed" | |
| item.last_score = float(score) | |
| if feature_values_df.empty or feature_masks_df.empty: | |
| raise ValueError("Feature tables cannot be empty in adaptive update") | |
| if "ligand_id" not in feature_values_df.columns or "ligand_id" not in feature_masks_df.columns: | |
| raise ValueError("Feature tables must include ligand_id column") | |
| ligand_order = feature_values_df["ligand_id"].astype(str).tolist() | |
| features = feature_values_df.drop(columns=["ligand_id"]).to_numpy(dtype=float) | |
| masks = feature_masks_df.drop(columns=["ligand_id"]).to_numpy(dtype=float) | |
| feature_names = feature_values_df.drop(columns=["ligand_id"]).columns.tolist() | |
| mask_names = feature_masks_df.drop(columns=["ligand_id"]).columns.tolist() | |
| target = np.full(len(ligand_order), np.nan, dtype=float) | |
| for i, ligand_id in enumerate(ligand_order): | |
| if ligand_id in self.queue_manager.items: | |
| score = self.queue_manager.items[ligand_id].last_score | |
| if score is not None: | |
| target[i] = float(score) | |
| fit_stats = self.surrogate.fit( | |
| features=features, | |
| masks=masks, | |
| y=target, | |
| feature_names=feature_names, | |
| mask_names=mask_names, | |
| ) | |
| n_train = int(fit_stats.get("n_train", 0.0)) | |
| instability_ratio = float(fit_stats.get("instability_ratio", 1.0)) | |
| model_weight = compute_model_weight( | |
| n_samples=n_train, | |
| instability_ratio=instability_ratio, | |
| config=self.config.weight_schedule, | |
| ) | |
| if self.surrogate.model is None: | |
| model_weight = 0.0 | |
| self.last_model_weight = float(model_weight) | |
| # Predict for active items. | |
| active_items = self.queue_manager.active_items() | |
| active_ids = [item.ligand_id for item in active_items] | |
| completed_items = [item for item in self.queue_manager.items.values() if item.last_score is not None] | |
| global_completed = [float(item.last_score) for item in completed_items if item.last_score is not None] | |
| global_mean_score = self._mean_or_default(global_completed, default=0.0) | |
| cluster_scores: Dict[int, list[float]] = {} | |
| hyper_scores: Dict[int, list[float]] = {} | |
| for item in completed_items: | |
| assert item.last_score is not None | |
| cluster_scores.setdefault(item.cluster_id, []).append(float(item.last_score)) | |
| hyper_scores.setdefault(item.hypercluster_id, []).append(float(item.last_score)) | |
| if active_ids: | |
| id_to_idx = {lid: idx for idx, lid in enumerate(ligand_order)} | |
| x_active = np.vstack([features[id_to_idx[lid]] for lid in active_ids]) | |
| m_active = np.vstack([masks[id_to_idx[lid]] for lid in active_ids]) | |
| bundle = self.surrogate.predict_bundle(x_active, m_active) | |
| cluster_load: Dict[int, int] = {} | |
| for item in active_items: | |
| cluster_load[item.cluster_id] = cluster_load.get(item.cluster_id, 0) + 1 | |
| for i, ligand_id in enumerate(active_ids): | |
| item = self.queue_manager.items[ligand_id] | |
| cluster_mean = self._mean_or_default(cluster_scores.get(item.cluster_id, []), default=np.nan) | |
| hyper_mean = self._mean_or_default(hyper_scores.get(item.hypercluster_id, []), default=np.nan) | |
| observed_docking = ( | |
| cluster_mean | |
| if np.isfinite(cluster_mean) | |
| else hyper_mean | |
| if np.isfinite(hyper_mean) | |
| else global_mean_score | |
| ) | |
| docking_component = -float(observed_docking) | |
| model_component = -float(bundle["expected_score"][i]) | |
| blended_utility = (1.0 - model_weight) * docking_component + model_weight * model_component | |
| bonus = cluster_bonus(cluster_load, item.cluster_id) | |
| item.priority = compute_priority( | |
| predicted_utility=float(blended_utility), | |
| uncertainty=float(bundle["uncertainty"][i]), | |
| diversity_gain=bonus, | |
| cluster_bonus=bonus, | |
| policy=self.policy, | |
| ) | |
| if self.config.conservative_deprioritize: | |
| priorities = np.asarray([self.queue_manager.items[lid].priority for lid in active_ids], dtype=float) | |
| threshold = float(np.quantile(priorities, self.policy.conservative_deprioritize_quantile)) | |
| for lid in active_ids: | |
| if self.queue_manager.items[lid].priority < threshold: | |
| self.queue_manager.items[lid].status = "deprioritized" | |
| self.state.round_idx += 1 | |
| sm = score_metrics(evaluated_df["docking_score"].astype(float).tolist()) | |
| batch_record: Dict[str, float | str] = { | |
| "round_idx": self.state.round_idx, | |
| "batch_size": int(evaluated_df.shape[0]), | |
| "model_weight": float(model_weight), | |
| "n_train": float(n_train), | |
| "train_mae": float(fit_stats.get("train_mae", np.nan)), | |
| "val_mae": float(fit_stats.get("val_mae", np.nan)), | |
| "instability_ratio": float(instability_ratio), | |
| "surrogate_backend": self.surrogate.backend, | |
| **sm, | |
| } | |
| self.state.batch_history.append(batch_record) | |
| return fit_stats | |
| def save_state(self, output_path: str | Path | None = None) -> Path: | |
| target = Path(output_path or self.config.state_path) | |
| self.state.queue = list(self.queue_manager.items.values()) | |
| return self.state.save(target) | |