"""Pure-NumPy Isolation Forest anomaly detector. Self-contained implementation of Liu, Ting & Zhou (2008) "Isolation Forest". No runtime dependency beyond NumPy. Exposed for reproducible loading of the daily risk-scoring model (model/isolation_forest_quality.joblib). """ import math import numpy as np def _c_factor(n): """Average path length of unsuccessful search in a BST for n samples.""" if n <= 1: return 0.0 euler = 0.5772156649015328606 return 2.0 * (math.log(n - 1) + euler) - 2.0 * (n - 1) / n class IsolationTree: """One random binary-partition tree of the isolation forest.""" __slots__ = ("height_limit", "split_feature", "split_value", "left", "right", "size", "n_features") def __init__(self, height_limit, n_features): self.height_limit = height_limit self.n_features = n_features self.split_feature = None self.split_value = None self.left = None self.right = None self.size = 0 def fit(self, X, current_height): self.size = X.shape[0] if current_height >= self.height_limit or self.size <= 1: return f = int(np.random.randint(0, self.n_features)) col = X[:, f] lo, hi = float(col.min()), float(col.max()) if hi - lo < 1e-12: return split = float(np.random.uniform(lo, hi)) left_idx = col < split right_idx = ~left_idx if left_idx.sum() == 0 or right_idx.sum() == 0: return self.split_feature = f self.split_value = split self.left = IsolationTree(self.height_limit, self.n_features) self.right = IsolationTree(self.height_limit, self.n_features) self.left.fit(X[left_idx], current_height + 1) self.right.fit(X[right_idx], current_height + 1) def path_length(self, x, current_height): if self.left is None or self.right is None: return current_height + _c_factor(self.size) if x[self.split_feature] < self.split_value: return self.left.path_length(x, current_height + 1) return self.right.path_length(x, current_height + 1) class IsolationForest: """Isolation Forest anomaly detector. Scores in [0.5, 1.0]; higher score => more anomalous (higher risk). """ def __init__(self, n_estimators=100, max_samples=256, contamination="auto", random_state=None): self.n_estimators = n_estimators self.max_samples = max_samples self.contamination = contamination self.random_state = random_state self.trees = [] self.n_features = None self._sample_size = None self._threshold = None def fit(self, X): prev_state = np.random.get_state() if self.random_state is not None: np.random.seed(self.random_state) X = np.asarray(X, dtype=np.float64) self.n_features = X.shape[1] n = X.shape[0] self._sample_size = min(self.max_samples, n) height_limit = int(math.ceil(math.log2(max(2, self._sample_size)))) self.trees = [] for _ in range(self.n_estimators): idx = np.random.choice(n, size=self._sample_size, replace=False) tree = IsolationTree(height_limit, self.n_features) tree.fit(X[idx], 0) self.trees.append(tree) scores = self.score_samples(X) if self.contamination == "auto": self._threshold = np.percentile(scores, 95.0) # 5% default else: self._threshold = np.percentile(scores, 100 * (1 - self.contamination)) np.random.set_state(prev_state) return self def score_samples(self, X): X = np.asarray(X, dtype=np.float64) n = X.shape[0] acc = np.zeros(n) c_n = _c_factor(self._sample_size) for tree in self.trees: for i in range(n): acc[i] += tree.path_length(X[i], 0) avg_path = acc / len(self.trees) / c_n return 2.0 ** (-avg_path) def predict(self, X): return (self.score_samples(X) >= self._threshold).astype(int) def decision_function(self, X): return (self.score_samples(X) - 0.5) * 2.0