Ejemplo n.º 1
0
    def __init__(self, perm, **kwargs):
        """
        Parameters
        ----------
        perm : list or tuple
            The permutation of coefficients.

        Returns
        -------
        A PermutationOperator instance.

        Exemple
        -------
        >>> import numpy as np
        >>> import linear_operators as lo
        >>> P = lo.PermutationOperator([3, 1, 0, 2])
        >>> P.todense()
        array([[ 0.,  0.,  0.,  1.],
               [ 0.,  1.,  0.,  0.],
               [ 1.,  0.,  0.,  0.],
               [ 0.,  0.,  1.,  0.]])

        """

        shape = 2 * (len(perm),)
        self.perm = perm
        # reverse permutation
        self.perm_inv = np.argsort(perm)
        def matvec(x):
            return np.asarray([x[pi] for pi in self.perm])
        def rmatvec(x):
            return np.asarray([x[pi] for pi in self.perm_inv])
        LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 2
0
    def __init__(self,
                 shapein,
                 shapeout,
                 matvec,
                 rmatvec=None,
                 matmat=None,
                 rmatmat=None,
                 dtypein=None,
                 dtypeout=None,
                 dtype=None):

        sizein = np.prod(shapein)
        sizeout = np.prod(shapeout)
        shape = (sizeout, sizein)

        ndmatvec = lambda x: matvec(x.reshape(shapein)).ravel()

        if rmatvec is not None:
            ndrmatvec = lambda x: rmatvec(x.reshape(shapeout)).ravel()
        else:
            ndrmatvec = None

        LinearOperator.__init__(self,
                                shape,
                                ndmatvec,
                                ndrmatvec,
                                dtype=dtype,
                                dtypein=dtypein,
                                dtypeout=dtypeout)

        self.ndmatvec = matvec
        self.ndrmatvec = rmatvec
        self.shapein = shapein
        self.shapeout = shapeout
Ejemplo n.º 3
0
    def __init__(self, shape, rep_num, **kwargs):
        """
        Parameters
        ----------
        shape : length 2 tuple.
            The shape of the operator.

        rep_num : int
            The number of replications.

        Returns
        -------
        A ReplicationOperator instance.

        Exemple
        -------
        >>> import numpy as np
        >>> import linear_operators as lo
        >>> R = lo.ReplicationOperator((4, 2), 2)
        >>> R.todense()
        array([[ 1.,  0.],
               [ 0.,  1.],
               [ 1.,  0.],
               [ 0.,  1.]])
        """
        self.rep_num = rep_num
        # ensure coherent input
        if not shape[0] == shape[1] * rep_num:
            raise ValueError("Output vector should be n times the size of input vector.")
        def matvec(x):
            return np.tile(x, self.rep_num)
        def rmatvec(x):
            N = shape[1]
            return sum([x[i * N:(i + 1) * N] for i in xrange(self.rep_num)])
        LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 4
0
    def __init__(self, shape, slice, **kwargs):
        """

        Exemple
        -------
        >>> S = lo.SliceOperator((2, 4), slice(None, None, 2))
        >>> S.todense()
        array([[ 1.,  0.,  0.,  0.],
               [ 0.,  0.,  1.,  0.]])

        >>> S.T.todense()
        array([[ 1.,  0.],
               [ 0.,  0.],
               [ 0.,  1.],
               [ 0.,  0.]])

        """
        def matvec(x):
            return x[slice]

        def rmatvec(x):
            out = np.zeros(shape[1])
            out[slice] = x
            return out

        LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 5
0
 def __init__(self, shape, shift, **kwargs):
     if shape[0] != shape[1]:
         raise ValueError("Only square operator is implemented.")
     if np.round(shift) != shift:
         raise ValueError("The shift argument should be an integer value.")
     self.shift = shift
     ashift = np.abs(shift)
     # square case
     matvec = lambda x: np.concatenate((x[ashift:], np.zeros(ashift)))
     rmatvec = lambda x: np.concatenate((np.zeros(ashift), x[:-ashift]))
     if self.shift < 0:
         matvec, rmatvec = rmatvec, matvec
     LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 6
