nifty_explicit.py 92.8 KB
Newer Older
Marco Selig's avatar
Marco Selig committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
## NIFTY (Numerical Information Field Theory) has been developed at the
## Max-Planck-Institute for Astrophysics.
##
## Copyright (C) 2013 Max-Planck-Society
##
## Author: Marco Selig
## Project homepage: <http://www.mpa-garching.mpg.de/ift/nifty/>
##
## 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/>.

"""
Marco Selig's avatar
Marco Selig committed
23
24
25
26
27
28
29
    ..                 __   ____   __
    ..               /__/ /   _/ /  /_
    ..     __ ___    __  /  /_  /   _/  __   __
    ..   /   _   | /  / /   _/ /  /   /  / /  /
    ..  /  / /  / /  / /  /   /  /_  /  /_/  /
    .. /__/ /__/ /__/ /__/    \___/  \___   /  explicit
    ..                              /______/
Marco Selig's avatar
Marco Selig committed
30

Marco Selig's avatar
Marco Selig committed
31
32
33
34
35
36
37
    This module extends NIFTY's versatility to the usage of explicit matrix
    representations of linear operator by the :py:class:`explicit_operator`.
    In order to access explicit operators, this module provides the
    :py:class:`explicit_probing` class and the :py:func:`explicify` function.
    Those objects are supposed to support the user in solving information field
    theoretical problems in low (or moderate) dimensions, or in debugging
    algorithms by studying operators in detail.
Marco Selig's avatar
Marco Selig committed
38
39
40
41
42
43
44
45
46

"""
from __future__ import division
#import numpy as np
from nifty_core import *


##-----------------------------------------------------------------------------

Marco Selig's avatar
Marco Selig committed
47
class explicit_operator(operator):
Marco Selig's avatar
Marco Selig committed
48
    """
Marco Selig's avatar
Marco Selig committed
49
50
51
52
53
54
55
        ..
        ..
        ..                                    __     __             __   __
        ..                                  /  /   /__/           /__/ /  /_
        ..    _______  __   __    ______   /  /    __   _______   __  /   _/
        ..  /   __  / \  \/  /  /   _   | /  /   /  / /   ____/ /  / /  /
        .. /  /____/  /     /  /  /_/  / /  /_  /  / /  /____  /  / /  /_
56
        .. \______/  /__/\__\ /   ____/  \___/ /__/  \______/ /__/  \___/  operator class
Marco Selig's avatar
Marco Selig committed
57
58
        ..                   /__/

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
        NIFTY subclass for explicit linear operators.

        This class essentially supports linear operators with explicit matrix
        representation in the NIFTY framework. Note that this class is not
        suited for handling huge dimensionalities.

        Parameters
        ----------
        domain : space
            The space wherein valid arguments live.
        matrix : {list, array}
            The matrix representation of the operator, ideally shaped in 2D
            according to dimensionality of target and domain (default: None).
        bare : {bool, 2-tuple}, *optional*
            Whether the matrix entries are `bare` or not
            (mandatory for the correct incorporation of volume weights)
            (default: True)
        sym : bool, *optional*
            Indicates whether the operator is self-adjoint or not
            (default: False).
        uni : bool, *optional*
            Indicates whether the operator is unitary or not (default: False).
        target : space, *optional*
            The space wherein the operator output lives (default: domain).

        See Also
        --------
        explicify : A function that returns an explicit oparator given an
            implicit one.

        Notes
        -----
        The ambiguity of `bare` or non-bare diagonal entries is based
        on the choice of a matrix representation of the operator in
        question. The naive choice of absorbing the volume weights
        into the matrix leads to a matrix-vector calculus with the
        non-bare entries which seems intuitive, though. The choice of
        keeping matrix entries and volume weights separate deals with the
        bare entries that allow for correct interpretation of the matrix
        entries; e.g., as variance in case of an covariance operator.

Marco Selig's avatar
Marco Selig committed
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
        Examples
        --------
        >>> x_space = rg_space(2) # default `dist` == 0.5
        >>> A = explicit_operator(x_space, matrix=[[2, 0], [1, 1]], bare=False)
        >>> A.get_matrix(bare=False)
        array([[2, 0],
               [1, 1]])
        >>> A.get_matrix(bare=True)
        array([[4, 0],
               [2, 2]])
        >>> c = field(x_space, val=[3, 5])
        >>> A(c).val
        array([ 6.,  8.])
        >>> A.inverse()
        <nifty_explicit.explicit_operator>
        >>> (A * A.inverse()).get_matrix(bare=False) # == identity
        array([[ 1.,  0.],
               [ 0.,  1.]])
        >>> B = A + diagonal_operator(x_space, diag=2, bare=False)
        >>> B.get_matrix(bare=False)
        array([[ 4.,  0.],
               [ 1.,  3.]])
        >>> B(c).val
        array([ 12.,  18.])
        >>> B.tr()
        7.0
        >>> B.det()
        12.000000000000005

129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
        Attributes
        ----------
        domain : space
            The space wherein valid arguments live.
        val : array
            An array containing the `bare` matrix entries.
        sym : bool
            Indicates whether the operator is self-adjoint or not
        uni : bool
            Indicates whether the operator is unitary or not
        imp : bool
            Indicates whether the incorporation of volume weights in
            multiplications is already implemented in the `multiply`
            instance methods or not.
        target : space
            The space wherein the operator output lives.
        _hidden : array
            An array specifying hidden degrees of freedom in domain and target.
        _inv : array
            An array containing the inverse matrix; set when needed.
Marco Selig's avatar
Marco Selig committed
149
150
151
152

    """
    epsilon = 1E-12 ## absolute precision for comparisons to identity

153
    def __init__(self,domain,matrix=None,bare=True,sym=None,uni=None,target=None):
Marco Selig's avatar
Marco Selig committed
154
        """
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
            Initializes the explicit operator and sets the standard operator
            properties as well as `values`.

            Parameters
            ----------
            domain : space
                The space wherein valid arguments live.
            matrix : {list, array}
                The matrix representation of the operator, ideally shaped in 2D
                according to dimensionality of target and domain (default: None).
            bare : {bool, 2-tuple}, *optional*
                Whether the matrix entries are `bare` or not
                (mandatory for the correct incorporation of volume weights)
                (default: True).
            sym : bool, *optional*
                Indicates whether the operator is self-adjoint or not
                (default: False).
            uni : bool, *optional*
                Indicates whether the operator is unitary or not (default: False).
            target : space, *optional*
                The space wherein the operator output lives (default: domain).

            Notes
            -----
            The ambiguity of `bare` or non-bare diagonal entries is based
            on the choice of a matrix representation of the operator in
            question. The naive choice of absorbing the volume weights
            into the matrix leads to a matrix-vector calculus with the
            non-bare entries which seems intuitive, though. The choice of
            keeping matrix entries and volume weights separate deals with the
            bare entries that allow for correct interpretation of the matrix
            entries; e.g., as variance in case of an covariance operator.

            Raises
            ------
            TypeError
                If invalid input is given.
            ValueError
                If dimensions of `domain`, `target`, and `matrix` mismatch;
                or if `bare` is invalid.
Marco Selig's avatar
Marco Selig committed
195
196
197
198
199
200
201

        """
        ## check domain
        if(not isinstance(domain,space)):
            raise TypeError(about._errors.cstring("ERROR: invalid input."))
        self.domain = domain

202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
        ## check matrix and target
        if(matrix is None):
            if(target is None):
                val = np.zeros((self.domain.dim(split=False),self.domain.dim(split=False)),dtype=np.int,order='C')
                target = self.domain
            else:
                if(not isinstance(target,space)):
                    raise TypeError(about._errors.cstring("ERROR: invalid input."))
                elif(target!=self.domain):
                    sym = False
                    uni = False
                val = np.zeros((target.dim(split=False),self.domain.dim(split=False)),dtype=np.int,order='C')
        elif(np.size(matrix,axis=None)%self.domain.dim(split=False)==0):
            val = np.array(matrix).reshape((-1,self.domain.dim(split=False)))
            if(target is not None):
                if(not isinstance(target,space)):
                    raise TypeError(about._errors.cstring("ERROR: invalid input."))
                elif(val.shape[0]!=target.dim(split=False)):
                    raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(val.shape[0])+" <> "+str(target.dim(split=False))+" )."))
                elif(target!=self.domain):
                    sym = False
                    uni = False
            elif(val.shape[0]==val.shape[1]):
                target = self.domain
            else:
                raise TypeError(about._errors.cstring("ERROR: insufficient input."))
        else:
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(matrix,axis=None))+" <> "+str(self.domain.dim(split=False))+" )."))
Marco Selig's avatar
Marco Selig committed
230
        if(val.size>1048576):
