nifty_probing.py 22.4 KB
Newer Older
Ultimanet's avatar
Ultimanet committed
1
2
3
4
5
## NIFTY (Numerical Information Field Theory) has been developed at the
## Max-Planck-Institute for Astrophysics.
##
## Copyright (C) 2015 Max-Planck-Society
##
Ultima's avatar
Ultima committed
6
## Author: Theo Steininger
Ultimanet's avatar
Ultimanet committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
## 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/>.

from __future__ import division

from nifty.nifty_about import about
from nifty.nifty_core import space, \
                         field 
Ultima's avatar
Ultima committed
27
from nifty.nifty_utilities import direct_dot
Ultimanet's avatar
Ultimanet committed
28
29
30
31


##=============================================================================

Ultima's avatar
Ultima committed
32
class prober(object):
Ultimanet's avatar
Ultimanet committed
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
    """
        ..                                    __        __
        ..                                  /  /      /__/
        ..      ______    _____   ______   /  /___    __   __ ___    ____ __
        ..    /   _   | /   __/ /   _   | /   _   | /  / /   _   | /   _   /
        ..   /  /_/  / /  /    /  /_/  / /  /_/  / /  / /  / /  / /  /_/  /
        ..  /   ____/ /__/     \______/  \______/ /__/ /__/ /__/  \____  /  class
        .. /__/                                                  /______/

        NIFTY class for probing (using multiprocessing)

        This is the base NIFTY probing class from which other probing classes
        (e.g. diagonal probing) are derived.

        When called, a probing class instance evaluates an operator or a
        function using random fields, whose components are random variables
        with mean 0 and variance 1. When an instance is called it returns the
        mean value of f(probe), where probe is a random field with mean 0 and
        variance 1. The mean is calculated as 1/N Sum[ f(probe_i) ].

        Parameters
        ----------
        op : operator
            The operator specified by `op` is the operator to be probed.
            If no operator is given, then probing will be done by applying
            `function` to the probes. (default: None)
        function : function, *optional*
            If no operator has been specified as `op`, then specification of
            `function` is non optional. This is the function, that is applied
            to the probes. (default: `op.times`)
        domain : space, *optional*
            If no operator has been specified as `op`, then specification of
            `domain` is non optional. This is the space that the probes live
            in. (default: `op.domain`)
        target : domain, *optional*
            `target` is the codomain of `domain`
            (default: `op.domain.get_codomain()`)
        random : string, *optional*
            the distribution from which the probes are drawn. `random` can be
            either "pm1" or "gau". "pm1" is a uniform distribution over {+1,-1}
            or {+1,+i,-1,-i}, respectively. "gau" is a normal distribution with
            zero-mean and unit-variance (default: "pm1")
        ncpu : int, *optional*
            the number of cpus to be used from parallel probing. (default: 2)
        nrun : int, *optional*
            the number of probes to be evaluated. If `nrun<ncpu`, it will be
            set to `ncpu`. (default: 8)
        nper : int, *optional*
            this number specifies how many probes will be evaluated by one
            worker. Afterwards a new worker will be created to evaluate a chunk
            of `nper` probes.
            If for example `nper=nrun/ncpu`, then every worker will be created
            for every cpu. This can lead to the case, that all workers but one
            are already finished, but have to wait for the last worker that
            might still have a considerable amount of evaluations left. This is
            obviously not very effective.
            If on the other hand `nper=1`, then for each evaluation a worker will
            be created. In this case all cpus will work until nrun probes have
            been evaluated.
            It is recommended to leave `nper` as the default value. (default: 1)
        var : bool, *optional*
            If `var` is True, then the variance of the sampled function will
            also be returned. The result is then a tuple with the mean in the
            zeroth entry and the variance in the first entry. (default: False)


        See Also
        --------
        diagonal_probing : A probing class to get the diagonal of an operator
        trace_probing : A probing class to get the trace of an operator


        Attributes
        ----------
        function : function
            the function, that is applied to the probes
        domain : space
            the space, where the probes live in
        target : space
            the codomain of `domain`
        random : string
            the random number generator used to create the probes
            (either "pm1" or "gau")
        ncpu : int
            the number of cpus used for probing
        nrun : int
            the number of probes to be evaluated, when the instance is called
        nper : int
            number of probes, that will be evaluated by one worker
        var : bool
            whether the variance will be additionally returned, when the
            instance is called
        quargs : dict
            Keyword arguments passed to `function` in each call.

    """