0
 def __init__(self, shape, shift, **kwargs):
     if shape[0] != shape[1]:
         raise ValueError("Only square operator is implemented.")
     if np.round(shift) != shift:
         raise ValueError("The shift argument should be an integer value.")
     self.shift = shift
     ashift = np.abs(shift)
     # square case
     matvec = lambda x: np.concatenate((x[ashift:], np.zeros(ashift)))
     rmatvec = lambda x: np.concatenate((np.zeros(ashift), x[:-ashift]))
     if self.shift < 0:
         matvec, rmatvec = rmatvec, matvec
     LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 7
0
    def __init__(self, shape, diag, subdiag, superdiag, **kwargs):
        """
        Parameters
        ----------
        shape : length 2 tuple.
            The shape of the operator.

        diag : ndarray of size shape[0]
            The diagonal of the matrix.

        subdiag : ndarray of size shape[0] - 1
            The subdiagonal of the matrix.

        superdiag : ndarray of size shape[0] - 1
            The superdiagonal of the matrix.

        Returns
        -------
        A Tridiagonal matrix operator instance.

        Exemple
        -------
        >>> import numpy as np
        >>> import linear_operators as lo
        >>> T = lo.TridiagonalOperator((3, 3), [1, 2, 3], [4, 5], [6, 7])
        >>> T.todense()
        array([[1, 6, 0],
               [4, 2, 7],
               [0, 5, 3]])
        """
        if shape[0] != shape[1]:
            raise ValueError("Only square operator is implemented.")
        self.diag = diag
        self.subdiag = subdiag
        self.superdiag = superdiag
        self.kwargs = kwargs

        def matvec(x):
            out = self.diag * x
            out[:-1] += self.superdiag * x[1:]
            out[1:] += self.subdiag * x[:-1]
            return out

        def rmatvec(x):
            out = self.diag * x
            out[:-1] += self.subdiag * x[1:]
            out[1:] += self.superdiag * x[:-1]
            return out

        LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 8
0
    def __init__(self, shape, diag, subdiag, superdiag, **kwargs):
        """
        Parameters
        ----------
        shape : length 2 tuple.
            The shape of the operator.

        diag : ndarray of size shape[0]
            The diagonal of the matrix.

        subdiag : ndarray of size shape[0] - 1
            The subdiagonal of the matrix.

        superdiag : ndarray of size shape[0] - 1
            The superdiagonal of the matrix.

        Returns
        -------
        A Tridiagonal matrix operator instance.

        Exemple
        -------
        >>> import numpy as np
        >>> import linear_operators as lo
        >>> T = lo.TridiagonalOperator((3, 3), [1, 2, 3], [4, 5], [6, 7])
        >>> T.todense()
        array([[1, 6, 0],
               [4, 2, 7],
               [0, 5, 3]])
        """
        if shape[0] != shape[1]:
            raise ValueError("Only square operator is implemented.")
        self.diag = diag
        self.subdiag = subdiag
        self.superdiag = superdiag
        self.kwargs = kwargs

        def matvec(x):
            out = self.diag * x
            out[:-1] += self.superdiag * x[1:]
            out[1:] += self.subdiag * x[:-1]
            return out

        def rmatvec(x):
            out = self.diag * x
            out[:-1] += self.subdiag * x[1:]
            out[1:] += self.superdiag * x[:-1]
            return out

        LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 9
0
def identity(shape, dtype=np.float64):
    "Returns the identity linear Operator"
    if shape[0] != shape[1]:
        raise ValueError('Identity operators must be square')

    def matvec(x):
        return x

    return LinearOperator(shape, matvec=matvec, rmatvec=matvec, dtype=dtype)
Ejemplo n.º 10
0
    def __init__(self, shape, matvec, **kwargs):
        """Returns a SymmetricOperator of given shape and matvec
        function.

        Parameters
        ----------

        shape : length 2 tuple
            The shape of the operator. Should be square.

        matvec : function
            The matrix-vector operation.

        Returns
        -------
        A SymmetricOperator instance.
        """
        if shape[0] != shape[1]:
            raise ValueError("Symmetric operators are square operators.")
        kwargs['rmatvec'] = matvec
        LinearOperator.__init__(self, shape, matvec, **kwargs)
