energy_adapter.py 1.2 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
5
from __future__ import absolute_import, division, print_function

from ..compat import *
from ..minimization.energy import Energy
from ..linearization import Linearization
Martin Reinecke's avatar
Martin Reinecke committed
6
import numpy as np
Martin Reinecke's avatar
Martin Reinecke committed
7
8
9
10
11
12


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

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

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

Martin Reinecke's avatar
Martin Reinecke committed
26
27
    @property
    def value(self):
Martin Reinecke's avatar
Martin Reinecke committed
28
        if self._val is None:
29
            self._val = self._op(self._position)
Martin Reinecke's avatar
Martin Reinecke committed
30
31
            if not np.isscalar(self._val):
                self._val = self._val.local_data[()]
Martin Reinecke's avatar
Martin Reinecke committed
32
        return self._val
Martin Reinecke's avatar
Martin Reinecke committed
33
34
35

    @property
    def gradient(self):
Martin Reinecke's avatar
Martin Reinecke committed
36
37
38
        if self._grad is None:
            self._fill_all()
        return self._grad
Martin Reinecke's avatar
Martin Reinecke committed
39
40
41

    @property
    def metric(self):
Martin Reinecke's avatar
Martin Reinecke committed
42
43
44
        if self._metric is None:
            self._fill_all()
        return self._metric