Ultima's avatar
Ultima committed
129
130
    def __init__(self, operator=None, function=None, domain=None, 
                 codomain=None, random="pm1", nrun=8, varQ=False, **kwargs):
Ultimanet's avatar
Ultimanet committed
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
        """
        initializes a probing instance

        Parameters
        ----------
        op : operator
            The operator specified by `op` is the operator to be probed.
            If no operator is given, then probing will be done by applying
            `function` to the probes. (default: None)
        function : function, *optional*
            If no operator has been specified as `op`, then specification of
            `function` is non optional. This is the function, that is applied
            to the probes. (default: `op.times`)
        domain : space, *optional*
            If no operator has been specified as `op`, then specification of
            `domain` is non optional. This is the space that the probes live
            in. (default: `op.domain`)
        target : domain, *optional*
            `target` is the codomain of `domain`
            (default: `op.domain.get_codomain()`)
        random : string, *optional*
            the distribution from which the probes are drawn. `random` can be
            either "pm1" or "gau". "pm1" is a uniform distribution over {+1,-1}
            or {+1,+i,-1,-i}, respectively. "gau" is a normal distribution with
            zero-mean and unit-variance (default: "pm1")
        ncpu : int, *optional*
            the number of cpus to be used from parallel probing. (default: 2)
        nrun : int, *optional*
            the number of probes to be evaluated. If `nrun<ncpu`, it will be
            set to `ncpu`. (default: 8)
        nper : int, *optional*
            this number specifies how many probes will be evaluated by one
            worker. Afterwards a new worker will be created to evaluate a chunk
            of `nper` probes.
            If for example `nper=nrun/ncpu`, then every worker will be created
            for every cpu. This can lead to the case, that all workers but one
            are already finished, but have to wait for the last worker that
            might still have a considerable amount of evaluations left. This is
            obviously not very effective.
            If on the other hand `nper=1`, then for each evaluation a worker will
            be created. In this case all cpus will work until nrun probes have
            been evaluated.
            It is recommended to leave `nper` as the default value. (default: 1)
        var : bool, *optional*
            If `var` is True, then the variance of the sampled function will
            also be returned. The result is then a tuple with the mean in the
            zeroth entry and the variance in the first entry. (default: False)

        """
Ultima's avatar
Ultima committed
180
181
182
183
184
185
186
        ## Case 1: no operator given. Check function and domain for general 
        ## sanity 
        if operator is None:
            ## check whether the given function callable
            if function is None or hasattr(function, "__call__") == False:
                raise ValueError(about._errors.cstring(
                "ERROR: invalid input: No function given or not callable."))
Ultimanet's avatar
Ultimanet committed
187
            ## check given domain
Ultima's avatar
Ultima committed
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
            if domain is None or isinstance(domain, space) == False:
                raise ValueError(about._errors.cstring(
                "ERROR: invalid input: given domain is not a nifty space"))
        
        ## Case 2: An operator is given. Take domain and function from that
        ## if not given explicitly 
        else:
            
            ## Case 2.1 extract function 
            ## explicit function overrides operator function
            if function is None or hasattr(function,"__call__") == False:
                try:
                    function = operator.times 
                except(AttributeError):
                    raise ValueError(about._errors.cstring(
   "ERROR: no explicit function given and given operator has no times method!"))
            ## check whether the given function is correctly bound to the 
            ## operator                     
            if operator != function.im_self:
                    raise ValueError(about._errors.cstring(
   "ERROR: the given function is not a bound function of the operator!"))
           


            ## Case 2.2 extract domain
            if domain is None or isinstance(domain, space):
                 if (function in [operator.inverse_times, 
                                  operator.adjoint_times]):
                     try:
                         domain = operator.target
                     except(AttributeError):
                         raise ValueError(about._errors.cstring(
   "ERROR: no explicit domain given and given operator has no target!"))
                        
                 else:
                     try:
                         domain = operator.domain
                     except(AttributeError):
                         raise ValueError(about._errors.cstring(
   "ERROR: no explicit domain given and given operator has no domain!"))
   
        self.function = function               
        self.domain = domain

        ## Check the given target
        if codomain is None:
            codomain = self.domain.get_codomain()