Marco Selig's avatar
Marco Selig committed
231
            about.infos.cprint("INFO: matrix size > 2 ** 20.")
Marco Selig's avatar
Marco Selig committed
232
233
        self.target = target

Marco Selig's avatar
Marco Selig committed
234
235
236
237
238
239
240
241
242
243
        ## check datatype
        if(np.any(np.iscomplex(val))):
            datatype,purelyreal = max(min(val.dtype,self.domain.datatype),min(val.dtype,self.target.datatype)),False
        else:
            datatype,purelyreal = max(min(val.dtype,self.domain.vol.dtype),min(val.dtype,self.target.vol.dtype)),True
        ## weight if ... (given `domain` and `target`)
        if(isinstance(bare,tuple)):
            if(len(bare)!=2):
                raise ValueError(about._errors.cstring("ERROR: invalid input."))
            else:
244
245
                val = self._calc_weight_rows(val,power=-int(not bare[0]))
                val = self._calc_weight_cols(val,power=-int(not bare[1]))
Marco Selig's avatar
Marco Selig committed
246
247
248
249
250
251
252
253
254
255
256
257
        elif(not bare):
            val = self._calc_weight_rows(val,-1)
        if(purelyreal):
            self.val = np.real(val).astype(datatype)
        else:
            self.val = val.astype(datatype)

        ## check hidden degrees of freedom
        self._hidden = np.array([self.domain.dim(split=False)<self.domain.dof(),self.target.dim(split=False)<self.target.dof()],dtype=np.bool)
#        if(np.any(self._hidden)):
#            about.infos.cprint("INFO: inappropriate space.")

Marco Selig's avatar
Marco Selig committed
258
        ## check flags
Marco Selig's avatar
Marco Selig committed
259
260
261
262
263
264
265
266
267
268
269
270
        self.sym,self.uni = self._check_flags(sym=sym,uni=uni)
        if(self.domain.discrete)and(self.target.discrete):
            self.imp = True
        else:
            self.imp = False ## bare matrix is stored for efficiency

        self._inv = None ## defined when needed

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def _check_flags(self,sym=None,uni=None): ## > determine `sym` and `uni`
        if(self.val.shape[0]==self.val.shape[1]):
Marco Selig's avatar
Marco Selig committed
271
            if(sym is None):
Marco Selig's avatar
Marco Selig committed
272
273
                adj = np.conjugate(self.val.T)
                sym = np.all(np.absolute(self.val-adj)<self.epsilon)
Marco Selig's avatar
Marco Selig committed
274
                if(uni is None):
Marco Selig's avatar
Marco Selig committed
275
                    uni = np.all(np.absolute(self._calc_mul(adj,0)-np.diag(1/self.target.get_meta_volume(total=False).flatten(order='C'),k=0))<self.epsilon)
Marco Selig's avatar
Marco Selig committed
276
            elif(uni is None):
Marco Selig's avatar
Marco Selig committed
277
                adj = np.conjugate(self.val.T)
Marco Selig's avatar
Marco Selig committed
278
                uni = np.all(np.absolute(self._calc_mul(adj,0)-np.diag(1/self.target.get_meta_volume(total=False).flatten(order='C'),k=0))<self.epsilon)
Marco Selig's avatar
Marco Selig committed
279
            return bool(sym),bool(uni)
Marco Selig's avatar
Marco Selig committed
280
        else:
Marco Selig's avatar
Marco Selig committed
281
282
283
284
285
286
287
288
289
290
291
292
            return False,False

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def _set_inverse(self): ## > define inverse matrix
        if(self._inv is None):
            if(np.any(self._hidden)):
                about.warnings.cprint("WARNING: inappropriate inversion.")
            self._inv = np.linalg.inv(self.weight(rowpower=1,colpower=1,overwrite=False))

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

293
294
    def cast_domain(self,newdomain):
        """
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
            Casts the domain of the operator.

            Parameters
            ----------
            newdomain : space
                New space wherein valid argument lives.

            Returns
            -------
            None

            Raises
            ------
            TypeError
                If `newdomain` is no instance of the nifty_core.space class
            ValueError
                If `newdomain` does not match the (unsplit) dimensionality of
                the current domain.
313
314
315
316
317
318
319
320
321
322

        """
        if(not isinstance(newdomain,space)):
            raise TypeError(about._errors.cstring("ERROR: invalid input."))
        elif(newdomain.dim(split=False)!=self.domain.dim(split=False)):
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(newdomain.dim(split=False))+" <> "+str(self.domain.dim(split=False))+" )."))
        self.domain = newdomain

    def cast_target(self,newtarget):
        """
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
            Casts the target of the operator.

            Parameters
            ----------
            newtarget : space
                New space wherein the operator output lives.

            Returns
            -------
            None

            Raises
            ------
            TypeError
                If `newtarget` is no instance of the nifty_core.space class
            ValueError
                If `newtarget` does not match the (unsplit) dimensionality of
                the current target.
341
342
343
344
345
346
347
348

        """
        if(not isinstance(newtarget,space)):
            raise TypeError(about._errors.cstring("ERROR: invalid input."))
        elif(newtarget.dim(split=False)!=self.target.dim(split=False)):
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(newtarget.dim(split=False))+" <> "+str(self.target.dim(split=False))+" )."))
        self.target = newtarget

349
    def cast_spaces(self,newdomain=None,newtarget=None):
350
        """
351
352
353
354
355
356
357
358
359
360
361
362
            Casts the domain and/or the target of the operator.

            Parameters
            ----------
            newdomain : space, *optional*
                New space wherein valid argument lives (default: None).
            newtarget : space, *optional*
                New space wherein the operator output lives (default: None).

            Returns
            -------
            None
363
364

        """
365
366
367
368
        if(newdomain is not None):
            self.cast_domain(newdomain)
        if(newtarget is not None):
            self.cast_target(newtarget)
369
370
371

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Marco Selig's avatar
Marco Selig committed
372
373
    def set_matrix(self,newmatrix,bare=True,sym=None,uni=None):
        """
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
            Resets the entire matrix.

            Parameters
            ----------
            matrix : {list, array}
                New matrix representation of the operator, ideally shaped in 2D
                according to dimensionality of target and domain (default: None).
            bare : {bool, 2-tuple}, *optional*
                Whether the new matrix entries are `bare` or not
                (mandatory for the correct incorporation of volume weights)
                (default: True).
            sym : bool, *optional*
                Indicates whether the new operator is self-adjoint or not
                (default: False).
            uni : bool, *optional*
                Indicates whether the new operator is unitary or not
                (default: False).

            Notes
            -----
            The ambiguity of `bare` or non-bare diagonal entries is based
            on the choice of a matrix representation of the operator in
            question. The naive choice of absorbing the volume weights
            into the matrix leads to a matrix-vector calculus with the
            non-bare entries which seems intuitive, though. The choice of
            keeping matrix entries and volume weights separate deals with the
            bare entries that allow for correct interpretation of the matrix
            entries; e.g., as variance in case of an covariance operator.

            Returns
            -------
            None

            Raises
            ------
            ValueError
                If matrix' dimensions mismatch;
                or if `bare` is invalid.
Marco Selig's avatar
Marco Selig committed
412
413

        """
414
415
416
417
418
419
420
421
422
423
        ## check matrix
        if(np.size(newmatrix,axis=None)==self.domain.dim(split=False)*self.target.dim(split=False)):
            val = np.array(newmatrix).reshape((self.target.dim(split=False),self.domain.dim(split=False)))
            if(self.target!=self.domain):
                sym = False
                uni = False
            if(val.size>1048576):
                about.infos.cprint("INFO: matrix size > 2 ** 20.")
        else:
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(matrix,axis=None))+" <> "+str(self.nrow())+" x "+str(self.ncol())+" )."))
Marco Selig's avatar
Marco Selig committed
424
425

        ## check datatype
