forked from dstndstn/tractor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cs82.py
1861 lines (1563 loc) · 48.2 KB
/
cs82.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
import os
import math
import time
import logging
import matplotlib
matplotlib.use('Agg')
import numpy as np
import pylab as plt
import multiprocessing
from glob import glob
from astrometry.util.pyfits_utils import *
from astrometry.util.sdss_radec_to_rcf import *
from astrometry.util.multiproc import *
from astrometry.util.file import *
from astrometry.util.plotutils import ArcsinhNormalize
from astrometry.util.util import *
from astrometry.sdss import *
from tractor import *
from tractor import cfht as cf
from tractor import sdss as st
from tractor.sdss_galaxy import *
from tractor.emfit import em_fit_2d
from tractor.fitpsf import em_init_params
import emcee
#from tractor.mpcache import createCache
def print_frozen(tractor):
for nm,meliq,liq in tractor.getParamStateRecursive():
if liq:
print ' ',
else:
print 'F',
if meliq:
print ' ',
else:
print 'F',
print nm
def get_cfht_image(fn, psffn, pixscale, RA, DEC, sz, bandname=None,
filtermap=None, rotate=True):
if filtermap is None:
filtermap = {'i.MP9701': 'i'}
wcs = Tan(fn, 0)
x,y = wcs.radec2pixelxy(RA,DEC)
x -= 1
y -= 1
print 'x,y', x,y
S = int(sz / pixscale) / 2
print '(half) S', S
cfx,cfy = int(np.round(x)),int(np.round(y))
P = pyfits.open(fn)
I = P[1].data
print 'Img data', I.shape
H,W = I.shape
cfroi = [np.clip(cfx-S, 0, W),
np.clip(cfx+S, 0, W),
np.clip(cfy-S, 0, H),
np.clip(cfy+S, 0, H)]
x0,x1,y0,y1 = cfroi
roislice = (slice(y0,y1), slice(x0,x1))
image = I[roislice]
sky = np.median(image)
print 'Sky', sky
# save for later...
cfsky = sky
skyobj = ConstantSky(sky)
# Third plane in image: variance map.
I = P[3].data
var = I[roislice]
cfstd = np.sqrt(np.median(var))
# Add source noise...
phdr = P[0].header
# e/ADU
gain = phdr.get('GAIN')
# Poisson statistics are on electrons; var = mean
el = np.maximum(0, (image - sky) * gain)
# var in ADU...
srcvar = el / gain**2
invvar = 1./(var + srcvar)
# Apply mask
# MP_BAD = 0
# MP_SAT = 1
# MP_INTRP= 2
# MP_CR = 3
# MP_EDGE = 4
# HIERARCH MP_DETECTED = 5
# HIERARCH MP_DETECTED_NEGATIVE = 6
I = P[2].data.astype(np.uint16)
#print 'I:', I
#print I.dtype
mask = I[roislice]
#print 'Mask:', mask
hdr = P[2].header
badbits = [hdr.get('MP_%s' % nm) for nm in ['BAD', 'SAT', 'INTRP', 'CR']]
print 'Bad bits:', badbits
badmask = sum([1 << bit for bit in badbits])
#print 'Bad mask:', badmask
#print 'Mask dtype', mask.dtype
invvar[(mask & int(badmask)) > 0] = 0.
del I
del var
psfimg = pyfits.open(psffn)[0].data
print 'PSF image shape', psfimg.shape
# number of Gaussian components
K = 3
PS = psfimg.shape[0]
w,mu,sig = em_init_params(K, None, None, None)
II = psfimg.copy()
II /= II.sum()
# HACK
II = np.maximum(II, 0)
print 'Multi-Gaussian PSF fit...'
xm,ym = -(PS/2), -(PS/2)
em_fit_2d(II, xm, ym, w, mu, sig)
print 'w,mu,sig', w,mu,sig
psf = GaussianMixturePSF(w, mu, sig)
if bandname is None:
# try looking up in filtermap.
filt = phdr['FILTER']
if filt in filtermap:
print 'Mapping filter', filt, 'to', filtermap[filt]
bandname = filtermap[filt]
else:
print 'No mapping found for filter', filt
bandname = flit
photocal = cf.CfhtPhotoCal(hdr=phdr, bandname=bandname)
filename = phdr['FILENAME'].strip()
(H,W) = image.shape
print 'Image shape', W, H
print 'x0,y0', x0,y0
print 'Original WCS:', wcs
rdcorners = [wcs.pixelxy2radec(x+x0,y+y0) for x,y in [(1,1),(W,1),(W,H),(1,H)]]
print 'Original RA,Dec corners:', rdcorners
wcs = crop_wcs(wcs, x0, y0, W, H)
print 'Cropped WCS:', wcs
rdcorners = [wcs.pixelxy2radec(x,y) for x,y in [(1,1),(W,1),(W,H),(1,H)]]
print 'cropped RA,Dec corners:', rdcorners
if rotate:
wcs = rot90_wcs(wcs, W, H)
print 'Rotated WCS:', wcs
rdcorners = [wcs.pixelxy2radec(x,y) for x,y in [(1,1),(H,1),(H,W),(1,W)]]
print 'rotated RA,Dec corners:', rdcorners
print 'rotating images...'
image = np.rot90(image, k=1)
invvar = np.rot90(invvar, k=1)
wcs = FitsWcs(wcs)
cftimg = Image(data=image, invvar=invvar, psf=psf, wcs=wcs,
sky=skyobj, photocal=photocal, name='CFHT %s' % filename)
return cftimg, cfsky, cfstd
def crop_wcs(wcs, x0, y0, W, H):
out = Tan()
out.set_crval(wcs.crval[0], wcs.crval[1])
out.set_crpix(wcs.crpix[0] - x0, wcs.crpix[1] - y0)
cd = wcs.get_cd()
out.set_cd(*cd)
out.imagew = W
out.imageh = H
return out
def rot90_wcs(wcs, W, H):
out = Tan()
out.set_crval(wcs.crval[0], wcs.crval[1])
out.set_crpix(wcs.crpix[1], W+1 - wcs.crpix[0])
cd = wcs.get_cd()
out.set_cd(cd[1], -cd[0], cd[3], -cd[2])
out.imagew = wcs.imageh
out.imageh = wcs.imagew
# opposite direction:
#out.set_crpix(H+1 - wcs.crpix[1], wcs.crpix[0])
#out.set_cd(-cd[1], cd[0], -cd[3], cd[2])
return out
def _mapf_sdss_im((r, c, f, band, sdss, sdss_psf, cut_sdss, RA, DEC, S, objname,
nanomaggies)):
print 'Retrieving', r,c,f,band
kwargs = {}
if cut_sdss:
kwargs.update(roiradecsize=(RA,DEC,S/2))
try:
im,info = st.get_tractor_image(r, c, f, band, sdssobj=sdss,
psf=sdss_psf, nanomaggies=nanomaggies,
**kwargs)
except:
import traceback
print 'Exception in get_tractor_image():'
traceback.print_exc()
print 'Failed to get R,C,F,band', r,c,f,band
return None,None
#raise
if im is None:
return None,None
if objname is not None:
print 'info', info
obj = info['object']
print 'Header object: "%s"' % obj
if obj != objname:
print 'Skipping obj !=', objname
return None,None
print 'Image size', im.getWidth(), im.getHeight()
if im.getWidth() == 0 or im.getHeight() == 0:
return None,None
im.rcf = (r,c,f)
return im,(info['sky'], info['skysig'])
def get_tractor(RA, DEC, sz, cffns, mp, filtermap=None, sdssbands=None,
just_rcf=False,
sdss_psf='kl-gm', cut_sdss=True,
good_sdss_only=False, sdss_object=None,
rotate_cfht=True,
nanomaggies=False,
nimages=None):
if sdssbands is None:
sdssbands = ['u','g','r','i','z']
tractor = Tractor()
skies = []
ims = []
pixscale = 0.187
print 'CFHT images:', cffns
for fn in cffns:
psffn = fn.replace('-cr', '-psf')
cfimg,cfsky,cfstd = get_cfht_image(fn, psffn, pixscale, RA, DEC, sz,
filtermap=filtermap, rotate=rotate_cfht)
ims.append(cfimg)
skies.append((cfsky, cfstd))
if nanomaggies:
# unimplemented
assert(False)
pixscale = 0.396
S = int(sz / pixscale)
print 'SDSS size:', S, 'pixels'
# Find all SDSS images that could overlap the RA,Dec +- S/2,S/2 box
R = np.sqrt(2.*(S/2.)**2 + (2048/2.)**2 + (1489/2.)**2) * pixscale / 60.
print 'Search radius:', R, 'arcmin'
rcf = radec_to_sdss_rcf(RA,DEC, radius=R, tablefn='s82fields.fits')
print 'SDSS fields nearby:', len(rcf)
rcf = [(r,c,f,ra,dec) for r,c,f,ra,dec in rcf if r != 206]
print 'Filtering out run 206:', len(rcf)
if just_rcf:
return rcf
sdss = DR7(basedir='cs82data/dr7')
#sdss = DR9(basedir='cs82data/dr9')
if good_sdss_only:
W = fits_table('window_flist-DR8-S82.fits')
print 'Building fidmap...'
fidmap = dict(zip(W.run * 10000 + W.camcol * 1000 + W.field, W.score))
print 'finding scores...'
scores = []
noscores = []
rcfscore = {}
for r,c,f,nil,nil in rcf:
print 'RCF', r,c,f
fid = r*10000 + c*1000 + f
score = fidmap.get(fid, None)
if score is None:
print 'No entry'
noscores.append((r,c,f))
continue
print 'score', score
scores.append(score)
rcfscore[(r,c,f)] = score
print 'No scores:', noscores
#plt.clf()
#plt.hist(scores, 20)
#plt.savefig('scores.png')
print len(scores), 'scores'
scores = np.array(scores)
print sum(scores > 0.5), '> 0.5'
args = []
for r,c,f,ra,dec in rcf:
if good_sdss_only:
score = rcfscore.get((r,c,f), 0.)
if score < 0.5:
print 'Skipping,', r,c,f
continue
for band in sdssbands:
args.append((r, c, f, band, sdss, sdss_psf, cut_sdss, RA, DEC, S, sdss_object, nanomaggies))
# Just do a subset of the fields?
if nimages:
args = args[:nimages]
print 'Getting', len(args), 'SDSS images...'
X = mp.map(_mapf_sdss_im, args)
print 'Got', len(X), 'SDSS images.'
for im,sky in X:
if im is None:
continue
ims.append(im)
skies.append(sky)
print 'Kept', len(X), 'SDSS images.'
tractor.setImages(Images(*ims))
return tractor,skies
def mysavefig(fn):
plt.savefig(fn)
print 'Wrote', fn
def get_cf_sources2(RA, DEC, sz, maglim=25, mags=['u','g','r','i','z'],
nanomaggies=False):
Tcomb = fits_table('cs82data/W4p1m1_i.V2.7A.swarp.cut.deVexp.fit', hdunum=2)
#Tcomb.about()
plt.clf()
plt.plot(Tcomb.mag_spheroid, Tcomb.mag_disk, 'r.')
plt.axhline(26)
plt.axvline(26)
plt.axhline(27)
plt.axvline(27)
plt.savefig('magmag.png')
plt.clf()
I = (Tcomb.chi2_psf < 1e7)
plt.loglog(Tcomb.chi2_psf[I], Tcomb.chi2_model[I], 'r.')
plt.xlabel('chi2 psf')
plt.ylabel('chi2 model')
ax = plt.axis()
plt.plot([ax[0],ax[1]], [ax[0],ax[1]], 'k-')
plt.axis(ax)
plt.savefig('psfgal.png')
# approx...
S = sz / 3600.
ra0 ,ra1 = RA-S/2., RA+S/2.
dec0,dec1 = DEC-S/2., DEC+S/2.
T = Tcomb
print 'Read', len(T), 'sources'
T.ra = T.alpha_j2000
T.dec = T.delta_j2000
T = T[(T.ra > ra0) * (T.ra < ra1) * (T.dec > dec0) * (T.dec < dec1)]
print 'Cut to', len(T), 'objects nearby.'
srcs = Catalog()
for t in T:
if t.chi2_psf < t.chi2_model and t.mag_psf <= maglim:
#print 'PSF'
themag = t.mag_psf
m = Mags(order=mags, **dict([(k, themag) for k in mags]))
if nanomaggies:
m = NanoMaggies.fromMag(m)
srcs.append(PointSource(RaDecPos(t.alpha_j2000, t.delta_j2000), m))
continue
if t.mag_disk > maglim and t.mag_spheroid > maglim:
#print 'Faint'
continue
# deV: spheroid
# exp: disk
themag = t.mag_spheroid
m_dev = Mags(order=mags, **dict([(k, themag) for k in mags]))
themag = t.mag_disk
m_exp = Mags(order=mags, **dict([(k, themag) for k in mags]))
if nanomaggies:
m_dev = NanoMaggies.fromMag(m_dev)
m_exp = NanoMaggies.fromMag(m_exp)
# SPHEROID_REFF [for Sersic index n= 1] = 1.68 * DISK_SCALE
shape_exp = GalaxyShape(t.disk_scale_world * 1.68 * 3600., t.disk_aspect_world,
t.disk_theta_world + 90.)
shape_dev = GalaxyShape(t.spheroid_reff_world * 3600., t.spheroid_aspect_world,
t.spheroid_theta_world + 90.)
pos = RaDecPos(t.alphamodel_j2000, t.deltamodel_j2000)
if t.mag_disk > maglim and t.mag_spheroid <= maglim:
srcs.append(DevGalaxy(pos, m_dev, shape_dev))
continue
if t.mag_disk <= maglim and t.mag_spheroid > maglim:
srcs.append(ExpGalaxy(pos, m_exp, shape_exp))
continue
srcs.append(CompositeGalaxy(pos, m_exp, shape_exp, m_dev, shape_dev))
print 'Sources:', len(srcs)
return srcs
def get_cf_sources3(RA, DEC, sz, magcut=100, mags=['u','g','r','i','z']):
Tcomb = fits_table('cs82data/cs82_morphology_may2012.fits')
Tcomb.about()
plt.clf()
plt.plot(Tcomb.mag_spheroid, Tcomb.mag_disk, 'r.')
plt.axhline(26)
plt.axvline(26)
plt.axhline(27)
plt.axvline(27)
plt.savefig('magmag.png')
plt.clf()
I = (Tcomb.chi2_psf < 1e7)
plt.loglog(Tcomb.chi2_psf[I], Tcomb.chi2_model[I], 'r.')
plt.xlabel('chi2 psf')
plt.ylabel('chi2 model')
ax = plt.axis()
plt.plot([ax[0],ax[1]], [ax[0],ax[1]], 'k-')
plt.axis(ax)
plt.savefig('psfgal.png')
# approx...
S = sz / 3600.
ra0 ,ra1 = RA-S/2., RA+S/2.
dec0,dec1 = DEC-S/2., DEC+S/2.
T = Tcomb
print 'Read', len(T), 'sources'
T.ra = T.alpha_j2000
T.dec = T.delta_j2000
T = T[(T.ra > ra0) * (T.ra < ra1) * (T.dec > dec0) * (T.dec < dec1)]
print 'Cut to', len(T), 'objects nearby.'
maglim = 27.
srcs = []
for t in T:
if t.chi2_psf < t.chi2_model and t.mag_psf <= maglim:
#print 'PSF'
themag = t.mag_psf
m = Mags(order=mags, **dict([(k, themag) for k in mags]))
srcs.append(PointSource(RaDecPos(t.alpha_j2000, t.delta_j2000), m))
continue
if t.mag_disk > maglim and t.mag_spheroid > maglim:
#print 'Faint'
continue
themag = t.mag_spheroid
m_exp = Mags(order=mags, **dict([(k, themag) for k in mags]))
themag = t.mag_disk
m_dev = Mags(order=mags, **dict([(k, themag) for k in mags]))
# SPHEROID_REFF [for Sersic index n= 1] = 1.68 * DISK_SCALE
shape_dev = GalaxyShape(t.disk_scale_world * 1.68 * 3600., t.disk_aspect_world,
t.disk_theta_world + 90.)
shape_exp = GalaxyShape(t.spheroid_reff_world * 3600., t.spheroid_aspect_world,
t.spheroid_theta_world + 90.)
pos = RaDecPos(t.alphamodel_j2000, t.deltamodel_j2000)
if t.mag_disk > maglim and t.mag_spheroid <= maglim:
# exp
#print 'Exp'
srcs.append(ExpGalaxy(pos, m_exp, shape_exp))
continue
if t.mag_disk <= maglim and t.mag_spheroid > maglim:
# deV
#print 'deV'
srcs.append(DevGalaxy(pos, m_dev, shape_dev))
continue
# exp + deV
#print 'comp'
srcs.append(CompositeGalaxy(pos, m_exp, shape_exp, m_dev, shape_dev))
print 'Sources:', len(srcs)
#for src in srcs:
# print ' ', src
return srcs
def tweak_wcs((tractor, im)):
#print 'Tractor', tractor
#print 'Image', im
tractor.images = Images(im)
print 'tweak_wcs: fitting params:', tractor.getParamNames()
for step in range(10):
print 'Run optimization step', step
t0 = Time()
dlnp,X,alpha = tractor.optimize(alphas=[0.5, 1., 2., 4.])
t_opt = (Time() - t0)
print 'alpha', alpha
print 'Optimization took', t_opt, 'sec'
lnp0 = tractor.getLogProb()
print 'Lnprob', lnp0
if dlnp == 0:
break
return im.getParams()
def plot1((tractor, i, zr, plotnames, step, pp, ibest, tsuf, colorbar, fmt)):
#plt.figure(figsize=(6,6))
plt.figure(figsize=(10,10))
plt.clf()
plotpos0 = [0.01, 0.01, 0.98, 0.94]
print 'zr = ', zr
ima = dict(interpolation='nearest', origin='lower',
vmin=zr[0], vmax=zr[1], cmap='gray')
imchi = dict(interpolation='nearest', origin='lower',
vmin=-5., vmax=+5., cmap='gray')
imchi2 = dict(interpolation='nearest', origin='lower',
vmin=-50., vmax=+50., cmap='gray')
tim = tractor.getImage(i)
data = tim.getImage()
q0,q1,q2,q3,q4 = np.percentile(data.ravel(), [0, 25, 50, 75, 100])
print 'Data quartiles:', q0, q1, q2, q3, q4
ima.update(norm=ArcsinhNormalize(mean=q2, std=(q3-q1)/2., vmin=zr[0], vmax=zr[1]),
vmin=None, vmax=None, nonl=True)
#plt.clf()
#plt.hist(data.ravel(), bins=100, log=True)
#plt.savefig('data-hist-%02i.png' % step)
if 'data' in plotnames:
data = tim.getImage()
plt.clf()
plt.gca().set_position(plotpos0)
myimshow(data, **ima)
tt = 'Data %s' % tim.name
if tsuf is not None:
tt += tsuf
plt.title(tt)
#plt.xticks([],[])
#plt.yticks([],[])
if colorbar:
plt.colorbar()
mysavefig('data-%02i' % i + fmt)
if 'dataann' in plotnames and i == 0:
ax = plt.axis()
xy = np.array([tim.getWcs().positionToPixel(s.getPosition())
for s in tractor.catalog])
plt.plot(xy[:,0], xy[:,1], 'r+')
plt.axis(ax)
mysavefig(('data-%02i-ann'+fmt) % i)
if ('modbest' in plotnames or 'chibest' in plotnames or
'modnoise' in plotnames or 'chinoise' in plotnames):
pbest = pp[ibest,:]
tractor.setParams(pp[ibest,:])
if 'modnoise' in plotnames or 'chinoise' in plotnames:
ierr = tim.getInvError()
noiseim = np.random.normal(size=ierr.shape)
I = (ierr > 0)
noiseim[I] *= 1./ierr[I]
noiseim[np.logical_not(I)] = 0.
if 'modbest' in plotnames or 'modnoise' in plotname:
mod = tractor.getModelImage(i)
if 'modbest' in plotnames:
#plt.clf()
#plt.hist(mod.ravel(), bins=100, log=True)
#plt.savefig(('mod-hist-%02i'+fmt) % step)
plt.clf()
plt.gca().set_position(plotpos0)
myimshow(mod, **ima)
tt = 'Model %s' % tim.name
if tsuf is not None:
tt += tsuf
plt.title(tt)
#plt.xticks([],[])
#plt.yticks([],[])
if colorbar:
plt.colorbar()
mysavefig(('modbest-%02i-%02i'+fmt) % (i,step))
if 'modnoise' in plotnames:
plt.clf()
plt.gca().set_position(plotpos0)
myimshow(mod + noiseim, **ima)
tt = 'Model+noise %s' % tim.name
if tsuf is not None:
tt += tsuf
plt.title(tt)
if colorbar:
plt.colorbar()
mysavefig(('modnoise-%02i-%02i'+fmt) % (i,step))
if 'chibest' in plotnames:
chi = tractor.getChiImage(i)
plt.clf()
plt.gca().set_position(plotpos0)
plt.imshow(chi, **imchi)
tt = 'Chi (best) %s' % tim.name
if tsuf is not None:
tt += tsuf
plt.title(tt)
plt.xticks([],[])
plt.yticks([],[])
if colorbar:
plt.colorbar()
mysavefig(('chibest-%02i-%02i'+fmt) % (i,step))
# plt.clf()
# plt.gca().set_position(plotpos0)
# plt.imshow(chi, **imchi2)
# plt.title(tt)
# plt.xticks([],[])
# plt.yticks([],[])
# plt.colorbar()
# mysavefig('chibest2-%02i-%02i'+fmt % (i,step))
if 'chinoise' in plotnames:
chi = (data - (mod + noiseim)) * tim.getInvError()
plt.clf()
plt.gca().set_position(plotpos0)
plt.imshow(chi, **imchi)
tt = 'Chi+noise %s' % tim.name
if tsuf is not None:
tt += tsuf
plt.title(tt)
plt.xticks([],[])
plt.yticks([],[])
if colorbar:
plt.colorbar()
mysavefig(('chinoise-%02i-%02i'+fmt) % (i,step))
if 'modsum' in plotnames or 'chisum' in plotnames:
modsum = None
chisum = None
if pp is None:
pp = np.array([tractor.getParams()])
nw = len(pp)
print 'modsum/chisum plots for', nw, 'walkers'
for k in xrange(nw):
tractor.setParams(pp[k,:])
mod = tractor.getModelImage(i)
chi = tractor.getChiImage(i)
if k == 0:
modsum = mod
chisum = chi
else:
modsum += mod
chisum += chi
if 'modsum' in plotnames:
plt.clf()
plt.gca().set_position(plotpos0)
myimshow(modsum/float(nw), **ima)
tt = 'Model (sum) %s' % tim.name
if tsuf is not None:
tt += tsuf
plt.title(tt)
plt.xticks([],[])
plt.yticks([],[])
if colorbar:
plt.colorbar()
mysavefig(('modsum-%02i-%02i'+fmt) % (i,step))
if 'chisum' in plotnames:
plt.clf()
plt.gca().set_position(plotpos0)
plt.imshow(chisum/float(nw), **imchi)
tt = 'Chi (sum) %s' % tim.name
if tsuf is not None:
tt += tsuf
plt.title(tt)
plt.xticks([],[])
plt.yticks([],[])
plt.colorbar()
mysavefig('chisum-%02i-%02i'+fmt % (i,step))
plt.clf()
plt.gca().set_position(plotpos0)
plt.imshow(chisum/float(nw), **imchi2)
plt.title(tt)
plt.xticks([],[])
plt.yticks([],[])
if colorbar:
plt.colorbar()
mysavefig(('chisum2-%02i-%02i'+fmt) % (i,step))
def plots(tractor, plotnames, step, pp=None, mp=None, ibest=None, imis=None, alllnp=None,
tsuf=None, colorbar=True, format='.png'):
print 'plots...'
if 'lnps' in plotnames:
plotnames.remove('lnps')
plt.figure(figsize=(6,6))
plt.clf()
plotpos0 = [0.15, 0.15, 0.84, 0.80]
plt.gca().set_position(plotpos0)
for s,lnps in enumerate(alllnp):
plt.plot(np.zeros_like(lnps)+s, lnps, 'r.')
plt.savefig('lnps-%02i.png' % step)
args = []
if imis is None:
imis = range(len(tractor.getImages()))
NI = len(tractor.getImages())
for i in imis:
if i >= NI:
print 'Skipping plot of image', i, 'with N images', NI
continue
zr = tractor.getImage(i).zr
args.append((tractor, i, zr, plotnames, step, pp, ibest, tsuf, colorbar, format))
if mp is None:
map(plot1, args)
else:
mp.map(plot1, args)
print 'plots done'
def nlmap(X):
S = 0.01
return np.arcsinh(X * S)/S
def myimshow(x, *args, **kwargs):
if kwargs.get('nonl', False):
kwargs = kwargs.copy()
kwargs.pop('nonl')
return plt.imshow(x, *args, **kwargs)
mykwargs = kwargs.copy()
if 'vmin' in kwargs:
mykwargs['vmin'] = nlmap(kwargs['vmin'])
if 'vmax' in kwargs:
mykwargs['vmax'] = nlmap(kwargs['vmax'])
return plt.imshow(nlmap(x), *args, **mykwargs)
def getlnp((tractor, i, par0, step)):
tractor.setParam(i, par0+step)
lnp = tractor.getLogProb()
tractor.setParam(i, par0)
return lnp
dpool = None
def pool_stats():
if dpool is None:
return
print 'Total pool CPU time:', dpool.get_worker_cpu()
def cut_bright(cat, magcut=24, mag='i'):
brightcat = Catalog()
I = []
mags = []
for i,src in enumerate(cat):
#m = getattr(src.getBrightness(), mag)
m = src.getBrightness().getMag(mag)
if m < magcut:
#brightcat.append(src)
I.append(i)
mags.append(m)
J = np.argsort(mags)
I = np.array(I)
I = I[J]
for i in I:
brightcat.append(cat[i])
return brightcat, I
def get_wise_coadd_images(RA, DEC, radius, bandnums = [1,2,3,4],
nanomaggies=False):
from wise import read_wise_coadd
bands = ['w%i' % n for n in bandnums]
basedir = 'cs82data/wise/level3/'
pat = '3342p000_ab41-w%i'
#pat = '04933b137-w%i'
filtermap = None
radius /= 3600.
# HACK - no cos(dec)
radecbox = [RA-radius, RA+radius, DEC-radius, DEC+radius]
ims = []
for band in bandnums:
base = pat % band
basefn = os.path.join(basedir, base)
im = read_wise_coadd(basefn, radecroi=radecbox, filtermap=filtermap,
nanomaggies=nanomaggies)
ims.append(im)
return ims
def get_cfht_coadd_image(RA, DEC, S, bandname=None, filtermap=None,
doplots=False, psfK=3, nanomaggies=False):
if filtermap is None:
filtermap = {'i.MP9701': 'i'}
fn = 'cs82data/W4p1m1_i.V2.7A.swarp.cut.fits'
wcs = Tan(fn, 0, 1)
P = pyfits.open(fn)
image = P[0].data
phdr = P[0].header
print 'Image', image.shape
(H,W) = image.shape
OH,OW = H,W
#x,y = np.array([1,W,W,1,1]), np.array([1,1,H,H,1])
#rco,dco = wcs.pixelxy2radec(x, y)
# The coadd image has my ROI roughly in the middle.
# Pixel 1,1 is the high-RA, low-Dec corner.
x,y = wcs.radec2pixelxy(RA, DEC)
x -= 1
y -= 1
print 'Center pix:', x,y
xc,yc = int(x), int(y)
image = image[yc-S: yc+S, xc-S: xc+S]
image = image.copy()
print 'Subimage:', image.shape
twcs = FitsWcs(wcs)
twcs.setX0Y0(xc-S, yc-S)
xs,ys = twcs.positionToPixel(RaDecPos(RA, DEC))
print 'Subimage center pix:', xs,ys
rd = twcs.pixelToPosition(xs, ys)
print 'RA,DEC vs RaDec', RA,DEC, rd
if bandname is None:
# try looking up in filtermap.
filt = phdr['FILTER']
if filt in filtermap:
print 'Mapping filter', filt, 'to', filtermap[filt]
bandname = filtermap[filt]
else:
print 'No mapping found for filter', filt
bandname = filt
zp = float(phdr['MAGZP'])
print 'Zeropoint', zp
if nanomaggies:
photocal = LinearPhotoCal(NanoMaggies.zeropointToScale(zp), band=bandname)
else:
photocal = MagsPhotoCal(bandname, zp)
print photocal
fn = 'cs82data/W4p1m1_i.V2.7A.swarp.cut.weight.fits'
P = pyfits.open(fn)
weight = P[0].data
weight = weight[yc-S:yc+S, xc-S:xc+S].copy()
print 'Weight', weight.shape
print 'Median', np.median(weight.ravel())
invvar = weight
fn = 'cs82data/W4p1m1_i.V2.7A.swarp.cut.flag.fits'
P = pyfits.open(fn)
flags = P[0].data
flags = flags[yc-S:yc+S, xc-S:xc+S].copy()
print 'Flags', flags.shape
del P
invvar[flags == 1] = 0.
fn = 'cs82data/snap_W4p1m1_i.V2.7A.swarp.cut.fits'
psfim = pyfits.open(fn)[0].data
H,W = psfim.shape
N = 9
assert(((H % N) == 0) and ((W % N) == 0))
# Select which of the NxN PSF images applies to our cutout.
ix = int(N * float(xc) / OW)
iy = int(N * float(yc) / OH)
print 'PSF image number', ix,iy
PW,PH = W/N, H/N
print 'PSF image shape', PW,PH
psfim = psfim[iy*PH: (iy+1)*PH, ix*PW: (ix+1)*PW]
print 'my PSF image shape', PW,PH
psfim = np.maximum(psfim, 0)
psfim /= np.sum(psfim)
K = psfK
w,mu,sig = em_init_params(K, None, None, None)
xm,ym = -(PW/2), -(PH/2)
em_fit_2d(psfim, xm, ym, w, mu, sig)
tpsf = GaussianMixturePSF(w, mu, sig)
tsky = ConstantSky(0.)
obj = phdr['OBJECT'].strip()
tim = Image(data=image, invvar=invvar, psf=tpsf, wcs=twcs, photocal=photocal,
sky=tsky, name='CFHT coadd %s %s' % (obj, bandname))
# set "zr" for plots
sig = 1./np.median(tim.inverr)
tim.zr = np.array([-1., +20.]) * sig
if not doplots:
return tim
psfimpatch = Patch(-(PW/2), -(PH/2), psfim)
# number of Gaussian components
for K in range(1, 4):
w,mu,sig = em_init_params(K, None, None, None)
xm,ym = -(PW/2), -(PH/2)
em_fit_2d(psfim, xm, ym, w, mu, sig)
#print 'w,mu,sig', w,mu,sig
psf = GaussianMixturePSF(w, mu, sig)
patch = psf.getPointSourcePatch(0, 0)
plt.clf()
plt.subplot(1,2,1)
plt.imshow(patch.getImage(), interpolation='nearest', origin='lower')
plt.colorbar()
plt.subplot(1,2,2)
plt.imshow((patch - psfimpatch).getImage(), interpolation='nearest', origin='lower')
plt.colorbar()
plt.savefig('copsf-%i.png' % K)
plt.clf()
plt.imshow(psfim, interpolation='nearest', origin='lower')
plt.colorbar()
plt.savefig('copsf.png')
print 'image min', image.min()
plt.clf()
plt.imshow(image, interpolation='nearest', origin='lower',
vmin=0, vmax=10.)
plt.colorbar()
plt.savefig('coim.png')
plt.clf()
plt.imshow(image, interpolation='nearest', origin='lower',
vmin=0, vmax=3.)
plt.colorbar()
plt.savefig('coim2.png')
plt.clf()
plt.imshow(image, interpolation='nearest', origin='lower',
vmin=0, vmax=1.)
plt.colorbar()
plt.savefig('coim3.png')
plt.clf()
plt.imshow(image, interpolation='nearest', origin='lower',
vmin=0, vmax=0.3)
plt.colorbar()
plt.savefig('coim4.png')
plt.clf()
plt.imshow(image * np.sqrt(invvar), interpolation='nearest', origin='lower',
vmin=-3, vmax=10.)
plt.colorbar()
plt.savefig('cochi.png')
plt.clf()
plt.imshow(weight, interpolation='nearest', origin='lower')
plt.colorbar()
plt.savefig('cowt.png')
plt.clf()
plt.imshow(invvar, interpolation='nearest', origin='lower')
plt.colorbar()
plt.savefig('coiv.png')
plt.clf()
plt.imshow(flags, interpolation='nearest', origin='lower')
plt.colorbar()
plt.savefig('cofl.png')
return tim
def optsources_searchlight(tractor, im, step0,
npix = 100,
doplots=True, plotsa={},
mindlnp=1e-3):
step = step0
alllnp = []
# # sweep across the image, optimizing in circles.
# # we'll use the healpix grid for circle centers.
# # how big? in arcmin
# R = 0.25
# Rpix = R / 60. / np.sqrt(np.abs(np.linalg.det(im.wcs.cdAtPixel(0,0))))
# nside = int(healpix_nside_for_side_length_arcmin(R/2.))
# if nside > 13377:
# print 'Clamping Nside from', nside, 'to 13376'
# nside = 13376
# print 'Nside', nside
# #print 'radius in pixels:', Rpix
# # start in one corner.
# pos = im.wcs.pixelToPosition(0, 0)
# hp = radecdegtohealpix(pos.ra, pos.dec, nside)
# hpqueue = [hp]
# hpdone = []
H,W = im.shape
nx,ny = int(np.ceil(W / float(npix))), int(np.ceil(H / float(npix)))
XX = np.linspace(npix/2, W-npix/2, nx)
YY = np.linspace(npix/2, H-npix/2, ny)
dx,dy = XX[1]-XX[0], YY[1]-YY[0]
print 'Optimizing on a grid of', len(XX), 'x', len(YY), 'cells'