Ultimanet's avatar
Ultimanet committed
235
        else:
Ultima's avatar
Ultima committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
            assert(self.domain.check_codomain(codomain))
        
        self.codomain = codomain

        if(random not in ["pm1","gau"]):
            raise ValueError(about._errors.cstring(
                "ERROR: unsupported random key '"+str(random)+"'."))
        self.random = random
        
        ## Parse the remaining arguments
        self.nrun = int(nrun) 
        self.varQ = bool(varQ)
        self.kwargs = kwargs

        """
Ultimanet's avatar
Ultimanet committed
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
            from nifty_operators import operator
            if(not isinstance(op,operator)):
                raise TypeError(about._errors.cstring("ERROR: invalid input."))
            ## check whether callable
            if(function is None)or(not hasattr(function,"__call__")):
                function = op.times
            elif(op==function):
                function = op.times
            ## check whether correctly bound
            if(op!=function.im_self):
                raise NameError(about._errors.cstring("ERROR: invalid input."))
            ## check given shape and domain
            if(domain is None)or(not isinstance(domain,space)):
                if(function in [op.inverse_times,op.adjoint_times]):
                    domain = op.target
                else:
                    domain = op.domain
            else:
                if(function in [op.inverse_times,op.adjoint_times]):
                    op.target.check_codomain(domain) ## a bit pointless
                    if(target is None)or(not isinstance(target,space)):
                        target = op.target
                else:
                    op.domain.check_codomain(domain) ## a bit pointless
                    if(target is None)or(not isinstance(target,space)):
                        target = op.domain

        self.function = function
        self.domain = domain

        ## check codomain
        if(target is None):
            target = self.domain.get_codomain()
        else:
            self.domain.check_codomain(target) ## a bit pointless
        self.target = target

        if(random not in ["pm1","gau"]):
            raise ValueError(about._errors.cstring("ERROR: unsupported random key '"+str(random)+"'."))
        self.random = random

        self.ncpu = int(max(1,ncpu))
        self.nrun = int(max(self.ncpu,nrun))
        if(nper is None):
            self.nper = None
        else:
            self.nper = int(max(1,min(self.nrun//self.ncpu,nper)))

        self.var = bool(var)

        self.quargs = quargs
Ultima's avatar
Ultima committed
302
        """
Ultimanet's avatar
Ultimanet committed
303
304
    ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Ultima's avatar
Ultima committed
305
    def configure(self, **kwargs):
Ultimanet's avatar
Ultimanet committed
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
        """
            changes the attributes of the instance

            Parameters
            ----------
            random : string, *optional*
                the random number generator used to create the probes (default: "pm1")
            ncpu : int, *optional*
                the number of cpus to be used for parallel probing. (default: 2)
            nrun : int, *optional*
                the number of probes to be evaluated. If `nrun<ncpu`, it will be
                set to `ncpu`. (default: 8)
            nper : int, *optional*
                number of probes, that will be evaluated by one worker (default: 1)
            var : bool, *optional*
                whether the variance will be additionally returned (default: False)

        """
        if("random" in kwargs):
Ultima's avatar
Ultima committed
325
326
327
            if kwargs.get("random") not in ["pm1","gau"]:
                raise ValueError(about._errors.cstring(
            "ERROR: unsupported random key '"+str(kwargs.get("random"))+"'."))
Ultimanet's avatar
Ultimanet committed
328
            else:
Ultima's avatar
Ultima committed
329
330
331
332
                self.random = kwargs.get("random")

        if "nrun" in kwargs:
            self.nrun = int(kwargs.get("nrun"))
Ultimanet's avatar
Ultimanet committed
333

Ultima's avatar
Ultima committed
334
335
        if "varQ" in kwargs:
            self.varQ = bool(kwargs.get("varQ"))
Ultimanet's avatar
Ultimanet committed
336
337
338

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

