"""Visit (N) table — UCB 정책의 방문 횟수 추적.""" from __future__ import annotations from dataclasses import dataclass from typing import Dict import numpy as np @dataclass class VisitTable: state_space_size: int action_space_size: int def __post_init__(self) -> None: self._counts = np.zeros( (self.state_space_size, self.action_space_size), dtype=np.int64 ) def increment(self, state_index: int, action_id: int, count: int = 1) -> None: self._validate_indices(state_index, action_id) if count < 0: raise ValueError("count must be non-negative") self._counts[state_index, action_id] += count def get_action_count(self, state_index: int, action_id: int) -> int: self._validate_indices(state_index, action_id) return int(self._counts[state_index, action_id]) def get_state_counts(self, state_index: int) -> np.ndarray: self._validate_state(state_index) return self._counts[state_index, :].copy() def total_visits(self, state_index: int) -> int: self._validate_state(state_index) return int(self._counts[state_index, :].sum()) def reset_state(self, state_index: int) -> None: self._validate_state(state_index) self._counts[state_index, :] = 0 def to_dict(self) -> Dict: return { "state_space_size": self.state_space_size, "action_space_size": self.action_space_size, "counts": self._counts.tolist(), } @classmethod def from_dict(cls, data: Dict) -> "VisitTable": table = cls( state_space_size=data["state_space_size"], action_space_size=data["action_space_size"], ) table._counts = np.array(data["counts"], dtype=np.int64) return table def _validate_state(self, state_index: int) -> None: if state_index < 0 or state_index >= self.state_space_size: raise ValueError( f"state_index {state_index} out of range [0, {self.state_space_size})" ) def _validate_indices(self, state_index: int, action_id: int) -> None: self._validate_state(state_index) if action_id < 0 or action_id >= self.action_space_size: raise ValueError( f"action_id {action_id} out of range [0, {self.action_space_size})" )