Ejemplo n.º 11
0
    def __init__(self, shape, matvec, **kwargs):
        """Returns a SymmetricOperator of given shape and matvec
        function.

        Parameters
        ----------

        shape : length 2 tuple
            The shape of the operator. Should be square.

        matvec : function
            The matrix-vector operation.

        Returns
        -------
        A SymmetricOperator instance.
        """
        if shape[0] != shape[1]:
            raise ValueError("Symmetric operators are square operators.")
        kwargs['rmatvec'] = matvec
        LinearOperator.__init__(self, shape, matvec, **kwargs)
Ejemplo n.º 12
0
def diag(d, shape=None, dtype=None):
    "Returns a diagonal Linear Operator"
    if shape is None:
        shape = 2 * (d.size, )
    if shape[0] != shape[1]:
        raise ValueError('Diagonal operators must be square')

    def matvec(x):
        return d * x

    if dtype is None:
        dtype = d.dtype
    return LinearOperator(shape, matvec=matvec, rmatvec=matvec, dtype=dtype)
Ejemplo n.º 13
0
    def __init__(self, shape, rep_num, **kwargs):
        """
        Parameters
        ----------
        shape : length 2 tuple.
            The shape of the operator.

        rep_num : int
            The number of replications.

        Returns
        -------
        A ReplicationOperator instance.

        Exemple
        -------
        >>> import numpy as np
        >>> import linear_operators as lo
        >>> R = lo.ReplicationOperator((4, 2), 2)
        >>> R.todense()
        array([[ 1.,  0.],
               [ 0.,  1.],
               [ 1.,  0.],
               [ 0.,  1.]])
        """
        self.rep_num = rep_num
        # ensure coherent input
        if not shape[0] == shape[1] * rep_num:
            raise ValueError(
                "Output vector should be n times the size of input vector.")

        def matvec(x):
            return np.tile(x, self.rep_num)

        def rmatvec(x):
            N = shape[1]
            return sum([x[i * N:(i + 1) * N] for i in xrange(self.rep_num)])

        LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 14
0
    def __init__(self, shapein, shapeout, matvec, rmatvec=None, matmat=None, rmatmat=None,
                 dtypein=None, dtypeout=None, dtype=np.float64):

        sizein = np.prod(shapein)
        sizeout = np.prod(shapeout)
        shape = (sizeout, sizein)

        ndmatvec = lambda x: matvec(x.reshape(shapein)).ravel()

        if rmatvec is not None:
            ndrmatvec = lambda x: rmatvec(x.reshape(shapeout)).ravel()
        else:
            ndrmatvec = None

        LinearOperator.__init__(self, shape, ndmatvec, ndrmatvec, dtype=dtype,
                                dtypein=dtypein, dtypeout=dtypeout)

        # rename to keep same interface as LinearOperator
        self.ndmatvec = matvec
        self.ndrmatvec = rmatvec
        self.shapein = shapein
        self.shapeout = shapeout
Ejemplo n.º 15
0
    def __init__(self, shape, ab, kl, ku, **kwargs):
        """
        Generate a BandOperator instance

        Arguments
        ---------
        shape : 2-tuple
           The shape of the operator
        ab : ndarray with ndim == 2
           Store the bands of the matrix using LAPACK storage scheme.
        kl : int
            Number of subdiagonals
        ku : int
            Number of superdiagonals
        """
        if ab.shape[0] != kl + ku + 1 or ab.shape[1] != shape[1]:
            raise ValueError("Wrong ab shape.")

        self.ab = ab
        self.kl = kl
        self.ku = ku
        self.kwargs = kwargs

        def matvec(x):
            # diag
            out = self.ab[ku] * x
            # upper part
            for i in xrange(ku):
                j = ku - i
                out[:-j] += self.ab[i, j:] * x[j:]
            for i in xrange(ku, kl + ku):
            # lower part
                out[i:] += self.ab[i + 1, :-i] * x[:-i]
            return out

        def rmatvec(x):
            rab = self._rab
            rkl, rku = ku, kl
            # diag
            out = rab[ku] * x
            # upper part
            for i in xrange(rku):
                j = rku - i
                out[:-j] += rab[i, j:] * x[j:]
            for i in xrange(rku, rkl + rku):
            # lower part
                out[i:] += rab[i + 1, :-i] * x[:-i]
            return out

        return LinearOperator.__init__(self, shape, matvec, rmatvec,
                                       **kwargs)