426
427
        if(np.any(np.iscomplex(val))):
            datatype,purelyreal = max(min(val.dtype,self.domain.datatype),min(val.dtype,self.target.datatype)),False
Marco Selig's avatar
Marco Selig committed
428
        else:
429
            datatype,purelyreal = max(min(val.dtype,self.domain.vol.dtype),min(val.dtype,self.target.vol.dtype)),True
Marco Selig's avatar
Marco Selig committed
430
        ## weight if ... (given `domain` and `target`)
Marco Selig's avatar
Marco Selig committed
431
432
433
434
        if(isinstance(bare,tuple)):
            if(len(bare)!=2):
                raise ValueError(about._errors.cstring("ERROR: invalid input."))
            else:
435
436
                val = self._calc_weight_rows(val,power=-int(not bare[0]))
                val = self._calc_weight_cols(val,power=-int(not bare[1]))
Marco Selig's avatar
Marco Selig committed
437
438
        elif(not bare):
            val = self._calc_weight_rows(val,-1)
439
440
441
442
        if(purelyreal):
            self.val = np.real(val).astype(datatype)
        else:
            self.val = val.astype(datatype)
Marco Selig's avatar
Marco Selig committed
443

Marco Selig's avatar
Marco Selig committed
444
445
446
        ## check flags
        self.sym,self.uni = self._check_flags(sym=sym,uni=uni)
        self._inv = None ## reset
Marco Selig's avatar
Marco Selig committed
447
448
449

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Marco Selig's avatar
Marco Selig committed
450
    def get_matrix(self,bare=True):
Marco Selig's avatar
Marco Selig committed
451
        """
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
            Returns the entire matrix.

            Parameters
            ----------
            bare : {bool, 2-tuple}, *optional*
                Whether the returned matrix entries are `bare` or not
                (default: True).

            Notes
            -----
            The ambiguity of `bare` or non-bare diagonal entries is based
            on the choice of a matrix representation of the operator in
            question. The naive choice of absorbing the volume weights
            into the matrix leads to a matrix-vector calculus with the
            non-bare entries which seems intuitive, though. The choice of
            keeping matrix entries and volume weights separate deals with the
            bare entries that allow for correct interpretation of the matrix
            entries; e.g., as variance in case of an covariance operator.

            Returns
            -------
            matrix : numpy.array
                The matrix representation of the operator, shaped in 2D
                according to dimensionality of target and domain.

            Raises
            ------
            ValueError
                If `bare` is invalid.
Marco Selig's avatar
Marco Selig committed
481
482

        """
Marco Selig's avatar
Marco Selig committed
483
484
485
486
487
488
489
        if(bare==True)or(self.imp):
            return self.val
        ## weight if ...
        elif(isinstance(bare,tuple)):
            if(len(bare)!=2):
                raise ValueError(about._errors.cstring("ERROR: invalid input."))
            else:
490
                return self.weight(rowpower=int(not bare[0]),colpower=int(not bare[1]),overwrite=False)
Marco Selig's avatar
Marco Selig committed
491
        elif(not bare):
492
            return self.weight(rowpower=int(not bare),colpower=0,overwrite=False)
Marco Selig's avatar
Marco Selig committed
493
494
495
496
497
498
499
500
501
502

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def _calc_weight_row(self,x,power): ## > weight row and flatten
        return self.domain.calc_weight(x,power=power).flatten(order='C')

    def _calc_weight_col(self,x,power): ## > weight column and flatten
        return self.target.calc_weight(x,power=power).flatten(order='C')

    def _calc_weight_rows(self,X,power=1): ## > weight all rows
503
504
505
506
        if(np.any(np.iscomplex(X)))and(not issubclass(self.domain.datatype,np.complexfloating)):
            return (np.apply_along_axis(self._calc_weight_row,1,np.real(X),power)+np.apply_along_axis(self._calc_weight_row,1,np.imag(X),power)*1j)
        else:
            return np.apply_along_axis(self._calc_weight_row,1,X,power)
Marco Selig's avatar
Marco Selig committed
507
508

    def _calc_weight_cols(self,X,power=1): ## > weight all columns
509
510
511
512
        if(np.any(np.iscomplex(X)))and(not issubclass(self.target.datatype,np.complexfloating)):
            return (np.apply_along_axis(self._calc_weight_col,0,np.real(X),power)+np.apply_along_axis(self._calc_weight_col,0,np.imag(X),power)*1j)
        else:
            return np.apply_along_axis(self._calc_weight_col,0,X,power)
Marco Selig's avatar
Marco Selig committed
513
514
515

    def weight(self,rowpower=0,colpower=0,overwrite=False):
        """
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
            Returns the entire matrix, weighted with the volume factors to a
            given power. The matrix entries will optionally be overwritten.

            Parameters
            ----------
            rowpower : scalar, *optional*
                Specifies the power of the volume factors applied to the rows
                of the matrix (default: 0).
            rowpower : scalar, *optional*
                Specifies the power of the volume factors applied to the columns
                of the matrix (default: 0).
            overwrite : bool, *optional*
                Whether to overwrite the matrix or not (default: False).

            Returns
            -------
            field : field, *optional*
                If overwrite is ``False``, the weighted matrix is returned;
                otherwise, nothing is returned.
Marco Selig's avatar
Marco Selig committed
535
536
537

        """
        if(overwrite):
Marco Selig's avatar
Marco Selig committed
538
            if(not self.domain.discrete)and(rowpower): ## rowpower <> 0
Marco Selig's avatar
Marco Selig committed
539
                self.val = self._calc_weight_rows(self.val,rowpower)
Marco Selig's avatar
Marco Selig committed
540
            if(not self.target.discrete)and(colpower): ## colpower <> 0
Marco Selig's avatar
Marco Selig committed
541
542
543
                self.val = self._calc_weight_cols(self.val,colpower)
        else:
            X = np.copy(self.val)
Marco Selig's avatar
Marco Selig committed
544
            if(not self.domain.discrete)and(rowpower): ## rowpower <> 0
Marco Selig's avatar
Marco Selig committed
545
                X = self._calc_weight_rows(X,rowpower)
Marco Selig's avatar
Marco Selig committed
546
            if(not self.target.discrete)and(colpower): ## colpower <> 0
Marco Selig's avatar
Marco Selig committed
547
548
549
550
551
552
                X = self._calc_weight_cols(X,colpower)
            return X

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def _multiply(self,x,**kwargs): ## > applies the matirx to a given field
Marco Selig's avatar
Marco Selig committed
553
554
555
556
        if(self._hidden[0]): ## hidden degrees of freedom
            x_ = np.apply_along_axis(self.domain.calc_dot,1,self.val,np.conjugate(x.val))
        else:
            x_ = np.dot(self.val,x.val.flatten(order='C'),out=None)
Marco Selig's avatar
Marco Selig committed
557
558
559
        return x_

    def _adjoint_multiply(self,x,**kwargs): ## > applies the adjoint operator to a given field
Marco Selig's avatar
Marco Selig committed
560
561
562
563
        if(self._hidden[1]): ## hidden degrees of freedom
            x_ = np.apply_along_axis(self.target.calc_dot,0,np.conjugate(self.val),np.conjugate(x.val))
        else:
            x_ = np.dot(np.conjugate(self.val.T),x.val.flatten(order='C'),out=None)
Marco Selig's avatar
Marco Selig committed
564
565
566
        return x_

    def _inverse_multiply(self,x,**kwargs): ## > applies the inverse operator to a given field
Marco Selig's avatar
Marco Selig committed
567
568
569
570
        if(self._hidden[1]): ## hidden degrees of freedom
            x_ = np.apply_along_axis(self.target.calc_dot,1,self._inv,np.conjugate(x.val))
        else:
            x_ = np.dot(self._inv,x.val.flatten(order='C'),out=None)
Marco Selig's avatar
Marco Selig committed
571
572
573
        return x_

    def _inverse_adjoint_multiply(self,x,**kwargs): ## > applies the adjoint inverse operator to a given field
