distributors.py 6.39 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
# 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/>.
#
14
# Copyright(C) 2013-2019 Max-Planck-Society
15
#
16
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik.
17

Martin Reinecke's avatar
Martin Reinecke committed
18
import numpy as np
19
20

from ..domain_tuple import DomainTuple
Martin Reinecke's avatar
Martin Reinecke committed
21
from ..domains.dof_space import DOFSpace
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
22
from ..domains.power_space import PowerSpace
23
from ..field import Field
Martin Reinecke's avatar
Martin Reinecke committed
24
from ..utilities import infer_space, special_add_at
25
from .linear_operator import LinearOperator
Martin Reinecke's avatar
Martin Reinecke committed
26
27


Martin Reinecke's avatar
Martin Reinecke committed
28
class DOFDistributor(LinearOperator):
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
29
30
31
    """Operator which distributes actual degrees of freedom (dof) according to
    some distribution scheme into a higher dimensional space. This distribution
    scheme is defined by the dofdex, a degree of freedom index, which
32
    associates the entries within the operator's domain to locations in its
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
33
34
    target. This operator's domain is a DOFSpace, which is defined according to
    the distribution scheme.
35
36
37
38

    Parameters
    ----------
    dofdex: Field of integers
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
39
        An integer Field on exactly one Space establishing the association
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
40
        between the locations in the operator's target and the underlying
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
41
        degrees of freedom in its domain.
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
42
        It has to start at 0 and it increases monotonically, no empty bins are
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
43
        allowed.
44
    target: Domain, tuple of Domain, or DomainTuple, optional
Martin Reinecke's avatar
PEP8    
Martin Reinecke committed
45
46
        The target of the operator. If not specified, the domain of the dofdex
        is used.
47
48
49
50
    space: int, optional:
       The index of the sub-domain on which the operator acts.
       Can be omitted if `target` only has one sub-domain.
    """
Martin Reinecke's avatar
Martin Reinecke committed
51

Martin Reinecke's avatar
Martin Reinecke committed
52
53
54
55
56
57
    def __init__(self, dofdex, target=None, space=None):
        if target is None:
            target = dofdex.domain
        self._target = DomainTuple.make(target)
        space = infer_space(self._target, space)
        partner = self._target[space]
Martin Reinecke's avatar
Martin Reinecke committed
58
59
        if not isinstance(dofdex, Field):
            raise TypeError("dofdex must be a Field")
Martin Reinecke's avatar
Martin Reinecke committed
60
        if not len(dofdex.domain) == 1:
Philipp Arras's avatar
Philipp Arras committed
61
            raise ValueError("dofdex must be defined on exactly one Space")
Martin Reinecke's avatar
Martin Reinecke committed
62
        if not np.issubdtype(dofdex.dtype, np.integer):
Martin Reinecke's avatar
Martin Reinecke committed
63
            raise TypeError("dofdex must contain integer numbers")
Martin Reinecke's avatar
Martin Reinecke committed
64
        if partner != dofdex.domain[0]:
Martin Reinecke's avatar
Martin Reinecke committed
65
66
            raise ValueError("incorrect dofdex domain")

Martin Reinecke's avatar
stage2    
Martin Reinecke committed
67
        ldat = dofdex.val
Martin Reinecke's avatar
Martin Reinecke committed
68
        if ldat.size == 0:  # can happen for weird configurations
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
69
70
71
            nbin = 0
        else:
            nbin = ldat.max()
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
72
        nbin = nbin + 1
Martin Reinecke's avatar
Martin Reinecke committed
73
        if partner.scalar_dvol is not None:
Martin Reinecke's avatar
stage2    
Martin Reinecke committed
74
            wgt = np.bincount(dofdex.val.ravel(), minlength=nbin)
Martin Reinecke's avatar
Martin Reinecke committed
75
            wgt = wgt*partner.scalar_dvol
Martin Reinecke's avatar
Martin Reinecke committed
76
        else:
Martin Reinecke's avatar
Martin Reinecke committed
77
            dvol = Field.from_raw(partner, partner.dvol).val
Martin Reinecke's avatar
stage2    
Martin Reinecke committed
78
            wgt = np.bincount(dofdex.val.ravel(),
Martin Reinecke's avatar
Martin Reinecke committed
79
80
81
82
83
84
85
86
                              minlength=nbin, weights=dvol)
        # The explicit conversion to float64 is necessary because bincount
        # sometimes returns its result as an integer array, even when
        # floating-point weights are present ...
        wgt = wgt.astype(np.float64, copy=False)
        if (wgt == 0).any():
            raise ValueError("empty bins detected")

