ensemble_likelihood.py 4.22 KB
Newer Older
1 2
# -*- coding: utf-8 -*-

Theo Steininger's avatar
Theo Steininger committed
3 4
import numpy as np

5
from nifty import FieldArray, Field
6

7
from imagine.likelihoods.likelihood import Likelihood
8

9 10

class EnsembleLikelihood(Likelihood):
11
    def __init__(self, observable_name,  measured_data,
12
                 data_covariance, profile=None):
13
        self.observable_name = observable_name
14
        self.measured_data = self._strip_data(measured_data)
15 16 17
        if isinstance(data_covariance, Field):
            data_covariance = data_covariance.val.get_full_data()
        self.data_covariance = data_covariance
18 19

    def __call__(self, observable):
20 21 22
        field = observable[self.observable_name]
        return self._process_simple_field(field,
                                          self.measured_data,
23
                                          self.data_covariance)
24

25
    def _process_simple_field(self, observable, measured_data,
26
                              data_covariance):
Theo Steininger's avatar
Theo Steininger committed
27 28 29 30 31
        # https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula#Generalization
        # B = A^{-1} + U U^dagger
        # A = data_covariance
        # B^{-1} c = (A_inv -
        #             A_inv U (I_k + U^dagger A_inv U)^{-1} U^dagger A_inv) c
Theo Steininger's avatar
bug fix  
Theo Steininger committed
32
        data_covariance = data_covariance.copy()
Theo Steininger's avatar
Theo Steininger committed
33
        k = observable.shape[0]
34
        n = observable.shape[1]
Theo Steininger's avatar
Theo Steininger committed
35 36

        obs_val = observable.val.get_full_data()
37
        obs_mean = observable.ensemble_mean().val.get_full_data()
Theo Steininger's avatar
Theo Steininger committed
38

39
        U = obs_val - obs_mean
Theo Steininger's avatar
Moved n  
Theo Steininger committed
40
        #U *= np.sqrt(n)
41
        # compute quantities for OAS estimator
42 43
        mu = np.vdot(U, U)/k/n
        alpha = (np.einsum(U, [0, 1], U, [2, 1])**2).sum()
44
        alpha /= k**2
45

46 47
        numerator = (1 - 2./n)*alpha + (mu*n)**2
        denominator = (k + 1 - 2./n) * (alpha - ((mu*n)**2)/n)
48 49 50 51

        if denominator == 0:
            rho = 1
        else:
52
            rho = np.min([1, numerator/denominator])
Theo Steininger's avatar
Theo Steininger committed
53 54
        self.logger.debug("rho: %f = %f / %f" % (rho, numerator, denominator))

55
        # rescale U half/half
56
        V = U * np.sqrt(1-rho) / np.sqrt(k)
57

58
        self.logger.info(('data_cov', np.mean(data_covariance),
Theo Steininger's avatar
Theo Steininger committed
59
                          'rho*mu', rho*mu,
60 61
                          'rho', rho,
                          'mu', mu,
62
                          'alpha', alpha))
63
        B = data_covariance + rho*mu
64

65
        V_B = V/B
Theo Steininger's avatar
Theo Steininger committed
66 67 68

        # build middle-matrix (kxk)
        middle = (np.eye(k) +
69 70
                  np.einsum(V.conjugate(), [0, 1],
                            V_B, [2, 1]))
Theo Steininger's avatar
Theo Steininger committed
71
        middle = np.linalg.inv(middle)
72 73
        c = measured_data - obs_mean

74 75
        # If the data was incomplete, i.e. contains np.NANs, set those values
        # to zero.
76
        c = np.nan_to_num(c)
77 78 79 80 81 82 83 84 85 86 87
        # assuming that A == A^dagger, this can be shortend
        # a_c = A.inverse_times(c)
        # u_a_c = a_c.dot(U, spaces=1)
        # u_a_c = u_a_c.conjugate()

        # and: double conjugate shouldn't make a difference
        # u_a_c = c.conjugate().dot(a_u, spaces=1).conjugate()

        # Pure NIFTy is
        # u_a_c = c.dot(a_u, spaces=1)
        # u_a_c_val = u_a_c.val.get_full_data()
88
        V_B_c = np.einsum(c, [1], V_B, [0, 1])
89

90 91 92
        first_summand_val = c/B
        second_summand_val = np.einsum(middle, [0, 1], V_B_c, [1])
        second_summand_val = np.einsum(V_B, [0, 1],
93
                                       second_summand_val, [0])
94 95 96
#        # second_summand_val *= -1
#        second_summand = first_summand.copy_empty()
#        second_summand.val = second_summand_val
97

98 99
        result_1 = np.vdot(c, first_summand_val)
        result_2 = -np.vdot(c, second_summand_val)
100 101 102

        # compute regularizing determinant of the covariance
        # det(A + UV^T) =  det(A) det(I + V^T A^-1 U)
103
        log_det_1 = np.sum(np.log(B))
Theo Steininger's avatar
bug fix  
Theo Steininger committed
104
        (sign, log_det_2) = np.linalg.slogdet(middle)
105 106 107
        if sign < 0:
            self.logger.error("Negative determinant of covariance!")

108 109 110 111 112
        result_1 /= n
        result_2 /= n
        log_det_1 /= n
        log_det_2 /= n

Theo Steininger's avatar
moved n  
Theo Steininger committed
113
        result = -0.5*(result_1 + result_2 + log_det_1 + log_det_2)
114

Theo Steininger's avatar
bug fix  
Theo Steininger committed
115
        self.logger.info("Calculated (%s): -(%g + %g + %g + %g) = %g" %
116
                         (self.observable_name,
Theo Steininger's avatar
bug fix  
Theo Steininger committed
117
                          result_1, result_2, log_det_1, log_det_2, result))
118 119
#        result_array[i] = result
#        total_result = result_array.mean()
120 121

        return result