Marco Selig's avatar
Marco Selig committed
574
575
576
577
        if(self._hidden[0]): ## hidden degrees of freedom
            x_ = np.apply_along_axis(self.domain.calc_dot,0,np.conjugate(self.val),np.conjugate(x.val))
        else:
            x_ = np.dot(np.conjugate(self._inv.T),x.val.flatten(order='C'),out=None)
Marco Selig's avatar
Marco Selig committed
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
        return x_

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def inverse_times(self,x,**kwargs):
        """
            Applies the inverse operator to a given object.

            Parameters
            ----------
            x : {scalar, ndarray, field}
                Scalars are interpreted as constant arrays, and an array will
                be interpreted as a field on the domain space of the operator.

            Returns
            -------
            OIx : field
                Mapped field on the target space of the operator.

            Raises
            ------
            ValueError
                If it is no square matrix.

        """
        ## check whether self-inverse
        if(self.sym)and(self.uni):
            return self.times(x,**kwargs)

        ## check whether square matrix
        elif(self.nrow()!=self.ncol()):
Marco Selig's avatar
Marco Selig committed
609
610
611
            raise ValueError(about._errors.cstring("ERROR: inverse ill-defined for "+str(self.nrow())+" x "+str(self.ncol())+" matrices."))

        self._set_inverse()
Marco Selig's avatar
Marco Selig committed
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645

        ## prepare
        x_ = self._briefing(x,self.target,True)
        ## apply operator
        x_ = self._inverse_multiply(x_,**kwargs)
        ## evaluate
        return self._debriefing(x,x_,self.domain,True)

    def adjoint_inverse_times(self,x,**kwargs):
        """
            Applies the inverse adjoint operator to a given object.

            Parameters
            ----------
            x : {scalar, ndarray, field}
                Scalars are interpreted as constant arrays, and an array will
                be interpreted as a field on the target space of the operator.

            Returns
            -------
            OAIx : field
                Mapped field on the domain of the operator.

            Notes
            -----
            For linear operators represented by square matrices, inversion and
            adjungation and inversion commute.

            Raises
            ------
            ValueError
                If it is no square matrix.

        """
Marco Selig's avatar
Marco Selig committed
646
        return self._inverse_adjoint_times(x,**kwargs)
Marco Selig's avatar
Marco Selig committed
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675

    def inverse_adjoint_times(self,x,**kwargs):
        """
            Applies the adjoint inverse operator to a given object.

            Parameters
            ----------
            x : {scalar, ndarray, field}
                Scalars are interpreted as constant arrays, and an array will
                be interpreted as a field on the target space of the operator.

            Returns
            -------
            OIAx : field
                Mapped field on the domain of the operator.

            Notes
            -----
            For linear operators represented by square matrices, inversion and
            adjungation and inversion commute.

            Raises
            ------
            ValueError
                If it is no square matrix.

        """
        ## check whether square matrix
        if(self.nrow()!=self.ncol()):
Marco Selig's avatar
Marco Selig committed
676
            raise ValueError(about._errors.cstring("ERROR: inverse ill-defined for "+str(self.nrow())+" x "+str(self.ncol())+" matrices."))
Marco Selig's avatar
Marco Selig committed
677
678
679

        ## check whether self-adjoint
        if(self.sym):
Marco Selig's avatar
Marco Selig committed
680
            return self._inverse_times(x,**kwargs)
Marco Selig's avatar
Marco Selig committed
681
682
683
684
        ## check whether unitary
        if(self.uni):
            return self.times(x,**kwargs)

Marco Selig's avatar
Marco Selig committed
685
        self._set_inverse()
Marco Selig's avatar
Marco Selig committed
686
687
688
689
690
691
692
693
694
695

        ## prepare
        x_ = self._briefing(x,self.domain,True)
        ## apply operator
        x_ = self._inverse_adjoint_multiply(x_,**kwargs)
        ## evaluate
        return self._debriefing(x,x_,self.target,True)

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Marco Selig's avatar
Marco Selig committed
696
697
698
    def tr(self,domain=None,**kwargs):
        """
            Computes the trace of the operator.
Marco Selig's avatar
Marco Selig committed
699

Marco Selig's avatar
Marco Selig committed
700
701
702
            Parameters
            ----------
            domain : space, *optional*
703
                Space wherein the probes live (default: self.domain).
Marco Selig's avatar
Marco Selig committed
704
            target : space, *optional*
705
                Space wherein the transform of the probes live (default: None).
Marco Selig's avatar
Marco Selig committed
706
            random : string, *optional*
707
708
709
710
711
712
713
714
715
716
717
                Specifies the pseudo random number generator (default: "pm1");
                supported distributions are:

                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
                - "gau" (normal distribution with zero-mean and a given standard deviation or variance)

            ncpu : integer, *optional*
                Number of used CPUs to use (default: 2).
            nrun : integer, *optional*
                Total number of probes (default: 8).
            nper : integer, *optional*
Marco Selig's avatar
Marco Selig committed
718
                Number of tasks performed by one worker (default: 1).
Marco Selig's avatar
Marco Selig committed
719
            var : bool, *optional*
720
721
                Whether to additionally return the probing variance or not
                (default: False).
Marco Selig's avatar
Marco Selig committed
722
            loop : bool, *optional*
723
                Whether to perform a loop or to parallelise (default: False).
Marco Selig's avatar
Marco Selig committed
724

Marco Selig's avatar
Marco Selig committed
725
726
727
            Returns
            -------
            tr : float
728
                Trace of the operator.
Marco Selig's avatar
Marco Selig committed
729
            delta : float, *optional*
730
731
732
733
734
735
736
737
738
739
740
                Probing variance of the trace; returned if `var` is ``True`` in
                case of probing.

            See Also
            --------
            trace_probing

            Raises
            ------
            ValueError
                If `domain` and `target` are unequal.
Marco Selig's avatar
Marco Selig committed
741
742
743
744

        """
        if(self.domain!=self.target):
            raise ValueError(about._errors.cstring("ERROR: trace ill-defined."))
Marco Selig's avatar
Marco Selig committed
745

