|
| 1 | +try: |
| 2 | + import torch |
| 3 | + from gpytorch.utils.permutation import apply_permutation |
| 4 | +except ImportError as e: |
| 5 | + raise ImportError("PyTorch and GPyTorch not found.") from e |
| 6 | + |
| 7 | +import numpy as np |
| 8 | + |
| 9 | +pp = lambda x: np.array2string(x, precision=4, floatmode="fixed") |
| 10 | + |
| 11 | + |
| 12 | +def pivoted_cholesky(mat: np.matrix, error_tol=1e-6, max_iter=np.inf): |
| 13 | + """ |
| 14 | + mat: numpy matrix of N x N |
| 15 | +
|
| 16 | + This is to replicate what is done in GPyTorch verbatim. |
| 17 | + """ |
| 18 | + n = mat.shape[-1] |
| 19 | + max_iter = min(int(max_iter), n) |
| 20 | + |
| 21 | + d = np.array(np.diag(mat)) |
| 22 | + orig_error = np.max(d) |
| 23 | + error = np.linalg.norm(d, 1) / orig_error |
| 24 | + pi = np.arange(n) |
| 25 | + |
| 26 | + L = np.zeros((max_iter, n)) |
| 27 | + |
| 28 | + m = 0 |
| 29 | + while m < max_iter and error > error_tol: |
| 30 | + permuted_d = d[pi] |
| 31 | + max_diag_idx = np.argmax(permuted_d[m:]) |
| 32 | + max_diag_idx = max_diag_idx + m |
| 33 | + max_diag_val = permuted_d[max_diag_idx] |
| 34 | + i = max_diag_idx |
| 35 | + |
| 36 | + # swap pi_m and pi_i |
| 37 | + pi[m], pi[i] = pi[i], pi[m] |
| 38 | + pim = pi[m] |
| 39 | + |
| 40 | + L[m, pim] = np.sqrt(max_diag_val) |
| 41 | + |
| 42 | + if m + 1 < n: |
| 43 | + row = apply_permutation( |
| 44 | + torch.from_numpy(mat), torch.tensor(pim), right_permutation=None |
| 45 | + ) # left permutation just swaps row |
| 46 | + row = row.numpy().flatten() |
| 47 | + pi_i = pi[m + 1 :] |
| 48 | + L_m_new = row[pi_i] # length = 9 |
| 49 | + |
| 50 | + if m > 0: |
| 51 | + L_prev = L[:m, pi_i] |
| 52 | + update = L[:m, pim] |
| 53 | + prod = update @ L_prev |
| 54 | + L_m_new = L_m_new - prod # np.sum(prod, axis=-1) |
| 55 | + |
| 56 | + L_m = L[m, :] |
| 57 | + L_m_new = L_m_new / L_m[pim] |
| 58 | + L_m[pi_i] = L_m_new |
| 59 | + |
| 60 | + matrix_diag_current = d[pi_i] |
| 61 | + d[pi_i] = matrix_diag_current - L_m_new**2 |
| 62 | + |
| 63 | + L[m, :] = L_m |
| 64 | + error = np.linalg.norm(d[pi_i], 1) / orig_error |
| 65 | + m = m + 1 |
| 66 | + return L, pi |
0 commit comments