-
Notifications
You must be signed in to change notification settings - Fork 50
/
prep.py
3585 lines (2796 loc) · 128 KB
/
prep.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
"""
Align direct images & make mosaics
"""
import os
from collections import OrderedDict
import glob
import numpy as np
import matplotlib.pyplot as plt
# conda install shapely
# from shapely.geometry.polygon import Polygon
import astropy.io.fits as pyfits
import astropy.wcs as pywcs
import astropy.units as u
import astropy.coordinates as coord
from astropy.table import Table
from . import utils
from . import model
def check_status():
"""Make sure all files and modules are in place and print some information if they're not
"""
for ref_dir in ['iref']:
if not os.getenv(ref_dir):
print("""
No ${0} set! Make a directory and point to it in ~/.bashrc or ~/.cshrc.
For example,
$ mkdir $GRIZLI/{0}
$ export {0}="$GRIZLI/{0}/" # put this in ~/.bashrc
""".format(ref_dir))
else:
### WFC3
if not os.getenv('iref').endswith('/'):
print("Warning: $iref should end with a '/' character [{0}]".format(os.getenv('iref')))
test_file = 'iref$uc72113oi_pfl.fits'.replace('iref$', os.getenv('iref'))
if not os.path.exists(test_file):
print("""
HST calibrations not found in $iref [{0}]
To fetch them, run
>>> import grizli.utils
>>> grizli.utils.fetch_default_calibs()
""".format(os.getenv('iref')))
### Sewpy
# try:
# import sewpy
# except:
# print("""
# `sewpy` module needed for wrapping SExtractor within python.
# Get it from https://github.com/megalut/sewpy.
# """)
#
check_status()
def go_all():
"""TBD
"""
from stsci.tools import asnutil
info = Table.read('files.info', format='ascii.commented_header')
# files=glob.glob('../RAW/i*flt.fits')
# info = utils.get_flt_info(files)
for col in info.colnames:
if not col.islower():
info.rename_column(col, col.lower())
output_list, filter_list = utils.parse_flt_files(info=info, uniquename=False)
for key in output_list:
#files = [os.path.basename(file) for file in output_list[key]]
files = output_list[key]
asn = asnutil.ASNTable(files, output=key)
asn.create()
asn.write()
def fresh_flt_file(file, preserve_dq=False, path='../RAW/', verbose=True, extra_badpix=True, apply_grism_skysub=True, crclean=False, mask_regions=True):
"""Copy "fresh" unmodified version of a data file from some central location
TBD
Parameters
----------
preserve_dq : bool
Preserve DQ arrays of files if they exist in './'
path : str
Path where to find the "fresh" files
verbose : bool
Print information about what's being done
extra_badpix : bool
Apply extra bad pixel mask. Currently this is hard-coded to look for
a file "badpix_spars200_Nov9.fits" in the directory specified by
the `$iref` environment variable. The file can be downloaded from
https://github.com/gbrammer/wfc3/tree/master/data
apply_grism_skysub : bool
xx nothing now xxx
Returns
-------
Nothing, but copies the file from `path` to `./`.
"""
import shutil
local_file = os.path.basename(file)
if preserve_dq:
if os.path.exists(local_file):
im = pyfits.open(local_file)
orig_dq = im['DQ'].data
else:
orig_dq = None
else:
dq = None
if file == local_file:
orig_file = pyfits.open(glob.glob(os.path.join(path, file)+'*')[0])
else:
orig_file = pyfits.open(file)
if dq is not None:
orig_file['DQ'] = dq
head = orig_file[0].header
### Divide grism images by imaging flats
### G102 -> F105W, uc72113oi_pfl.fits
### G141 -> F140W, uc72113oi_pfl.fits
flat, extra_msg = 1., ''
filter = utils.get_hst_filter(head)
### Copy calibs for ACS/UVIS files
if '_flc' in file:
ftpdir = 'https://hst-crds.stsci.edu/unchecked_get/references/hst/'
calib_types = ['IDCTAB', 'NPOLFILE', 'D2IMFILE']
if filter == 'G800L':
calib_types.append('PFLTFILE')
utils.fetch_hst_calibs(orig_file.filename(), ftpdir=ftpdir,
calib_types=calib_types,
verbose=False)
if filter in ['G102', 'G141']:
flat_files = {'G102': 'uc72113oi_pfl.fits',
'G141': 'uc721143i_pfl.fits'}
flat_file = flat_files[filter]
extra_msg = ' / flat: {0}'.format(flat_file)
flat_im = pyfits.open(os.path.join(os.getenv('iref'), flat_file))
flat = flat_im['SCI'].data[5:-5, 5:-5]
flat_dq = (flat < 0.2)
### Grism FLT from IR amplifier gain
pfl_file = orig_file[0].header['PFLTFILE'].replace('iref$',
os.getenv('iref'))
grism_pfl = pyfits.open(pfl_file)[1].data[5:-5,5:-5]
orig_file['DQ'].data |= 4*flat_dq
orig_file['SCI'].data *= grism_pfl/flat
# if apply_grism_skysub:
# if 'GSKY001' in orig_file:
if filter == 'G280':
### Use F200LP flat
flat_files = {'G280':'zcv2053ei_pfl.fits'} # F200LP
flat_file = flat_files[filter]
extra_msg = ' / flat: {0}'.format(flat_file)
flat_im = pyfits.open(os.path.join(os.getenv('jref'), flat_file))
for ext in [1,2]:
flat = flat_im['SCI',ext].data
flat_dq = (flat < 0.2)
orig_file['DQ',ext].data |= 4*flat_dq
orig_file['SCI',ext].data *= 1./flat
if filter == 'G800L':
flat_files = {'G800L':'n6u12592j_pfl.fits'} # F814W
flat_file = flat_files[filter]
extra_msg = ' / flat: {0}'.format(flat_file)
flat_im = pyfits.open(os.path.join(os.getenv('jref'), flat_file))
pfl_file = orig_file[0].header['PFLTFILE'].replace('jref$',
os.getenv('jref'))
pfl_im = pyfits.open(pfl_file)
for ext in [1,2]:
flat = flat_im['SCI',ext].data
flat_dq = (flat < 0.2)
grism_pfl = pfl_im['SCI',ext].data
orig_file['DQ',ext].data |= 4*flat_dq
orig_file['SCI',ext].data *= grism_pfl/flat
if orig_file[0].header['NPOLFILE'] == 'N/A':
# Use an F814W file, but this should be updated
orig_file[0].header['NPOLFILE'] = 'jref$v971826jj_npl.fits'
if head['INSTRUME'] == 'WFPC2':
head['DETECTOR'] = 'WFPC2'
if (head['INSTRUME'] == 'WFC3') & (head['DETECTOR'] == 'IR')&extra_badpix:
bp = pyfits.open(os.path.join(os.getenv('iref'),
'badpix_spars200_Nov9.fits'))
if orig_file['DQ'].data.shape == bp[0].data.shape:
orig_file['DQ'].data |= bp[0].data
extra_msg += ' / bpix: $iref/badpix_spars200_Nov9.fits'
if crclean:
import lacosmicx
for ext in [1,2]:
print('Clean CRs with LACosmic, extension {0:d}'.format(ext))
sci = orig_file['SCI',ext].data
dq = orig_file['DQ',ext].data
crmask, clean = lacosmicx.lacosmicx(sci, inmask=None,
sigclip=4.5, sigfrac=0.3, objlim=5.0, gain=1.0,
readnoise=6.5, satlevel=65536.0, pssl=0.0, niter=4,
sepmed=True, cleantype='meanmask', fsmode='median',
psfmodel='gauss', psffwhm=2.5,psfsize=7, psfk=None,
psfbeta=4.765, verbose=False)
dq[crmask] |= 1024
sci[crmask] = 0
if verbose:
print('{0} -> {1} {2}'.format(orig_file.filename(), local_file, extra_msg))
### WFPC2
if '_c0m' in file:
# point to FITS reference files
for key in ['MASKFILE', 'ATODFILE', 'BLEVFILE', 'BLEVDFIL', 'BIASFILE', 'BIASDFIL', 'DARKFILE', 'DARKDFIL', 'FLATFILE', 'FLATDFIL', 'SHADFILE']:
ref_file = '_'.join(head[key].split('.'))+'.fits'
orig_file[0].header[key] = ref_file.replace('h.fits', 'f.fits')
waiv = orig_file[0].header['FLATFILE']
orig_file[0].header['FLATFILE'] = waiv.replace('.fits', '_c0h.fits')
#
# ## testing
# orig_file[0].header['FLATFILE'] = 'm341820ju_pfl.fits'
# Make sure has correct header keys
for ext in range(4):
if 'BUNIT' not in orig_file[ext+1].header:
orig_file[ext+1].header['BUNIT'] = 'COUNTS'
# Copy WFPC2 DQ file (c1m)
dqfile = os.path.join(path, file.replace('_c0m', '_c1m'))
print('Copy WFPC2 DQ file: {0}'.format(dqfile))
if os.path.exists(os.path.basename(dqfile)):
os.remove(os.path.basename(dqfile))
shutil.copy(dqfile, './')
## Add additional masking since AstroDrizzle having trouble with flats
flat_file = orig_file[0].header['FLATFILE'].replace('uref$', os.getenv('uref')+'/')
pfl = pyfits.open(flat_file)
c1m = pyfits.open(os.path.basename(dqfile), mode='update')
for ext in [1,2,3,4]:
mask = pfl[ext].data > 1.3
c1m[ext].data[mask] |= 2
c1m.flush()
orig_file.writeto(local_file, clobber=True)
if mask_regions:
apply_region_mask(local_file, dq_value=1024)
def apply_persistence_mask(flt_file, path='../Persistence', dq_value=1024,
err_threshold=0.6, grow_mask=3, subtract=True,
verbose=True):
"""Make a mask for pixels flagged as being affected by persistence
Persistence products can be downloaded from https://archive.stsci.edu/prepds/persist/search.php, specifically the
"_persist.fits" files.
Parameters
----------
flt_file : str
Filename of the WFC3/IR FLT exposure
path : str
Path to look for the "persist.fits" file.
dq_value : int
DQ bit to flip for flagged pixels
err_threshold : float
Threshold for defining affected pixels:
flagged = persist > err_threshold*ERR
grow_mask : int
Factor by which to dilate the persistence mask.
subtract : bool
Subtract the persistence model itself from the SCI extension.
verbose : bool
Print information to the terminal
Returns
-------
Nothing, updates the DQ extension of `flt_file`.
"""
import scipy.ndimage as nd
flt = pyfits.open(flt_file, mode='update')
pers_file = os.path.join(path,
os.path.basename(flt_file).replace('_flt.fits', '_persist.fits'))
if not os.path.exists(pers_file):
if verbose:
print('Persistence file {0} not found'.format(pers_file))
#return 0
pers = pyfits.open(pers_file)
pers_mask = pers['SCI'].data > err_threshold*flt['ERR'].data
if grow_mask > 0:
pers_mask = nd.maximum_filter(pers_mask*1, size=grow_mask)
else:
pers_mask = pers_mask * 1
NPERS = pers_mask.sum()
if verbose:
print('{0}: flagged {1:d} pixels affected by persistence (pers/err={2:.2f})'.format(pers_file, NPERS, err_threshold))
if NPERS > 0:
flt['DQ'].data[pers_mask > 0] |= dq_value
if subtract:
dont_subtract=False
if 'SUBPERS' in flt[0].header:
if flt[0].header['SUBPERS']:
dont_subtract = True
if not dont_subtract:
flt['SCI'].data -= pers['SCI'].data
flt['ERR'].data = np.sqrt(flt['ERR'].data**2+pers['SCI'].data**2)
flt[0].header['SUBPERS'] = (True, 'Persistence model subtracted')
flt.flush()
def apply_region_mask(flt_file, dq_value=1024, verbose=True):
"""Apply DQ mask from a DS9 region file
Parameters
----------
flt_file : str
Filename of the FLT exposure
dq_value : int
DQ bit to flip for affected pixels
Searches for region files with filenames like
`flt_file.replace('_flt.fits','.[ext].mask.reg')`, where `[ext]` is an
integer referring to the SCI extension in the FLT file.
"""
import pyregion
mask_files = glob.glob(flt_file.replace('_flt.fits','.*.mask.reg').replace('_flc.fits','.*.mask.reg').replace('_c0m.fits','.*.mask.reg'))
if len(mask_files) == 0:
return True
if verbose:
print('Region mask for {0}: {1}'.format(flt_file, mask_files))
flt = pyfits.open(flt_file, mode='update')
for mask_file in mask_files:
ext = int(mask_file.split('.')[-3])
try:
reg = pyregion.open(mask_file).as_imagecoord(flt['SCI',ext].header)
mask = reg.get_mask(hdu=flt['SCI',ext])
except:
# Above fails for lookup-table distortion (ACS / UVIS)
# Here just assume the region file is defined in image coords
reg = pyregion.open(mask_file)
mask = reg.get_mask(shape=flt['SCI',ext].data.shape)
flt['DQ',ext].data[mask] |= dq_value
flt.flush()
return True
def apply_saturated_mask(flt_file, dq_value=1024):
"""Saturated WFC3/IR pixels have some pulldown in the opposite amplifier
Parameters
----------
flt_file : str
Filename of the FLT exposure
dq_value : int
DQ bit to flip for affected pixels
Returns
-------
Nothing, modifies DQ extension of `flt_file` in place.
"""
import scipy.ndimage as nd
flt = pyfits.open(flt_file, mode='update')
sat = (((flt['DQ'].data & 256) > 0) & ((flt['DQ'].data & 4) == 0))
## Don't flag pixels in lower right corner
sat[:80,-80:] = False
## Flag only if a number of nearby pixels also saturated
kern = np.ones((3,3))
sat_grow = nd.convolve(sat*1, kern)
sat_mask = (sat & (sat_grow > 2))[::-1,:]*1
NSAT = sat_mask.sum()
if verbose:
print('{0}: flagged {1:d} pixels affected by saturation pulldown'.format(flt_file, NSAT))
if NSAT > 0:
flt['DQ'].data[sat_mask > 0] |= dq_value
flt.flush()
def clip_lists(input, output, clip=20):
"""TBD
Clip [x,y] arrays of objects that don't have a match within `clip` pixels
in either direction
"""
import scipy.spatial
tree = scipy.spatial.cKDTree(input, 10)
### Forward
N = output.shape[0]
dist, ix = np.zeros(N), np.zeros(N, dtype=int)
for j in range(N):
dist[j], ix[j] = tree.query(output[j,:], k=1,
distance_upper_bound=np.inf)
ok = dist < clip
out_arr = output[ok]
if ok.sum() == 0:
print('No matches within `clip={0:f}`'.format(clip))
return False
### Backward
tree = scipy.spatial.cKDTree(out_arr, 10)
N = input.shape[0]
dist, ix = np.zeros(N), np.zeros(N, dtype=int)
for j in range(N):
dist[j], ix[j] = tree.query(input[j,:], k=1,
distance_upper_bound=np.inf)
ok = dist < clip
in_arr = input[ok]
return in_arr, out_arr
def match_lists(input, output, transform=None, scl=3600., simple=True,
outlier_threshold=5, toler=5):
"""TBD
Compute matched objects and transformation between two [x,y] lists.
If `transform` is None, use Similarity transform (shift, scale, rot)
"""
import copy
from astropy.table import Table
import skimage.transform
from skimage.measure import ransac
import stsci.stimage
if transform is None:
transform = skimage.transform.SimilarityTransform
#print 'xyxymatch'
if (len(output) == 0) | (len(input) == 0):
print('No entries!')
return input, output, None, transform()
match = stsci.stimage.xyxymatch(copy.copy(input), copy.copy(output),
origin=np.median(input, axis=0),
mag=(1.0, 1.0), rotation=(0.0, 0.0),
ref_origin=np.median(input, axis=0),
algorithm='tolerance', tolerance=toler,
separation=0.5, nmatch=10, maxratio=10.0,
nreject=10)
m = Table(match)
output_ix = m['ref_idx'].data
input_ix = m['input_idx'].data
tf = transform()
tf.estimate(input[input_ix,:], output[output_ix])
if not simple:
model, inliers = ransac((input[input_ix,:], output[output_ix]),
transform, min_samples=3,
residual_threshold=2, max_trials=100)
outliers = ~inliers
else:
model = tf
### Compute statistics
if len(input_ix) > 10:
mout = tf(input[input_ix,:])
dx = mout - output[output_ix]
dr = np.sqrt(np.sum(dx**2, axis=1))
outliers = dr > outlier_threshold
else:
outliers = np.zeros(len(input_ix), dtype=bool)
return input_ix, output_ix, outliers, model
def align_drizzled_image(root='', mag_limits=[14,23], radec=None, NITER=3,
clip=20, log=True, outlier_threshold=5,
verbose=True, guess=[0., 0., 0., 1]):
"""TBD
"""
if hasattr(radec, 'upper'):
rd_ref = np.loadtxt(radec)
else:
rd_ref = radec*1
if not os.path.exists('{0}.cat.fits'.format(root)):
#cat = make_drz_catalog(root=root)
cat = make_SEP_catalog(root=root)
else:
cat = Table.read('{0}.cat.fits'.format(root))
### Clip obviously distant files to speed up match
rd_cat = np.array([cat['X_WORLD'], cat['Y_WORLD']])
rd_cat_center = np.median(rd_cat, axis=1)
cosdec = np.array([np.cos(rd_cat_center[1]/180*np.pi),1])
dr_cat = np.sqrt(np.sum((rd_cat.T-rd_cat_center)**2*cosdec**2, axis=1))
#print('xxx', rd_ref.shape, rd_cat_center.shape, cosdec.shape)
dr = np.sqrt(np.sum((rd_ref-rd_cat_center)**2*cosdec**2, axis=1))
rd_ref = rd_ref[dr < 1.1*dr_cat.max(),:]
ok = (cat['MAG_AUTO'] > mag_limits[0]) & (cat['MAG_AUTO'] < mag_limits[1])
if ok.sum() == 0:
print('{0}.cat: no objects found in magnitude range {1}'.format(root,
mag_limits))
return False
xy_drz = np.array([cat['X_IMAGE'][ok], cat['Y_IMAGE'][ok]]).T
drz_file = glob.glob('{0}_dr[zc]_sci.fits'.format(root))[0]
drz_im = pyfits.open(drz_file)
sh = drz_im[0].data.shape
drz_wcs = pywcs.WCS(drz_im[0].header, relax=True)
orig_wcs = drz_wcs.copy()
#out_shift, out_rot, out_scale = np.zeros(2), 0., 1.
out_shift, out_rot, out_scale = guess[:2], guess[2], guess[3]
drz_wcs = utils.transform_wcs(drz_wcs, out_shift, out_rot, out_scale)
print('{0} (guess) : {1:6.2f} {2:6.2f} {3:7.3f} {4:7.3f}'.format(root, guess[0], guess[1], guess[2]/np.pi*180, 1./guess[3]))
NGOOD, rms = 0, 0
for iter in range(NITER):
#print('xx iter {0} {1}'.format(iter, NITER))
xy = np.array(drz_wcs.all_world2pix(rd_ref, 0))
pix = np.cast[int](np.round(xy)).T
### Find objects where drz pixels are non-zero
okp = (pix[0,:] > 0) & (pix[1,:] > 0)
okp &= (pix[0,:] < sh[1]) & (pix[1,:] < sh[0])
ok2 = drz_im[0].data[pix[1,okp], pix[0,okp]] != 0
N = ok2.sum()
status = clip_lists(xy_drz, xy+1, clip=clip)
if not status:
print('Problem xxx')
input, output = status
#print np.sum(input) + np.sum(output)
toler=5
titer=0
while (titer < 3):
try:
res = match_lists(output, input, scl=1., simple=True,
outlier_threshold=outlier_threshold, toler=toler)
output_ix, input_ix, outliers, tf = res
break
except:
toler += 5
titer += 1
#print(output.shape, output_ix.shape, output_ix.min(), output_ix.max(), titer, toler, input_ix.shape, input.shape)
titer = 0
while (len(input_ix)*1./len(input) < 0.1) & (titer < 3):
titer += 1
toler += 5
try:
res = match_lists(output, input, scl=1., simple=True,
outlier_threshold=outlier_threshold,
toler=toler)
except:
pass
output_ix, input_ix, outliers, tf = res
#print(output.shape, output_ix.shape, output_ix.min(), output_ix.max(), titer, toler, input_ix.shape, input.shape)
tf_out = tf(output[output_ix])
dx = input[input_ix] - tf_out
rms = utils.nmad(np.sqrt((dx**2).sum(axis=1)))
#outliers = outliers | (np.sqrt((dx**2).sum(axis=1)) > 4*rms)
outliers = (np.sqrt((dx**2).sum(axis=1)) > 4*rms)
if outliers.sum() > 0:
res2 = match_lists(output[output_ix][~outliers],
input[input_ix][~outliers], scl=1., simple=True,
outlier_threshold=outlier_threshold,
toler=toler)
output_ix2, input_ix2, outliers2, tf = res2
if verbose:
shift = tf.translation
NGOOD = (~outliers).sum()
print('{0} ({1:d}) {2:d}: {3:6.2f} {4:6.2f} {5:7.3f} {6:7.3f}'.format(root,iter,NGOOD,
shift[0], shift[1],
tf.rotation/np.pi*180,
1./tf.scale))
out_shift += tf.translation
out_rot -= tf.rotation
out_scale *= tf.scale
drz_wcs = utils.transform_wcs(drz_wcs, tf.translation, tf.rotation,
tf.scale)
# drz_wcs.wcs.crpix += tf.translation
# theta = -tf.rotation
# _mat = np.array([[np.cos(theta), -np.sin(theta)],
# [np.sin(theta), np.cos(theta)]])
#
# drz_wcs.wcs.cd = np.dot(drz_wcs.wcs.cd, _mat)/tf.scale
if log:
tf_out = tf(output[output_ix][~outliers])
dx = input[input_ix][~outliers] - tf_out
rms = utils.nmad(np.sqrt((dx**2).sum(axis=1)))
interactive_status=plt.rcParams['interactive']
plt.ioff()
fig = plt.figure(figsize=[6.,6.])
ax = fig.add_subplot(111)
ax.scatter(dx[:,0], dx[:,1], alpha=0.5, color='b')
ax.scatter([0],[0], marker='+', color='red', s=40)
ax.set_xlabel(r'$dx$'); ax.set_ylabel(r'$dy$')
ax.set_title(root)
ax.set_xlim(-7*rms, 7*rms)
ax.set_ylim(-7*rms, 7*rms)
ax.grid()
fig.tight_layout(pad=0.1)
fig.savefig('{0}_wcs.png'.format(root))
plt.close()
if interactive_status:
plt.ion()
log_wcs(root, orig_wcs, out_shift, out_rot/np.pi*180, out_scale, rms,
n=NGOOD, initialize=False)
return orig_wcs, drz_wcs, out_shift, out_rot/np.pi*180, out_scale
def log_wcs(root, drz_wcs, shift, rot, scale, rms=0., n=-1, initialize=True):
"""Save WCS offset information to a file
"""
if (not os.path.exists('{0}_wcs.log'.format(root))) | initialize:
print('Initialize {0}_wcs.log'.format(root))
orig_hdul = pyfits.HDUList()
fp = open('{0}_wcs.log'.format(root), 'w')
fp.write('# ext xshift yshift rot scale rms N\n')
fp.write('# {0}\n'.format(root))
count = 0
else:
orig_hdul = pyfits.open('{0}_wcs.fits'.format(root))
fp = open('{0}_wcs.log'.format(root), 'a')
count = len(orig_hdul)
hdu = drz_wcs.to_fits()[0]
orig_hdul.append(hdu)
orig_hdul.writeto('{0}_wcs.fits'.format(root), clobber=True)
fp.write('{0:5d} {1:13.4f} {2:13.4f} {3:13.4f} {4:13.5f} {5:13.3f} {6:4d}\n'.format(
count, shift[0], shift[1], rot, scale, rms, n))
fp.close()
def table_to_radec(table, output='coords.radec'):
"""Make a DS9 region file from a table object
"""
if 'X_WORLD' in table.colnames:
rc, dc = 'X_WORLD', 'Y_WORLD'
else:
rc, dc = 'ra', 'dec'
table[rc, dc].write(output, format='ascii.commented_header',
overwrite=True)
def table_to_regions(table, output='ds9.reg', comment=None):
"""Make a DS9 region file from a table object
"""
fp = open(output,'w')
fp.write('fk5\n')
if 'X_WORLD' in table.colnames:
rc, dc = 'X_WORLD', 'Y_WORLD'
else:
rc, dc = 'ra', 'dec'
### GAIA
if 'solution_id' in table.colnames:
e = np.sqrt(table['ra_error']**2+table['dec_error']**2)/1000.
e = np.maximum(e, 0.1)
else:
e = np.ones(len(table))*0.5
lines = ['circle({0:.7f}, {1:.7f}, {2:.3f}")\n'.format(table[rc][i],
table[dc][i], e[i])
for i in range(len(table))]
if comment is not None:
for i in range(len(table)):
lines[i] = '{0} # text={{{1}}}\n'.format(lines[i].strip(), comment[i])
fp.writelines(lines)
fp.close()
SEXTRACTOR_DEFAULT_PARAMS = ["NUMBER", "X_IMAGE", "Y_IMAGE", "X_WORLD",
"Y_WORLD", "A_IMAGE", "B_IMAGE", "THETA_IMAGE",
"MAG_AUTO", "MAGERR_AUTO", "FLUX_AUTO", "FLUXERR_AUTO",
"FLUX_RADIUS", "BACKGROUND", "FLAGS"]
SEXTRACTOR_PHOT_APERTURES = "6, 8.335, 16.337, 20"
SEXTRACTOR_CONFIG_3DHST = {'DETECT_MINAREA':14, 'DEBLEND_NTHRESH':32, 'DEBLEND_MINCONT':0.005, 'FILTER_NAME':'/usr/local/share/sextractor/gauss_3.0_7x7.conv', 'FILTER':'Y'}
# /usr/local/share/sextractor/gauss_3.0_7x7.conv
GAUSS_3_7x7 = np.array(
[[ 0.004963, 0.021388, 0.051328, 0.068707, 0.051328, 0.021388, 0.004963],
[ 0.021388, 0.092163, 0.221178, 0.296069, 0.221178, 0.092163, 0.021388],
[ 0.051328, 0.221178, 0.530797, 0.710525, 0.530797, 0.221178, 0.051328],
[ 0.068707, 0.296069, 0.710525, 0.951108, 0.710525, 0.296069, 0.068707],
[ 0.051328, 0.221178, 0.530797, 0.710525, 0.530797, 0.221178, 0.051328],
[ 0.021388, 0.092163, 0.221178, 0.296069, 0.221178, 0.092163, 0.021388],
[ 0.004963, 0.021388, 0.051328, 0.068707, 0.051328, 0.021388, 0.004963]])
def make_SEP_catalog(root='',threshold=2., get_background=True,
verbose=True, extra_config={}, sci=None, wht=None,
phot_apertures=SEXTRACTOR_PHOT_APERTURES,
filter_kernel=GAUSS_3_7x7, filter_type='conv',
clean=True, rescale_weight=True, minarea=14,
column_case=str.upper, save_to_fits=True,
source_xy=None, autoparams=[2.5, 3.5], mask_kron=False,
max_total_corr=2,
**kwargs):
"""Make a catalog from drizzle products using the SEP implementation of SExtractor
"""
import copy
import astropy.units as u
import sep
if sci is not None:
drz_file = sci
else:
drz_file = glob.glob('{0}_dr[zc]_sci.fits'.format(root))[0]
im = pyfits.open(drz_file)
## Get AB zeropoint
if 'PHOTFNU' in im[0].header:
ZP = -2.5*np.log10(im[0].header['PHOTFNU'])+8.90
elif 'PHOTFLAM' in im[0].header:
ZP = (-2.5*np.log10(im[0].header['PHOTFLAM']) - 21.10 -
5*np.log10(im[0].header['PHOTPLAM']) + 18.6921)
elif 'FILTER' in im[0].header:
fi = im[0].header['FILTER'].upper()
if fi in model.photflam_list:
ZP = (-2.5*np.log10(model.photflam_list[fi]) - 21.10 -
5*np.log10(model.photplam_list[fi]) + 18.6921)
else:
print('Couldn\'t find PHOTFNU or PHOTPLAM/PHOTFLAM keywords, use ZP=25')
ZP = 25
else:
print('Couldn\'t find FILTER, PHOTFNU or PHOTPLAM/PHOTFLAM keywords, use ZP=25')
ZP = 25
if verbose:
print('Image AB zeropoint: {0:.3f}'.format(ZP))
# Scale fluxes to mico-Jy
uJy_to_dn = 1/(3631*1e6*10**(-0.4*ZP))
weight_file = drz_file.replace('_sci.fits', '_wht.fits').replace('_drz.fits', '_wht.fits')
if (weight_file == drz_file) | (not os.path.exists(weight_file)):
WEIGHT_TYPE = "NONE"
weight_file = None
else:
WEIGHT_TYPE = "MAP_WEIGHT"
drz_im = pyfits.open(drz_file)
data = drz_im[0].data.byteswap().newbyteorder()
data_mask = np.cast[data.dtype](data == 0)
try:
wcs = pywcs.WCS(drz_im[0].header)
wcs_header = utils.to_header(wcs)
except:
wcs = None
wcs_header = drz_im[0].header.copy()
if weight_file is not None:
wht_im = pyfits.open(weight_file)
wht_data = wht_im[0].data.byteswap().newbyteorder()
err = 1/np.sqrt(wht_data)
err[~np.isfinite(err)] = 0
mask = (err == 0)
else:
mask = (data == 0)
err = None
if get_background:
bkg = sep.Background(data, mask=mask, bw=32, bh=32, fw=3, fh=3)
bkg_data = bkg.back()
pyfits.writeto('{0}_bkg.fits'.format(root), data=bkg_data,
header=wcs_header, overwrite=True)
if err is None:
err = bkg.rms()
ratio = bkg.rms()/err
err_scale = np.median(ratio[(~mask) & np.isfinite(ratio)])
else:
bkg_data = 0.
err_scale = 1.
if rescale_weight:
err *= err_scale
#mask = None
if source_xy is None:
### Run the detection
objects, seg = sep.extract(data - bkg_data, threshold, err=err,
mask=mask, minarea=minarea,
filter_kernel=filter_kernel,
filter_type=filter_type, deblend_nthresh=32,
deblend_cont=0.005, clean=clean, clean_param=1.,
segmentation_map=True)
tab = utils.GTable(objects)
# make one indexed like SExtractor
tab['x'] += 1
tab['y'] += 1
# ID
tab['number'] = np.arange(len(tab), dtype=np.int32)+1
## Segmentation
pyfits.writeto('{0}_seg.fits'.format(root), data=seg,
header=wcs_header, overwrite=True)
for c in ['a','b']:
tab = tab[np.isfinite(tab[c])]
# WCS coordinates
if wcs is not None:
tab['ra'], tab['dec'] = wcs.all_pix2world(tab['x'], tab['y'], 1)
tab['ra'].unit = u.deg
tab['dec'].unit = u.deg
tab['x_world'], tab['y_world'] = tab['ra'], tab['dec']
tab.meta['MINAREA'] = (minarea, 'Minimum source area in pixels')
tab.meta['CLEAN'] = clean
tab.meta['FILTER_TYPE'] = (filter_type, 'Type of filter applied, conv or weight')
tab.meta['THRESHOLD'] = (threshold, 'Detection threshold')
## FLUX_AUTO
# https://sep.readthedocs.io/en/v1.0.x/apertures.html#equivalent-of-flux-auto-e-g-mag-auto-in-source-extractor
kronrad, krflag = sep.kron_radius(data - bkg_data,
tab['x']-1, tab['y']-1,
tab['a'], tab['b'], tab['theta'], 6.0)
#kronrad *= 2.5
kronrad *= autoparams[0]
kronrad[~np.isfinite(kronrad)] = autoparams[1]
kronrad = np.maximum(kronrad, autoparams[1])
kron_out = sep.sum_ellipse(data - bkg_data,
tab['x']-1, tab['y']-1,
tab['a'], tab['b'], tab['theta'],
kronrad, subpix=5, err=err)
kron_flux, kron_fluxerr, kron_flag = kron_out
kron_flux_flag = kron_flag
## By object
# kronrad = tab['x']*1.
# krflag = kronrad*1.
if mask_kron:
if mask_kron*1 == 1:
# Only flagged objects
keep = (tab['flag'] & 1) > 0
else:
keep = tab['flag'] > -1
print('Manual mask for Kron radius/flux')
for i in range(len(tab)):
#print(keep[i], tab['flag'][i], mask_kron*1)
if not keep[i]:
continue
id = tab['number'][i]
#print('Kron ',id)
mask = (seg > 0) & (seg != id)
kr, krflag[i] = sep.kron_radius(data - bkg_data,
tab['x'][i]-1, tab['y'][i]-1,
tab['a'][i], tab['b'][i],
tab['theta'][i], 6.0, mask=mask)
kronrad[i] = np.maximum(kr*autoparams[0], autoparams[1])
out = sep.sum_ellipse(data - bkg_data,
tab['x'][i]-1, tab['y'][i]-1,
tab['a'][i], tab['b'][i],
tab['theta'][i],
kronrad[i], subpix=5, mask=mask,
err=err)
kron_flux[i], kron_fluxerr[i], kron_flux_flag[i] = out
# Minimum radius = 3.5, PHOT_AUTOPARAMS 2.5, 3.5
# r_min = autoparams[1] #3.5
# #use_circle = kronrad * np.sqrt(tab['a'] * tab['b']) < r_min
# use_circle = kronrad < r_min
# kron_out = sep.sum_ellipse(data - bkg_data,
# tab['x'][use_circle]-1,
# tab['y'][use_circle]-1,
# tab['a'][use_circle], tab['b'][use_circle],
# tab['theta'][use_circle],
# r_min, subpix=5)
#
# cflux, cfluxerr, cflag = kron_out
# kron_flux_flag[use_circle] = cflag
# cflux, cfluxerr, cflag = sep.sum_circle(data - bkg_data,
# tab['x'][use_circle]-1,