-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPhotometry.py
executable file
·1371 lines (1263 loc) · 58.7 KB
/
Photometry.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
#################################################################
# Name: Photometry.py #
# Author: Yuan Qi Ni #
# Version: August 25, 2016 #
# Function: Program contains functions that perform essential #
# photometric tasks. #
#################################################################
#essential modules
import numpy as np
#maximum fev for curve_fit
maxfev = 1000
#class: exception to clarify cause of crash as missing object in image
class MissingError(Exception):
def __init__(self, value):
#value is error message
self.value = value
def __str__(self):
#set error message as value
return repr(self.value)
#function: distance metric on images
def dist(x1, y1, x2, y2):
#Euclidean distance
return np.sqrt(np.square(x1-x2)+np.square(y1-y2))
#function: photometric aperture at (x0,y0) from r1 to r2
def ap_get(image, x0, y0, r1, r2):
#limits of subimage
xl = int(np.floor(max([0,x0-r2])))
xu = int(np.ceil(min(image.shape[1],x0+r2+1)))
yl = int(np.floor(max([0,y0-r2])))
yu = int(np.ceil(min(image.shape[0],y0+r2+1)))
#extract subimage
subimage = image[yl:yu, xl:xu]
xaxis = np.arange(xl, xu, dtype=int)
yaxis = np.arange(yl, yu, dtype=int)
x, y = np.meshgrid(xaxis, yaxis)
#find in aperture
inap = np.logical_and(dist(x0,y0,x,y)<=r2, dist(x0,y0,x,y)>=r1)
#mask out not in aperture
mask = np.logical_not(inap)
api = np.ma.MaskedArray(subimage, mask).compressed()
apx = np.ma.MaskedArray(x, mask).compressed()
apy = np.ma.MaskedArray(y, mask).compressed()
return api, apx, apy
#function: photometric aperture around multiple sources from r1 to r2
def ap_multi(image, x0, y0, fitsky, r1, r2):
if hasattr(x0, '__iter__'):
Nobj = len(x0)
if not hasattr(r1, '__iter__'):
r1 = [r1]*Nobj
if not hasattr(r2, '__iter__'):
r2 = [r2]*Nobj
else:
Nobj = 1
x0 = [x0]
y0 = [y0]
fitsky = [fitsky]
r1 = [r1]
r2 = [r2]
#limits of subimage
xl = int(np.floor(max([0,min(x0)-max(r2)])))
xu = int(np.ceil(min(image.shape[1],max(x0)+max(r2)+1)))
yl = int(np.floor(max([0,min(y0)-max(r2)])))
yu = int(np.ceil(min(image.shape[0],max(y0)+max(r2)+1)))
#extract subimage
subimage = image[yl:yu, xl:xu]
xaxis = np.arange(xl, xu, dtype=int)
yaxis = np.arange(yl, yu, dtype=int)
x, y = np.meshgrid(xaxis, yaxis)
#find in any aperture
inap = np.zeros(subimage.shape)
exap = np.zeros(subimage.shape)
for i in range(Nobj):
if fitsky[i] or i == 0:
inap = np.logical_or(inap, dist(x0[i],y0[i],x,y)<=r2[i])
#exclusive radius
exap = np.logical_or(exap, dist(x0[i],y0[i],x,y)<r1[i])
#mask out not in aperture
mask = np.logical_or(np.logical_not(inap), exap)
api = np.ma.MaskedArray(subimage, mask).compressed()
apx = np.ma.MaskedArray(x, mask).compressed()
apy = np.ma.MaskedArray(y, mask).compressed()
return api, apx, apy
#function: clean out cosmic rays and junk from PSF
def PSFclean(x,y,psf,ref,skyN=None,sat=40000,fu=10,fl=10):
#remove saturated pixels
mask = psf<sat
#if the source is saturated, remove bleeding
satmask = np.logical_not(mask)
if np.sum(satmask) > 5:
#find centroid of saturation
x_sat = np.mean(x[satmask])
y_sat = np.mean(y[satmask])
#remove vertical bleeding within 2 pixels
x_mask = np.logical_or(x<x_sat-2, x>x_sat+2)
xy_mask = np.logical_or(x_mask, y<y_sat-2)
mask = np.logical_and(mask, xy_mask)
#discard pixels based on fit noise
if skyN is not None:
#remove pixels that are 10sigma below or above fit (dead? hot?)
mask1 = psf-ref<fu*np.sqrt(np.absolute(ref)+skyN**2)
mask = np.logical_and(mask, mask1)
mask1 = ref-psf<fl*np.sqrt(np.absolute(ref)+skyN**2)
mask = np.logical_and(mask, mask1)
#remove pixels that are a result of masking
mask1 = np.absolute(psf) > 2e-30
mask = np.logical_and(mask, mask1)
return x[mask], y[mask], psf[mask]
#function: measure saturation level of CCD
def satpix(image):
#Make histogram of pixel values
ns, bins = np.histogram(image, bins=100)
bins = (bins[1:]-bins[:-1])/2.0 + bins[:-1]
#Half of max pixel value
half = bins[-1]/2.0
mask = bins > half
#Determine pixel full well capacity
full = bins[mask][np.argmax[ns[mask]]]
#Return saturation level
return full/2.0
#function: get best aperture for sky
def choose_an(image, x0, y0, fitsky, fwhm, sat=40000.0, large=False):
if hasattr(x0, '__iter__'):
Nobj = len(x0)
else:
Nobj = 1
x0 = [x0]
y0 = [y0]
fitsky = [fitsky]
#get background sky annulus
annulus1, x1, y1 = ap_multi(image, x0, y0, fitsky, 4*fwhm, 5*fwhm)
annulus2, x2, y2 = ap_multi(image, x0, y0, fitsky, 5*fwhm, 6*fwhm)
annulus3, x3, y3 = ap_multi(image, x0, y0, fitsky, 6*fwhm, 7*fwhm)
annulus4, x4, y4 = ap_multi(image, x0, y0, fitsky, 7*fwhm, 10*fwhm)
annulus5, x5, y5 = ap_multi(image, x0, y0, fitsky, 10*fwhm, 12*fwhm)
xs = [x1,x2,x3,x4,x5]
ys = [y1,y2,y3,y4,y5]
annuli = [annulus1, annulus2, annulus3, annulus4, annulus5]
colors = ['m','r','y','g','b']
#check all annuli
B = np.zeros(len(annuli))
for i in range(len(annuli)):
#clean saturated pixels
xs[i], ys[i], annuli[i] = PSFclean(xs[i],ys[i],annuli[i],annuli[i],sat=sat)
#get first estimate mean background value
B[i] = np.mean(np.absolute(annuli[i]))
#pick annulus with lowest background
lowest = np.argmin(B)
outer = lowest == 4 or lowest == 3
#large aperture needed or source photometry needs to accomodate
if large or (Nobj > 1 and outer):
annulus6, x6, y6 = ap_multi(image, x0, y0, fitsky, 12*fwhm, 14*fwhm)
annulus7, x7, y7 = ap_multi(image, x0, y0, fitsky, 14*fwhm, 16*fwhm)
annulus8, x8, y8 = ap_multi(image, x0, y0, fitsky, 16*fwhm, 18*fwhm)
annulus9, x9, y9 = ap_multi(image, x0, y0, fitsky, 18*fwhm, 20*fwhm)
annulus10, x10, y10 = ap_multi(image, x0, y0, fitsky, 20*fwhm, 22*fwhm)
xl = [x6,x7,x8,x9,x10]
yl = [y6,y7,y8,y9,y10]
annulil = [annulus6, annulus7, annulus8, annulus9, annulus10]
colorl = ['c', 'c', 'c', 'c', 'c']
#check all annuli
Bl = np.zeros(len(annulil))
for i in range(len(annulil)):
#clean saturated pixels
xl[i], yl[i], annulil[i] = PSFclean(xl[i],yl[i],annulil[i],annulil[i],sat=sat)
#get first estimate mean background value
Bl[i] = np.mean(np.absolute(annulil[i]))
B = np.concatenate([B, Bl])
xs = xs + xl
ys = ys + yl
annuli = annuli + annulil
colors = colors + colorl
lowest = np.argmin(B)
skyB, skyi, skyx, skyy = B[lowest], annuli[lowest], xs[lowest], ys[lowest]
color = colors[lowest]
return skyi, skyx, skyy, skyB, color
#function: fits background sky plane and noise
def SkyFit(image, x0, y0, fitsky, fwhm=5.0, sat=40000.0, verbosity=0, large=False):
#update 180610: x0, y0 need to be lists (even if length is 1)
from scipy.optimize import curve_fit
from PSFlib import D2plane
from MagCalc import PSFError
if hasattr(x0, '__iter__'):
Nobj = len(x0)
else:
Nobj = 1
x0 = [x0]
y0 = [y0]
fitsky = [fitsky]
skyi, skyx, skyy, skyB, color = choose_an(image, x0, y0, fitsky, fwhm, sat, large=large)
#fit sky background
try:
skypopt, skypcov = curve_fit(D2plane, (skyx, skyy), skyi, p0=[0,0,skyB], maxfev=maxfev, absolute_sigma=True)
#Fit function
skyTheo = D2plane((skyx,skyy),*skypopt)
skyN = np.std(skyi-skyTheo)
#filter out noisy pixels at 5sigma level (star)
skyx, skyy, skyi = PSFclean(skyx,skyy,skyi,skyTheo,skyN,sat,fu=2, fl=1000)
#calculate better fit from cleaner data
skypopt, skypcov = curve_fit(D2plane, (skyx, skyy), skyi, p0=skypopt, maxfev=maxfev, absolute_sigma=True)
#Fit function
skyTheo = D2plane((skyx,skyy),*skypopt)
skyN = np.std(skyi-skyTheo)
#filter out noisy pixels at 5sigma level (cosmic rays/hot pix)
skyx, skyy, skyi = PSFclean(skyx,skyy,skyi,skyTheo,skyN,sat,fu=2, fl=2)
if any(fitsky):
#calculate better fit from cleaner data
skypopt, skypcov = curve_fit(D2plane, (skyx, skyy), skyi, p0=skypopt, maxfev=maxfev, absolute_sigma=True)
try:
#try to calculate fit error
skyperr = np.sqrt(np.diag(skypcov))
except:
#fit error uncalculable
try:
#take closer initial conditions, try again
skypopt, skypcov = curve_fit(D2plane, (skyx, skyy), skyi, p0=skypopt, maxfev=maxfev, absolute_sigma=True)
skyperr = np.sqrt(np.diag(skypcov))
except:
#fit error really is uncalculable, how???
raise PSFError('Unable to fit sky.')
else:
skypopt = np.array([0,0,0])
skyperr = np.array([0,0,0])
#calculate sky noise near source
skyTheo = D2plane((skyx,skyy),*skypopt)
skyN = np.std(skyi-skyTheo)
#calculate goodness of fit
skyX2dof = np.square((skyi-skyTheo)/skyN)/(len(skyi)-3)
if verbosity > 1:
import matplotlib.pyplot as plt
I_t = np.copy(image)
x1, x2 = min(skyx),max(skyx)+1
y1, y2 = min(skyy),max(skyy)+1
for i in np.arange(x1, x2):
for j in np.arange(y1, y2):
I_t[j][i] = D2plane((i, j),*skypopt)
print "Plotting sky planar fit residual"
print "Plotting image at x:", x1, x2
print "Plotting image at y:", y1, y2
sb = image[y1:y2,x1:x2]-I_t[y1:y2,x1:x2]
sbmax = 5*skyN
sbmin = -5*skyN
plt.title("Sky planar fit residual")
plt.imshow(sb, cmap='Greys',vmax=sbmax,vmin=sbmin)
plt.colorbar()
plt.scatter(skyx-x1, skyy-y1, c=color, marker='.')
plt.scatter(np.array(x0, dtype=int)-x1, np.array(y0, dtype=int)-y1, color='r', marker='.')
plt.show()
except:
#catastrophic failure of sky plane fitting, How???
raise PSFError('Sky fitting catastrophic failure.')
if verbosity > 0:
print "sky plane fit parameters"
print "[a, b, c] = "+str(skypopt)
print "errors = "+str(skyperr)
print "Noise = "+str(skyN)
#return sky plane, sky noise, and goodness of fit
return skypopt, skyperr, skyX2dof, skyN
#function: extracts PSF from source
def PSFextract(image, x0, y0, fwhm=5.0, fitsky=True, sat=40000.0, verbosity=0):
from scipy.optimize import curve_fit
from PSFlib import D2plane, E2moff, E2moff_toFWHM, E2moff_verify
#fit sky background in an annulus
skypopt, skyperr, skyX2dof, skyN = SkyFit(image, [x0], [y0], [fitsky], fwhm, sat, verbosity)
#get fit box to fit psf
fsize = 1
intens, x, y = ap_get(image, x0, y0, 0, fsize*fwhm)
if len(intens) == 0 or intens.sum() == 0:
raise MissingError('Ref star at ('+str(x0)+','+str(y0)+') not in image')
#get an approximate fix on position
x0 = np.sum(intens*x)/intens.sum()
y0 = np.sum(intens*y)/intens.sum()
#get centered fit box
fsize = 3
intens, x, y = ap_get(image, x0, y0, 0, fsize*fwhm)
if len(intens) == 0 or intens.sum() == 0:
raise MissingError('Ref star at ('+str(x0)+','+str(y0)+') not in image')
#get an approximate fix on position
x0 = np.sum(intens*x)/intens.sum()
y0 = np.sum(intens*y)/intens.sum()
#get centered fit box
fsize = 3
intens, x, y = ap_get(image, x0, y0, 0, fsize*fwhm)
#filter out saturated pixels
x, y, intens = PSFclean(x,y,intens,intens,skyN,sat,10,10)
if fitsky:
#get sky background
sky = D2plane((x,y),*skypopt)
#subtract sky background
intens = intens - sky
#filter out saturated pixels
#x, y, intens = PSFclean(x,y,intens,intens,skyN,sat,10,10)
try:
#fit 2d psf to background subtracted source light
est = [image[int(y0)][int(x0)],fwhm/4.0,fwhm,3.0,120.0,x0,y0]
bounds = ([-float("Inf"),0.01,0.01,1.01,-float("Inf"),0.0,0.0],[float("Inf"),5*fwhm,5*fwhm,float("Inf"),float("Inf"),image.shape[1],image.shape[0]])
PSFpopt, PSFpcov = curve_fit(E2moff, (x, y), intens, sigma=np.sqrt(np.absolute(intens)+skyN**2), p0=est, bounds=bounds, absolute_sigma=True, maxfev=maxfev)
#DONT FLAG COSMICS IN PSFEXTRACT, will break moffat function.
#Fit function
#I_theo = E2moff((x,y),*PSFpopt)
#filter out noisy pixels at 5sigma level (cos rays/hot pix)
#x, y, intens = PSFclean(x,y,intens,I_theo,skyN,sat,10)
#calculate better PSF from cleaner data
#PSFpopt, PSFpcov = curve_fit(E2moff, (x, y), intens, sigma=np.sqrt(np.absolute(intens)+skyN**2) , p0=PSFpopt, bounds=bounds, absolute_sigma=True, maxfev=maxfev)
try:
#try to calculate fit error
PSFperr = np.sqrt(np.diag(PSFpcov))
except:
try:
#take closer initial conditions
PSFpopt, PSFpcov = curve_fit(E2moff, (x, y), intens, sigma=np.sqrt(np.absolute(intens)+skyN**2) , p0=PSFpopt, bounds=bounds, absolute_sigma=True, maxfev=maxfev)
PSFperr = np.sqrt(np.diag(PSFpcov))
except:
PSFperr = [0]*5
#calculate goodness of fit
I_theo = E2moff((x, y),*PSFpopt)
X2dof = np.sum(np.square((intens-I_theo)/np.sqrt(np.absolute(intens)+skyN**2)))/(len(intens)-len(PSFpopt))
except:
#catastrophic failure of PSF fitting
print "PSF fitting catastrophic failure"
PSFpopt = [0]*7
PSFperr = [0]*7
X2dof = 0
#get values from fit
A = PSFpopt[0]
ax = abs(PSFpopt[1])
ay = abs(PSFpopt[2])
b = PSFpopt[3]
theta = PSFpopt[4] % 180
X0 = PSFpopt[5]
Y0 = PSFpopt[6]
PSFpopt = [A, ax, ay, b, theta, X0, Y0]
FWHMx, FWHMy = E2moff_toFWHM(ax, ay, b)
if verbosity > 0:
print "PSF moffat fit parameters"
print "[A,ax,ay,b,theta,X0,Y0] = "+str(PSFpopt)
print "parameter errors = "+str(PSFperr)
print "Chi2 = "+str(X2dof)
print "[FWHMx', FWHMy]' = "+str([FWHMx, FWHMy])
#graph fits if verbosity is high enough
if verbosity > 1:
PSF_plot(image, x0, y0, PSFpopt, X2dof, skypopt, skyN, fitsky, fsize*fwhm)
#check, if fit is ridiculous or noise object: give no fit
if E2moff_verify(PSFpopt, x0, y0):
return PSFpopt, PSFperr, X2dof, skypopt, skyN
else:
return [0]*7, [0]*7, 0, [0]*3, skyN
#function: fits PSF to source
def PSFfit(image, PSF, PSFerr, x0, y0, fitsky=True, sat=40000.0, verbosity=0):
from scipy.optimize import curve_fit
from PSFlib import D2plane, E2moff, E2moff_toFWHM, E2moff_verify
#get given fit parameters
ax, axerr = PSF[0], PSFerr[0]
ay, ayerr = PSF[1], PSFerr[1]
b, berr = PSF[2], PSFerr[2]
theta, thetaerr = PSF[3], PSFerr[3]
FWHMx, FWHMy = E2moff_toFWHM(ax, ay, b)
fwhm = max(FWHMx, FWHMy)
#fit sky background in an annulus
skypopt, skyperr, skyX2dof, skyN = SkyFit(image, [x0], [y0], [fitsky], fwhm, sat, verbosity)
#get fit box to fit psf
fsize = 3
intens, x, y = ap_get(image, x0, y0, 0, fsize*fwhm)
#get an approximate fix on position
x0 = np.sum(intens*x)/intens.sum()
y0 = np.sum(intens*y)/intens.sum()
#get centered fit box
intens, x, y = ap_get(image, x0, y0, 0, fsize*fwhm)
#filter out saturated pixels
x, y, intens = PSFclean(x,y,intens,intens,skyN,sat,10,10)
if fitsky:
#get sky background
sky = D2plane((x,y),*skypopt)
#subtract sky background
intens = intens - sky
#filter out saturated pixels
#x, y, intens = PSFclean(x,y,intens,intens,skyN,sat,10,10)
try:
#fit 2d fixed psf to background subtracted source light
est = [image[int(y0)][int(x0)],x0,y0]
bounds = ([-float("Inf"),0,0],[float("Inf"),image.shape[1],image.shape[0]])
fitpopt, fitpcov = curve_fit(lambda (x, y),A,x0,y0: E2moff((x, y),A,ax,ay,b,theta,x0,y0), (x,y), intens, sigma=np.sqrt(np.absolute(intens)+skyN**2), p0=est, bounds=bounds, absolute_sigma=True, maxfev=maxfev)
#parameters fitted to source
A = fitpopt[0]
X0 = fitpopt[1]
Y0 = fitpopt[2]
PSFpopt = [A,ax,ay,b,theta,X0,Y0]
#Fit function
I_theo = E2moff((x,y),*PSFpopt)
#filter out noisy pixels at 5sigma level (cos rays/hot pix)
x, y, intens = PSFclean(x,y,intens,I_theo,skyN,sat,10,10)
#calculate better PSF from cleaner data
fitpopt, fitpcov = curve_fit(lambda (x, y),A,x0,y0: E2moff((x, y),A,ax,ay,b,theta,X0,Y0), (x,y), intens, sigma=np.sqrt(np.absolute(intens)+skyN**2), p0=fitpopt, bounds=bounds, absolute_sigma=True, maxfev=maxfev)
try:
#try to calculate fit error
fitperr = np.sqrt(np.diag(fitpcov))
except:
try:
#take closer initial conditions
fitpopt, fitpcov = curve_fit(lambda (x, y),A,x0,y0: E2moff((x, y),A,ax,ay,b,theta,x0,y0), (x,y), intens, sigma=np.sqrt(np.absolute(intens)+skyN**2), p0=fitpopt, bounds=bounds, absolute_sigma=True, maxfev=maxfev)
fitperr = np.sqrt(np.diag(fitpcov))
except:
fitperr = [0]*3
#parameters fitted to source
A, Aerr = fitpopt[0], fitperr[0]
X0, X0err = fitpopt[1], fitperr[1]
Y0, Y0err = fitpopt[2], fitperr[2]
PSFpopt = [A,ax,ay,b,theta,X0,Y0]
PSFperr = [Aerr,axerr,ayerr,berr,thetaerr,X0err,Y0err]
#calculate goodness of fit
I_theo = E2moff((x, y),*PSFpopt)
X2dof = np.sum(np.square((intens-I_theo)/np.sqrt(np.absolute(intens)+skyN**2)))/(len(intens)-len(fitpopt))
except:
#catastrophic failure of PSF fitting
print "PSF fitting catastrophic failure"
PSFpopt = [0]*7
PSFperr = [0]*7
X2dof = 0
if verbosity > 0:
print "PSF moffat fit parameters"
print "[A,ax,ay,b,theta,X0,Y0] = "+str(PSFpopt)
print "parameter errors = "+str(PSFperr)
print "Chi2 = "+str(X2dof)
print "[FWHMx', FWHMy]' = "+str([FWHMx, FWHMy])
#graph fits if verbosity is high enough
if verbosity > 1:
PSF_plot(image, x0, y0, PSFpopt, X2dof, skypopt, skyN, fitsky, fsize*fwhm)
"""
#diagnostic image
import matplotlib.pyplot as plt
I_t = np.copy(image)
x1, x2 = min(x)-10,max(x)+11
y1, y2 = min(y)-10,max(y)+11
for i in np.arange(x1, x2):
for j in np.arange(y1, y2):
I_t[j][i] = D2plane((i, j),*skypopt)
print "Plotting sky planar fit residual"
print "Plotting image at x:", x1, x2
print "Plotting image at y:", y1, y2
sb = image[y1:y2,x1:x2]-I_t[y1:y2,x1:x2]
sbmax = np.mean(sb)
sbmin = -skyN
plt.title("Sky planar fit residual")
plt.imshow(sb, cmap='Greys',vmax=sbmax,vmin=sbmin)
plt.colorbar()
plt.scatter(x-x1, y-y1, c='b', marker='.')
plt.scatter(np.array(x0, dtype=int)-x1, np.array(y0, dtype=int)-y1, color='r', marker='.')
plt.show()
"""
#check if fit is ridiculous
if E2moff_verify(PSFpopt, x0, y0):
#not ridiculous, give back fit
return PSFpopt, PSFperr, X2dof, skypopt, skyN
else:
return [0]*7, [0]*7, 0, [0]*3, skyN
#function: scales PSF to source location
def PSFscale(image, PSF, PSFerr, x0, y0, fitsky=True, sat=40000.0, verbosity=0):
from scipy.optimize import curve_fit
from PSFlib import D2plane, E2moff, E2moff_toFWHM, E2moff_verify
#get given fit parameters
ax, axerr = PSF[0], PSFerr[0]
ay, ayerr = PSF[1], PSFerr[1]
b, berr = PSF[2], PSFerr[2]
theta, thetaerr = PSF[3], PSFerr[3]
FWHMx, FWHMy = E2moff_toFWHM(ax, ay, b)
fwhm = max(FWHMx, FWHMy)
#fit sky background in an annulus
skypopt, skyperr, skyX2dof, skyN = SkyFit(image, [x0], [y0], [fitsky], fwhm, sat, verbosity)
#get fit box to fit psf
fsize = 3
intens, x, y = ap_get(image, x0, y0, 0, fsize*fwhm)
#filter out saturated pixels
x, y, intens = PSFclean(x,y,intens,intens,skyN,sat,10,10)
if fitsky:
#get sky background
sky = D2plane((x,y),*skypopt)
#subtract sky background
intens = intens - sky
try:
#fit 2d fixed psf to background subtracted source light
est = [image[int(y0)][int(x0)]]
fitpopt, fitpcov = curve_fit(lambda (x, y),A: E2moff((x, y),A,ax,ay,b,theta,x0,y0), (x,y), intens, sigma=np.sqrt(np.absolute(intens)+skyN**2), p0=est, absolute_sigma=True, maxfev=maxfev)
#parameters fitted to source
PSFpopt = [fitpopt[0],ax,ay,b,theta,x0,y0]
#Fit function
I_theo = E2moff((x,y),*PSFpopt)
#filter out noisy pixels at 5sigma level (cos rays/hot pix)
x, y, intens = PSFclean(x,y,intens,I_theo,skyN,sat,10,10)
#calculate better PSF from cleaner data
fitpopt, fitpcov = curve_fit(lambda (x, y),A: E2moff((x, y),A,ax,ay,b,theta,x0,y0), (x,y), intens, sigma=np.sqrt(np.absolute(intens)+skyN**2), p0=fitpopt, absolute_sigma=True, maxfev=maxfev)
try:
#try to calculate fit error
fitperr = np.sqrt(np.diag(fitpcov))
except:
try:
#take closer initial conditions
fitpopt, fitpcov = curve_fit(lambda (x, y),A: E2moff((x, y),A,ax,ay,b,theta,x0,y0), (x,y), intens, sigma=np.sqrt(np.absolute(intens)+skyN**2), p0=fitpopt, absolute_sigma=True, maxfev=maxfev)
fitperr = np.sqrt(np.diag(fitpcov))
except:
fitperr = [0]
#parameters fitted to source
A, Aerr = fitpopt[0], fitperr[0]
PSFpopt = [A,ax,ay,b,theta,x0,y0]
PSFperr = [Aerr,axerr,ayerr,berr,thetaerr,0,0]
#calculate goodness of fit
I_theo = E2moff((x, y),*PSFpopt)
X2dof = np.sum(np.square((intens-I_theo)/np.sqrt(np.absolute(intens)+skyN**2)))/(len(intens)-len(fitpopt))
except:
#catastrophic failure of PSF fitting
print "PSF fitting catastrophic failure"
PSFpopt = [0]*7
PSFperr = [0]*7
X2dof = 0
if verbosity > 0:
print "PSF moffat fit parameters"
print "[A,ax,ay,b,theta,X0,Y0] = "+str(PSFpopt)
print "parameter errors = "+str(PSFperr)
print "Chi2 = "+str(X2dof)
print "[FWHMx', FWHMy]' = "+str([FWHMx, FWHMy])
#graph fits if verbosity is high enough
if verbosity > 1:
PSF_plot(image, x0, y0, PSFpopt, X2dof, skypopt, skyN, fitsky, fsize*fwhm)
#check if fit is ridiculous, give back no fit
if E2moff_verify(PSFpopt, x0, y0):
return PSFpopt, PSFperr, X2dof, skypopt, skyN
else:
return [0]*7, [0]*7, 0, [0]*3, skyN
#function: fit multiple PSFs
def PSFmulti(image, PSF, PSFerr, psftype, x0, y0, fitsky, sat=40000.0, fsize=3, infile=None, outfile=None, verbosity=0):
from scipy.optimize import curve_fit
from PSFlib import D2plane, E2moff_multi, E2moff_toFWHM, E2moff_verify, PSFlen, PSFparams, Mdist
maxfev = 100000000
#get given fit parameters
ax, axerr = PSF[0], PSFerr[0]
ay, ayerr = PSF[1], PSFerr[1]
b, berr = PSF[2], PSFerr[2]
theta, thetaerr = PSF[3], PSFerr[3]
FWHMx, FWHMy = E2moff_toFWHM(ax, ay, b)
fwhm = max(FWHMx, FWHMy)
#number of objects
Nobj = len(psftype)
#get fit box (around all sources) to multi-fit psf
intens, x, y = ap_multi(image, x0, y0, [1]*Nobj, 0, fsize*fwhm)
#sky fitting
large = False
for psfi in psftype:
if psfi == 'cn' or psfi == 'sn':
large = True
#fit sky background in an annulus
skypopt, skyperr, skyX2dof, skyN = SkyFit(image, x0, y0, fitsky, fwhm, sat, verbosity, large=large)
#filter out saturated pixels
x, y, intens = PSFclean(x,y,intens,intens,skyN,sat,10,10)
if fitsky[0]:
#get sky background
sky = D2plane((x,y),*skypopt)
#subtract sky background
intens = intens - sky
#filter out saturated pixels
#x, y, intens = PSFclean(x,y,intens,intens,skyN,sat,10,10)
#given, estimate free parameters, upper lower bounds
given = []
est = []
estnames = []
lbounds, ubounds = [], []
for i in range(Nobj):
if psftype[i] == '3':
#given is empty, general psf params are all in free
given.append([])
est = np.concatenate((est,[image[int(y0[i])][int(x0[i])],fwhm/4.0,fwhm,4.0,120.0,x0[i],y0[i]]))
lbounds = np.concatenate((lbounds,[-float("Inf"),0.01,0.01,1.01,-float("Inf"),0.0,0.0]))
ubounds = np.concatenate((ubounds,[float("Inf"),8*fwhm,8*fwhm,float("Inf"),float("Inf"),image.shape[1],image.shape[0]]))
estnames = np.concatenate((estnames,[str(i)+namei for namei in PSFparams(psftype[i])]))
if psftype[i] == '2':
#given contains [ax,ay,b,theta], free has [A, x0, y0]
given.append(PSF)
est = np.concatenate((est,[image[int(y0[i])][int(x0[i])],x0[i],y0[i]]))
lbounds = np.concatenate((lbounds,[-float("Inf"),0.0,0.0]))
ubounds = np.concatenate((ubounds,[float("Inf"),image.shape[1],image.shape[0]]))
estnames = np.concatenate((estnames,[str(i)+namei for namei in PSFparams(psftype[i])]))
if psftype[i] == '1':
#given contains [ax,ay,b,theta,x0,y0], free has [A]
given.append([PSF[0],PSF[1],PSF[2],PSF[3],x0[i],y0[i]])
est = np.concatenate((est,[image[int(y0[i])][int(x0[i])]]))
lbounds = np.concatenate((lbounds,[-float("Inf")]))
ubounds = np.concatenate((ubounds,[float("Inf")]))
estnames = np.concatenate((estnames,[str(i)+namei for namei in PSFparams(psftype[i])]))
if psftype[i][0] == 's':
Iest = np.mean(ap_get(image, x0[i], y0[i], 0, fwhm))
if psftype[i][1] == 'n':
#given is empty, general Sersic params are all in free
given.append([])
est = np.concatenate((est,[Iest,fwhm,4.0,x0[i],y0[i],0.0,120.0]))
#est = np.concatenate((est,[Iest,fwhm,4.0,x0[i],y0[i],0.6,30.0]))
#est = np.concatenate((est,[0.5*Iest,fwhm,4.0,x0[i],y0[i],0.3,40.0]))
"""
#e.g., for N247_2017cv
if i==0:
est = np.concatenate((est,[0.5*Iest,2*fwhm,4.0,x0[i],y0[i],0.6,40.0]))
elif i==1:
est = np.concatenate((est,[0.5*Iest,2*fwhm,4.0,x0[i],y0[i],0.0,40.0]))
#e.g., for E149_2017gp
if i==0:
est = np.concatenate((est,[0.01*Iest,4*fwhm,4.0,x0[i],y0[i],0.7,14.0]))
elif i==1:
est = np.concatenate((est,[0.1*Iest,fwhm,4.0,x0[i],y0[i],0.5,12.0]))
#e.g., for ZN7314_2021D
if i==0:
est = np.concatenate((est,[Iest,1.5*fwhm,3.0,x0[i],y0[i],0.52,170.0]))
if i==1:
est = np.concatenate((est,[-Iest,fwhm,1.0,x0[i],y0[i],0.55,170.0]))
#e.g., for N300_2017cz needed better tuning of initial params
if i==0:
est = np.concatenate((est,[0.1*Iest,1.5*fwhm,0.5,x0[i],y0[i],0.3,25.0]))
elif i==1:
est = np.concatenate((est,[Iest,0.5*fwhm,1.0,x0[i],y0[i],0.6,70.0]))
elif i==2:
est = np.concatenate((est,[Iest,fwhm,1.0,x0[i],y0[i],0.8,130.0]))
"""
lbounds = np.concatenate((lbounds,[-float("Inf"),0.0001,0.0001,0.0,0.0,-0.99,-float("Inf")]))
ubounds = np.concatenate((ubounds,[float("Inf"),float("Inf"),float("Inf"),image.shape[1],image.shape[0],0.99,float("Inf")]))
estnames = np.concatenate((estnames,[str(i)+namei for namei in PSFparams(psftype[i])]))
elif psftype[i][-1] == 'f': #check for fixed position
#given contains [x0, y0], free has [Ie]
given.append([x0[i], y0[i]])
est = np.concatenate((est, [Iest]))
"""
#for ZN7314_2021D
if i == 1:
est = np.concatenate((est, [0.5*Iest]))
elif i == 2:
est = np.concatenate((est, [-0.5*Iest]))
"""
lbounds = np.concatenate((lbounds,[-float("Inf")]))
ubounds = np.concatenate((ubounds,[float("Inf")]))
estnames = np.concatenate((estnames,[str(i)+namei for namei in PSFparams(psftype[i])]))
else:
#given is empty, Sersic n is fixed
given.append([])
est = np.concatenate((est,[Iest,x0[i],y0[i]]))
"""
#for ZN7314_2021D
if i == 1:
est = np.concatenate((est,[0.5*Iest,x0[i],y0[i]]))
elif i == 2:
est = np.concatenate((est,[-0.5*Iest,x0[i],y0[i]]))
"""
lbounds = np.concatenate((lbounds,[-float("Inf"),0.0,0.0]))
ubounds = np.concatenate((ubounds,[float("Inf"),image.shape[1],image.shape[0]]))
estnames = np.concatenate((estnames,[str(i)+namei for namei in PSFparams(psftype[i])]))
if psftype[i][0] == 'c':
Iest = np.mean(ap_get(image, x0[i], y0[i], 0, fwhm))
if psftype[i][1] == 'n':
#given is empty, general Sersic params are all in free
given.append([])
est = np.concatenate((est,[x0[i],y0[i],10*Iest,0.0,120.0,2*fwhm,4.0,0.2,0.1]))
lbounds = np.concatenate((lbounds,[0.0,0.0,0.0,-0.99,-float("Inf"),0.01,0.01,0.01,0.001]))
ubounds = np.concatenate((ubounds,[image.shape[1],image.shape[0],float("Inf"),0.99,float("Inf"),float("Inf"),50.0,0.99,0.99]))
estnames = np.concatenate((estnames,[str(i)+namei for namei in PSFparams(psftype[i])]))
elif psftype[i][-1] == 'f': #check for fixed position
#given contains [x0, y0], free has [Ie]
given.append([x0[i], y0[i]])
est = np.concatenate((est, [10*Iest]))
lbounds = np.concatenate((lbounds,[-float("Inf")]))
ubounds = np.concatenate((ubounds,[float("Inf")]))
estnames = np.concatenate((estnames,[str(i)+namei for namei in PSFparams(psftype[i])]))
else:
#given is empty, Sersic n is fixed
given.append([])
est = np.concatenate((est,[x0[i],y0[i],10*Iest]))
lbounds = np.concatenate((lbounds,[0.0,0.0,-float("Inf")]))
ubounds = np.concatenate((ubounds,[image.shape[1],image.shape[0],float("Inf")]))
estnames = np.concatenate((estnames,[str(i)+namei for namei in PSFparams(psftype[i])]))
if fitsky[0]==2:
skyflag = 1
#add to parameter arrays
given.append([])
est = np.concatenate((est, [0, 0, 0]))
lbounds = np.concatenate((lbounds,[-float("Inf"),-float("Inf"),-float("Inf")]))
ubounds = np.concatenate((ubounds,[float("Inf"),float("Inf"),float("Inf")]))
estnames = np.concatenate((estnames,['p'+namei for namei in PSFparams('p')]))
else:
skyflag = 0
estnames = np.array(estnames)
given = np.array(given)
bounds = (lbounds,ubounds)
#if there is an infile, replace est
if infile is not None:
if verbosity > 1:
print "Loading params"
prevest = np.loadtxt(infile+"v")
prevnames = np.loadtxt(infile+"n", dtype='str')
#replace est for same parameter names
for i, name in enumerate(estnames):
if name in prevnames:
est[i] = prevest[np.argwhere(prevnames == name)[0]]
if (outfile is not None) and verbosity > 1:
print "Saving params"
#annoying try/except structure, necessaary evil
try:
if verbosity > 1:
print "Initial fit"
#estimate errorbars
intens_err = np.sqrt(np.absolute(intens)+skyN**2)
if skyflag:
#weight closer to source of interest when flattening sky
#sigdist, sigrate = 3, 1 #1.5sig 1/2 point
#sigdist, sigrate = 1, 10 #fast and close, for nearby sources
dists = Mdist(x, y, x0[0], y0[0], ax, ay, theta)
#dists = Mdist(x, y, x0[0], y0[0], 5, 5, 0)
sigdist, sigrate = 1, 10
weights = 1./(1.+np.exp(-sigrate*(dists-sigdist))) #1.5sig 1/2 point
weights = 0.1+0.9*weights
intens_err = intens_err*weights
if verbosity > 1:
print "Fitting source weighted plane"
#first estimation of best fit, use LM for speed with no bounds
fitpopt, fitpcov = curve_fit(lambda (x, y),*free: E2moff_multi((x, y),psftype, PSF, given, free, skyflag=skyflag), (x,y), intens, sigma=intens_err, p0=est, absolute_sigma=True, maxfev=maxfev)
#record first set of parameters
if outfile is not None:
np.savetxt(outfile+"v", fitpopt)
np.savetxt(outfile+"n", estnames, fmt="%s")
if verbosity > 1:
print "Filtering outliers"
#Fit function
I_theo = E2moff_multi((x, y),psftype, PSF, given, fitpopt, skyflag=skyflag)
#filter out noisy pixels at 5sigma level (cos rays/hot pix)
x, y, intens = PSFclean(x,y,intens,I_theo,skyN,sat,10,10)
if verbosity > 1:
print "Second fit, with init:"
print fitpopt
if skyflag:
#get sky background
sky = D2plane((x,y),*fitpopt[-3:])
#subtract sky background
intens = intens - sky
skypopt = np.array(skypopt)+np.array(fitpopt[-3:])
#no longer fit sky
skyflag = 0
fitpopt = fitpopt[:-3]
lbounds = lbounds[:-3]
ubounds = ubounds[:-3]
estnames = estnames[:-3]
given = given[:-1]
bounds = (lbounds,ubounds)
if verbosity > 1:
print "Fitting plane-flattened image"
#re-estimate errorbars
intens_err = np.sqrt(np.absolute(intens)+skyN**2)
#calculate better PSF from cleaner data
fitpopt, fitpcov = curve_fit(lambda (x, y),*free: E2moff_multi((x, y),psftype, PSF, given, free, skyflag=skyflag), (x,y), intens, sigma=intens_err, p0=fitpopt, bounds=bounds, absolute_sigma=True, maxfev=maxfev)
try:
#try to calculate fit error
fitperr = np.sqrt(np.diag(fitpcov))
except:
try:
if verbosity > 1:
print "Re-fit to get errors, with init:"
print fitpopt
#take closer initial conditions
fitpopt, fitpcov = curve_fit(lambda (x, y),*free: E2moff_multi((x, y), psftype, PSF, given, free, skyflag=skyflag), (x,y), intens, sigma=intens_err, p0=fitpopt, bounds=bounds, absolute_sigma=True, maxfev=maxfev)
fitperr = np.sqrt(np.diag(fitpcov))
except:
fitperr = [0]*len(est)
#record final set of parameters as formatted data table
if outfile is not None:
outarray = np.zeros(fitpopt.size,
dtype=[('names', 'U6'), ('data', float)])
outarray['names'] = estnames
outarray['data'] = fitpopt
np.savetxt(outfile, outarray, fmt='%5s %16.5f')
#parameters fitted to source
PSFpopt, PSFperr = [], []
count = 0
for i in range(Nobj):
if psftype[i] == '3':
#given is empty, general psf params are all in free
fitpopt[count+4] = fitpopt[count+4] % 180.0
PSFpopt.append(fitpopt[count:count+7])
PSFperr.append(fitperr[count:count+7])
count = count+7
elif psftype[i] == '2':
#given contains [ax,ay,b,theta], free has [A, x0, y0]
PSFpopt.append([fitpopt[count],given[i][0],given[i][1],given[i][2],given[i][3],fitpopt[count+1],fitpopt[count+2]])
PSFperr.append([fitperr[count],axerr,ayerr,berr,thetaerr,fitperr[count+1],fitperr[count+2]])
count = count+3
elif psftype[i] == '1':
#given contains [ax,ay,b,theta,x0,y0], free has [A]
PSFpopt.append([fitpopt[count],given[i][0],given[i][1],given[i][2],given[i][3],given[i][4],given[i][5]])
PSFperr.append([fitperr[count],axerr,ayerr,berr,thetaerr,0,0])
count = count+1
elif psftype[i][0] == 's':
if psftype[i][1] == 'n':
#given is empty, general Sersic params are all in free
fitpopt[count+6] = fitpopt[count+6] % 180.0 #principle angle
PSFpopt.append(fitpopt[count:count+7])
PSFperr.append(fitperr[count:count+7])
count = count+7
elif psftype[i][-1] == 'f':
#given position, n must also be fixed
PSFpopt.append([fitpopt[count],given[i][0],given[i][1]])
PSFperr.append([fitperr[count],0,0])
count = count+1
else:
#given is empty, Sersic n is fixed
PSFpopt.append(fitpopt[count:count+3])
PSFperr.append(fitperr[count:count+3])
count = count+3
elif psftype[i][0] == 'c':
if psftype[i][1] == 'n':
fitpopt[count+4] = fitpopt[count+4] % 180.0 #principle angle
#given is empty, general Sersic params are all in free
PSFpopt.append(fitpopt[count:count+9])
PSFperr.append(fitperr[count:count+9])
count = count+9
elif psftype[i][-1] == 'f':
#given position, n must also be fixed
PSFpopt.append(list(given[i])+list([fitpopt[count]]))
PSFperr.append([0,0]+list([fitperr[count]]))
count = count+1
else:
#given is empty, Sersic n is fixed
PSFpopt.append(fitpopt[count:count+3])
PSFperr.append(fitperr[count:count+3])
count = count+3
#calculate goodness of fit
I_theo = E2moff_multi((x, y),psftype, PSF, given, fitpopt, skyflag=skyflag)
X2dof = np.sum(np.square((intens-I_theo)/np.sqrt(np.absolute(intens)+skyN**2)))/(len(intens)-len(fitpopt))
#Graph residual if verbosity is high enough
if verbosity > 1:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 3)
fig.set_figwidth(12)
#limits of subimage to show
x1, x2 = int(min(x0)-fsize*fwhm),int(max(x0)+fsize*fwhm)
y1, y2 = int(min(y0)-fsize*fwhm),int(max(y0)+fsize*fwhm)
#create subimage prediction
xi, yi = np.arange(x1,x2), np.arange(y1,y2)
xi, yi = np.meshgrid(xi,yi)
I_t = E2moff_multi((xi, yi), psftype, PSF, given, fitpopt, skyflag=skyflag) + D2plane((xi, yi),*skypopt)
#plot residual
print "Plotting image at x:", x1, x2
print "Plotting image at y:", y1, y2
sb = image[y1:y2,x1:x2]-I_t
sbmax = 5*skyN
sbmin = -5*skyN
ax[0].set_title("Multi-obj fit data")
ax[0].imshow(image[y1:y2,x1:x2], cmap='Greys',vmax=sbmax,vmin=sbmin)
ax[0].scatter(np.array(x0, dtype=int)-x1, np.array(y0, dtype=int)-y1, color='r', marker='.')
ax[1].set_title("Model")
ax[1].imshow(I_t, cmap='Greys',vmax=sbmax,vmin=sbmin)
ax[1].scatter(np.array(x0, dtype=int)-x1, np.array(y0, dtype=int)-y1, color='r', marker='.')
ax[2].set_title("Residual")
im = ax[2].imshow(sb, cmap='Greys',vmax=sbmax,vmin=sbmin)
ax[2].scatter(np.array(x0, dtype=int)-x1, np.array(y0, dtype=int)-y1, color='r', marker='.')
plt.tight_layout()
plt.show()
except ValueError:
#catastrophic failure of PSF fitting
print "x0 is infeasible after initial LM fit, try different x0."
print "Setting fit parameters to zero for now."
PSFpopt = [[0]*PSFlen(psfi) for psfi in psftype]
PSFperr = [[0]*PSFlen(psfi) for psfi in psftype]
skyflag = 0
X2dof = 0
except:
#catastrophic failure of PSF fitting
print "PSF fitting catastrophic failure"
PSFpopt = [[0]*PSFlen(psfi) for psfi in psftype]
PSFperr = [[0]*PSFlen(psfi) for psfi in psftype]
skyflag = 0
X2dof = 0
if verbosity > 0:
print "Multi-obj best fit parameters"
for i in range(Nobj):
if psftype[i][0] == 's':
print "Object "+str(i+1)+":"
print "[Ie,re,n,X0,Y0,e,theta] = ", repr(list(PSFpopt[i]))
print "parameter errors = ", repr(list(PSFperr[i]))
elif psftype[i][0] == 'c':
print "Object "+str(i+1)+":"
print "[X0,Y0,Ib,e,theta,re,n,gma,rbe] = ", repr(list(PSFpopt[i]))
print "parameter errors = ", repr(list(PSFperr[i]))
else:
print "Object "+str(i+1)+":"
print "[A,ax,ay,b,theta,X0,Y0] = ", repr(list(PSFpopt[i]))
print "parameter errors = ", repr(list(PSFperr[i]))
FWHMx, FWHMy = E2moff_toFWHM(PSFpopt[i][1], PSFpopt[i][2], PSFpopt[i][3])
print "[FWHMx', FWHMy]' = ", repr([FWHMx, FWHMy])
print "Chi2 = "+str(X2dof)
#graph fits if verbosity is high enough
if verbosity > 1:
PSFmulti_plot(image, x0, y0, PSFpopt, psftype, PSF, X2dof, skypopt, skyN, fitsky)
#check if fit is ridiculous, give back no fit
ridic = False
checks = []
for i in range(Nobj):
if psftype[i] != '3' and psftype[i][0] != 's' and psftype[i][0] != 'c':
if not E2moff_verify(PSFpopt[i], x0[i], y0[i]):
ridic = True
if verbosity > 0:
print "Bad PSF: Object "+str(i+1)
print dist(PSFpopt[i][5],PSFpopt[i][6],x0[i],y0[i])
if not ridic:
#None of the fits were ridiculous
return PSFpopt, PSFperr, X2dof, skypopt, skyN
else:
return [[0]*PSFlen(psfi) for psfi in psftype], [[0]*PSFlen(psfi) for psfi in psftype], 0, [0]*3, skyN
#function: plot PSF fitting
def PSF_plot(image, x0, y0, PSFpopt, X2dof, skypopt, skyN, fitsky, window=15):
import matplotlib.pyplot as plt
from PSFlib import D2plane, E2moff, E2moff_toFWHM
#get fit parameters
A = PSFpopt[0]
ax = abs(PSFpopt[1])
ay = abs(PSFpopt[2])
b = PSFpopt[3]
theta = PSFpopt[4]
X0 = PSFpopt[5]
Y0 = PSFpopt[6]
FWHMx, FWHMy = E2moff_toFWHM(ax, ay, b)
xw_min, xw_max = max(x0-window, 0), min(x0+window+1, image.shape[1]-1)