local_nonlinearity.py 2 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
# 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.

Philipp Arras's avatar
Fixups  
Philipp Arras committed
19
from ..nonlinearities import Exponential, PositiveTanh, Tanh
Martin Reinecke's avatar
Martin Reinecke committed
20
from ..sugar import makeOp
21

Philipp Arras's avatar
Philipp Arras committed
22
from .model import Model
23 24


Philipp Arras's avatar
Philipp Arras committed
25
class LocalModel(Model):
Philipp Arras's avatar
Philipp Arras committed
26
    def __init__(self, inp, nonlinearity):
27 28
        """
        Computes nonlinearity(inp)
29
            - LocalModel.value = nonlinearity(value) (pointwise)
Julian Ruestig's avatar
Julian Ruestig committed
30
            - LocalModel.gradient = Outer Product of gradients
31 32 33 34 35 36 37

        Parameters
        ----------
        inp : Model
            The model for which the  nonlinarity will be applied.
        nonlinearity: Function
            The nonlinearity to be applied to model.
38
        """
Philipp Arras's avatar
Philipp Arras committed
39 40
        super(LocalModel, self).__init__(inp.position)
        self._inp = inp
41 42
        self._nonlinearity = nonlinearity
        self._value = nonlinearity(self._inp.value)
Philipp Arras's avatar
Philipp Arras committed
43 44 45
        d_inner = self._inp.gradient
        d_outer = makeOp(self._nonlinearity.derivative(self._inp.value))
        self._gradient = d_outer * d_inner
46 47

    def at(self, position):
Philipp Arras's avatar
Philipp Arras committed
48
        return self.__class__(self._inp.at(position), self._nonlinearity)
Philipp Arras's avatar
Philipp Arras committed
49 50 51 52 53 54 55 56 57 58 59 60


def PointwiseExponential(inp):
    return LocalModel(inp, Exponential())


def PointwiseTanh(inp):
    return LocalModel(inp, Tanh())


def PointwisePositiveTanh(inp):
    return LocalModel(inp, PositiveTanh())