psfmodel.py 20.7 KB
Newer Older
FETICK Romain's avatar
FETICK Romain committed
1
2
3
4
5
6
7
8
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 27 17:31:18 2019

@author: rfetick
"""

FETICK Romain's avatar
FETICK Romain committed
9
10
11
12
13
import numpy as np
from scipy.optimize import least_squares
from astropy.io import fits
import time
from numpy.fft import fft2, fftshift, ifft2
FETICK Romain's avatar
FETICK Romain committed
14
from maoppy.config import _EPSILON
FETICK Romain's avatar
FETICK Romain committed
15
from maoppy.utils import binning #, getgaussnoise
16
from functools import lru_cache
FETICK Romain's avatar
FETICK Romain committed
17
18

#%% FITTING FUNCTION
FETICK Romain's avatar
FETICK Romain committed
19
def rmserror(model,image,weights=None,background=True, positive_bck=False):
20
    """Compute the RMS error between a PSF model and an image"""
FETICK Romain's avatar
FETICK Romain committed
21
    if weights is None: weights = np.ones_like(image)
22
23
    amp,bck = lsq_flux_bck(model, image, weights=weights, background=background, positive_bck=positive_bck)
    diff = amp*model+bck - image
FETICK Romain's avatar
FETICK Romain committed
24
25
    #noise_std = getgaussnoise(image)
    err = np.sqrt(np.sum(diff**2.0))
26
27
28
    err = err/np.sum(image)
    return err

FETICK Romain's avatar
FETICK Romain committed
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
def lsq_flux_bck(model, data, weights, background=True, positive_bck=False):
    """Compute the analytical least-square solution for flux and background
    LS = SUM_pixels { weights*(flux*model + bck - data)² }
    
    Parameters
    ----------
    model: numpy.ndarray
    data: numpy.ndarray
    weights: numpy.ndarray
    
    Keywords
    --------
    background: bool
        Activate/inactivate background (activated by default:True)
    positive_bck : bool
        Makes background positive (default:False)
    """
    ws = np.sum(weights)
    mws = np.sum(model * weights)
    mwds = np.sum(model * weights * data)
    m2ws = np.sum(weights * (model ** 2))
    wds = np.sum(weights * data)

    if background:
        delta = mws ** 2 - ws * m2ws
        amp = 1. / delta * (mws * wds - ws * mwds)
        bck = 1. / delta * (-m2ws * wds + mws * mwds)
    else:
        amp = mwds / m2ws
        bck = 0.0
        
    if bck<0 and positive_bck: #re-implement above equation
        amp = mwds / m2ws
        bck = 0.0

    return amp, bck

def psffit(psf,Model,x0,weights=None,dxdy=(0.,0.),flux_bck=(True,True),
67
           positive_bck=False,fixed=None,npixfit=None,**kwargs):
FETICK Romain's avatar
FETICK Romain committed
68
69
70
71
72
73
74
75
76
77
78
79
80
    """Fit a PSF with a parametric model solving the least-square problem
       epsilon(x) = SUM_pixel { weights * (amp * Model(x) + bck - psf)² }
    
    Parameters
    ----------
    psf : numpy.ndarray
        The experimental image to be fitted
    Model : class
        The class representing the fitting model
    x0 : tuple, list, numpy.ndarray
        Initial guess for parameters
    weights : numpy.ndarray
        Least-square weighting matrix (same size as `psf`)
FETICK Romain's avatar
FETICK Romain committed
81
        Inverse of the noise's variance
FETICK Romain's avatar
FETICK Romain committed
82
83
84
85
86
87
88
89
90
91
        Default: uniform weighting
    dxdy : tuple of two floats
        Eventual guess on PSF shifting
    flux_bck : tuple of two bool
        Only background can be activate/inactivated
        Flux is always activated (sorry!)
    positive_bck : bool
        Force background to be positive or null
    fixed : numpy.ndarray
        Fix some parameters to their initial value (default: None)
92
93
    npixfit : int (default=None)
        Increased pixel size for improved fitting accuracy
