hamiltonian.py 2.14 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
Martin Reinecke's avatar
Martin Reinecke committed
22
from ..operators.sampling_enabler import SamplingEnabler
23
24
25
26
from ..utilities import memo


class Hamiltonian(Energy):
Martin Reinecke's avatar
Martin Reinecke committed
27
    def __init__(self, lh, iteration_controller_sampling=None):
28
29
30
31
32
33
        """
        lh: Likelihood (energy object)
        prior:
        """
        super(Hamiltonian, self).__init__(lh.position)
        self._lh = lh
34
        self._ic_samp = iteration_controller_sampling
35
        self._prior = GaussianEnergy(Variable(self.position))
36
37

    def at(self, position):
Martin Reinecke's avatar
Martin Reinecke committed
38
        return self.__class__(self._lh.at(position), self._ic_samp)
39
40
41
42
43
44
45
46
47
48
49
50
51

    @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
Martin Reinecke's avatar
Martin Reinecke committed
52
53
    def metric(self):
        prior_mtr = self._prior.metric
Philipp Arras's avatar
Philipp Arras committed
54
        if self._ic_samp is None:
Martin Reinecke's avatar
Martin Reinecke committed
55
            return self._lh.metric + prior_mtr
Philipp Arras's avatar
Philipp Arras committed
56
        else:
Martin Reinecke's avatar
Martin Reinecke committed
57
58
            return SamplingEnabler(self._lh.metric, prior_mtr.inverse,
                                   self._ic_samp, prior_mtr.inverse)
59
60
61
62
63

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