Marco Selig's avatar
Marco Selig committed
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
        if(domain is None)or(domain==self.domain):
            diag = self.diag(bare=False,domain=self.domain)
            if(self._hidden[0]): ## hidden degrees of freedom
                return self.domain.calc_dot(np.ones(self.domain.dim(split=True),dtype=self.domain.datatype,order='C'),diag) ## discrete inner product
            else:
                return np.sum(diag,axis=None,dtype=None,out=None)
        else:
            return super(explicit_operator,self).tr(domain=domain,**kwargs) ## probing

    def inverse_tr(self,domain=None,**kwargs):
        """
            Computes the trace of the inverse operator.

            Parameters
            ----------
            domain : space, *optional*
762
                Space wherein the probes live (default: self.domain).
Marco Selig's avatar
Marco Selig committed
763
            target : space, *optional*
764
                Space wherein the transform of the probes live (default: None).
Marco Selig's avatar
Marco Selig committed
765
            random : string, *optional*
766
767
768
769
770
771
772
773
774
775
776
                Specifies the pseudo random number generator (default: "pm1");
                supported distributions are:

                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
                - "gau" (normal distribution with zero-mean and a given standard deviation or variance)

            ncpu : integer, *optional*
                Number of used CPUs to use (default: 2).
            nrun : integer, *optional*
                Total number of probes (default: 8).
            nper : integer, *optional*
Marco Selig's avatar
Marco Selig committed
777
                Number of tasks performed by one worker (default: 1).
Marco Selig's avatar
Marco Selig committed
778
            var : bool, *optional*
779
780
                Whether to additionally return the probing variance or not
                (default: False).
Marco Selig's avatar
Marco Selig committed
781
            loop : bool, *optional*
782
                Whether to perform a loop or to parallelise (default: False).
Marco Selig's avatar
Marco Selig committed
783
784
785
786

            Returns
            -------
            tr : float
787
                Trace of the operator.
Marco Selig's avatar
Marco Selig committed
788
            delta : float, *optional*
789
790
791
792
793
794
795
796
797
798
799
                Probing variance of the trace; returned if `var` is ``True`` in
                case of probing.

            See Also
            --------
            trace_probing

            Raises
            ------
            ValueError
                If `domain` and `target` are unequal.
Marco Selig's avatar
Marco Selig committed
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822

        """
        if(self.domain!=self.target):
            raise ValueError(about._errors.cstring("ERROR: trace ill-defined."))

        if(domain is None)or(domain==self.domain):
            diag = self.inverse_diag(bare=False,domain=self.domain)
            if(self._hidden[0]): ## hidden degrees of freedom
                return self.domain.calc_dot(np.ones(self.domain.dim(split=True),dtype=self.domain.datatype,order='C'),diag) ## discrete inner product
            else:
                return np.sum(diag,axis=None,dtype=None,out=None)
        else:
            return super(explicit_operator,self).tr(domain=domain,**kwargs) ## probing

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def diag(self,bare=False,domain=None,**kwargs):
        """
            Computes the diagonal of the operator.

            Parameters
            ----------
            bare : bool, *optional*
823
824
                Whether the returned diagonal entries are `bare` or not
                (default: True).
Marco Selig's avatar
Marco Selig committed
825
            domain : space, *optional*
826
                Space wherein the probes live (default: self.domain).
Marco Selig's avatar
Marco Selig committed
827
            target : space, *optional*
828
                Space wherein the transform of the probes live (default: None).
Marco Selig's avatar
Marco Selig committed
829
            random : string, *optional*
830
831
832
833
834
835
836
837
838
839
840
                Specifies the pseudo random number generator (default: "pm1");
                supported distributions are:

                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
                - "gau" (normal distribution with zero-mean and a given standard deviation or variance)

            ncpu : integer, *optional*
                Number of used CPUs to use (default: 2).
            nrun : integer, *optional*
                Total number of probes (default: 8).
            nper : integer, *optional*
Marco Selig's avatar
Marco Selig committed
841
                Number of tasks performed by one worker (default: 1).
Marco Selig's avatar
Marco Selig committed
842
            var : bool, *optional*
843
844
                Whether to additionally return the probing variance or not
                (default: False).
Marco Selig's avatar
Marco Selig committed
845
            save : bool, *optional*
846
847
                Whether all individual probing results are saved or not
                (default: False).
Marco Selig's avatar
Marco Selig committed
848
            path : string, *optional*
849
                Path wherein the results are saved (default: "tmp").
Marco Selig's avatar
Marco Selig committed
850
            prefix : string, *optional*
851
                Prefix for all saved files (default: "")
Marco Selig's avatar
Marco Selig committed
852
            loop : bool, *optional*
853
                Whether to perform a loop or to parallelise (default: False).
Marco Selig's avatar
Marco Selig committed
854
855
856
857

            Returns
            -------
            diag : ndarray
858
                Diagonal of the operator.
Marco Selig's avatar
Marco Selig committed
859
            delta : float, *optional*
860
861
                Probing variance of the trace; returned if `var` is ``True`` in
                case of probing.
Marco Selig's avatar
Marco Selig committed
862
863
864
865
866
867
868
869
870
871
872
873

            Notes
            -----
            The ambiguity of `bare` or non-bare diagonal entries is based
            on the choice of a matrix representation of the operator in
            question. The naive choice of absorbing the volume weights
            into the matrix leads to a matrix-vector calculus with the
            non-bare entries which seems intuitive, though. The choice of
            keeping matrix entries and volume weights separate deals with the
            bare entries that allow for correct interpretation of the matrix
            entries; e.g., as variance in case of an covariance operator.

874
875
876
877
878
879
880
881
882
            See Also
            --------
            diagonal_probing

            Raises
            ------
            ValueError
                If it is no square matrix.

Marco Selig's avatar
Marco Selig committed
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
        """
        if(self.val.shape[0]!=self.val.shape[1]):
            raise ValueError(about._errors.cstring("ERROR: diagonal ill-defined for "+str(self.val.shape[0])+" x "+str(self.val.shape[1])+" matrices."))
        if(self.domain!=self.target)and(not bare):
            about.warnings.cprint("WARNING: ambiguous non-bare diagonal.")

        if(domain is None)or(domain==self.domain):
            diag = np.diagonal(self.val,offset=0,axis1=0,axis2=1)
            ## weight if ...
            if(not self.domain.discrete)and(not bare):
                diag = self.domain.calc_weight(diag,power=1)
                ## check complexity
                if(np.all(np.imag(diag)==0)):
                    diag = np.real(diag)
            return diag
        elif(domain==self.target):
            diag = np.diagonal(np.conjugate(self.val.T),offset=0,axis1=0,axis2=1)
            ## weight if ...
            if(not self.target.discrete)and(not bare):
                diag = self.target.calc_weight(diag,power=1)
                ## check complexity
                if(np.all(np.imag(diag)==0)):
                    diag = np.real(diag)
            return diag
        else:
            return super(explicit_operator,self).diag(bare=bare,domain=domain,**kwargs) ## probing

    def inverse_diag(self,bare=False,domain=None,**kwargs):
        """
            Computes the diagonal of the inverse operator.
Marco Selig's avatar
Marco Selig committed
913

Marco Selig's avatar
Marco Selig committed
914
915
916
            Parameters
            ----------
            bare : bool, *optional*
917
918
                Whether the returned diagonal entries are `bare` or not
                (default: True).
Marco Selig's avatar
Marco Selig committed
919
            domain : space, *optional*
920
                Space wherein the probes live (default: self.domain).
Marco Selig's avatar
Marco Selig committed
921
            target : space, *optional*
922
                Space wherein the transform of the probes live (default: None).
Marco Selig's avatar
Marco Selig committed
923
            random : string, *optional*
924
925
926
927
928
929
930
931
932
933
934
                Specifies the pseudo random number generator (default: "pm1");
                supported distributions are:

                - "pm1" (uniform distribution over {+1,-1} or {+1,+i,-1,-i}
                - "gau" (normal distribution with zero-mean and a given standard deviation or variance)

            ncpu : integer, *optional*
                Number of used CPUs to use (default: 2).
            nrun : integer, *optional*
                Total number of probes (default: 8).
            nper : integer, *optional*
Marco Selig's avatar
Marco Selig committed
935
                Number of tasks performed by one worker (default: 1).
Marco Selig's avatar
Marco Selig committed
936
            var : bool, *optional*
937
938
                Whether to additionally return the probing variance or not
                (default: False).
Marco Selig's avatar
Marco Selig committed
939
            save : bool, *optional*
940
941
                Whether all individual probing results are saved or not
                (default: False).
Marco Selig's avatar
Marco Selig committed
942
            path : string, *optional*
943
                Path wherein the results are saved (default: "tmp").
Marco Selig's avatar
Marco Selig committed
944
            prefix : string, *optional*
945
                Prefix for all saved files (default: "")
Marco Selig's avatar
Marco Selig committed
946
            loop : bool, *optional*
947
                Whether to perform a loop or to parallelise (default: False).
Marco Selig's avatar
Marco Selig committed
948
949
950
951

            Returns
            -------
            diag : ndarray
952
                Diagonal of the inverse operator.
Marco Selig's avatar
Marco Selig committed
953
            delta : float, *optional*
954
955
                Probing variance of the trace; returned if `var` is ``True`` in
                case of probing.
Marco Selig's avatar
Marco Selig committed
956
957
958
959
960
961
962
963
964
965
966
967

            Notes
            -----
            The ambiguity of `bare` or non-bare diagonal entries is based
            on the choice of a matrix representation of the operator in
            question. The naive choice of absorbing the volume weights
            into the matrix leads to a matrix-vector calculus with the
            non-bare entries which seems intuitive, though. The choice of
            keeping matrix entries and volume weights separate deals with the
            bare entries that allow for correct interpretation of the matrix
            entries; e.g., as variance in case of an covariance operator.

968
969
970
971
972
973
974
975
976
            See Also
            --------
            diagonal_probing

            Raises
            ------
            ValueError
                If it is no square matrix.

Marco Selig's avatar
Marco Selig committed
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
        """
        if(self.val.shape[0]!=self.val.shape[1]):
            raise ValueError(about._errors.cstring("ERROR: inverse ill-defined for "+str(self.val.shape[0])+" x "+str(self.val.shape[1])+" matrices."))
        if(self.domain!=self.target)and(not bare):
            about.warnings.cprint("WARNING: ambiguous non-bare diagonal.")

        if(domain is None)or(domain==self.target):
            self._set_inverse()
            diag = np.diagonal(self._inv,offset=0,axis1=0,axis2=1)
            ## weight if ...
            if(not self.target.discrete)and(not bare):
                diag = self.target.calc_weight(diag,power=1)
                ## check complexity
                if(np.all(np.imag(diag)==0)):
                    diag = np.real(diag)
            return diag
        elif(domain==self.domain):
            self._set_inverse()
            diag = np.diagonal(np.conjugate(self._inv.T),offset=0,axis1=0,axis2=1)
            ## weight if ...
            if(not self.domain.discrete)and(not bare):
                diag = self.domain.calc_weight(diag,power=1)
                ## check complexity
                if(np.all(np.imag(diag)==0)):
                    diag = np.real(diag)
            return diag
        else:
            return super(explicit_operator,self).inverse_diag(bare=bare,domain=domain,**kwargs) ## probing

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def det(self):
        """
1010
1011
1012
1013
1014
            Computes the determinant of the operator.

            Parameters
            ----------
            None
Marco Selig's avatar
Marco Selig committed
1015
1016
1017
1018

            Returns
            -------
            det : float
1019
1020
1021
1022
1023
1024
                Determinant of the operator.

            Raises
            ------
            ValueError
                If `domain` and `target` are unequal.
Marco Selig's avatar
Marco Selig committed
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035

        """
        if(self.domain!=self.target):
            raise ValueError(about._errors.cstring("ERROR: determinant ill-defined."))

        if(np.any(self._hidden)):
            about.warnings.cprint("WARNING: inappropriate determinant calculation.")
        return np.linalg.det(self.weight(rowpower=0.5,colpower=0.5,overwrite=False))

    def inverse_det(self):
        """
1036
1037
1038
1039
1040
            Computes the determinant of the inverse operator.

            Parameters
            ----------
            None
Marco Selig's avatar
Marco Selig committed
1041
1042
1043
1044

            Returns
            -------
            det : float
1045
1046
1047
1048
1049
1050
                Determinant of the inverse operator.

            Raises
            ------
            ValueError
                If it is a singular matrix.
Marco Selig's avatar
Marco Selig committed
1051
1052
1053
1054
1055
1056
1057
1058
1059

        """
        det = self.det()
        if(det<>0):
            return 1/det
        else:
            raise ValueError(about._errors.cstring("ERROR: singular matrix."))

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Marco Selig's avatar
Marco Selig committed
1060