Martin Reinecke's avatar
Martin Reinecke committed
87
88
89
        self._init2(dofdex.val, space, DOFSpace(wgt))

    def _init2(self, dofdex, space, other_space):
Martin Reinecke's avatar
Martin Reinecke committed
90
        self._space = space
Martin Reinecke's avatar
Martin Reinecke committed
91
92
93
        dom = list(self._target)
        dom[self._space] = other_space
        self._domain = DomainTuple.make(dom)
Martin Reinecke's avatar
Martin Reinecke committed
94
        self._capability = self.TIMES | self.ADJOINT_TIMES
Martin Reinecke's avatar
Martin Reinecke committed
95
96

        self._dofdex = dofdex.ravel()
Martin Reinecke's avatar
Martin Reinecke committed
97
98
        firstaxis = self._target.axes[self._space][0]
        lastaxis = self._target.axes[self._space][-1]
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
99
        arrshape = self._target.shape
100
101
        presize = np.prod(arrshape[0:firstaxis], dtype=np.int64)
        postsize = np.prod(arrshape[lastaxis+1:], dtype=np.int64)
Martin Reinecke's avatar
Martin Reinecke committed
102
        self._hshape = (presize, self._domain[self._space].shape[0], postsize)
Martin Reinecke's avatar
Martin Reinecke committed
103
104
        self._pshape = (presize, self._dofdex.size, postsize)

Martin Reinecke's avatar
Martin Reinecke committed
105
    def _adjoint_times(self, x):
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
106
        arr = x.val
Martin Reinecke's avatar
Martin Reinecke committed
107
108
        arr = arr.reshape(self._pshape)
        oarr = np.zeros(self._hshape, dtype=x.dtype)
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
109
        oarr = special_add_at(oarr, 1, self._dofdex, arr)
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
110
        oarr = oarr.reshape(self._domain.shape)
Martin Reinecke's avatar
Martin Reinecke committed
111
        res = Field.from_raw(self._domain, oarr)
112
        return res
Martin Reinecke's avatar
Martin Reinecke committed
113

Martin Reinecke's avatar
Martin Reinecke committed
114
    def _times(self, x):
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
115
        arr = x.val
Martin Reinecke's avatar
Martin Reinecke committed
116
        arr = arr.reshape(self._hshape)
Martin Reinecke's avatar
Martin Reinecke committed
117
118
        oarr = np.empty(self._pshape, dtype=x.dtype)
        oarr[()] = arr[(slice(None), self._dofdex, slice(None))]
Martin Reinecke's avatar
stage 1    
Martin Reinecke committed
119
        return Field(self._target, oarr.reshape(self._target.shape))
Martin Reinecke's avatar
Martin Reinecke committed
120

Martin Reinecke's avatar
Martin Reinecke committed
121
122
    def apply(self, x, mode):
        self._check_input(x, mode)
Martin Reinecke's avatar
Martin Reinecke committed
123
        return self._times(x) if mode == self.TIMES else self._adjoint_times(x)
Martin Reinecke's avatar
cleanup    
Martin Reinecke committed
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157


class PowerDistributor(DOFDistributor):
    """Operator which transforms between a PowerSpace and a harmonic domain.

    Parameters
    ----------
    target: Domain, tuple of Domain, or DomainTuple
        the total *target* domain of the operator.
    power_space: PowerSpace, optional
        the input sub-domain on which the operator acts.
        If not supplied, a matching PowerSpace with natural binbounds will be
        used.
    space: int, optional:
       The index of the sub-domain on which the operator acts.
       Can be omitted if `target` only has one sub-domain.
    """

    def __init__(self, target, power_space=None, space=None):
        # Initialize domain and target
        self._target = DomainTuple.make(target)
        self._space = infer_space(self._target, space)
        hspace = self._target[self._space]
        if not hspace.harmonic:
            raise ValueError("Operator requires harmonic target space")
        if power_space is None:
            power_space = PowerSpace(hspace)
        else:
            if not isinstance(power_space, PowerSpace):
                raise TypeError("power_space argument must be a PowerSpace")
            if power_space.harmonic_partner != hspace:
                raise ValueError("power_space does not match its partner")

        self._init2(power_space.pindex, self._space, power_space)