Ultima's avatar
Ultima committed
339
    def generate_probe(self):
Ultimanet's avatar
Ultimanet committed
340
341
342
343
344
345
346
347
348
349
        """
            Generates a single probe

            Returns
            -------
            probe : field
                a random field living in `domain` with mean 0 and variance 1 in
                each component

        """
Ultima's avatar
Ultima committed
350
        return field(self.domain,
351
352
                     codomain = self.codomain,
                     random = self.random)
Ultimanet's avatar
Ultimanet committed
353
354
355

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

Ultima's avatar
Ultima committed
356
    def evaluate_probe(self, probe, idnum=0):
Ultimanet's avatar
Ultimanet committed
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
        """
            Computes a single probing result given one probe

            Parameters
            ----------
            probe : field
                the field on which `function` will be applied
            idnum : int
                    the identification number of the probing

            Returns
            -------
            result : array-like
                the result of applying `function` to `probe`. The exact type
                depends on the function.

        """
Ultima's avatar
Ultima committed
374
375
376
        f = self.function(probe, **self.kwargs)
        return f
        
Ultimanet's avatar
Ultimanet committed
377
378
379

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

Ultima's avatar
Ultima committed
380
    def finalize(self, sum_of_probes, sum_of_squares, num):
Ultimanet's avatar
Ultimanet committed
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
        """
            Evaluates the probing results.

            Parameters
            ----------
            summa : numpy.array
                Sum of all probing results.
            num : int
                Number of successful probings (not returning ``None``).
            var : numpy.array
                Sum of all squared probing results

            Returns
            -------
            final : numpy.array
                The final probing result; 1/N Sum[ probing(probe_i) ]
            var : array-like
                The variance of the final probing result;
                1/(N(N-1)) Sum[( probing(probe_i) - final )^2];
                if the variance is returned, the return will be a tuple of
                (`final`,`var`).

        """
Ultima's avatar
Ultima committed
404
405
406
407
408
409
        ## Check the success and efficiency of the probing
        if num < self.nrun:
            about.infos.cflush(
            " ( %u probe(s) failed, effectiveness == %.1f%% )\n"\
                %(self.nrun-num, 100*num/self.nrun))
            if num == 0:
Ultimanet's avatar
Ultimanet committed
410
411
412
413
414
                about.warnings.cprint("WARNING: probing failed.")
                return None
        else:
            about.infos.cflush("\n")

Ultima's avatar
Ultima committed
415
416
417
418
419
420
        
        if self.varQ == True:
            if num == 1:
                about.warnings.cprint(
                "WARNING: Only one probe available -> infinite variance.")
                return (sum_of_probes, None)
Ultimanet's avatar
Ultimanet committed
421
            else:
Ultima's avatar
Ultima committed
422
423
                var = 1/(num-1)*(sum_of_squares - 1/num*(sum_of_probes**2))
                return (sum_of_probes*(1./num), var)
Ultimanet's avatar
Ultimanet committed
424
        else:
Ultima's avatar
Ultima committed
425
            return sum_of_probes*(1./num)
Ultimanet's avatar
Ultimanet committed
426
427
428

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