Marco Selig's avatar
Marco Selig committed
1061
1062
    def __len__(self):
        return int(self.nrow()[0])
Marco Selig's avatar
Marco Selig committed
1063

Marco Selig's avatar
Marco Selig committed
1064
1065
    def __getitem__(self,key):
        return self.val[key]
Marco Selig's avatar
Marco Selig committed
1066

Marco Selig's avatar
Marco Selig committed
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
    def __setitem__(self,key,value):
        self.val[key] = self.val.dtype(value)

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def __pos__(self):
        return explicit_operator(self.domain,self.val,bare=True,sym=self.sym,uni=self.uni,target=self.target)

    def __neg__(self):
        return explicit_operator(self.domain,-self.val,bare=True,sym=self.sym,uni=self.uni,target=self.target)

    def __abs__(self):
        return explicit_operator(self.domain,np.absolute(self.val),bare=True,sym=self.sym,uni=self.uni,target=self.target)

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def transpose(self):
        """
            Computes the transposed matrix.

            Returns
            -------
            T : explicit_operator
                The transposed matrix.

        """
        return explicit_operator(self.domain,self.val.T,bare=True,sym=self.sym,uni=self.uni,target=self.target)

    def conjugate(self):
        """
            Computes the complex conjugated matrix.

            Returns
            -------
            CC : explicit_operator
                The complex conjugated matrix.

        """
        return explicit_operator(self.domain,np.conjugate(self.val),bare=True,sym=self.sym,uni=self.uni,target=self.target)

    def adjoint(self):
        """
            Computes the adjoint matrix.

            Returns
            -------
            A : explicit_operator
                The adjoint matrix.

        """
        return explicit_operator(self.target,np.conjugate(self.val.T),bare=True,sym=self.sym,uni=self.uni,target=self.domain)

    def inverse(self):
        """
            Computes the inverted matrix.

            Returns
            -------
            I : explicit_operator
                The inverted matrix.

1128
1129
1130
1131
1132
            Raises
            ------
            ValueError
                If it is no square matrix.

Marco Selig's avatar
Marco Selig committed
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
        """
        ## check whether square matrix
        if(self.nrow()!=self.ncol()):
            raise ValueError(about._errors.cstring("ERROR: inverse ill-defined for "+str(self.nrow())+" x "+str(self.ncol())+" matrices."))
        self._set_inverse()
        return explicit_operator(self.target,self._inv,bare=True,sym=self.sym,uni=self.uni,target=self.domain)

    def adjoint_inverse(self):
        """
            Computes the adjoint inverted matrix.

            Returns
            -------
            AI : explicit_operator
                The adjoint inverted matrix.

1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
            Notes
            -----
            For linear operators represented by square matrices, inversion and
            adjungation and inversion commute.

            Raises
            ------
            ValueError
                If it is no square matrix.

Marco Selig's avatar
Marco Selig committed
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
        """
        return self.inverse_adjoint()

    def inverse_adjoint(self):
        """
            Computes the inverted adjoint matrix.

            Returns
            -------
            IA : explicit_operator
                The inverted adjoint matrix.

1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
            Notes
            -----
            For linear operators represented by square matrices, inversion and
            adjungation and inversion commute.

            Raises
            ------
            ValueError
                If it is no square matrix.

Marco Selig's avatar
Marco Selig committed
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
        """
        ## check whether square matrix
        if(self.nrow()!=self.ncol()):
            raise ValueError(about._errors.cstring("ERROR: inverse ill-defined for "+str(self.nrow())+" x "+str(self.ncol())+" matrices."))
        self._set_inverse()
        return explicit_operator(self.target,np.conjugate(self._inv.T),bare=True,sym=self.sym,uni=self.uni,target=self.domain)

    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    def __add__(self,X): ## __add__ : self + X
        if(isinstance(X,operator)):
            if(self.domain!=X.domain):
                raise ValueError(about._errors.cstring("ERROR: inequal domains."))
            sym = (self.sym and X.sym)
            uni = None
            if(isinstance(X,explicit_operator)):
                if(self.target!=X.target):
                    raise ValueError(about._errors.cstring("ERROR: inequal codomains."))
                matrix = self.val+X.val
            elif(isinstance(X,diagonal_operator)):
                if(self.target.dim(split=False)!=X.target.dim(split=False))or(not self.target.check_codomain(X.target)):
                    raise ValueError(about._errors.cstring("ERROR: incompatible codomains."))
                matrix = self.val+np.diag(X.diag(bare=True,domain=None),k=0) ## domain == X.domain
            elif(isinstance(X,vecvec_operator)):
                if(self.target!=X.target):
                    raise ValueError(about._errors.cstring("ERROR: inequal codomains."))
                matrix = self.val+np.tensordot(X.val,X.val,axes=0)
            else:
                raise TypeError(about._errors.cstring("ERROR: unsupported or incompatible operator."))
        elif(np.size(X)==1):
            if(self.nrow()!=self.ncol()):
                raise ValueError(about._errors.cstring("ERROR: identity ill-defined for "+str(self.nrow())+" x "+str(self.ncol())+" matrices."))
            sym = self.sym
            uni = None
1215
1216
            X = X*np.ones(self.domain.dim(split=False),dtype=np.int,order='C')
            X = self.domain.calc_weight(X,power=-1).astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype)))
Marco Selig's avatar
Marco Selig committed
1217
1218
1219
1220
1221
1222
            matrix = self.val+np.diag(X,k=0)
        elif(np.size(X)==np.size(self.val)):
            sym = None
            uni = None
            X = np.array(X).reshape(self.val.shape)
            if(np.all(np.isreal(X))):
1223
1224
                X = np.real(X)
            X = X.astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype)))
