field_zero_padder.py 2.15 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
1
2
3
4
5
6
7
from __future__ import absolute_import, division, print_function

import numpy as np

from .. import dobj
from ..compat import *
from ..domain_tuple import DomainTuple
8
9
from ..domains.rg_space import RGSpace
from ..field import Field
Martin Reinecke's avatar
Martin Reinecke committed
10
11
12
13
from .linear_operator import LinearOperator


class FieldZeroPadder(LinearOperator):
14
    def __init__(self, domain, factor, space=0):
Martin Reinecke's avatar
Martin Reinecke committed
15
        super(FieldZeroPadder, self).__init__()
16
        self._domain = DomainTuple.make(domain)
Martin Reinecke's avatar
Martin Reinecke committed
17
        self._space = int(space)
18
19
        dom = self._domain[self._space]
        if not isinstance(dom, RGSpace):
Martin Reinecke's avatar
Martin Reinecke committed
20
            raise TypeError("RGSpace required")
21
        if not len(dom.shape) == 1:
Martin Reinecke's avatar
Martin Reinecke committed
22
            raise TypeError("RGSpace must be one-dimensional")
23
        if dom.harmonic:
Martin Reinecke's avatar
Martin Reinecke committed
24
25
            raise TypeError("RGSpace must not be harmonic")

26
27
28
29
        tgt = RGSpace((int(factor*dom.shape[0]),), dom.distances)
        self._target = list(self._domain)
        self._target[self._space] = tgt
        self._target = DomainTuple.make(self._target)
Martin Reinecke's avatar
Martin Reinecke committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

    @property
    def domain(self):
        return self._domain

    @property
    def target(self):
        return self._target

    @property
    def capability(self):
        return self.TIMES | self.ADJOINT_TIMES

    def apply(self, x, mode):
        self._check_input(x, mode)
        x = x.val
        dax = dobj.distaxis(x)
        shp_in = x.shape
        shp_out = self._tgt(mode).shape
49
        ax = self._target.axes[self._space][0]
Martin Reinecke's avatar
Martin Reinecke committed
50
51
52
53
        if dax == ax:
            x = dobj.redistribute(x, nodist=(ax,))
        curax = dobj.distaxis(x)

54
        if mode == self.ADJOINT_TIMES:
Martin Reinecke's avatar
Martin Reinecke committed
55
56
57
58
59
60
61
62
63
64
65
            newarr = np.empty(dobj.local_shape(shp_out), dtype=x.dtype)
            newarr[()] = dobj.local_data(x)[(slice(None),)*ax +
                                            (slice(0, shp_out[ax]),)]
        else:
            newarr = np.zeros(dobj.local_shape(shp_out), dtype=x.dtype)
            newarr[(slice(None),)*ax +
                   (slice(0, shp_in[ax]),)] = dobj.local_data(x)
        newarr = dobj.from_local_data(shp_out, newarr, distaxis=curax)
        if dax == ax:
            newarr = dobj.redistribute(newarr, dist=ax)
        return Field(self._tgt(mode), val=newarr)