linear_interpolation.py 5.5 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
tweaks    
Martin Reinecke committed
18
import numpy as np
Philipp Arras's avatar
Cleanup    
Philipp Arras committed
19
20
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import aslinearoperator
21

22
from ..domains.rg_space import RGSpace
Philipp Arras's avatar
Cleanup    
Philipp Arras committed
23
24
from ..domains.unstructured_domain import UnstructuredDomain
from ..field import Field
25
from ..sugar import makeDomain
26
27
28
29
30
31
from .linear_operator import LinearOperator


class LinearInterpolator(LinearOperator):
    def __init__(self, domain, positions):
        """
32
        Multilinear interpolation for points in an RGSpace
33
34

        :param domain:
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
35
            RGSpace
36
37
38
        :param positions:
            positions at which to interpolate
            Field with UnstructuredDomain, shape (dim, ndata)
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
39
            positions that are not within the RGSpace are wrapped
40
            according to periodic boundary conditions
41
42
43
44
45
46
47
48
49
        """
        self._domain = makeDomain(domain)
        N_points = positions.shape[1]
        self._target = makeDomain(UnstructuredDomain(N_points))
        self._capability = self.TIMES | self.ADJOINT_TIMES
        self._build_mat(positions, N_points)

    def _build_mat(self, positions, N_points):
        ndim = positions.shape[0]
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
50
51
        mg = np.mgrid[(slice(0, 2),)*ndim]
        mg = np.array(list(map(np.ravel, mg)))
52
53
        dist = []
        for dom in self.domain:
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
54
            if not isinstance(dom, RGSpace):
55
                raise TypeError
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
56
            dist.append(list(dom.distances))
Philipp Arras's avatar
Tweaks    
Philipp Arras committed
57
        dist = np.array(dist).reshape(-1, 1)
58
        pos = positions/dist
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
59
60
61
62
63
64
        excess = pos-pos.astype(np.int64)
        pos = pos.astype(np.int64)
        max_index = np.array(self.domain.shape).reshape(-1, 1)
        data = np.zeros((len(mg[0]), N_points))
        ii = np.zeros((len(mg[0]), N_points), dtype=np.int64)
        jj = np.zeros((len(mg[0]), N_points), dtype=np.int64)
65
        for i in range(len(mg[0])):
Philipp Arras's avatar
Tweaks    
Philipp Arras committed
66
            factor = np.prod(np.abs(1-mg[:, i].reshape(-1, 1)-excess),
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
67
                             axis=0)
68
            data[i, :] = factor
Philipp Arras's avatar
Tweaks    
Philipp Arras committed
69
            fromi = (pos+mg[:, i].reshape(-1, 1)) % max_index
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
70
71
            ii[i, :] = np.arange(N_points)
            jj[i, :] = np.ravel_multi_index(fromi, self.domain.shape)
72
73
        self._mat = coo_matrix((data.reshape(-1),
                               (ii.reshape(-1), jj.reshape(-1))),
Martin Reinecke's avatar
tweaks    
Martin Reinecke committed
74
                               (N_points, np.prod(self.domain.shape)))
75
        self._mat = aslinearoperator(self._mat)
76

77
78
79
80
    def apply(self, x, mode):
        self._check_input(x, mode)
        x_val = x.to_global_data()
        if mode == self.TIMES:
Philipp Arras's avatar
Tweaks    
Philipp Arras committed
81
            res = self._mat.matvec(x_val.reshape(-1))
82
83
84
85
            return Field.from_global_data(self.target, res)
        res = self._mat.rmatvec(x_val).reshape(self.domain.shape)
        return Field.from_global_data(self.domain, res)

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

# import numpy as np
# from ..domains.rg_space import RGSpace
# import itertools
#
#
# class LinearInterpolator(LinearOperator):
#     def __init__(self, domain, positions):
#         """
#         :param domain:
#             RGSpace
#         :param target:
#             UnstructuredDomain, shape (ndata,)
#         :param positions:
#             positions at which to interpolate
#             Field with UnstructuredDomain, shape (dim, ndata)
#         """
#         if not isinstance(domain, RGSpace):
#             raise TypeError("RGSpace needed")
#         if np.any(domain.shape < 2):
#             raise ValueError("RGSpace shape too small")
#         if positions.ndim != 2:
#             raise ValueError("positions must be a 2D array")
#         ndim = len(domain.shape)
#         if positions.shape[0] != ndim:
#             raise ValueError("shape mismatch")
#         self._domain = makeDomain(domain)
#         N_points = positions.shape[1]
#         dist = np.array(domain.distances).reshape((ndim, -1))
#         self._pos = positions/dist
#         shp = np.array(domain.shape, dtype=int).reshape((ndim, -1))
#         self._idx = np.maximum(0, np.minimum(shp-2, self._pos.astype(int)))
#         self._pos -= self._idx
#         tmp = tuple([0, 1] for i in range(ndim))
#         self._corners = np.array(list(itertools.product(*tmp)))
#         self._target = makeDomain(UnstructuredDomain(N_points))
#         self._capability = self.TIMES | self.ADJOINT_TIMES
#
#     def apply(self, x, mode):
#         self._check_input(x, mode)
#         x = x.to_global_data()
#         ndim = len(self._domain.shape)
#
#         res = np.zeros(self._tgt(mode).shape, dtype=x.dtype)
#         for corner in self._corners:
#             corner = corner.reshape(ndim, -1)
#             idx = self._idx+corner
#             idx2 = tuple(idx[t, :] for t in range(idx.shape[0]))
#             wgt = np.prod(self._pos*corner+(1-self._pos)*(1-corner), axis=0)
#             if mode == self.TIMES:
#                 res += wgt*x[idx2]
#             else:
#                 np.add.at(res, idx2, wgt*x)
#         return Field.from_global_data(self._tgt(mode), res)