Marco Selig's avatar
Marco Selig committed
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
            matrix = self.val+X
        else:
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(X))+" <> "+str(self.nrow())+" x "+str(self.ncol())+" )."))
        return explicit_operator(self.domain,matrix,bare=True,sym=sym,uni=uni,target=self.target)

    __radd__ = __add__  ## __add__ : X + self

    def __iadd__(self,X): ## __iadd__ : self += X
        if(isinstance(X,operator)):
            if(self.domain!=X.domain):
                raise ValueError(about._errors.cstring("ERROR: inequal domains."))
            self.sym = (self.sym and X.sym)
            self.uni = None
            if(isinstance(X,explicit_operator)):
                if(self.target!=X.target):
                    raise ValueError(about._errors.cstring("ERROR: inequal codomains."))
1241
                X = X.val
Marco Selig's avatar
Marco Selig committed
1242
1243
1244
            elif(isinstance(X,diagonal_operator)):
                if(self.target.dim(split=False)!=X.target.dim(split=False))or(not self.target.check_codomain(X.target)):
                    raise ValueError(about._errors.cstring("ERROR: incompatible codomains."))
1245
                X = np.diag(X.diag(bare=True,domain=None),k=0) ## domain == X.domain
Marco Selig's avatar
Marco Selig committed
1246
1247
1248
            elif(isinstance(X,vecvec_operator)):
                if(self.target!=X.target):
                    raise ValueError(about._errors.cstring("ERROR: inequal codomains."))
1249
                X = np.tensordot(X.val,X.val,axes=0)
Marco Selig's avatar
Marco Selig committed
1250
1251
1252
1253
1254
1255
            else:
                raise TypeError(about._errors.cstring("ERROR: unsupported or incompatible operator."))
        elif(np.size(X)==1):
            if(self.nrow()!=self.ncol()):
                raise ValueError(about._errors.cstring("ERROR: identity ill-defined for "+str(self.nrow())+" x "+str(self.ncol())+" matrices."))
            self.uni = None
1256
            X = X*np.ones(self.domain.dim(split=False),dtype=np.int,order='C')
1257
            X = np.diag(self.domain.calc_weight(X,power=-1).astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype))),k=0)
Marco Selig's avatar
Marco Selig committed
1258
1259
1260
1261
1262
        elif(np.size(X)==np.size(self.val)):
            self.sym = None
            self.uni = None
            X = np.array(X).reshape(self.val.shape)
            if(np.all(np.isreal(X))):
1263
1264
                X = np.real(X)
            X = X.astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype)))
Marco Selig's avatar
Marco Selig committed
1265
1266
1267
        else:
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(X))+" <> "+str(self.nrow())+" x "+str(self.ncol())+" )."))

1268
1269
1270
1271
1272
        ## add
        if(X.dtype>self.val.dtype):
            about.warnings.cprint("WARNING: datatype reset.")
        self.val += X

Marco Selig's avatar
Marco Selig committed
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
        ## check flags
        self.sym,self.uni = self._check_flags(sym=self.sym,uni=self.uni)

        self._inv = None ## reset

        return self

    def __sub__(self,X): ## __sub__ : self - X
        if(isinstance(X,operator)):
            if(self.domain!=X.domain):
                raise ValueError(about._errors.cstring("ERROR: inequal domains."))
            sym = (self.sym and X.sym)
            uni = None
            if(isinstance(X,explicit_operator)):
                if(self.target!=X.target):
                    raise ValueError(about._errors.cstring("ERROR: inequal codomains."))
                matrix = self.val-X.val
            elif(isinstance(X,diagonal_operator)):
                if(self.target.dim(split=False)!=X.target.dim(split=False))or(not self.target.check_codomain(X.target)):
                    raise ValueError(about._errors.cstring("ERROR: incompatible codomains."))
                matrix = self.val-np.diag(X.diag(bare=True,domain=None),k=0) ## domain == X.domain
            elif(isinstance(X,vecvec_operator)):
                if(self.target!=X.target):
                    raise ValueError(about._errors.cstring("ERROR: inequal codomains."))
                matrix = self.val-np.tensordot(X.val,X.val,axes=0)
            else:
                raise TypeError(about._errors.cstring("ERROR: unsupported or incompatible operator."))
        elif(np.size(X)==1):
            if(self.nrow()!=self.ncol()):
                raise ValueError(about._errors.cstring("ERROR: identity ill-defined for "+str(self.nrow())+" x "+str(self.ncol())+" matrices."))
            sym = self.sym
            uni = None
1305
1306
            X = X*np.ones(self.domain.dim(split=False),dtype=np.int,order='C')
            X = self.domain.calc_weight(X,power=-1).astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype)))
Marco Selig's avatar
Marco Selig committed
1307
1308
1309
1310
1311
1312
            matrix = self.val-np.diag(X,k=0)
        elif(np.size(X)==np.size(self.val)):
            sym = None
            uni = None
            X = np.array(X).reshape(self.val.shape)
            if(np.all(np.isreal(X))):
1313
1314
                X = np.real(X)
            X = X.astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype)))
Marco Selig's avatar
Marco Selig committed
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
            matrix = self.val-X
        else:
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(X))+" <> "+str(self.nrow())+" x "+str(self.ncol())+" )."))
        return explicit_operator(self.domain,matrix,bare=True,sym=sym,uni=uni,target=self.target)

    def __rsub__(self,X): ## __rsub__ : X - self
        if(isinstance(X,operator)):
            if(self.domain!=X.domain):
                raise ValueError(about._errors.cstring("ERROR: inequal domains."))
            sym = (self.sym and X.sym)
            uni = None
            if(isinstance(X,explicit_operator)):
                if(self.target!=X.target):
                    raise ValueError(about._errors.cstring("ERROR: inequal codomains."))
                matrix = X.val-self.val
            elif(isinstance(X,diagonal_operator)):
                if(self.target.dim(split=False)!=X.target.dim(split=False))or(not self.target.check_codomain(X.target)):
                    raise ValueError(about._errors.cstring("ERROR: incompatible codomains."))
                matrix = np.diag(X.diag(bare=True,domain=None),k=0)-self.val ## domain == X.domain
            elif(isinstance(X,vecvec_operator)):
                if(self.target!=X.target):
                    raise ValueError(about._errors.cstring("ERROR: inequal codomains."))
                matrix = np.tensordot(X.val,X.val,axes=0)-self.val
            else:
                raise TypeError(about._errors.cstring("ERROR: unsupported or incompatible operator."))
        elif(np.size(X)==1):
            if(self.nrow()!=self.ncol()):
                raise ValueError(about._errors.cstring("ERROR: identity ill-defined for "+str(self.nrow())+" x "+str(self.ncol())+" matrices."))
            sym = self.sym
            uni = None
1345
1346
            X = X*np.ones(self.domain.dim(split=False),dtype=np.int,order='C')
            X = self.domain.calc_weight(X,power=-1).astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype)))
Marco Selig's avatar
Marco Selig committed
1347
1348
1349
1350
1351
1352
            matrix = np.diag(X,k=0)-self.val
        elif(np.size(X)==np.size(self.val)):
            sym = None
            uni = None
            X = np.array(X).reshape(self.val.shape)
            if(np.all(np.isreal(X))):
1353
1354
                X = np.real(X)
            X = X.astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype)))
Marco Selig's avatar
Marco Selig committed
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
            matrix = X-self.val
        else:
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(X))+" <> "+str(self.nrow())+" x "+str(self.ncol())+" )."))
        return explicit_operator(self.domain,matrix,bare=True,sym=sym,uni=uni,target=self.target)

    def __isub__(self,X): ## __isub__ : self -= X
        if(isinstance(X,operator)):
            if(self.domain!=X.domain):
                raise ValueError(about._errors.cstring("ERROR: inequal domains."))
            self.sym = (self.sym and X.sym)
            self.uni = None
            if(isinstance(X,explicit_operator)):
                if(self.target!=X.target):
                    raise ValueError(about._errors.cstring("ERROR: inequal codomains."))
1369
                X = X.val
Marco Selig's avatar
Marco Selig committed
1370
1371
1372
            elif(isinstance(X,diagonal_operator)):
                if(self.target.dim(split=False)!=X.target.dim(split=False))or(not self.target.check_codomain(X.target)):
                    raise ValueError(about._errors.cstring("ERROR: incompatible codomains."))