FETICK Romain's avatar
FETICK Romain committed
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
    **kwargs :
        All keywords used to instantiate your `Model`
    
    Returns
    -------
    out.x : numpy.array
            Parameters at optimum
       .dxdy : tuple of 2 floats
           PSF shift at optimum
       .flux_bck : tuple of two floats
           Estimated image flux and background
       .psf : numpy.ndarray (dim=2)
           Image of the PSF model at optimum
       .success : bool
           Minimization success
       .status : int
           Minimization status (see scipy doc)
       .message : string
           Human readable minimization status
       .active_mask : numpy.array
           Saturated bounds
       .nfev : int
           Number of function evaluations
       .cost : float
           Value of cost function at optimum
    """
120
    
121
122
    if weights is None: weights = np.ones_like(psf)
    elif len(psf)!=len(weights): raise ValueError("Keyword `weights` must have same number of elements as `psf`")
123
124
125
126
127
128
129
130
131
132
133
134
    
    # Increase array size for improved fitting accuracy
    if npixfit is not None:
        sx,sy = np.shape(psf)
        if (sx>npixfit) or (sy>npixfit): raise ValueError('npixfit must be greater or equal to both psf dimensions')
        psfbig = np.zeros((npixfit,npixfit))
        wbig = np.zeros((npixfit,npixfit))
        psfbig[npixfit//2-sx//2:npixfit//2+sx//2,npixfit//2-sy//2:npixfit//2+sy//2] = psf
        wbig[npixfit//2-sx//2:npixfit//2+sx//2,npixfit//2-sy//2:npixfit//2+sy//2] = weights
        psf = psfbig
        weights = wbig
    
FETICK Romain's avatar
FETICK Romain committed
135
    sqW = np.sqrt(weights)
136
    Model_inst = Model(np.shape(psf),**kwargs)
FETICK Romain's avatar
FETICK Romain committed
137
138
139
140
141
    
    class CostClass(object):
        def __init__(self):
            self.iter = 0
        def __call__(self,y):
142
            if (self.iter%3)==0: print("-",end="")
FETICK Romain's avatar
FETICK Romain committed
143
144
145
146
147
148
149
150
151
            self.iter += 1
            x, dxdy = mini2input(y)
            m = Model_inst(x,dx=dxdy[0],dy=dxdy[1])
            amp, bck = lsq_flux_bck(m, psf, weights, background=flux_bck[1], positive_bck=positive_bck)
            return np.reshape(sqW * (amp * m + bck - psf), np.size(psf))
    
    cost = CostClass()
    
    if fixed is not None:
152
        if len(fixed)!=len(x0): raise ValueError("When defined, `fixed` must be same size as `x0`")
FETICK Romain's avatar
FETICK Romain committed
153
154
155
156
157
        FREE = [not fixed[i] for i in range(len(fixed))]
        INDFREE = np.where(FREE)[0]
    
    def input2mini(x,dxdy):
        # Transform user parameters to minimizer parameters
158
159
        if fixed is None: xfree = x
        else: xfree = np.take(x,INDFREE)
FETICK Romain's avatar
FETICK Romain committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
        return np.concatenate((xfree,dxdy))
    
    def mini2input(y):
        # Transform minimizer parameters to user parameters
        if fixed is None:
            xall = y[0:-2]
        else:
            xall = np.copy(x0)
            for i in range(len(y)-2):
                xall[INDFREE[i]] = y[i]
        return (xall,y[-2:])
    
    def get_bound(inst):
        b_low = inst.bounds[0]
174
        if fixed is not None: b_low = np.take(b_low,INDFREE)
FETICK Romain's avatar
FETICK Romain committed
175
176
        b_low = np.concatenate((b_low,[-np.inf,-np.inf]))
        b_up = inst.bounds[1]
177
        if fixed is not None: b_up = np.take(b_up,INDFREE)
FETICK Romain's avatar
FETICK Romain committed
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
        b_up = np.concatenate((b_up,[np.inf,np.inf]))
        return (b_low,b_up)
    
    result = least_squares(cost, input2mini(x0,dxdy), bounds=get_bound(Model_inst))
    
    print("") #finish line of "-"
    
    result.x, result.dxdy = mini2input(result.x) #split output between x and dxdy

    m = Model_inst(result.x,dx=result.dxdy[0],dy=result.dxdy[1])
    amp, bck = lsq_flux_bck(m, psf, weights, background=flux_bck[1], positive_bck=positive_bck)
    
    result.flux_bck = (amp,bck)
    result.psf = m    
    return result

194
#%% BASIC FUNCTIONS
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
def reduced_coord(XY,ax,ay,theta,cx,cy):
    c = np.cos(theta)
    s = np.sin(theta)
    s2 = np.sin(2.0 * theta)

    Rxx = (c/ax)**2 + (s/ay)**2
    Ryy = (c/ay)**2 + (s/ax)**2
    Rxy =  s2/ay**2 -  s2/ax**2
    
    u = Rxx*(XY[0]-cx)**2 + Rxy*(XY[0]-cx)*(XY[1]-cy) + Ryy*(XY[1]-cy)**2
    return u    

def moffat(XY, param, norm=None):
    """
    Compute a Moffat function on a meshgrid
    moff = Enorm * (1+u)^(-beta)
    with `u` the quadratic coordinates in the shifted and rotated frame
    
    Parameters
    ----------
    XY : numpy.ndarray (dim=2)
        The (X,Y) meshgrid with X = XY[0] and Y = XY[1]
    param : list, tuple, numpy.ndarray (len=6)
        param[0] - Alpha X
        param[1] - Alpha Y
        param[2] - Theta
        param[3] - Beta
        param[4] - Center X
        param[5] - Center Y
        
    Keywords
    --------
    norm : None, np.inf, float (>0), int (>0)
        Radius for energy normalization
        None      - No energy normalization (maximum=1.0)
                    Enorm = 1.0
        np.inf    - Total energy normalization (on the whole X-Y plane)
                    Enorm = (beta-1)/(pi*ax*ay)
        float,int - Energy normalization up to the radius defined by this value
                    Enorm = (beta-1)/(pi*ax*ay)*(1-(1+(R**2)/(ax*ay))**(1-beta))    
    """
    if len(param)!=6: raise ValueError("Parameter `param` must contain exactly 6 elements, but input has %u elements"%len(param))
    ax,ay,theta,beta,cx,cy = param
    
    u = reduced_coord(XY,ax,ay,theta,cx,cy)
    
    if norm is None:
        Enorm = 1
    elif norm == np.inf:
        if beta<=1: raise ValueError("Cannot compute Moffat energy for beta<=1")
        Enorm = (beta-1) / (np.pi*ax*ay)
    else:
        if beta==1: raise ValueError("Energy computation for beta=1.0 not implemented yet. Sorry!")
        Enorm = (beta-1) / (np.pi*ax*ay)
        Enorm = Enorm / (1 - (1 + (norm**2) / (ax*ay))**(1-beta))
    
    return Enorm * (1.0+u)**(-beta)

def gauss(XY,param):
    """
    Compute a Gaussian function on a meshgrid

    Parameters
    ----------
    XY : numpy.ndarray (dim=2)
        The (X,Y) meshgrid with X = XY[0] and Y = XY[1]
    param : list, tuple, numpy.ndarray (len=5)
        param[0] - Sigma X
        param[1] - Sigma Y
        param[2] - Theta
        param[3] - Center X
        param[4] - Center Y  
    """
    if len(param)!=5: raise ValueError("Parameter `param` must contain exactly 5 elements, but input has %u elements"%len(param))
    ax = np.sqrt(2)*param[0]
    ay = np.sqrt(2)*param[1]
    u = reduced_coord(XY,ax,ay,param[2],param[3],param[4])
    return 1.0/(2*np.pi*param[0]*param[1])*np.exp(-u)

FETICK Romain's avatar
FETICK Romain committed
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
#%% CLASS PARAMETRIC PSF AND ITS SUBCLASSES
class ParametricPSF(object):
    """Super-class defining parametric PSFs
    Not to be instantiated, only serves as a referent for subclasses
    """
    
    def __init__(self,Npix):
        """
        Parameters
        ----------
        Npix : tuple of two elements
            Model X and Y pixel size when called
        """
        if type(Npix)!=tuple:
            raise TypeError("Argument `Npix` must be a tuple")
        self.Npix = Npix
        self.bounds = (-np.inf,np.inf)
    
    def __repr__(self):
        return "ParametricPSF of size (%u,%u)"%self.Npix
    
    def __call__(self,*args,**kwargs):
        raise ValueError("ParametricPSF is not made to be instantiated. Better use its subclasses")
    
    def otf(self,*args,**kwargs):
        """Return the Optical Transfer Function (OTF)"""
        psf = self.__call__(args,kwargs)
        return fftshift(fft2(psf))
    
    def mtf(self,*args,**kwargs):
        """Return the Modulation Transfer Function (MTF)"""
        return np.abs(self.otf(args,kwargs))
    
    def tofits(self,param,filename,*args,keys=None,keys_comment=None,**kwargs):
        psf = self.__call__(param,*args,**kwargs)
        hdr = self._getfitshdr(param,keys=keys,keys_comment=keys_comment)
        hdu = fits.PrimaryHDU(psf, hdr)
        hdu.writeto(filename, overwrite=True)
        
    def _getfitshdr(self,param,keys=None,keys_comment=None):
        if keys is None:
            keys = ["PARAM %u"%(i+1) for i in range(len(param))]
        if len(keys)!=len(param):
            raise ValueError("When defined, `keys` must be same size as `param`")
        if keys_comment is not None:
            if len(keys_comment)!=len(param):
                raise ValueError("When defined, `keys_comment` must be same size as `param`")
        hdr = fits.Header()
        
FETICK Romain's avatar
FETICK Romain committed
323
        hdr["HIERARCH ORIGIN"] = "MAOPPY automatic header"
FETICK Romain's avatar
FETICK Romain committed
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
        hdr["HIERARCH CREATION"] = (time.ctime(),"Date of file creation")
        for i in range(len(param)):
            if keys_comment is None:
                hdr["HIERARCH PARAM "+keys[i]] = param[i]
            else:
                hdr["HIERARCH PARAM "+keys[i]] = (param[i],keys_comment[i])
        return hdr


class ConstantPSF(ParametricPSF):
    """Create a constant PSF, given as a 2D image, using ParametricPSF formalism
    With such a formalism, a constant PSF is just a particular case of a parametric PSF
    """
    def __init__(self,image_psf):
        super().__init__(np.shape(image_psf))
        self.image_psf = image_psf
        self.bounds = ()
        
    def __call__(self,*args,**kwargs):
        return self.image_psf


class Moffat(ParametricPSF):
    def __init__(self,Npix,norm=np.inf):
        self.Npix = Npix
        self.norm = norm
        bounds_down = [_EPSILON,_EPSILON,-np.inf,1+_EPSILON]
        bounds_up = [np.inf for i in range(4)]
        self.bounds = (bounds_down,bounds_up)
FETICK Romain's avatar
FETICK Romain committed
353
354
355
356
        
        self._XY = np.mgrid[0:Npix[0],0:Npix[1]]
        self._XY[1] -= Npix[0]/2
        self._XY[0] -= Npix[1]/2
FETICK Romain's avatar
FETICK Romain committed
357
358
359
360
361
362
363
364
365
366
367
    
    def __call__(self,x,dx=0,dy=0):
        """
        Parameters
        ----------
        x : list, tuple, numpy.ndarray (len=4)
            x[0] - Alpha X
            x[1] - Alpha Y
            x[2] - Theta
            x[3] - Beta
        """
368
        y = np.concatenate((x,[dx,dy]))
FETICK Romain's avatar
FETICK Romain committed
369
        return moffat(self._XY,y,norm=self.norm)
FETICK Romain's avatar
FETICK Romain committed
370
371
372
373
374
    
    def tofits(self,param,filename,*args,keys=["ALPHA_X","ALPHA_Y","THETA","BETA"],**kwargs):
        super(Moffat,self).tofits(param,filename,*args,keys=keys,**kwargs)


FETICK Romain's avatar
FETICK Romain committed
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
class Gaussian(ParametricPSF):
    def __init__(self,Npix):
        self.Npix = Npix
        bounds_down = [_EPSILON,_EPSILON,-np.inf]
        bounds_up = [np.inf for i in range(3)]
        self.bounds = (bounds_down,bounds_up)
        
        self._XY = np.mgrid[0:Npix[0],0:Npix[1]]
        self._XY[1] -= Npix[0]/2
        self._XY[0] -= Npix[1]/2
    
    def __call__(self,x,dx=0,dy=0):
        """
        Parameters
        ----------
        x : list, tuple, numpy.ndarray (len=4)
            x[0] - Sigma X
            x[1] - Sigma Y
            x[2] - Theta
        """
        y = np.concatenate((x,[dx,dy]))
        return gauss(self._XY,y)
    
    def tofits(self,param,filename,*args,keys=["SIGMA_X","SIGMA_Y","THETA"],**kwargs):
FETICK Romain's avatar
FETICK Romain committed
399
        super(Gaussian,self).tofits(param,filename,*args,keys=keys,**kwargs)
400
401
402


def oversample(samp):
FETICK Romain's avatar
FETICK Romain committed
403
404
405
    """Find the minimal integer that allows oversampling"""
    k = int(np.ceil(2.0/samp))
    return (k*samp,k)
406
407
408
        


FETICK Romain's avatar
FETICK Romain committed
409
410
411
412
class Psfao(ParametricPSF):
    """
    Name:        PSFAO
    Description: a long-exposure PSF model dedicated to AO correction
