energy_adapter.py 1.02 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
5
6
7
8
9
10
11
from __future__ import absolute_import, division, print_function

from ..compat import *
from ..minimization.energy import Energy
from ..linearization import Linearization


class EnergyAdapter(Energy):
    def __init__(self, position, op):
        super(EnergyAdapter, self).__init__(position)
        self._op = op
Martin Reinecke's avatar
Martin Reinecke committed
12
        self._val = self._grad = self._metric = None
Martin Reinecke's avatar
Martin Reinecke committed
13
14
15
16

    def at(self, position):
        return EnergyAdapter(position, self._op)

Martin Reinecke's avatar
Martin Reinecke committed
17
18
19
20
21
22
    def _fill_all(self):
        tmp = self._op(Linearization.make_var(self._position))
        self._val = tmp.val.local_data[()]
        self._grad = tmp.gradient
        self._metric = tmp.metric

Martin Reinecke's avatar
Martin Reinecke committed
23
24
    @property
    def value(self):
Martin Reinecke's avatar
Martin Reinecke committed
25
        if self._val is None:
26
            self._val = self._op(self._position)
Martin Reinecke's avatar
Martin Reinecke committed
27
        return self._val
Martin Reinecke's avatar
Martin Reinecke committed
28
29
30

    @property
    def gradient(self):
Martin Reinecke's avatar
Martin Reinecke committed
31
32
33
        if self._grad is None:
            self._fill_all()
        return self._grad
Martin Reinecke's avatar
Martin Reinecke committed
34
35
36

    @property
    def metric(self):
Martin Reinecke's avatar
Martin Reinecke committed
37
38
39
        if self._metric is None:
            self._fill_all()
        return self._metric