| 36 | SIGMA_MIN, SIGMA_MAX, SIGMA_N = 3e-3, 2, 5000 |
| 37 | |
| 38 | def __init__(self, PI, cache_folder): |
| 39 | super().__init__() |
| 40 | self.PI = PI |
| 41 | self.cache_folder = os.path.expanduser(cache_folder) if cache_folder is not None \ |
| 42 | else os.path.join(os.path.dirname(__file__), "cache") |
| 43 | self.x = 10 ** np.linspace(np.log10(self.X_MIN), 0, |
| 44 | self.X_N + 1) * PI |
| 45 | self.sigma = 10 ** np.linspace(np.log10(self.SIGMA_MIN), np.log10(self.SIGMA_MAX), |
| 46 | self.SIGMA_N + 1) * PI |
| 47 | |
| 48 | os.makedirs(self.cache_folder, exist_ok=True) |
| 49 | self.p_table_path = os.path.join(self.cache_folder, f'Periodic.{PI:.3f}.p.npy') |
| 50 | self.score_table_path = os.path.join(self.cache_folder, f'Periodic.{PI:.3f}.score.npy') |
| 51 | if os.path.exists(self.p_table_path): |
| 52 | self.p_ = np.load(self.p_table_path) |
| 53 | self.score_ = np.load(self.score_table_path) |
| 54 | else: |
| 55 | self.p_ = p(self.x, self.sigma[:, None], N=100, PI=PI) |
| 56 | self.score_ = grad(self.x, self.sigma[:, None], N=100, PI=PI) / self.p_ |
| 57 | np.save(self.p_table_path, self.p_) |
| 58 | np.save(self.score_table_path, self.score_) |
| 59 | |
| 60 | # Precompute the normalization constant |
| 61 | score_norm_table = self.score( |
| 62 | sample(self.sigma[None].repeat(10000, 0).flatten(), PI=PI), |
| 63 | (self.sigma[None].repeat(10000, 0).flatten()), |
| 64 | ).reshape(10000, -1) |
| 65 | |
| 66 | self.score_norm_ = (score_norm_table ** 2).mean(0) |
| 67 | |
| 68 | def score(self, x, sigma): |
| 69 | x = (x + self.PI) % (2 * self.PI) - self.PI # range from -pi to pi |