"""The six selected trained decision heads and their frozen numerical policy.""" from __future__ import annotations from pathlib import Path import json import struct import joblib import numpy as np def _need(value: bool, message: str) -> None: if not value: raise ValueError(message) def feature3(raw): raw = np.asarray(raw) _need(raw.dtype == np.dtype('float64') and raw.ndim == 2 and (raw.shape[1] == 3) and np.isfinite(raw).all() and bool(((raw[:, :2] >= 0) & (raw[:, :2] <= 1)).all()), 'finite original raw F64 B/H/G') p = np.clip(raw[:, :2], 1e-06, 1.0 - 1e-06) return np.column_stack((np.log(p[:, 0]) - np.log1p(-p[:, 0]), np.log(p[:, 1]) - np.log1p(-p[:, 1]), raw[:, 2])).astype('= 0) & (a <= 1)).all() for a in (b, h, hc, bc))), 'probabilities in0..1') return ((h <= 0.05) | (hc <= 0.05)) & ((b >= 0.25) & (g > 0) | (bc >= 0.5)) class PolicyHeads: def __init__(self, directory): directory = Path(directory) config = json.loads((directory / 'config.json').read_text()) self.package_root = directory.resolve().parents[1] self.mapping = {'feature_names': config['feature_names']} self.feature_names_Entry = tuple(config['feature_names']['Entry']) self.feature_names_Gate = tuple(config['feature_names']['Gate']) self._models = {name: joblib.load(directory / (name + '.joblib')) for name in config['heads']} with np.load(directory / 'normalization.npz', allow_pickle=False) as arrays: self._normalization = {name: arrays[name] for name in arrays.files} self.theta = np.float32(config['theta']) if struct.pack('= 0) & (a <= 1)).all(), 'Entry F64 True probability') return a.astype(np.float32) def entry_pass(self, probabilities): a = np.asarray(probabilities) _need(a.dtype == np.dtype('float32') and a.ndim == 1 and np.isfinite(a).all() and ((a >= 0) & (a <= 1)).all(), 'Entry exact F32 probabilities') return a >= self.theta def score_actions(self, features): raw = np.asarray(features) x = self._normalized(raw, 'Gate') if not len(x): z = np.empty(0, dtype=np.float64) return dict(benefit=z.copy(), harm=z.copy(), gain=z.copy(), Hcal3=z.copy(), B49cost3=z.copy(), passing=np.empty(0, dtype=np.bool_)) b = self._models['benefit'].predict_proba(x)[:, 1] h = self._models['harm'].predict_proba(x)[:, 1] g = self._models['gain'].predict(x) f3 = (feature3(np.column_stack((b, h, g))) - self._normalization['feature3_mean']) / self._normalization['feature3_scale'] hc = self._models['Hcal3'].predict_proba(f3)[:, 1] X49 = np.concatenate((raw.astype(np.float64), f3), axis=1) bc = self._models['B49cost3'].predict_proba(X49)[:, 1] passing = gate_pass(b, h, g, hc, bc) return dict(benefit=b, harm=h, gain=g, Hcal3=hc, B49cost3=bc, passing=passing) def load(components_directory): return PolicyHeads(Path(components_directory)/"decision")