hamiltonian.py 2.34 KB
Newer Older
Philipp Arras's avatar
Philipp Arras committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Copyright(C) 2013-2018 Max-Planck-Society
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik
# and financially supported by the Studienstiftung des deutschen Volkes.

from ..library.gaussian_energy import GaussianEnergy
20
21
from ..minimization.energy import Energy
from ..models.variable import Variable
Philipp Arras's avatar
Philipp Arras committed
22
from ..operators import InversionEnabler, SamplingEnabler
23
24
25
26
27
28
29
30
31
32
33
34
35
from ..utilities import memo


class Hamiltonian(Energy):
    def __init__(self, lh, iteration_controller,
                 iteration_controller_sampling=None):
        """
        lh: Likelihood (energy object)
        prior:
        """
        super(Hamiltonian, self).__init__(lh.position)
        self._lh = lh
        self._ic = iteration_controller
36
        self._ic_samp = iteration_controller_sampling
37
        self._prior = GaussianEnergy(Variable(self.position))
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
        self._precond = self._prior.curvature

    def at(self, position):
        return self.__class__(self._lh.at(position), self._ic, self._ic_samp)

    @property
    @memo
    def value(self):
        return self._lh.value + self._prior.value

    @property
    @memo
    def gradient(self):
        return self._lh.gradient + self._prior.gradient

    @property
    @memo
    def curvature(self):
        prior_curv = self._prior.curvature
57
58
59
60
61
        if self._ic_samp is not None:
            c = SamplingEnabler(self._lh.curvature, prior_curv.inverse,
                                self._ic_samp, prior_curv.inverse)
        else:
            c = self._lh.curvature + prior_curv
62
63
64
65
66
67
        return InversionEnabler(c, self._ic, self._precond)

    def __str__(self):
        res = 'Likelihood:\t{:.2E}\n'.format(self._lh.value)
        res += 'Prior:\t\t{:.2E}'.format(self._prior.value)
        return res