Ultima's avatar
Ultima committed
429
430
    def print_progress(self, num): ## > prints progress status by in upto 10 dots
        tenths = 1+(10*num//self.nrun)
Ultimanet's avatar
Ultimanet committed
431
        about.infos.cflush(("\b")*10+('.')*tenths+(' ')*(10-tenths))
Ultima's avatar
Ultima committed
432
    """
Ultimanet's avatar
Ultimanet committed
433
434
435
436
437
438
    def _single_probing(self,zipped): ## > performs one probing operation
        ## generate probe
        np.random.seed(zipped[0])
        probe = self.gen_probe()
        ## do the actual probing
        return self.probing(zipped[1],probe)
Ultima's avatar
Ultima committed
439
    """
Ultimanet's avatar
Ultimanet committed
440

Ultima's avatar
Ultima committed
441
442
443
444
445
446
    def probe(self): ## > performs the probing operations one after another
        ## initialize the variables
        sum_of_probes = 0
        sum_of_squares = 0
        num = 0
        
Ultimanet's avatar
Ultimanet committed
447
        for ii in xrange(self.nrun):
Ultima's avatar
Ultima committed
448
449
450
451
452
453
454
455
456
            temp_probe = self.generate_probe()
            temp_result = self.evaluate_probe(probe = temp_probe)
            
            if temp_result is not None:
                sum_of_probes += temp_result
                if self.varQ:                
                    sum_of_squares += ((temp_result).conjugate())*temp_result 
                num += 1
                self.print_progress(num)
Ultimanet's avatar
Ultimanet committed
457
458
        about.infos.cflush(" done.")
        ## evaluate
Ultima's avatar
Ultima committed
459
        return self.finalize(sum_of_probes, sum_of_squares, num)
Ultimanet's avatar
Ultimanet committed
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483

    def __call__(self,loop=False,**kwargs):
        """

            Starts the probing process.
            All keyword arguments that can be given to `configure` can also be
            given to `__call__` and have the same effect.

            Parameters
            ----------
            loop : bool, *optional*
                if `loop` is True, then multiprocessing will be disabled and
                all probes are evaluated by a single worker (default: False)

            Returns
            -------
            results : see **Returns** in `evaluate`

            other parameters
            ----------------
            kwargs : see **Parameters** in `configure`

        """
        self.configure(**kwargs)
Ultima's avatar
Ultima committed
484
        return self.probe()
Ultimanet's avatar
Ultimanet committed
485
486
487
488
489
490
491
492
493
494

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

    def __repr__(self):
        return "<nifty_core.probing>"

##=============================================================================



Ultima's avatar
Ultima committed
495
496
497
class _specialized_prober(object):
    def __init__(self, operator, domain=None, inverseQ=False, **kwargs):
        ## remove a potentially supplied function keyword argument
Ultimanet's avatar
Ultimanet committed
498
        try:
Ultima's avatar
Ultima committed
499
500
501
            kwargs.pop('function')
        except(KeyError):
            pass
Ultimanet's avatar
Ultimanet committed
502
        else:
Ultima's avatar
Ultima committed
503
504
505
506
507
508
509
            about.warnings.cprint(
                "WARNING: Dropped the supplied function keyword-argument!")
       
        if domain is None and inverseQ == False:
            kwargs.update({'domain': operator.domain})
        elif domain is None and inverseQ == True:
            kwargs.update({'domain': operator.target})
Ultimanet's avatar
Ultimanet committed
510
        else:
Ultima's avatar
Ultima committed
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
            kwargs.update({'domain': domain})
        self.operator = operator            
        
        self.prober = prober(function = self._probing_function,
                             **kwargs)
    
    def _probing_function(self, probe):
        return None
        
    def __call__(self, *args, **kwargs):
        return self.prober(*args, **kwargs)
        
               
    def __getattr__(self, attr):
        return getattr(self.prober, attr)
    
        
        


class trace_prober(_specialized_prober):
    def __init__(self, operator, **kwargs):                
        super(trace_prober, self).__init__(operator = operator, 
                                           inverseQ=False, 
                                           **kwargs)
    def _probing_function(self, probe):
        return direct_dot(probe.conjugate(), self.operator.times(probe))

class inverse_trace_prober(_specialized_prober):
    def __init__(self, operator, **kwargs):                
        super(inverse_trace_prober, self).__init__(operator = operator,
                                                   inverseQ=True, 
                                                   **kwargs)
    def _probing_function(self, probe):
        return direct_dot(probe.conjugate(), 
                          self.operator.inverse_times(probe))

class diagonal_prober(_specialized_prober):
    def __init__(self, **kwargs):                
        super(diagonal_prober, self).__init__(inverseQ = False, 
                                              **kwargs)
    def _probing_function(self, probe):
        return probe.conjugate()*self.operator.times(probe)
        
class inverse_diagonal_prober(_specialized_prober):
    def __init__(self, operator, **kwargs):                
        super(inverse_diagonal_prober, self).__init__(operator = operator, 
                                                      inverseQ=True, 
                                                      **kwargs)
    def _probing_function(self, probe):
        return probe.conjugate()*self.operator.inverse_times(probe)