413
    Reference:   Fétick et al., August 2019, A&A, Vol. 628 [Fétick2019b]
FETICK Romain's avatar
FETICK Romain committed
414
415
    Note:        the PSF is parametrised through the PSD of the electromagnetic phase
    """
416
    def __init__(self,Npix,system=None,Lext=10.,samp=None):
FETICK Romain's avatar
FETICK Romain committed
417
418
419
420
421
422
423
424
425
426
427
428
429
        """
        Parameters
        ----------
        Npix : tuple
            Size of output PSF
        system : OpticalSystem
            Optical system for this PSF
        samp : float
            Sampling at the observation wavelength
        Lext : float
            Von-Karman external scale (default = 10 m)
            Useless if Fao >> 1/Lext
        """
430
        
431
432
433
434
435
        if not (type(Npix) in [tuple,list,np.ndarray]): raise ValueError("Npix must be a tuple, list or numpy.ndarray")
        if len(Npix)!=2: raise ValueError("Npix must be of length = 2")
        if (Npix[0]%2) or (Npix[1]%2): raise ValueError("Each Npix component must be even")
        if system is None: raise ValueError("Keyword `system` must be defined")
        if samp is None: raise ValueError("Keyword `samp` must be defined")
FETICK Romain's avatar
FETICK Romain committed
436
437
438
439
        self.Npix = Npix
        self.system = system
        self.Lext = Lext
        self.samp = samp
rfetick's avatar
rfetick committed
440
        # r0,C,A,alpha,ratio,theta,beta 
441
442
        bounds_down = [_EPSILON,0,0,_EPSILON,_EPSILON,-np.inf,1+_EPSILON]
        bounds_up = [np.inf for i in range(7)]
FETICK Romain's avatar
FETICK Romain committed
443
444
445
446
        self.bounds = (bounds_down,bounds_up)
    
    @property
    def samp(self):
FETICK Romain's avatar
FETICK Romain committed
447
        return self._samp_over/self._k
FETICK Romain's avatar
FETICK Romain committed
448
449
450
451
    
    @samp.setter
    def samp(self,value):
        # Manage cases of undersampling
FETICK Romain's avatar
FETICK Romain committed
452
        self._samp_over, self._k = oversample(value)
FETICK Romain's avatar
FETICK Romain committed
453
    
454
455
456
457
458
459
460
461
462
463
    def check_parameters(self,x0):
        bd, bu = self.bounds
        x0 = np.array(x0)
        bd = np.array(bd)
        bu = np.array(bu)
        if len(x0)!=7: raise ValueError('len(x0) is different from length of bounds')
        if np.any(x0<bd): raise ValueError('Lower bounds are not respected')
        if np.any(x0>bu): raise ValueError('Upper bounds are not respected')
        
    
FETICK Romain's avatar
FETICK Romain committed
464
465
466
467
468
469
470
471
472
473
474
475
476
477
    def psd(self,x0):
        """Compute the PSD model from parameters
        PSD is given in [rad²/f²] = [rad² m²]
        
        Parameters
        ----------
        x0 : numpy.array (dim=1), tuple, list
            See __call__ for more details
            
        Returns
        -------
        psd : numpy.array (dim=2)
            
        """
478
        self.check_parameters(x0)
FETICK Romain's avatar
FETICK Romain committed
479
        
480
481
482
        Nx_over = self.Npix[0]*self._k
        Ny_over = self.Npix[1]*self._k
        
FETICK Romain's avatar
FETICK Romain committed
483
        pix2freq = 1.0/(self.system.D*self._samp_over)
484
485
486
487
488
489
        f2D = np.mgrid[0:Nx_over, 0:Ny_over].astype(float)
        f2D[0] -= Nx_over//2
        f2D[1] -= Ny_over//2
        f2D *= pix2freq
        F2 = f2D[0]**2. + f2D[1]**2.
        
FETICK Romain's avatar
FETICK Romain committed
490
491
        Fao = self.system.Nact/(2.0*self.system.D)
        
rfetick's avatar
rfetick committed
492
        r0,C,A,alpha,ratio,theta,beta = x0
493
494
        
        PSD = 0.0229* r0**(-5./3.) * ((1. / self.Lext**2.) + F2)**(-11./6.)
FETICK Romain's avatar
FETICK Romain committed
495
496
        PSD *= (F2 >= Fao**2.)
        
rfetick's avatar
rfetick committed
497
498
        ax = alpha*ratio
        ay = alpha/ratio
499
500
        param = (ax,ay,theta,beta,0,0)
        PSD += (F2 < Fao**2.) * np.abs(C + A*moffat(f2D,param,norm=Fao))
501
502
        # Set PSD = 0 at null frequency
        PSD[Nx_over//2,Ny_over//2] = 0.0
FETICK Romain's avatar
FETICK Romain committed
503
504
505
506
507
508
509
510
511
512
513
514
515
        return PSD
    
    def otf(self,x0,dx=0,dy=0,_caller='user'):
        """
        See __call__ for input arguments
        Warning: result of otf will be unconsistent if undersampled!!!
        This issue is solved with oversampling + binning in __call__ but not here
        For the moment, the `_caller` keyword prevents user to misuse otf
        """
        
        if (self._k > 1) and (_caller != 'self'):
            raise ValueError("Cannot call `Psfao.otf(...)` when undersampled (functionality not implemented yet)")
        
516
517
518
        OTF_TURBULENT = self._otf_turbulent(x0)
        OTF_DIFFRACTION = self._otf_diffraction()
        OTF_SHIFT = self._otf_shift(dx,dy)
FETICK Romain's avatar
FETICK Romain committed
519
        
520
521
522
523
        return OTF_TURBULENT * OTF_DIFFRACTION * OTF_SHIFT
    
    def _otf_turbulent(self,x0):
        PSD = self.psd(x0)
FETICK Romain's avatar
FETICK Romain committed
524
        L = self.system.D * self._samp_over
525
        Bg = fft2(fftshift(PSD)) / L**2
FETICK Romain's avatar
FETICK Romain committed
526
        Dphi = fftshift(np.real(2 * (Bg[0, 0] - Bg)))
527
528
        return np.exp(-Dphi/2.) 
    
529
    @lru_cache(maxsize=2)
FETICK Romain's avatar
FETICK Romain committed
530
531
    def _otf_diffraction(self):
        #TODO: @lru_cache to prevent unecessary calls to this? (2 FFT)
532
533
        Nx_over = self.Npix[0]*self._k
        Ny_over = self.Npix[1]*self._k
FETICK Romain's avatar
FETICK Romain committed
534
        
FETICK Romain's avatar
FETICK Romain committed
535
536
        NpupX = np.ceil(Nx_over/self._samp_over)
        NpupY = np.ceil(Ny_over/self._samp_over)
537
        tab = np.zeros((Nx_over, Ny_over), dtype=np.complex)
FETICK Romain's avatar
FETICK Romain committed
538
        tab[0:int(NpupX), 0:int(NpupY)] = self.system.pupil((NpupX,NpupY),samp=self._samp_over)
539
540
541
542
543
544
545
546
547
548
        return fftshift(abs(ifft2(abs(fft2(tab)) ** 2)) / np.sum(tab))
    
    def _otf_shift(self,dx,dy):
        Nx_over = self.Npix[0]*self._k
        Ny_over = self.Npix[1]*self._k
        
        Y, X = np.mgrid[0:Nx_over,0:Ny_over].astype(float)
        X = (X-Nx_over/2) * 2*np.pi*1j/Nx_over
        Y = (Y-Ny_over/2) * 2*np.pi*1j/Ny_over
        return np.exp(-X*dx*self._k - Y*dy*self._k)
FETICK Romain's avatar
FETICK Romain committed
549
550
551
552
553
554
555
556
557
    
    def __call__(self,x0,dx=0,dy=0):
        """
        Parameters
        ----------
        x0 : numpy.array (dim=1), tuple, list
            x[0] - Fried parameter r0 [m]
            x[1] - PSD corrected area background C [rad² m²]
            x[2] - PSD corrected area phase variance A [rad²]
