-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpsf.py
executable file
·1816 lines (1458 loc) · 66.6 KB
/
psf.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
#!/usr/bin/env python
import numpy as np
from astropy.io import fits
import pickle
import os.path as op
import time
import matplotlib.pyplot as plt
from croaks import NTuple
import scipy.linalg as SL
import scipy.sparse as SS
import scipy.optimize as SO
from scipy.sparse import linalg as SSLA
from scipy.interpolate import RectBivariateSpline as RBS
import sksparse.cholmod
from numpy.polynomial.legendre import leggauss
import argparse
import psutil
import os
cholesky = sksparse.cholmod.cholesky
process = psutil.Process(os.getpid())
def get_sxy(path):
sstars = NTuple.fromfile(op.join(path, 'standalone_stars.list'))
seeing = float(sstars.keys['SEEING'])
x = sstars['x']
y = sstars['y']
f = sstars['flux']
fluxmax = sstars['fluxmax']
return seeing, x, y, f, fluxmax
def get_data(path, xc, yc, hsize):
data_file = fits.getdata(op.join(path, 'calibrated.fz'))
weight_file = fits.getdata(op.join(path, 'weight.fz'))
if op.isfile(op.join(path, 'satur.fits.gz')):
satur = fits.getdata(op.join(path, 'satur.fits.gz'))
weight_file *= (1 - satur)
gain = fits.getval(op.join(path, 'calibrated.fz'), 'Gain', 1)
x_int = np.round(xc).astype(int)
y_int = np.round(yc).astype(int)
n_stars = len(xc)
vsize = 2 * hsize + 1
ymax, xmax = data_file.shape
z = np.zeros(n_stars, dtype=int)
ymins = np.max(np.vstack([(y_int - hsize), z]), axis=0)
ymaxs = np.min(np.vstack([(y_int + hsize) - ymax, z]), axis=0) + ymax + 1
yminp = -1 * (np.min(np.vstack([(y_int - hsize), z]), axis=0))
ymaxp = (-1 * np.max(np.vstack([(y_int + hsize) +1 - ymax, z]), axis=0)
+ vsize)
xmins = np.max(np.vstack([(x_int - hsize), z]), axis=0)
xmaxs = np.min(np.vstack([(x_int + hsize) - xmax, z]), axis=0) + xmax + 1
xminp = -1 * (np.min(np.vstack([(x_int - hsize), z]), axis=0))
xmaxp = (-1 * np.max(np.vstack([(x_int + hsize) +1 - xmax, z]), axis=0)
+ vsize)
data_cube = np.zeros((n_stars, vsize, vsize))
weight_cube = np.zeros((n_stars, vsize, vsize))
for i in range(n_stars):
data_cube[i, yminp[i]:ymaxp[i],
xminp[i]:xmaxp[i]] = data_file[ymins[i]:ymaxs[i],
xmins[i]:xmaxs[i]]
weight_cube[i, yminp[i]:ymaxp[i],
xminp[i]:xmaxp[i]] = weight_file[ymins[i]:ymaxs[i],
xmins[i]:xmaxs[i]]
n_stars = len(xc)
data = data_cube.reshape(n_stars,-1)
weights = weight_cube.reshape(n_stars, -1)
corners = np.array([[0, 0], [0, xmax], [ymax, xmax], [ymax, 0]])
return data, weights, corners, gain, data_file, weight_file
def vignette(data, weight, hsize, x, y):
hsize = int(hsize)
y_int = int(np.round(y))
x_int = int(np.round(x))
vsize = 2 * hsize + 1
y_mx, x_mx = data.shape
z = 0
ymin = np.max([(y_int - hsize), z])
ymax = np.min([(y_int + hsize) - y_mx, z]) + y_mx + 1
yminp = -1 * np.min([(y_int - hsize), z])
ymaxp = -1 * np.max([(y_int + hsize) +1 - y_mx, z]) + vsize
xmin = np.max([(x_int - hsize), z])
xmax = np.min([(x_int + hsize) - x_mx, z]) + x_mx + 1
xminp = -1 * np.min([(x_int - hsize), z])
xmaxp = (-1 * np.max([(x_int + hsize) +1 - x_mx, z]) + vsize)
data_vign = np.zeros((vsize, vsize))
weight_vign = np.zeros((vsize, vsize))
try:
data_vign[yminp:ymaxp, xminp:xmaxp] = data[ymin:ymax,xmin:xmax]
except:
print x, y
print ymin, ymax, xmin, xmax
print yminp, ymaxp, xminp, xmaxp
1/0
weight_vign[yminp:ymaxp, xminp:xmaxp] = weight[ymin:ymax, xmin:xmax]
return data_vign.ravel(), weight_vign.ravel()
quadrature_order = 3
intp,intw = leggauss(quadrature_order)
intp *= 0.5 ; intw *= 0.5
intgx,intgy = np.meshgrid(intp,intp)
intwx,intwy = np.meshgrid(intw,intw)
intww = (intwx*intwy).ravel()
def integ_in_pixels(x, y, f):
"""Integrate a 2D function in pixels
(Totally borrowed from saunerie)
Given a function f (typically, a psf profile), and a series of
positions (x,y), evaluate the integral of the function on the
pixels corresponding to each of the positions (x,y) specified in
argument.
Args
x (ndarray of floats): x-positions, in pixels.
y (ndarray of floats): y-positions, in pixels.
f (callable): function to integrate
quadrature_order (int, optional): order of the gaussian quadrature to use.
Returns:
ndarray of floats: integrated PSF value.
.. note:
the function is written to preserve the shape of x and y
"""
# put this integration code in cache
"""
p,w = leggauss(quadrature_order)
p *= 0.5 ; w *= 0.5
gx,gy = np.meshgrid(p,p)
wx,wy = np.meshgrid(w,w)
ww = (wx*wy).ravel()
xc = x.reshape(x.shape + (1,1,)) + gx
yc = y.reshape(y.shape + (1,1,)) + gy
"""
xc = x.reshape(x.shape + (1,1,)) + intgx
yc = y.reshape(y.shape + (1,1,)) + intgy
v = f(xc,yc)
v = v.reshape(v.shape[0], v.shape[1], -1)
return np.dot(v, intww)
class Star(object):
def __init__(self, data, weight, inv_weight, x, y, gain, fluxmax, nd):
self.data = data
self.weight = weight
self.init_weight_inv = inv_weight
self.hsize = (nd - 1)/2.
self.gain = gain
self.fluxmax = fluxmax
self.x = x
self.y = y
self.xi_int = np.tile(np.arange(-hsize, hsize+1), (nd, 1))
self.yi_int = np.tile(np.arange(-hsize, hsize+1)[:, None], (1, nd))
self.xi = self.xi_int.ravel()
self.yi = self.yi_int.ravel()
ymax, xmax = data.shape
self.ax = 2./ xmax
self.bx = 1 - self.ax * xmax
self.ay = 2./ ymax
self.by = 1 - self.ay * ymax
def set_globalpsfparams(self, params):
self.g_wxx = params[0]
self.g_wyy = params[1]
self.g_wxy = params[2]
def phi_grad_pos(self, dx, dy, wxx, wyy, wxy):
norm = (wxx * wyy - wxy**2)**0.5 * (2.5 - 1)/np.pi
fact = (1 + wxx * dx**2 + wyy * dy**2 + 2 * wxy * dx * dy)
grad1 = -2.5 * norm * fact**-3.5
gradx = -2 * wxx * dx - 2 * wxy * dy
grady = -2 * wyy * dy - 2 * wxy * dx
return grad1 * np.array([gradx, grady])
def phi_grad_par(self, dx, dy, wxx, wyy, wxy):
norm_arg = (wxx * wyy - wxy**2)**0.5
norm_c = (2.5 - 1)/np.pi
fact = (1 + wxx * dx**2 + wyy * dy**2 + 2 * wxy * dx * dy)
grad1 = -2.5 * norm_c * norm_arg * fact**-3.5
grad2 = 0.5 * norm_c * norm_arg**-1 * fact**-2.5
dwxx = grad1 * dx**2 + grad2 * wyy
dwyy = grad1 * dy**2 + grad2 * wyy
dwxy = grad1 * 2 * dx * dy + grad2 * -2 * wxy
return np.array([dwxx, dwyy, dwxy])
def computeABchi2(self, vars, only_chi=False,plot=False):
wxx, wyy, wxy, flux, new_x, new_y, fluxforweight = vars
xc = new_x - np.round(new_x)
yc = new_y - np.round(new_y)
dx = self.xi - xc
dy = self.yi - yc
dxi = self.xi_int - xc
dyi = self.yi_int - yc
fact = (1 + wxx * dx**2 + wyy * dy**2 + 2 * wxy * dx * dy)
norm = (wxx * wyy - wxy**2)**0.5 * (2.5 - 1)/np.pi
def tmp(x, y):
ft = (1 + wxx * x**2 + wyy * y**2 + 2 * wxy * x * y)
return norm * ft**-2.5
phi = integ_in_pixels(dxi, dyi, tmp).ravel()
self.phi = phi
self.data_slice, self.weight_slice = vignette(self.data, self.weight,
self.hsize, new_x, new_y)
if plot:
nd = int(len(dx)**0.5)
d_s = self.data_slice.reshape(nd, nd)
m_s = (flux * phi).reshape(nd, nd)
r_s = (d_s - m_s)
plt.imshow(np.hstack([d_s, m_s, r_s]), interpolation='nearest')
plt.show()
res = (self.data_slice - flux * phi)
weight = (self.weight_slice**-1 + fluxforweight * phi /self.gain)**-1
dweight = - weight**2 * res**2 * fluxforweight / gain
chi2 = (weight * res**2).sum()
if only_chi:
return chi2
def tmp_xpos(x, y):
return self.phi_grad_pos(x, y, wxx, wyy, wxy)[0]
def tmp_ypos(x, y):
return self.phi_grad_pos(x, y, wxx, wyy, wxy)[1]
def tmp_wxx(x, y):
return self.phi_grad_par(x, y, wxx, wyy, wxy)[0]
def tmp_wyy(x, y):
return self.phi_grad_par(x, y, wxx, wyy, wxy)[1]
def tmp_wxy(x, y):
return self.phi_grad_par(x, y, wxx, wyy, wxy)[2]
dpos = np.array([integ_in_pixels(dxi, dyi, tmp_xpos).ravel(),
integ_in_pixels(dxi, dyi, tmp_ypos).ravel()])
dpar = np.array([integ_in_pixels(dxi, dyi, tmp_wxx).ravel(),
integ_in_pixels(dxi, dyi, tmp_wyy).ravel(),
integ_in_pixels(dxi, dyi, tmp_wxy).ravel()])
h_vector = np.zeros((6, len(self.xi)))
grad_w = np.zeros((6, len(self.xi)))
h_vector[:3] = dpar * flux
h_vector[3] = phi
h_vector[4:] = dpos * flux
grad_w[:3] = dpar * dweight
grad_w[4:] = dpos * dweight
# d_chi:
B = (-2 * weight * res * h_vector + grad_w).sum(axis=1)
# hessian_chi:
A = (2 * weight * h_vector[:, None,:] * h_vector[None,:, :]).sum(axis=2)
return A, B, chi2
def fit_all_params(self, init_flux, init_w, max_iter=30):
# Minimize equation 5 from the note:
self.flux = init_flux
self.wxx, self.wyy = init_w, init_w
self.wxy = 0
init_vars = np.array([self.wxx, self.wyy, self.wxy, self.flux,
self.x, self.y, self.flux])
vars = np.copy(init_vars)
min_diff = [0.1, 0.01]
for l in range(2): # 2 loops to fit flux, correct weight, refit flux
oldchi = 1e30
dchi2 = 1e30
iter = 0
# Gauss-Newton minimizer
while (dchi2 > min_diff[l]) & (iter < max_iter):
A, B, chi = self.computeABchi2(vars)
factor = SL.cho_factor(A)
solution = SL.cho_solve(factor, B)
# get bracket for Brent linesearch:
init_step = 3
c = np.nan
while np.isnan(c):
new_vars = np.copy(vars)
new_vars[:6] -= init_step * solution
try:
c = self.computeABchi2(new_vars, only_chi=True)
except:
c = np.nan
if np.isnan(c):
init_step *= 0.6
# do Brent line search to get step along gradient:
def brent_lnsrch(x):
new_vars = np.copy(vars)
new_vars[:6] -= x * solution
return self.computeABchi2(new_vars, only_chi=True)
try:
step_fit = SO.brent(brent_lnsrch, brack=(0, init_step),
tol=1e-4, full_output=1)
chi2 = step_fit[1]
except:
chi2 = np.nan
# For certain scipy versions Brent search goes outside bounds and finds NaN!
# Check for this and, if chi2=nan, just use initial step
if not np.isnan(chi2):
vars[:6] -= step_fit[0] * solution
else:
vars[:6] -= 0.5 * init_step * solution
chi2 = self.computeABchi2(vars, only_chi=True)
dchi2 = np.copy(abs(chi2 - oldchi))
iter += 1
oldchi = np.copy(chi2)
vars[6] = np.copy(vars[3])
self.chi2 = chi2
self.covariance = SL.inv(A)
self.flux = vars[3]
self.eflux = self.covariance[3,3]**0.5
self.x = vars[4]
self.y = vars[5]
self.vxc = self.covariance[4,4]
self.vyc = self.covariance[5,5]
self.wxx, self.wyy, self.wxy = np.copy(vars[:3])
self.psfparams = np.copy(vars[:3])
w_covs = self.covariance[:3,:3]
self.paramweight = SL.inv(w_covs)
def computeABchi2_pos(self, vars, wxx, wyy, wxy, fluxforweight, res_fns, c,
only_chi=False, plot=False):
flux, new_x, new_y = vars
xc = new_x - np.round(new_x)
yc = new_y - np.round(new_y)
dx = self.xi - xc
dy = self.yi - yc
dxi = self.xi_int - xc
dyi = self.yi_int - yc
fact = (1 + wxx * dx**2 + wyy * dy**2 + 2 * wxy * dx * dy)
norm = (wxx * wyy - wxy**2)**0.5 * (2.5 - 1)/np.pi
def tmp(x, y):
ft = (1 + wxx * x**2 + wyy * y**2 + 2 * wxy * x * y)
return norm * ft**-2.5
phi = integ_in_pixels(dxi, dyi, tmp).ravel()
self.phi = phi
orig_x = np.arange(-self.hsize, self.hsize+1)
r_conv = np.array([fn(orig_x - yc, orig_x - xc).ravel()
for fn in res_fns])
pos_array = np.array([1, new_x, new_y])
pos_array = np.array([1, self.ax * new_x + self.bx,
self.ay * new_y + self.by])
resid = (r_conv * pos_array[:,None]).sum(axis=0)
phi_part = phi * (1 - (c * pos_array).sum())
psi = phi_part + resid
self.data_slice, self.weight_slice = vignette(self.data, self.weight,
self.hsize, new_x, new_y)
if plot:
nd = int(len(dx)**0.5)
d_s = self.data_slice.reshape(nd, nd)
m_s = (flux * psi).reshape(nd, nd)
r_s = (d_s - m_s)
plt.imshow(np.hstack([d_s, m_s, r_s]), interpolation='nearest')
plt.show()
res = (self.data_slice - flux * psi)
weight = (self.weight_slice**-1 + fluxforweight * psi /self.gain)**-1
dweight = - weight**2 * res**2 * fluxforweight / gain
chi2 = (weight * res**2).sum()
if only_chi:
return chi2
def tmp_xpos(x, y):
return self.phi_grad_pos(x, y, wxx, wyy, wxy)[0]
def tmp_ypos(x, y):
return self.phi_grad_pos(x, y, wxx, wyy, wxy)[1]
dpos = np.array([integ_in_pixels(dxi, dyi, tmp_xpos).ravel(),
integ_in_pixels(dxi, dyi, tmp_ypos).ravel()])
# 3 = 1 flux + 2 position params
h_vector = np.zeros((3, len(self.xi)))
grad_w = np.zeros((3, len(self.xi)))
h_vector[0] = psi
h_vector[1:] = dpos * flux
grad_w[1:] = dpos * dweight
# d_chi:
B = (-2 * weight * res * h_vector + grad_w).sum(axis=1)
# hessian_chi:
A = (2 * weight * h_vector[:, None,:] * h_vector[None,:, :]).sum(axis=2)
return A, B, chi2
def fit_pos(self, init_flux, res_fns, c, use_global_w_params=True):
#init_vars = np.array([init_flux, self.xc, self.yc])
init_vars = np.array([init_flux, self.x, self.y])
if use_global_w_params:
wxx = self.g_wxx
wyy = self.g_wyy
wxy = self.g_wxy
else:
wxx = self.wxx
wyy = self.wyy
wxy = self.wxy
vars = np.copy(init_vars)
min_diff = [0.1, 0.01]
max_iter=30
fluxforweight = init_flux
for l in range(2): # 2 loops to fit flux, correct weight, refit flux
oldchi = 1e30
dchi2 = 1e30
iter = 0
# Gauss-Newton minimizer
while (dchi2 > min_diff[l]) & (iter < max_iter):
A, B, chi = self.computeABchi2_pos(vars, wxx, wyy, wxy,
fluxforweight, res_fns, c)
try:
factor = SL.cho_factor(A)
except:
print self.flux
print init_vars
print vars
print A
print B
raise ValueError("Problem with Hessian of chi2, look at A "
"because this should not happen")
solution = SL.cho_solve(factor, B)
# get bracket:
init_step = 3
tmp_chi = np.nan
while np.isnan(tmp_chi):
new_vars = np.copy(vars)
new_vars -= init_step * solution
tmp_chi = self.computeABchi2_pos(new_vars, wxx, wyy, wxy,
fluxforweight, res_fns,
c, only_chi=True)
if np.isnan(tmp_chi):
init_step *= 0.6
# do Brent line search to get step along gradient:
def brent_lnsrch(x):
new_vars = np.copy(vars)
new_vars -= x * solution
return self.computeABchi2_pos(new_vars, wxx, wyy,
wxy, fluxforweight,
res_fns, c, only_chi=True)
try:
step_fit = SO.brent(brent_lnsrch, brack=(0, init_step),
tol=1e-4, full_output=1)
chi2 = step_fit[1]
except:
chi2 = np.nan
# Sometimes Brent search goes outside bounds and finds NaN!
# Check for this and, if chi2=nan, just use initial step
if not np.isnan(chi2):
vars -= step_fit[0] * solution
else:
vars -= 0.5 * init_step * solution
chi2 = self.computeABchi2_pos(vars, wxx, wyy,
wxy, fluxforweight,
res_fns, c, only_chi=True)
dchi2 = np.copy(abs(chi2 - oldchi))
iter += 1
oldchi = np.copy(chi2)
fluxforweight = vars[0]
# Reset phi, etc.:
self.computeABchi2_pos(vars, wxx, wyy, wxy,
fluxforweight, res_fns, c, only_chi=True)
self.chi2 = chi2
self.covariance = SL.inv(A)
self.flux = vars[0]
self.eflux = self.covariance[0,0]**0.5
self.x = vars[1]
self.y = vars[2]
self.xc = self.x - np.round(self.x)
self.yc = self.y - np.round(self.y)
self.vxc = self.covariance[1,1]
self.vyc = self.covariance[2,2]
class MoffatPSF(object):
"""This class produces postage-stamps for a Moffat PSF model with beta=2.5.
The PSF parameters are allowed to vary as a poluynomial function of the
position (presumed to be the position on a ccd).
Parameters
----------
hsize : int
Determines stamp size, where each side = 2*hsize + 1
xc : numpy.ndarray (float)
x-dimension position of psf centers
yc : numpy.ndarray (float)
y-dimension position of psf centers
xmax, ymax : int
Dimensions of the full image used to normalize the psf spatial
parameters. Essentially arbitrary.
degree : int
Sets the degree of the polynomial function for spatial variation
seeing : float
Gaussian seeing to make initial guess of moffat parameters
"""
#def __init__(self, hsize, xc, yc, full_data, full_weights, gain, fluxmax, degree=1):
def __init__(self, hsize, xc, yc, xmax=1, ymax=1, degree=1, seeing=3):
self.name = "MOFFAT25"
self.xc = xc
self.yc = yc
self.n_stars = len(xc)
# Set up indices for the PSF vignettes
self.nd = hsize * 2 + 1
self.xi = np.tile(np.arange(-hsize, hsize+1), (self.nd, 1))
self.yi = np.tile(np.arange(-hsize, hsize+1)[:, None], (1, self.nd))
xdiffs = self.xc - np.round(self.xc)
ydiffs = self.yc - np.round(self.yc)
self.x_inds = self.xi[None,:,:] - xdiffs[:,None,None]
self.y_inds = self.yi[None,:,:] - ydiffs[:,None,None]
self.outliers = np.zeros(self.n_stars, dtype=bool)
self.use_outliers = np.zeros(self.n_stars, dtype=bool)
self.ymax, self.xmax = ymax, xmax
# Set up parameters to normalize the CCD-position dependent polynomials:
self.ax = 2./self.xmax
self.bx = 1 - self.ax * self.xmax
self.ay = 2./self.ymax
self.by = 1 - self.ay * self.ymax
# Set up variables to help calculate the derivative of the chi2 function
der = np.array([np.ones(self.n_stars), self.ax * self.xc + self.bx,
self.ay * self.yc + self.by])
deg_dict = {0: 1, 1: 3, 2: 6}
self.degree = deg_dict[degree]
self.wder = der[:self.degree].T
# Calculate the number of variables:
self.nvars = self.n_stars + self.degree * 3
self.initparamsfromseeing(seeing)
def set_data(self, full_data, full_weights, gain, fluxmax=None):
# Load data:
self.full_data = full_data
self.full_weights = full_weights
# Need gain to correct weights:
self.gain = gain
# Fluxmax is just carried through so it is output
if fluxmax is None:
self.fluxmax = np.zeros(self.n_stars)
else:
self.fluxmax = fluxmax
def initparamsfromseeing(self, seeing):
init_w = (0.6547/seeing)**2
w_vars = np.zeros(self.degree * 3)
w_vars[0] = init_w
w_vars[self.degree] = init_w
self.set_moffat(w_vars)
def reset_pos(self):
# Given changed self.xc and self.yc, reset helper variables
xdiffs = self.xc - np.round(self.xc)
ydiffs = self.yc - np.round(self.yc)
self.x_inds = self.xi[None,:,:] - xdiffs[:,None,None]
self.y_inds = self.yi[None,:,:] - ydiffs[:,None,None]
der = np.array([np.ones(self.n_stars), self.ax * self.xc + self.bx,
self.ay * self.yc + self.by])
self.wder = der[:self.degree].T
def set_moffat(self, vars, expn=-2.5):
self.wxx_vector = vars[:self.degree]
self.wyy_vector = vars[self.degree:-self.degree]
self.wxy_vector = vars[-self.degree:]
self.wxx = (self.wxx_vector[None,:] * self.wder).sum(axis=1)
self.wyy = (self.wyy_vector[None,:] * self.wder).sum(axis=1)
self.wxy = (self.wxy_vector[None,:] * self.wder).sum(axis=1)
self.det = self.wxx * self.wyy - self.wxy**2
self.norm = np.sqrt(np.fabs(self.det)) * (-expn - 1) / np.pi
def moffat(self, x, y, i, expn=-2.5):
fact = (1 + x**2 * self.wxx[i] + y**2 * self.wyy[i] +
2 * x * y * self.wxy[i])
return self.norm[i] * np.power(fact, expn)
def moffat_integ(self, x, y, i, quadrature_order=4, expn=-2.5):
p,w = leggauss(quadrature_order)
p *= 0.5 ; w *= 0.5
gx,gy = np.meshgrid(p,p)
wx,wy = np.meshgrid(w,w)
ww = (wx*wy).ravel()
xc = x.reshape(x.shape + (1,1,)) + gx
yc = y.reshape(y.shape + (1,1,)) + gy
v = self.moffat(xc,yc, i, expn=-2.5)
v = v.reshape(v.shape[0], v.shape[1], -1)
return np.dot(v, ww)
def check_corners(self, corners):
okparams = True
for c in corners:
c_array = np.array([1, self.ax * c[1] + self.bx,
self.ay * c[0] + self.by])
wxx = (self.wxx_vector * c_array).sum()
wyy = (self.wyy_vector * c_array).sum()
wxy = (self.wxy_vector * c_array).sum()
if (wxx * wyy - wxy**2) < 0:
okparams = False
return okparams
def set_phi(self):
self.phi = np.array([self.moffat_integ(xi, yi, i) for (xi, yi, i)
in zip(self.x_inds, self.y_inds,
np.arange(self.n_stars))])
def remove_outliers(self, all_chi2s, sigmacut=4):
chi2s = all_chi2s[~self.outliers]
chi2_median = np.median(chi2s)
chi2_sigma =((chi2s**2).sum()/len(chi2s) - np.mean(chi2s)**2)**0.5
max_chi2 = chi2_median + chi2_sigma * sigmacut
new_non_outliers = (all_chi2s <= max_chi2) | self.outliers
print 'Max chi2', max_chi2, len(chi2s)
print all_chi2s[~new_non_outliers]
self.tmp_outliers = np.zeros(self.n_stars, dtype=bool)
self.tmp_outliers[~new_non_outliers] = True
self.use_outliers = self.tmp_outliers | self.outliers
def moffat_fit(self, init_seeing=5, init_fluxes=None,
max_iter=20, chi_tol=1e-5):
try:
self.full_data
except:
raise ValueError('self.full_data must be set in order to '
'fit moffat')
# Get initial estimate of the Moffat PSF from the Gaussian seeing:
self.initparamsfromseeing(init_seeing)
# The initial parameters:
w_vars = np.hstack([self.wxx_vector, self.wyy_vector, self.wxy_vector])
# Solve equation 5 from the note:
# Fit an elliptical Moffat PSF and position for each star,
# skipping failure cases in this first estimate:
Stars = []
self.fluxes = np.zeros(self.n_stars)
init_chis = np.zeros(self.n_stars)
init_params = np.zeros((self.n_stars,3))
init_paramweights = np.zeros((self.n_stars, 3, 3))
init_param_sig = np.zeros((self.n_stars, 3))
inv_weights = self.full_weights**-1
for i in range(self.n_stars):
S = Star(self.full_data, self.full_weights, inv_weights,
self.xc[i], self.yc[i],
self.gain, self.fluxmax[i], self.nd)
Stars.append(S)
try:
S.fit_all_params(init_fluxes[i], self.wxx_vector[0])
self.fluxes[i] = S.flux
self.xc[i] = S.x
self.yc[i] = S.y
init_chis[i] = S.chi2
init_params[i] = S.psfparams
init_paramweights[i] = S.paramweight
init_param_sig[i] = np.diagonal(SL.inv(S.paramweight))**0.5
except:
print i, "outlier at %s, %s" % (S.x, S.y)
self.fluxes[i] = init_fluxes[i]
S.x = self.xc[i]
S.y = self.yc[i]
S.flux = init_fluxes[i]
S.data_slice, S.weight_slice = vignette(self.full_data,
self.full_weights,
S.hsize, S.x, S.y)
S.paramweight = np.zeros((3,3))
init_chis[i] = 1e10
# Reset some helper variables based on the new positions:
self.reset_pos()
self.stars = Stars
init_chi = init_chis.sum()
init_nstars = np.copy(self.n_stars)
#print u"Initial \u03C7\u00B2=%s (\u03C7\u00B2/dof=%s)" \
print u"Initial chi2=%s (chi2/dof=%s)" \
% (init_chi, init_chi.sum()/(self.n_stars*self.nd**2
- self.n_stars * (1 + 3)))
print "Average ", init_chis.mean()
tmp = self.remove_outliers(init_chis)
print 'Stars passing cuts:', (~self.tmp_outliers).sum()
# Fit equation 8 from the note:
# Fit a first-degree polynomial to the individual stars' PSF parameters
# as a function of the CCD position. Iterate, removing outliers, until there
# are no more outliers. (Fit is otherwise linear)
for i in range(max_iter):
# Solve Ax=b using Newton-Raphson (where here A=hess_chi, b=dchi, x = d(new_vars)):
dchi = np.zeros(9)
hess_chi = np.zeros((9,9))
b1 = np.array([init_paramweights[ip].dot(init_params[ip])
for ip in range(self.n_stars)])
b = np.array([(self.wder[ip,None,:]*b1[ip,:, None]).ravel()
for ip in range(self.n_stars)])
b_noout = b[~self.use_outliers]
dchi = 2 * b_noout.sum(axis=0)
h = np.tile(self.wder, 3)
big_weight = np.array([np.repeat(np.repeat(ip,3, axis=0), 3, axis=1)
for ip in init_paramweights])
hess_chi = 2 * (big_weight * h[:, :, None] *
h[:,None,:])
hess_chi = hess_chi[~self.use_outliers].sum(axis=0)
factor = SL.cho_factor(hess_chi)
new_vars = SL.cho_solve(factor, dchi)
# Reset the parameters
var_array = new_vars.reshape(3,3)
w_params = np.array([var_array.dot(self.wder[s]) for s in
range(self.n_stars)])
d_params = (w_params - init_params)
param_chis = np.array([d_params[j].dot(init_paramweights[j].dot(d_params[j])) for j in range(self.n_stars)])
print 'Mean before cuts', param_chis[~self.outliers].mean()
ndof = (~self.use_outliers).sum() * 3 - 9
print 'chi/dof (before)', param_chis[~self.outliers].sum(), \
ndof, param_chis[~self.outliers].sum()/ndof
# Remove outlier stars:
self.remove_outliers(param_chis)
print 'New cuts', np.flatnonzero(self.tmp_outliers), \
self.xc[self.tmp_outliers], self.yc[self.tmp_outliers]
for xo in np.flatnonzero(self.tmp_outliers):
print 'Erasing star at', self.xc[xo], self.yc[xo], \
self.fluxes[xo], param_chis[xo]
if self.tmp_outliers.sum() == 0:
print 'No more outliers, stop here'
break
else:
self.outliers |= self.tmp_outliers
# Given the fit parameters, get the analytic psf for each star:
self.set_moffat(new_vars)
self.set_phi()
for s in range(self.n_stars):
self.stars[s].set_globalpsfparams(w_params[s])
print 'Initial PSF parameters:'
print w_vars
print 'Final PSF parameters:'
print new_vars
covariance = SL.inv(hess_chi)
print 'PSF error: ', np.diagonal(covariance)**0.5
self.covariance = covariance
class PSFResiduals(object):
def __init__(self, hsize, xc, yc, phi, xmax=1, ymax=1,
degree=1, fx=True, fx_index=(0,0)):
self.xc = xc
self.yc = yc
self.n_stars = len(xc)
self.hsize = hsize
self.nd = 2*self.hsize + 1
self.n_r = self.nd**2
print self.n_r, self.nd
# Degree of polynomial of R function determines shape of arrays:
deg_dict = {0: 1, 1: 3, 2: 6}
self.degree = deg_dict[degree]
self.all_vars = self.n_stars + self.n_r * self.degree + 2*self.degree
self.phi = phi
self.fx = fx
if self.fx:
self.set_fix(fx_index)
self.xmax = xmax
self.ymax = ymax
self.ax = 2./ xmax
self.bx = 1 - self.ax * xmax
self.ay = 2./ ymax
self.by = 1 - self.ay * ymax
norm_x = self.ax * self.xc + self.bx
norm_y = self.ay * self.yc + self.by
cder = np.array([np.ones((self.n_stars,1)), norm_x[:,None],
norm_y[:,None], norm_x[:,None]**2,
norm_y[:,None]**2,
(norm_x * norm_y)[:,None]])[:self.degree]
# Equation N:
self.cder = cder.reshape(-1, self.n_stars)[:self.degree]
#Equation N repeated by the number of pixels to use for R:
self.rder = np.repeat(self.cder[:self.degree], self.n_r, axis=0).T
self.rtile = np.tile(self.cder[:self.degree], (self.n_r, 1, 1)).T
self.s_list = [None for s in range(self.n_stars)]
def set_data(self, stars, gain):
# Allow for debug cases where we don't have a list of stars
self.stars = np.array(stars)
self.data = np.array([S.data_slice for S in stars])
self.weights = np.array([S.weight_slice for S in stars])
self.init_weights_inv = np.copy(self.weights**-1)
self.bad_pix = np.zeros_like(self.weights, dtype=bool)
not_finite = (~np.isfinite(self.data).all(axis=1) |
~np.isfinite(self.weights).all(axis=1) |
(self.weights.sum(axis=1) == 0))
self.remove_outliers(~not_finite)
self.gain = gain
#@profile
def reset_pos(self):
t0 =time.time()
norm_x = self.ax * self.xc + self.bx
norm_y = self.ay * self.yc + self.by
cder = np.array([np.ones((self.n_stars,1)), norm_x[:,None],
norm_y[:,None], norm_x[:,None]**2,
norm_y[:,None]**2,
(norm_x * norm_y)[:,None]])[:self.degree]
# Equation N:
self.cder = cder.reshape(-1, self.n_stars)[:self.degree]
# Equation N repeated by the number of pixels to use for R:
self.rder = np.repeat(self.cder[:self.degree], self.n_r, axis=0).T
self.rtile = np.tile(self.cder[:self.degree], (self.n_r, 1, 1)).T
t1 = time.time()
# Calculate the convolution matrices (C_s in the note)
self.dconvolve()
t2 = time.time()
print 'reset times', t1 - t0, t2 - t1
def set_fix(self, ind):
x, y = ind
xi = np.tile(np.arange(-self.hsize, self.hsize+1), (self.nd, 1))
yi = np.tile(np.arange(-self.hsize, self.hsize+1)[:, None], (1, self.nd))
# This sets where to fix the residual grid:
fx = True
self.fx_index = np.flatnonzero((xi.ravel() == 0) & (yi.ravel() == 0))[0]
self.fx_value = 0
def set_weights(self, vars, rconv):
# The weights need to be corrected for the flux of the star
fluxes = vars[:self.n_stars]
correction = fluxes[:,None] * self.psi_model(vars[self.n_stars:],
rconv=rconv) / self.gain
self.weights = (self.init_weights_inv + correction)**-1
self.weights[self.bad_pix] = 0
def convolve(self, r, return_fn=False):
# Function to convolve between model grid and pixel grid
dx = self.xc - np.round(self.xc)
dy = self.yc - np.round(self.yc)
rr = r.reshape(self.nd, self.nd)
orig_x = np.arange(-self.hsize, self.hsize+1)
new_x = np.arange(-self.hsize-1, self.hsize + 2)
r_tmp = np.zeros((self.nd+2, self.nd+2))
r_tmp[1:-1, 1:-1] = rr
rr = r_tmp
spl = RBS(new_x, new_x, rr, kx=1, ky=1)
if return_fn:
return spl
r_conv = np.zeros((self.n_stars, self.nd, self.nd))
for i in range(self.n_stars):
r_conv[i] = spl(orig_x - dy[i], orig_x - dx[i])
return r_conv.reshape(self.n_stars, -1)
#@profile
def dconvolve(self):
# Set self.s_list variable which gives the derivative of the
# convolution between model grid and data grid
t0d = time.time()
dx = (self.xc - np.round(self.xc))
dy = (self.yc - np.round(self.yc))
orig = np.zeros((3,3))
orig[1,1] = 1
t1d = time.time()
x = np.array([-1, 0, 1])
y = np.array([0.5,1,0.5])
tx1 = time.time()
spl = RBS(x, x, orig, kx=1, ky=1)
kernels = np.array([spl(x - dy[s], x - dx[s]) for s in range(len(dx))])