Ejemplo n.º 16
0
    def __init__(self, shape, ab, kl, ku, **kwargs):
        """
        Generate a BandOperator instance

        Arguments
        ---------
        shape : 2-tuple
           The shape of the operator
        ab : ndarray with ndim == 2
           Store the bands of the matrix using LAPACK storage scheme.
        kl : int
            Number of subdiagonals
        ku : int
            Number of superdiagonals
        """
        if ab.shape[0] != kl + ku + 1 or ab.shape[1] != shape[1]:
            raise ValueError("Wrong ab shape.")

        self.ab = ab
        self.kl = kl
        self.ku = ku
        self.kwargs = kwargs

        def matvec(x):
            # diag
            out = self.ab[ku] * x
            # upper part
            for i in xrange(ku):
                j = ku - i
                out[:-j] += self.ab[i, j:] * x[j:]
            for i in xrange(ku, kl + ku):
                # lower part
                out[i:] += self.ab[i + 1, :-i] * x[:-i]
            return out

        def rmatvec(x):
            rab = self._rab
            rkl, rku = ku, kl
            # diag
            out = rab[ku] * x
            # upper part
            for i in xrange(rku):
                j = rku - i
                out[:-j] += rab[i, j:] * x[j:]
            for i in xrange(rku, rkl + rku):
                # lower part
                out[i:] += rab[i + 1, :-i] * x[:-i]
            return out

        return LinearOperator.__init__(self, shape, matvec, rmatvec, **kwargs)
Ejemplo n.º 17
0
    def __init__(self, shape, slice, **kwargs):
        """

        Exemple
        -------
        >>> S = lo.SliceOperator((2, 4), slice(None, None, 2))
        >>> S.todense()
        array([[ 1.,  0.,  0.,  0.],
               [ 0.,  0.,  1.,  0.]])

        >>> S.T.todense()
        array([[ 1.,  0.],
               [ 0.,  0.],
               [ 0.,  1.],
               [ 0.,  0.]])

        """
        def matvec(x):
            return x[slice]
        def rmatvec(x):
            out = np.zeros(shape[1])
            out[slice] = x
            return out
        LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 18
0
    def __init__(self, perm, **kwargs):
        """
        Parameters
        ----------
        perm : list or tuple
            The permutation of coefficients.

        Returns
        -------
        A PermutationOperator instance.

        Exemple
        -------
        >>> import numpy as np
        >>> import linear_operators as lo
        >>> P = lo.PermutationOperator([3, 1, 0, 2])
        >>> P.todense()
        array([[ 0.,  0.,  0.,  1.],
               [ 0.,  1.,  0.,  0.],
               [ 1.,  0.,  0.,  0.],
               [ 0.,  0.,  1.,  0.]])

        """

        shape = 2 * (len(perm), )
        self.perm = perm
        # reverse permutation
        self.perm_inv = np.argsort(perm)

        def matvec(x):
            return np.asarray([x[pi] for pi in self.perm])

        def rmatvec(x):
            return np.asarray([x[pi] for pi in self.perm_inv])

        LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 19