1373
                X = np.diag(X.diag(bare=True,domain=None),k=0) ## domain == X.domain
Marco Selig's avatar
Marco Selig committed
1374
1375
1376
            elif(isinstance(X,vecvec_operator)):
                if(self.target!=X.target):
                    raise ValueError(about._errors.cstring("ERROR: inequal codomains."))
1377
                X = np.tensordot(X.val,X.val,axes=0)
Marco Selig's avatar
Marco Selig committed
1378
1379
1380
1381
1382
1383
            else:
                raise TypeError(about._errors.cstring("ERROR: unsupported or incompatible operator."))
        elif(np.size(X)==1):
            if(self.nrow()!=self.ncol()):
                raise ValueError(about._errors.cstring("ERROR: identity ill-defined for "+str(self.nrow())+" x "+str(self.ncol())+" matrices."))
            self.uni = None
1384
            X = X*np.ones(self.domain.dim(split=False),dtype=np.int,order='C')
1385
            X = np.diag(self.domain.calc_weight(X,power=-1).astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype))),k=0)
Marco Selig's avatar
Marco Selig committed
1386
1387
1388
1389
1390
        elif(np.size(X)==np.size(self.val)):
            self.sym = None
            self.uni = None
            X = np.array(X).reshape(self.val.shape)
            if(np.all(np.isreal(X))):
1391
1392
                X = np.real(X)
            X = X.astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype)))
Marco Selig's avatar
Marco Selig committed
1393
1394
1395
        else:
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(X))+" <> "+str(self.nrow())+" x "+str(self.ncol())+" )."))

1396
1397
1398
1399
1400
        ## subtract
        if(X.dtype>self.val.dtype):
            about.warnings.cprint("WARNING: datatype reset.")
        self.val -= X

Marco Selig's avatar
Marco Selig committed
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
        ## check flags
        self.sym,self.uni = self._check_flags(sym=self.sym,uni=self.uni)

        self._inv = None ## reset

        return self

    def _calc_mul(self,X,side): ## > multiplies self with X ...
        if(side==0): ## ... from right
            if(self._hidden[0]): ## hidden degrees of freedom
                return np.array([np.apply_along_axis(self.domain.calc_dot,0,X,np.conjugate(rr)) for rr in self.weight(rowpower=1,colpower=0,overwrite=False)])
            else:
                return np.dot(self.weight(rowpower=1,colpower=0,overwrite=False),X,out=None)
        elif(side==1): ## ... from left
            if(self._hidden[1]): ## hidden degrees of freedom
                return np.array([np.apply_along_axis(self.target.calc_dot,0,self.weight(rowpower=0,colpower=1,overwrite=False),np.conjugate(rr)) for rr in X])
            else:
                return np.dot(X,self.weight(rowpower=0,colpower=1,overwrite=False),out=None)
        else:
            raise ValueError(about._errors.cstring("ERROR: invalid input."))

    def __mul__(self,X): ## __mul__ : self * X
        if(isinstance(X,operator)):
            if(self.domain!=X.target):
                raise ValueError(about._errors.cstring("ERROR: incompatible spaces."))
            newdomain = X.domain
            sym = None
            uni = (self.uni and X.uni)
            if(isinstance(X,explicit_operator)):
                X = X.val
            elif(isinstance(X,diagonal_operator)):
                X = np.diag(X.diag(bare=True,domain=None),k=0) ## domain == X.domain
            elif(isinstance(X,vecvec_operator)):
                X = np.tensordot(X.val,X.val,axes=0)
            else:
                raise TypeError(about._errors.cstring("ERROR: unsupported or incompatible operator."))
        elif(np.size(X)==1):
            newdomain = self.domain
            sym = None
            uni = None
1441
1442
            X = X*np.ones(self.domain.dim(split=False),dtype=np.int,order='C')
            X = np.diag(self.domain.calc_weight(X,power=-1).astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype))),k=0)
Marco Selig's avatar
Marco Selig committed
1443
1444
1445
1446
1447
1448
        elif(np.size(X)==self.val.shape[1]**2):
            newdomain = self.domain
            sym = None
            uni = None
            X = np.array(X).reshape((self.val.shape[1],self.val.shape[1]))
            if(np.all(np.isreal(X))):
1449
1450
                X = np.real(X)
            X = X.astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype)))
Marco Selig's avatar
Marco Selig committed
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
        else:
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(X))+" <> "+str(self.nrow())+" x "+str(self.nrow())+" )."))
        return explicit_operator(newdomain,self._calc_mul(X,0),bare=True,sym=sym,uni=uni,target=self.target)

    def __rmul__(self,X): ## __mul__ : X * self
        if(isinstance(X,operator)):
            if(X.domain!=self.target):
                raise ValueError(about._errors.cstring("ERROR: incompatible spaces."))
            newtarget = X.target
            sym = None
            uni = (self.uni and X.uni)
            if(isinstance(X,explicit_operator)):
                X = X.val
            elif(isinstance(X,diagonal_operator)):
                X = np.diag(X.diag(bare=True,domain=None),k=0) ## domain == X.domain
            elif(isinstance(X,vecvec_operator)):
                X = np.tensordot(X.val,X.val,axes=0)
            else:
                raise TypeError(about._errors.cstring("ERROR: unsupported or incompatible operator."))
        elif(np.size(X)==1):
            newtarget = self.target
            sym = None
            uni = None
1474
1475
            X = X*np.ones(self.domain.dim(split=False),dtype=np.int,order='C')
            X = np.diag(self.domain.calc_weight(X,power=-1).astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype))),k=0)
Marco Selig's avatar
Marco Selig committed
1476
1477
1478
1479
1480
1481
        elif(np.size(X)==self.val.shape[0]**2):
            newtarget = self.target
            sym = None
            uni = None
            X = np.array(X).reshape((self.val.shape[0],self.val.shape[0]))
            if(np.all(np.isreal(X))):
1482
1483
                X = np.real(X)
            X = X.astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype)))
Marco Selig's avatar
Marco Selig committed
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
        else:
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(X))+" <> "+str(self.ncol())+" x "+str(self.ncol())+" )."))
        return explicit_operator(self.domain,self._calc_mul(X,1),bare=True,sym=sym,uni=uni,target=newtarget)

    def __imul__(self,X): ## __imul__ : self *= X
        if(isinstance(X,operator)):
            if(self.domain!=X.target):
                raise ValueError(about._errors.cstring("ERROR: incompatible spaces."))
            if(self.domain!=X.domain):
                raise ValueError(about._errors.cstring("ERROR: incompatible operator."))
            self.sym = None
            self.uni = (self.uni and X.uni)
            if(isinstance(X,explicit_operator)):
                X = X.val
            elif(isinstance(X,diagonal_operator)):
                X = np.diag(X.diag(bare=True,domain=None),k=0) ## domain == X.domain
            elif(isinstance(X,vecvec_operator)):
                X = np.tensordot(X.val,X.val,axes=0)
            else:
                raise TypeError(about._errors.cstring("ERROR: unsupported or incompatible operator."))
        elif(np.size(X)==1):
            self.sym = None
            self.uni = None
1507
1508
            X = X*np.ones(self.domain.dim(split=False),dtype=np.int,order='C')
            X = np.diag(self.domain.calc_weight(X,power=-1).astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype))),k=0)
Marco Selig's avatar
Marco Selig committed
1509
1510
1511
1512
1513
        elif(np.size(X)==self.val.shape[1]**2):
            self.sym = None
            self.uni = None
            X = np.array(X).reshape((self.val.shape[1],self.val.shape[1]))
            if(np.all(np.isreal(X))):
1514
1515
                X = np.real(X)
            X = X.astype(max(min(X.dtype,self.domain.datatype),min(X.dtype,self.target.datatype)))
Marco Selig's avatar
Marco Selig committed
1516
1517
1518
1519
        else:
            raise ValueError(about._errors.cstring("ERROR: dimension mismatch ( "+str(np.size(X))+" <> "+str(self.nrow())+" x "+str(self.nrow())+" )."))

        ## multiply
1520
1521
        if(X.dtype>self.val.dtype):
            about.warnings.cprint("WARNING: datatype reset.")
Marco Selig's avatar
Marco Selig committed
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550