558
            x[3] - PSD alpha [1/m]
rfetick's avatar
rfetick committed
559
            x[4] - PSD ax/ay ratio
560
561
            x[5] - PSD theta   [rad]
            x[6] - PSD beta power law
FETICK Romain's avatar
FETICK Romain committed
562
563
564
565
566
        dx : float
            PSF X shifting [pix] (default = 0)
        dy : float
            PSF Y shifting [pix] (default = 0)
        """
567
        
FETICK Romain's avatar
FETICK Romain committed
568
569
570
571
572
573
574
575
576
577
        out = np.real(fftshift(ifft2(fftshift(self.otf(x0,dx=dx,dy=dy,_caller='self')))))
        out = out/out.sum() # ensure unit energy on the field of view
        
        if self._k==1:
            return out
        else:
            return binning(out,int(self._k))
        
    def tofits(self,param,filename,*args,keys=None,**kwargs):
        if keys is None:
rfetick's avatar
rfetick committed
578
            keys = ["R0","CST","SIGMA2","ALPHA","RATIO","THETA","BETA"]
FETICK Romain's avatar
FETICK Romain committed
579
580
581
            keys_comment = ["Fried parameter [m]",
                            "PSD AO area constant C [rad2]",
                            "PSD AO area Moffat variance A [rad2]",
582
                            "PSD AO area Moffat alpha [1/m]",
rfetick's avatar
rfetick committed
583
                            "PSD AO area Moffat ax/ay ratio",
FETICK Romain's avatar
FETICK Romain committed
584
585
                            "PSD AO area Moffat theta [rad]",
                            "PSD AO area Moffat beta"]
FETICK Romain's avatar
FETICK Romain committed
586
587
588
589
590
591
        
        # redefine tofits() because extra hdr is required
        psf = self.__call__(param,*args,**kwargs)
        hdr = self._getfitshdr(param,keys=keys,keys_comment=keys_comment)
        
        hdr["HIERARCH SYSTEM"] = (self.system.name,"System name")
592
593
        hdr["HIERARCH SYSTEM D"] = (self.system.D,"Primary mirror diameter")
        hdr["HIERARCH SYSTEM NACT"] = (self.system.Nact,"Linear number of AO actuators")
FETICK Romain's avatar
FETICK Romain committed
594
595
596
597
598
        hdr["HIERARCH SAMP"] = (self.samp,"Sampling (eg. 2 for Shannon)")
        hdr["HIERARCH LEXT"] = (self.Lext,"Von-Karman outer scale")
        
        hdu = fits.PrimaryHDU(psf, hdr)
        hdu.writeto(filename, overwrite=True)