forked from information-field-theory/nifty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nifty_explicit.py
2376 lines (2053 loc) · 96.6 KB
/
nifty_explicit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
195
196
197
198
199
200
201
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
609
610
611
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
646
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## 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/>.
"""
.. __ ____ __
.. /__/ / _/ / /_
.. __ ___ __ / /_ / _/ __ __
.. / _ | / / / _/ / / / / / /
.. / / / / / / / / / /_ / /_/ /
.. /__/ /__/ /__/ /__/ \___/ \___ / explicit
.. /______/
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.
"""
from __future__ import division
#from nifty_core import *
from sys import stdout as so
import numpy as np
import pylab as pl
from matplotlib.colors import LogNorm as ln
from matplotlib.ticker import LogFormatter as lf
from multiprocessing import Pool as mp
from multiprocessing import Value as mv
from multiprocessing import Array as ma
from nifty_core import about, \
space, \
field, \
operator,diagonal_operator,identity,vecvec_operator, \
probing
##-----------------------------------------------------------------------------
class explicit_operator(operator):
"""
..
..
.. __ __ __ __
.. / / /__/ /__/ / /_
.. _______ __ __ ______ / / __ _______ __ / _/
.. / __ / \ \/ / / _ | / / / / / ____/ / / / /
.. / /____/ / / / /_/ / / /_ / / / /____ / / / /_
.. \______/ /__/\__\ / ____/ \___/ /__/ \______/ /__/ \___/ operator class
.. /__/
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.
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
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.
"""
epsilon = 1E-12 ## absolute precision for comparisons to identity
def __init__(self,domain,matrix=None,bare=True,sym=None,uni=None,target=None):
"""
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.
"""
## check domain
if(not isinstance(domain,space)):
raise TypeError(about._errors.cstring("ERROR: invalid input."))
self.domain = domain
## 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))+" )."))
# if(val.size>1048576):
# about.infos.cprint("INFO: matrix size > 2 ** 20.")
self.target = target
## 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:
val = self._calc_weight_rows(val,power=-int(not bare[0]))
val = self._calc_weight_cols(val,power=-int(not bare[1]))
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.")
## check flags
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]):
if(sym is None):
adj = np.conjugate(self.val.T)
sym = np.all(np.absolute(self.val-adj)<self.epsilon)
if(uni is None):
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)
elif(uni is None):
adj = np.conjugate(self.val.T)
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)
return bool(sym),bool(uni)
else:
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))
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def cast_domain(self,newdomain):
"""
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.
"""
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):
"""
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.
"""
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
def cast_spaces(self,newdomain=None,newtarget=None):
"""
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
"""
if(newdomain is not None):
self.cast_domain(newdomain)
if(newtarget is not None):
self.cast_target(newtarget)
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def set_matrix(self,newmatrix,bare=True,sym=None,uni=None):
"""
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.
"""
## 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(newmatrix,axis=None))+" <> "+str(self.nrow())+" x "+str(self.ncol())+" )."))
## 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:
val = self._calc_weight_rows(val,power=-int(not bare[0]))
val = self._calc_weight_cols(val,power=-int(not bare[1]))
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 flags
self.sym,self.uni = self._check_flags(sym=sym,uni=uni)
self._inv = None ## reset
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def get_matrix(self,bare=True):
"""
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.
"""
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:
return self.weight(rowpower=int(not bare[0]),colpower=int(not bare[1]),overwrite=False)
elif(not bare):
return self.weight(rowpower=int(not bare),colpower=0,overwrite=False)
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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
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)
def _calc_weight_cols(self,X,power=1): ## > weight all columns
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)
def weight(self,rowpower=0,colpower=0,overwrite=False):
"""
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.
"""
if(overwrite):
if(not self.domain.discrete)and(rowpower): ## rowpower <> 0
self.val = self._calc_weight_rows(self.val,rowpower)
if(not self.target.discrete)and(colpower): ## colpower <> 0
self.val = self._calc_weight_cols(self.val,colpower)
else:
X = np.copy(self.val)
if(not self.domain.discrete)and(rowpower): ## rowpower <> 0
X = self._calc_weight_rows(X,rowpower)
if(not self.target.discrete)and(colpower): ## colpower <> 0
X = self._calc_weight_cols(X,colpower)
return X
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def _multiply(self,x,**kwargs): ## > applies the matirx to a given field
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)
return x_
def _adjoint_multiply(self,x,**kwargs): ## > applies the adjoint operator to a given field
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)
return x_
def _inverse_multiply(self,x,**kwargs): ## > applies the inverse operator to a given field
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)
return x_
def _inverse_adjoint_multiply(self,x,**kwargs): ## > applies the adjoint inverse operator to a given field
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)
return x_
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def _briefing(self,x,domain,inverse): ## > prepares x for `multiply`
## inspect x
if(not isinstance(x,field)):
x_ = field(domain,val=x,target=None)
else:
## check x.domain
if(domain==x.domain):
x_ = x
## transform
else:
x_ = x.transform(target=domain,overwrite=False)
## weight if ...
if(not self.imp)and(not domain.discrete):
x_ = x_.weight(power=1,overwrite=False)
return x_
def _debriefing(self,x,x_,target,inverse): ## > evaluates x and x_ after `multiply`
if(x_ is None):
return None
else:
## inspect x_
if(not isinstance(x_,field)):
x_ = field(target,val=x_,target=None)
elif(x_.domain!=target):
raise ValueError(about._errors.cstring("ERROR: invalid output domain."))
## inspect x
if(isinstance(x,field)):
## repair ...
if(self.domain==self.target!=x.domain):
x_ = x_.transform(target=x.domain,overwrite=False) ## ... domain
if(x_.domain==x.domain)and(x_.target!=x.target):
x_.set_target(newtarget=x.target) ## ... codomain
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()):
raise ValueError(about._errors.cstring("ERROR: inverse ill-defined for "+str(self.nrow())+" x "+str(self.ncol())+" matrices."))
self._set_inverse()
## 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.
"""
return self.inverse_adjoint_times(x,**kwargs)
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()):
raise ValueError(about._errors.cstring("ERROR: inverse ill-defined for "+str(self.nrow())+" x "+str(self.ncol())+" matrices."))
## check whether self-adjoint
if(self.sym):
return self._inverse_times(x,**kwargs)
## check whether unitary
if(self.uni):
return self.times(x,**kwargs)
self._set_inverse()
## 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)
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def tr(self,domain=None,**kwargs):
"""
Computes the trace of the operator.
Parameters
----------
domain : space, *optional*
Space wherein the probes live (default: self.domain).
target : space, *optional*
Space wherein the transform of the probes live (default: None).
random : string, *optional*
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*
Number of tasks performed by one worker (default: 1).
var : bool, *optional*
Whether to additionally return the probing variance or not
(default: False).
loop : bool, *optional*
Whether to perform a loop or to parallelise (default: False).
Returns
-------
tr : float
Trace of the operator.
delta : float, *optional*
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.
"""
if(self.domain!=self.target):
raise ValueError(about._errors.cstring("ERROR: trace ill-defined."))
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*
Space wherein the probes live (default: self.domain).
target : space, *optional*
Space wherein the transform of the probes live (default: None).
random : string, *optional*
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*
Number of tasks performed by one worker (default: 1).
var : bool, *optional*
Whether to additionally return the probing variance or not
(default: False).
loop : bool, *optional*
Whether to perform a loop or to parallelise (default: False).
Returns
-------
tr : float
Trace of the operator.
delta : float, *optional*
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.
"""
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*
Whether the returned diagonal entries are `bare` or not
(default: True).
domain : space, *optional*
Space wherein the probes live (default: self.domain).
target : space, *optional*
Space wherein the transform of the probes live (default: None).
random : string, *optional*
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*
Number of tasks performed by one worker (default: 1).
var : bool, *optional*
Whether to additionally return the probing variance or not
(default: False).
save : bool, *optional*
Whether all individual probing results are saved or not
(default: False).
path : string, *optional*
Path wherein the results are saved (default: "tmp").
prefix : string, *optional*
Prefix for all saved files (default: "")
loop : bool, *optional*
Whether to perform a loop or to parallelise (default: False).
Returns
-------
diag : ndarray
Diagonal of the operator.
delta : float, *optional*
Probing variance of the trace; returned if `var` is ``True`` in
case of probing.
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.
See Also
--------
diagonal_probing
Raises
------
ValueError
If it is no square matrix.
"""
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.
Parameters
----------
bare : bool, *optional*
Whether the returned diagonal entries are `bare` or not
(default: True).
domain : space, *optional*
Space wherein the probes live (default: self.domain).
target : space, *optional*
Space wherein the transform of the probes live (default: None).
random : string, *optional*
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*
Number of tasks performed by one worker (default: 1).
var : bool, *optional*
Whether to additionally return the probing variance or not
(default: False).
save : bool, *optional*
Whether all individual probing results are saved or not
(default: False).
path : string, *optional*
Path wherein the results are saved (default: "tmp").
prefix : string, *optional*
Prefix for all saved files (default: "")
loop : bool, *optional*
Whether to perform a loop or to parallelise (default: False).
Returns
-------
diag : ndarray
Diagonal of the inverse operator.