0
def masubclass(xin=None,
               xout=None,
               shapein=None,
               shapeout=None,
               classin=None,
               classout=None,
               dictin=None,
               dictout=None,
               matvec=None,
               rmatvec=None,
               dtype=np.float64,
               dtypein=None,
               dtypeout=None):
    "Wrap linear operation working on ndarray subclasses in MaskedArray style"
    if xin is not None:
        shapein = xin.shape
        classin = xin.__class__
        dictin = xin.__dict__
        dtype = xin.dtype
    if xout is not None:
        shapeout = xout.shape
        classout = xout.__class__
        dictout = xout.__dict__
    sizein = np.prod(shapein)
    sizeout = np.prod(shapeout)
    shape = (sizeout, sizein)
    if matvec is not None:

        def ndmatvec(x):
            xi = classin(x.reshape(shapein))
            xi.__dict__ = dictin
            return matvec(xi).reshape(sizeout)
    else:
        raise ValueError('Requires a matvec function')
    if rmatvec is not None:

        def ndrmatvec(x):
            xo = classout(x.reshape(shapeout))
            xo.__dict__ = dictout
            return rmatvec(xo).reshape(sizein)
    else:
        ndrmatvec = None
    return LinearOperator(shape,
                          matvec=ndmatvec,
                          rmatvec=ndrmatvec,
                          dtype=dtype,
                          dtypein=dtypein,
                          dtypeout=dtypeout)
Ejemplo n.º 20
0
def eye(shape, dtype=np.float64):
    "Returns the identity linear Operator"
    if shape[0] == shape[1]:
        return identity(shape, dtype=dtype)
    else:

        def matvec(x):
            return x[:shape[0]]

        def rmatvec(x):
            return np.concatenate(x, np.zeros(shape[0] - shape[1]))

        return LinearOperator(shape,
                              matvec=matvec,
                              rmatvec=rmatvec,
                              dtype=dtype)
Ejemplo n.º 21
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)
     return s[:-1] + " and shift=%d >" % self.shift
Ejemplo n.º 22
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)[:-1]
     s += ",\n superdiagonal=" + self.superdiag.__repr__()
     s += ",\n diagonal=" + self.diag.__repr__()
     s += ",\n subdiagonal=" + self.subdiag.__repr__() + ">"
     return s
Ejemplo n.º 23
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)[:-1]
     s += ",\n superdiagonal=" + self.superdiag.__repr__()
     s +=  ",\n diagonal=" + self.diag.__repr__()
     s += ",\n subdiagonal=" + self.subdiag.__repr__() + ">"
     return s
Ejemplo n.º 24
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)
     return s[:-1] + ",\n diagonal=" + self.diag.__repr__() + ">"
Ejemplo n.º 25
0
 def __init__(self, shape, **kwargs):
     matvec = lambda x: np.fft.fft(x, n=shape[0]) / np.sqrt(shape[0])
     rmatvec = lambda x: np.fft.ifft(x, n=shape[1]) * np.sqrt(shape[0])
     LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 26
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)
     return s[:-1] + " and shift=%d >" % self.shift
Ejemplo n.º 27
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)
     return s[:-1] + " and coef=%f >" % self.coef
Ejemplo n.º 28
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)
     return s[:-1] + "\n and diagonal=" + self.d.__repr__() + ">"
Ejemplo n.º 29
0
 def __init__(self, shape, **kwargs):
     matvec = lambda x: np.fft.fft(x, n=shape[0]) / np.sqrt(shape[0])
     rmatvec = lambda x: np.fft.ifft(x, n=shape[1]) * np.sqrt(shape[0])
     LinearOperator.__init__(self, shape, matvec, rmatvec=rmatvec, **kwargs)
Ejemplo n.º 30
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)
     return s[:-1] + ",\n permutation=" + self.perm.__repr__() + ">"
Ejemplo n.º 31
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)
     return s[:-1] + ",\n Replicate %i times" % self.n + ">"
Ejemplo n.º 32
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)
     return s[:-1] + ",\n diagonal=" + self.diag.__repr__() + ">"
Ejemplo n.º 33
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)
     return s[:-1] + ",\n Replicate %i times" % self.n + ">"
Ejemplo n.º 34
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)
     return s[:-1] + " and coef=%f >" % self.coef
Ejemplo n.º 35
0
 def __repr__(self):
     s = LinearOperator.__repr__(self)
     return s[:-1] + ",\n permutation=" + self.perm.__repr__() + ">"