-
Notifications
You must be signed in to change notification settings - Fork 35
/
kepfit.py
executable file
·915 lines (742 loc) · 29.7 KB
/
kepfit.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
import kepmsg, kepstat, kepfunc, keparray
import math, sys
import numpy as np
from scipy import optimize, ndimage
from scipy.optimize import fmin_powell, fmin_tnc, fmin, leastsq
from scipy.ndimage import interpolation
from scipy.ndimage.interpolation import shift
from keparray import rebin2D
# -----------------------------------------------------------
# linear least square polynomial fit using scipy
def leastsquare(functype,pinit,xdata,ydata,yerr,logfile,verbose):
status = 0
coeffs = []
# functional form
if (functype == 'poly0'): fitfunc = kepfunc.poly0()
if (functype == 'poly1'): fitfunc = kepfunc.poly1()
if (functype == 'poly2'): fitfunc = kepfunc.poly2()
if (functype == 'poly3'): fitfunc = kepfunc.poly3()
if (functype == 'poly4'): fitfunc = kepfunc.poly4()
if (functype == 'poly5'): fitfunc = kepfunc.poly5()
if (functype == 'poly6'): fitfunc = kepfunc.poly6()
if (functype == 'poly7'): fitfunc = kepfunc.poly7()
if (functype == 'poly8'): fitfunc = kepfunc.poly8()
if (functype == 'poly1con'): fitfunc = kepfunc.poly1con()
if (functype == 'gauss'): fitfunc = kepfunc.gauss()
if (functype == 'gauss0'): fitfunc = kepfunc.gauss0()
if (functype == 'congauss'): fitfunc = kepfunc.congauss()
if (functype == 'sine'): fitfunc = kepfunc.sine()
if (functype == 'moffat0'): fitfunc = kepfunc.moffat0()
if (functype == 'conmoffat'): fitfunc = kepfunc.conmoffat()
# define error coefficent calculation
errfunc = lambda p, x, y, err: (y - fitfunc(p, x)) / err
# if no data errors, substitude rms of fit
if yerr is None:
yerr = []
rerr = []
for i in range(len(ydata)):
rerr.append(1.e10)
try:
out = optimize.leastsq(errfunc,pinit,args=(xdata,ydata,rerr),full_output=1)
except:
message = 'ERROR -- KEPFIT.LEASTSQUARE: failed to fit data'
status = kepmsg.err(logfile,message,verbose)
if functype == 'poly0':
out = [np.mean(ydata),math.sqrt(np.mean(ydata))]
if (functype == 'poly0' or functype == 'sineCompareBinPSF'):
coeffs.append(out[0])
else:
coeffs = out[0]
if (len(coeffs) > 1):
fit = fitfunc(coeffs,xdata)
else:
fit = np.zeros(len(xdata))
for i in range(len(fit)):
fit[i] = coeffs[0]
sigma, status = kepstat.rms(ydata,fit,logfile,verbose)
for i in range(len(ydata)):
yerr.append(sigma)
# fit data
try:
out = optimize.leastsq(errfunc, pinit, args=(xdata, ydata, yerr), full_output=1)
except:
message = 'ERROR -- KEPFIT.LEASTSQUARE: failed to fit data'
status = kepmsg.err(logfile,message,verbose)
if functype == 'poly0':
out = [np.mean(ydata),math.sqrt(np.mean(ydata))]
# define coefficients
coeffs = []
covar = []
if (functype == 'poly0' or functype == 'poly1con' or
functype == 'sineCompareBinPSF'):
coeffs.append(out[0])
covar.append(out[1])
else:
coeffs = out[0]
covar = out[1]
# calculate 1-sigma error on coefficients
errors = []
if (covar is None):
message = 'WARNING -- KEPFIT.leastsquare: NULL covariance matrix'
# kepmsg.log(logfile,message,verbose)
for i in range(len(coeffs)):
if (covar is not None and len(coeffs) > 1):
errors.append(math.sqrt(abs(covar[i][i])))
else:
errors.append(coeffs[i])
# generate fit points for rms calculation
if (len(coeffs) > 1):
fit = fitfunc(coeffs,xdata)
else:
fit = np.zeros(len(xdata))
for i in range(len(fit)):
fit[i] = coeffs[0]
sigma, status = kepstat.rms(ydata,fit,logfile,verbose)
# generate fit points for plotting
dx = xdata[len(xdata)-1] - xdata[0]
plotx = np.linspace(xdata.min(),xdata.max(),10000)
ploty = fitfunc(coeffs,plotx)
if (len(coeffs) == 1):
ploty = []
for i in range(len(plotx)):
ploty.append(coeffs[0])
ploty = np.array(ploty)
# reduced chi^2 calculation
chi2 = 0
dof = len(ydata) - len(coeffs)
for i in range(len(ydata)):
chi2 += (ydata[i] - fit[i])**2 / yerr[i]
chi2 /= dof
return coeffs, errors, covar, sigma, chi2, dof, fit, plotx, ploty, status
# -----------------------------------------------------------
# linear least square fit with sigma-clipping
def lsqclip(functype,pinit,x,y,yerr,rej_lo,rej_hi,niter,logfile,verbose):
# functype = unctional form
# pinit = initial guess for parameters
# x = list of x data
# y = list of y data
# yerr = list of 1-sigma y errors
# order = polynomial order
# rej_lo = lower rejection threshold (units=sigma)
# rej_hi = upper rejection threshold (units=sugma)
# niter = number of sigma-clipping iterations
npts = []
iiter = 0
iterstatus = 1
status = 0
# error catching
if (len(x) == 0):
status = kepmsg.exit('ERROR -- KEPFIT.LSQCLIP: x data array is empty')
if (len(y) == 0):
status = kepmsg.exit('ERROR -- KEPFIT.LSQCLIP: y data array is empty')
if (len(x) < len(pinit)):
kepmsg.warn(logfile,'WARNING -- KEPFIT.LSQCLIP: no degrees of freedom')
# sigma-clipping iterations
while (iiter < niter and len(x) > len(pinit) and iterstatus > 0):
iterstatus = 0
tmpx = []
tmpy = []
tmpyerr = []
npts.append(len(x))
coeffs,errors,covar,sigma,chi2,dof,fit,plotx,ploty,status = \
leastsquare(functype,pinit,x,y,yerr,logfile,verbose)
pinit = coeffs
# point-by-point sigma-clipping test
for ix in range(npts[iiter]):
if (y[ix] - fit[ix] < rej_hi * sigma and
fit[ix] - y[ix] < rej_lo * sigma):
tmpx.append(x[ix])
tmpy.append(y[ix])
if (yerr is not None): tmpyerr.append(yerr[ix])
else:
iterstatus = 1
x = np.array(tmpx)
y = np.array(tmpy)
if (yerr is not None): yerr = np.array(tmpyerr)
iiter += 1
# coeffs = best fit coefficients
# covar = covariance matrix
# iiter = number of sigma clipping iteration before convergence
return coeffs, errors, covar, iiter, sigma, chi2, dof, fit, plotx, ploty, status
# linear least square polynomial fit with sigma-clipping
# -----------------------------------------------------------
def poly(x,y,order,rej_lo,rej_hi,niter):
# x = list of x data
# y = list of y data
# order = polynomial order
# rej_lo = lower rejection threshold (units=sigma)
# rej_hi = upper rejection threshold (units=sugma)
# niter = number of sigma-clipping iterations
npts = []
iiter = 0
iterstatus = 1
# sigma-clipping iterations
while (iiter < niter and iterstatus > 0):
iterstatus = 0
tmpx = []
tmpy = []
npts.append(len(x))
coeffs = np.polyfit(x,y,order)
fit = np.polyval(coeffs,x)
# calculate sigma of fit
sig = 0
for ix in range(npts[iiter]):
sig = sig + (y[ix] - fit[ix])**2
sig = math.sqrt(sig / (npts[iiter] - 1))
# point-by-point sigma-clipping test
for ix in range(npts[iiter]):
if (y[ix] - fit[ix] < rej_hi * sig and
fit[ix] - y[ix] < rej_lo * sig):
tmpx.append(x[ix])
tmpy.append(y[ix])
else:
iterstatus = 1
x = tmpx
y = tmpy
iiter += 1
# coeffs = best fit coefficients
# iiter = number of sigma clipping iteration before convergence
return coeffs, iiter
# Fit single PRF model to Kepler pixel mask data
# -----------------------------------------------------------
def fitPRF(flux,ydim,xdim,column,row,prfn,crval1p,crval2p,cdelt1p,cdelt2p,
interpolation,tolerance,guess,type,verbose):
# construct input summed image
status = 0
if status == 0:
imgflux = np.empty((ydim,xdim))
n = 0
for i in range(ydim):
for j in range(xdim):
imgflux[i,j] = flux[n]
n += 1
# interpolate the calibrated PRF shape to the target position
if status == 0:
prf = np.zeros(shape(prfn[0]),dtype='float32')
prfWeight = np.zeros((5),dtype='float32')
for i in xrange(5):
prfWeight[i] = math.sqrt((column - crval1p[i])**2 + (row - crval2p[i])**2)
if prfWeight[i] == 0.0:
prfWeight[i] = 1.0e6
prf = prf + prfn[i] / prfWeight[i]
prf = prf / nansum(prf)
# dimensions of data image
if status == 0:
datDimY = shape(imgflux)[0]
datDimX = shape(imgflux)[1]
# dimensions of data image if it had PRF-sized pixels
if status == 0:
prfDimY = datDimY / cdelt1p[0]
prfDimX = datDimX / cdelt2p[0]
# location of the data image centered on the PRF image (in PRF pixel units)
if status == 0:
prfY0 = (shape(prf)[0] - prfDimY) / 2
prfX0 = (shape(prf)[1] - prfDimX) / 2
# fit input image with model
if status == 0:
args = (imgflux,prf,cdelt1p[0],cdelt2p[0],prfDimY,prfDimX,prfY0,prfX0,
interpolation,verbose)
if type == '2D':
[f,y,x] = fmin_powell(kepfunc.kepler_prf_2d,guess,args=args,xtol=tolerance,
ftol=1.0,disp=False)
elif type == '1D':
guess.insert(0,guess[0])
[fy,fx,y,x] = fmin_powell(kepfunc.kepler_prf_1d,guess,args=args,xtol=tolerance,
ftol=1.0,disp=False)
f = (fx + fy) / 2.0
# calculate best-fit model
if status == 0:
prfMod = shift(prf,[y,x],order=1,mode='constant')
prfMod = prfMod[prfY0:prfY0+prfDimY,prfX0:prfX0+prfDimX]
prfFit = rebin2D(prfMod,[np.shape(imgflux)[0],np.shape(imgflux)[1]],
interpolation,True,False)
prfFit = prfFit * f / cdelt1p[0] / cdelt2p[0]
# calculate residual between data and model
if status == 0:
prfRes = imgflux - prfFit
return f, y * cdelt1p[0], x * cdelt2p[0], prfMod, prfFit, prfRes
# Fit multi- PRF model to Kepler pixel mask data
# -----------------------------------------------------------
def fitMultiPRF(flux,ydim,xdim,column,row,prfn,crval1p,crval2p,cdelt1p,cdelt2p,interpolation,
tolerance,ftol,fluxes,columns,rows,type,verbose,logfile):
# caonstruct input summed image
status = 0
if status == 0:
imgflux = np.empty((ydim,xdim))
n = 0
for i in xrange(ydim):
for j in xrange(xdim):
imgflux[i,j] = flux[n]
n += 1
# interpolate the calibrated PRF shape to the target position
if status == 0:
prf = np.zeros(shape(prfn[0]),dtype='float32')
prfWeight = np.zeros((5),dtype='float32')
for i in xrange(5):
prfWeight[i] = math.sqrt((column - crval1p[i])**2 + (row - crval2p[i])**2)
if prfWeight[i] == 0.0:
prfWeight[i] = 1.0e6
prf = prf + prfn[i] / prfWeight[i]
prf = prf / nansum(prf)
# dimensions of data image
if status == 0:
datDimY = shape(imgflux)[0]
datDimX = shape(imgflux)[1]
# dimensions of data image if it had PRF-sized pixels
if status == 0:
prfDimY = datDimY / cdelt1p[0]
prfDimX = datDimX / cdelt2p[0]
# center of the data image (in CCD pixel units)
if status == 0:
datCenY = row + float(datDimY) / 2 - 0.5
datCenX = column + float(datDimX) / 2 - 0.5
# location of the data image centered on the PRF image (in PRF pixel units)
if status == 0:
prfY0 = (shape(prf)[0] - prfDimY) / 2
prfX0 = (shape(prf)[1] - prfDimX) / 2
# initial guess for fit parameters
if status == 0:
guess = []
try:
f = fluxes.strip().split(',')
y = rows.strip().split(',')
x = columns.strip().split(',')
for i in xrange(len(f)):
f[i] = float(f[i]) * np.nanmax(flux)
except:
f = fluxes
y = rows
x = columns
for i in xrange(len(f)):
try:
guess.append(float(f[i]))
except:
message = 'ERROR -- KEPPRF: Fluxes must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
for i in xrange(len(y)):
try:
guess.append((float(y[i]) - datCenY) / cdelt2p[0])
except:
message = 'ERROR -- KEPPRF: Rows must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
for i in xrange(len(x)):
try:
guess.append((float(x[i]) - datCenX) / cdelt1p[0])
except:
message = 'ERROR -- KEPPRF: Columns must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
if len(x) != len(y) or len(x) != len(f):
message = 'ERROR -- KEPFIT:FITMULTIPRF: Guesses for rows, columns and '
message += 'fluxes must have the same number of sources'
status = kepmsg.err(logfile,message,verbose)
# fit input image with model
if status == 0:
f = []
x = []
y = []
nsrc = len(guess) / 3
args = (imgflux,prf,cdelt1p[0],cdelt2p[0],prfDimY,prfDimX,prfY0,prfX0,
interpolation,verbose)
if type == '2D' and nsrc == 1:
ans = fmin_powell(kepfunc.kepler_prf_2d,guess,args=args,xtol=tolerance,
ftol=ftol,disp=False)
f.append(ans[0])
y.append(ans[1])
x.append(ans[2])
elif type == '1D' and nsrc == 1:
guess.insert(0,guess[0])
ans = fmin_powell(kepfunc.kepler_prf_1d,guess,args=args,xtol=tolerance,
ftol=ftol,disp=False)
f.append((ans[0] + ans[1]) / 2)
y.append(ans[2])
x.append(ans[3])
else:
ans = fmin_powell(kepfunc.kepler_multi_prf_2d,guess,args=args,xtol=tolerance,
ftol=ftol,disp=False)
for i in xrange(nsrc):
f.append(ans[i])
y.append(ans[nsrc+i])
x.append(ans[nsrc*2+i])
# calculate best-fit model
if status == 0:
prfMod = np.zeros((prfDimY+1,prfDimX+1))
for i in xrange(nsrc):
prfTmp = shift(prf,[y[i],x[i]],order=1,mode='constant')
prfTmp = prfTmp[prfY0:prfY0+prfDimY,prfX0:prfX0+prfDimX]
prfMod = prfMod + prfTmp * f[i]
prfFit = rebin2D(prfMod,[np.shape(imgflux)[0],np.shape(imgflux)[1]],
interpolation,True,False) / cdelt1p[0] / cdelt2p[0]
# calculate residual between data and model
if status == 0:
prfRes = imgflux - prfFit
# convert PRF pixels sizes to CCD pixel sizes
if status == 0:
for i in xrange(nsrc):
y[i] = y[i] * cdelt1p[0] + datCenY
x[i] = x[i] * cdelt2p[0] + datCenX
return f, y, x, prfMod, prfFit, prfRes
# Fit multi- PRF model + constant background to Kepler pixel mask data
# -----------------------------------------------------------
def fitBackMultiPRF(flux,ydim,xdim,column,row,prfn,crval1p,crval2p,cdelt1p,cdelt2p,interpolation,
tolerance,ftol,fluxes,columns,rows,bkg,type,verbose,logfile):
# caonstruct input summed image
status = 0
if status == 0:
imgflux = np.empty((ydim,xdim))
n = 0
for i in xrange(ydim):
for j in xrange(xdim):
imgflux[i,j] = flux[n]
n += 1
# interpolate the calibrated PRF shape to the target position
if status == 0:
prf = np.zeros(shape(prfn[0]),dtype='float32')
prfWeight = np.zeros((5),dtype='float32')
for i in xrange(5):
prfWeight[i] = math.sqrt((column - crval1p[i])**2 + (row - crval2p[i])**2)
if prfWeight[i] == 0.0:
prfWeight[i] = 1.0e6
prf = prf + prfn[i] / prfWeight[i]
prf = prf / nansum(prf)
# dimensions of data image
if status == 0:
datDimY = shape(imgflux)[0]
datDimX = shape(imgflux)[1]
# dimensions of data image if it had PRF-sized pixels
if status == 0:
prfDimY = datDimY / cdelt1p[0]
prfDimX = datDimX / cdelt2p[0]
# center of the data image (in CCD pixel units)
if status == 0:
datCenY = row + float(datDimY) / 2 - 0.5
datCenX = column + float(datDimX) / 2 - 0.5
# location of the data image centered on the PRF image (in PRF pixel units)
if status == 0:
prfY0 = (shape(prf)[0] - prfDimY) / 2
prfX0 = (shape(prf)[1] - prfDimX) / 2
# initial guess for fit parameters
if status == 0:
guess = []
try:
f = fluxes.strip().split(',')
y = rows.strip().split(',')
x = columns.strip().split(',')
for i in xrange(len(f)):
f[i] = float(f[i]) * np.nanmax(flux)
except:
f = fluxes
y = rows
x = columns
b = bkg
for i in xrange(len(f)):
try:
guess.append(float(f[i]))
except:
message = 'ERROR -- KEPPRF: Fluxes must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
for i in xrange(len(y)):
try:
guess.append((float(y[i]) - datCenY) / cdelt2p[0])
except:
message = 'ERROR -- KEPPRF: Rows must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
for i in xrange(len(x)):
try:
guess.append((float(x[i]) - datCenX) / cdelt1p[0])
except:
message = 'ERROR -- KEPPRF: Columns must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
guess.append(b)
if status == 0:
if len(x) != len(y) or len(x) != len(f):
message = 'ERROR -- KEPFIT:FITMULTIPRF: Guesses for rows, columns and '
message += 'fluxes must have the same number of sources'
status = kepmsg.err(logfile,message,verbose)
# fit input image with model
if status == 0:
f = []
x = []
y = []
nsrc = (len(guess) - 1) / 3
args = (imgflux,prf,cdelt1p[0],cdelt2p[0],prfDimY,prfDimX,prfY0,prfX0,
interpolation,verbose)
ans = fmin_powell(kepfunc.kepler_bkg_multi_prf_2d,guess,args=args,xtol=tolerance,
ftol=ftol,disp=False)
for i in xrange(nsrc):
f.append(ans[i])
y.append(ans[nsrc+i])
x.append(ans[nsrc*2+i])
b = ans[nsrc*3]
# calculate best-fit model
if status == 0:
prfMod = np.zeros((prfDimY+1,prfDimX+1))
for i in xrange(nsrc):
prfTmp = shift(prf,[y[i],x[i]],order=1,mode='constant')
prfTmp = prfTmp[prfY0:prfY0+prfDimY,prfX0:prfX0+prfDimX]
prfMod = prfMod + prfTmp * f[i]
prfFit = rebin2D(prfMod,[np.shape(imgflux)[0],np.shape(imgflux)[1]],
interpolation,True,False) / cdelt1p[0] / cdelt2p[0]
prfFit = prfFit + b
# calculate residual between data and model
if status == 0:
prfRes = imgflux - prfFit
# convert PRF pixels sizes to CCD pixel sizes
if status == 0:
for i in xrange(nsrc):
y[i] = y[i] * cdelt1p[0] + datCenY
x[i] = x[i] * cdelt2p[0] + datCenX
return f, y, x, b, prfMod, prfFit, prfRes
# Fit multi- PRF model + constant background with focus variations to Kepler pixel mask data
# ------------------------------------------------------------------------------------------
def fitFocusMultiPRF(flux,ydim,xdim,column,row,prfn,crval1p,crval2p,cdelt1p,cdelt2p,interpolation,
tolerance,ftol,fluxes,columns,rows,bkg,wfac,type,verbose,logfile):
# caonstruct input summed image
status = 0
if status == 0:
imgflux = np.empty((ydim,xdim))
n = 0
for i in xrange(ydim):
for j in xrange(xdim):
imgflux[i,j] = flux[n]
n += 1
# interpolate the calibrated PRF shape to the target position
if status == 0:
prf = np.zeros(shape(prfn[0]),dtype='float32')
prfWeight = np.zeros((5),dtype='float32')
for i in xrange(5):
prfWeight[i] = math.sqrt((column - crval1p[i])**2 + (row - crval2p[i])**2)
if prfWeight[i] == 0.0:
prfWeight[i] = 1.0e6
prf = prf + prfn[i] / prfWeight[i]
prf = prf / nansum(prf)
# dimensions of data image
if status == 0:
datDimY = shape(imgflux)[0]
datDimX = shape(imgflux)[1]
# dimensions of data image if it had PRF-sized pixels
# if status == 0:
# prfDimY = datDimY / cdelt1p[0]
# prfDimX = datDimX / cdelt2p[0]
# center of the data image (in CCD pixel units)
if status == 0:
datCenY = row + float(datDimY) / 2 - 0.5
datCenX = column + float(datDimX) / 2 - 0.5
# location of the data image centered on the PRF image (in PRF pixel units)
# if status == 0:
# prfY0 = (shape(prf)[0] - prfDimY) / 2
# prfX0 = (shape(prf)[1] - prfDimX) / 2
# initial guess for fit parameters
if status == 0:
guess = []
try:
f = fluxes.strip().split(',')
y = rows.strip().split(',')
x = columns.strip().split(',')
for i in xrange(len(f)):
f[i] = float(f[i]) * np.nanmax(flux)
except:
f = fluxes
y = rows
x = columns
b = bkg
w = wfac
for i in xrange(len(f)):
try:
guess.append(float(f[i]))
except:
message = 'ERROR -- KEPPRF: Fluxes must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
for i in xrange(len(y)):
try:
guess.append((float(y[i]) - datCenY) / cdelt2p[0])
except:
message = 'ERROR -- KEPPRF: Rows must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
for i in xrange(len(x)):
try:
guess.append((float(x[i]) - datCenX) / cdelt1p[0])
except:
message = 'ERROR -- KEPPRF: Columns must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
guess.append(b)
guess.append(w)
if status == 0:
if len(x) != len(y) or len(x) != len(f):
message = 'ERROR -- KEPFIT:FITMULTIPRF: Guesses for rows, columns and '
message += 'fluxes must have the same number of sources'
status = kepmsg.err(logfile,message,verbose)
# fit input image with model
if status == 0:
f = []
x = []
y = []
nsrc = (len(guess) - 2) / 3
args = (imgflux,prf,cdelt1p[0],cdelt2p[0],datDimY,datDimX,interpolation,verbose)
ans = fmin_powell(kepfunc.kepler_focus_multi_prf_2d,guess,args=args,xtol=tolerance,
ftol=ftol,disp=False)
for i in xrange(nsrc):
f.append(ans[i])
y.append(ans[nsrc+i])
x.append(ans[nsrc*2+i])
b = ans[nsrc*3]
w = ans[nsrc*3+1]
print ans
print f,y,x,b,w
# calculate best-fit model
if status == 0:
prfDimY = datDimY / cdelt1p[0] / w
prfDimX = datDimX / cdelt2p[0] / w
prfY0 = (shape(prf)[0] - prfDimY) / 2
prfX0 = (shape(prf)[1] - prfDimX) / 2
DY = 0.0; DX = 0.0
if int(prfDimY) % 2 == 0: DY = 1.0
if int(prfDimX) % 2 == 0: DX = 1.0
print w, prfDimY, prfDimX
prfMod = np.zeros((prfDimY+DY,prfDimX+DX))
for i in range(nsrc):
prfTmp = shift(prf,[y[i]/w,x[i]/w],order=1,mode='constant')
prfMod = prfMod + prfTmp[prfY0:prfY0+prfDimY,prfX0:prfX0+prfDimX] * f[i]
prfFit = rebin2D(prfMod,[shape(imgflux)[0],shape(imgflux)[1]],interpolation,True,False)
prfFit = prfFit / cdelt1p[0] / cdelt2p[0] / w / w
prfFit = prfFit + b
# calculate residual between data and model
if status == 0:
prfRes = imgflux - prfFit
# convert PRF pixels sizes to CCD pixel sizes
if status == 0:
for i in xrange(nsrc):
y[i] = y[i] * cdelt1p[0] * w + datCenY
x[i] = x[i] * cdelt2p[0] * w + datCenX
return f, y, x, b, w, prfMod, prfFit, prfRes
# Fit multi-PRF model to Kepler pixel mask data
# -----------------------------------------------------------
def test(flux,ydim,xdim,column,row,prfn,crval1p,crval2p,cdelt1p,cdelt2p,interpolation,
tolerance,ftol,fluxes,columns,rows,type,verbose,logfile):
# construct input summed image
status = 0
if status == 0:
imgflux = np.empty((ydim,xdim))
n = 0
for i in xrange(ydim):
for j in xrange(xdim):
imgflux[i,j] = flux[n]
n += 1
# interpolate the calibrated PRF shape to the target position
if status == 0:
prf = np.zeros(shape(prfn[0]),dtype='float32')
prfWeight = np.zeros((5),dtype='float32')
for i in xrange(5):
prfWeight[i] = math.sqrt((column - crval1p[i])**2 + (row - crval2p[i])**2)
if prfWeight[i] == 0.0:
prfWeight[i] = 1.0e6
prf = prf + prfn[i] / prfWeight[i]
prf = prf / nansum(prf)
# dimensions of data image
if status == 0:
datDimY = shape(imgflux)[0]
datDimX = shape(imgflux)[1]
# dimensions of data image if it had PRF-sized pixels
if status == 0:
prfDimY = datDimY / cdelt1p[0]
prfDimX = datDimX / cdelt2p[0]
# center of the data image (in CCD pixel units)
if status == 0:
datCenY = row + float(datDimY) / 2 - 0.5
datCenX = column + float(datDimX) / 2 - 0.5
# location of the data image centered on the PRF image (in PRF pixel units)
if status == 0:
prfY0 = (shape(prf)[0] - prfDimY) / 2
prfX0 = (shape(prf)[1] - prfDimX) / 2
# initial guess for fit parameters
if status == 0:
guess = []
try:
f = fluxes.strip().split(',')
y = rows.strip().split(',')
x = columns.strip().split(',')
for i in xrange(len(f)):
f[i] = float(f[i]) * np.nanmax(flux)
except:
f = fluxes
y = rows
x = columns
for i in xrange(len(f)):
try:
guess.append(float(f[i]))
except:
message = 'ERROR -- KEPPRF: Fluxes must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
for i in xrange(len(y)):
try:
guess.append((float(y[i]) - datCenY) / cdelt2p[0])
except:
message = 'ERROR -- KEPPRF: Rows must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
for i in xrange(len(x)):
try:
guess.append((float(x[i]) - datCenX) / cdelt1p[0])
except:
message = 'ERROR -- KEPPRF: Columns must be floating point numbers'
status = kepmsg.err(logfile,message,verbose)
if status == 0:
if len(x) != len(y) or len(x) != len(f):
message = 'ERROR -- KEPFIT:FITMULTIPRF: Guesses for rows, columns and '
message += 'fluxes must have the same number of sources'
status = kepmsg.err(logfile,message,verbose)
# fit input image with model
if status == 0:
f = []
x = []
y = []
nsrc = len(guess) / 3
args = (imgflux,prf,cdelt1p[0],cdelt2p[0],prfDimY,prfDimX,prfY0,prfX0,
interpolation,verbose)
if type == '2D' and nsrc == 1:
ans = fmin_powell(kepfunc.kepler_prf_2d,guess,args=args,xtol=tolerance,
ftol=ftol,disp=False)
f.append(ans[0])
y.append(ans[1])
x.append(ans[2])
elif type == '1D' and nsrc == 1:
guess.insert(0,guess[0])
ans = fmin_powell(kepfunc.kepler_prf_1d,guess,args=args,xtol=tolerance,
ftol=ftol,disp=False)
f.append((ans[0] + ans[1]) / 2)
y.append(ans[2])
x.append(ans[3])
else:
ans = fmin_powell(kepfunc.kepler_multi_prf_2d,guess,args=args,xtol=tolerance,
ftol=ftol,disp=False)
for i in xrange(nsrc):
f.append(ans[i])
y.append(ans[nsrc+i])
x.append(ans[nsrc*2+i])
# calculate best-fit model
if status == 0:
prfMod = np.zeros((prfDimY+1,prfDimX+1))
for i in xrange(nsrc):
prfTmp = shift(prf,[y[i],x[i]],order=1,mode='constant')
prfTmp = prfTmp[prfY0:prfY0+prfDimY,prfX0:prfX0+prfDimX]
prfMod = prfMod + prfTmp * f[i]
prfFit = rebin2D(prfMod,[np.shape(imgflux)[0],np.shape(imgflux)[1]],
interpolation,True,False) / cdelt1p[0] / cdelt2p[0]
# calculate residual between data and model
if status == 0:
prfRes = imgflux - prfFit
# convert PRF pixels sizes to CCD pixel sizes
if status == 0:
for i in xrange(nsrc):
y[i] = y[i] * cdelt1p[0] + datCenY
x[i] = x[i] * cdelt2p[0] + datCenX
return f, y, x, prfMod, prfFit, prfRes