/
prep.py
7686 lines (5970 loc) · 266 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
import inspect
import gc
import warnings
import shutil
from collections import OrderedDict
import glob
import traceback
import yaml
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 jwst_utils
from . import grismconf
try:
import jwst
from jwst.pipeline import Detector1Pipeline
except ImportError:
jwst = None
print('`import jwst` failed so JWST processing will not work!')
from . import utils
from . import model
from . import GRIZLI_PATH
# Catalog table tools now put elsewhere
from .catalog import *
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')))
# check_status()
def fresh_flt_file(file, preserve_dq=False, path='../RAW/', verbose=True, extra_badpix=True, apply_grism_skysub=True, crclean=False, mask_regions=True, oneoverf_correction=True, oneoverf_kwargs={}, use_skyflats=True, do_pure_parallel_wcs=True
):
"""Copy "fresh" unmodified version of a data file from some central location
Parameters
----------
file : str
Filename
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
crclean : bool
Run LACosmicx (astroscrappy) on the exposure
mask_regions : bool
Apply exposure region mask (like ``_flt.01.mask.reg``) if it exists.
do_pure_parallel_wcs : bool
Update the WCS for JWST pure-parallel exposures from the FGS logs to fix
a MAST bug.
Returns
-------
Nothing, but copies the file from ``path`` to ``./``.
"""
try:
from astroscrappy import detect_cosmics
has_scrappy = True
except ImportError:
has_scrappy = False
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)
local_file = local_file.split('.gz')[0]
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.parse_filter_from_header(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'
# New flags for bad pix in old dark reference files
old_darks = ['x5g1509ki_drk.fits']
old_darks += ['xag1929{x}i_drk.fits'.format(x=x) for x in '345689a']
# For more recent SPARS5
old_darks += ['zb21929si_drk.fits']
#need_badpix = head['DARKFILE'].strip('iref$') in old_darks
need_badpix = True # always add the additional bad pix files
if need_badpix:
new_bp = pyfits.open(os.path.join(os.path.dirname(__file__),
'data',
'wfc3ir_dark_badpix_2019.01.12.fits.gz'))
if orig_file['DQ'].data.shape == new_bp[0].data.shape:
orig_file['DQ'].data |= new_bp[0].data
extra_msg += ' / wfc3ir_dark_badpix_2019.01.12.fits'
logstr = '# {0} -> {1} {2}'
logstr = logstr.format(orig_file.filename(), local_file, extra_msg)
utils.log_comment(utils.LOGFILE, logstr, verbose=verbose)
isACS = head['DETECTOR'] in ['UVIS','WFC']
####
# JWST
isJWST = False
if 'TELESCOP' in orig_file[0].header:
if orig_file[0].header['TELESCOP'] == 'JWST':
isJWST = True
jwst_utils.DO_PURE_PARALLEL_WCS = do_pure_parallel_wcs
orig_file.writeto(local_file, overwrite=True)
status = jwst_utils.initialize_jwst_image(local_file,
oneoverf_correction=oneoverf_correction,
oneoverf_kwargs=oneoverf_kwargs,
use_skyflats=use_skyflats)
orig_file = pyfits.open(local_file)
if crclean and has_scrappy:
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 = detect_cosmics(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
# WFPC2
if '_c0' 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')
if not os.path.exists(''):
pass
#
# ## 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('_c0', '_c1'))
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, overwrite=True)
if mask_regions:
apply_region_mask(local_file, dq_value=1024)
apply_region_mask_from_db(local_file, dq_value=1024)
# Flush objects
orig_file.close()
del(orig_file)
for _iter in range(3):
gc.collect()
def apply_persistence_mask(flt_file, path='../Persistence', dq_value=1024,
err_threshold=0.6, sci_threshold=0.1,
grow_mask=3, subtract=True,
verbose=True, reset=False):
"""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
ERR array 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.
reset : bool
Unset `dq_value` bit.
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').replace('_rate.fits', '_persist.fits'))
if not os.path.exists(pers_file):
logstr = '# Persistence file {0} not found'.format(pers_file)
utils.log_comment(utils.LOGFILE, logstr, verbose=verbose)
# return 0
pers = pyfits.open(pers_file)
if pers['SCI'].data.min() < -40:
subtract = False
pers_data = pers['SCI'].data*1
pers_data = np.maximum(pers_data, 0)
pers_mask = pers['SCI'].data > err_threshold*flt['ERR'].data
#pers_mask &= pers['SCI'].data > sci_threshold*flt['SCI'].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()
logstr = '# {0}: flagged {1:d} pixels affected by persistence (pers/err={2:.2f})'.format(pers_file, NPERS, err_threshold)
utils.log_comment(utils.LOGFILE, logstr, verbose=verbose)
flt[0].header['PERSNPIX'] = (NPERS, 'Number of persistence-flagged pixels')
flt[0].header['PERSLEVL'] = (err_threshold, 'Perristence threshold err_threshold')
flt[0].header['PERSGROW'] = (grow_mask, 'Perristence mask dilation grow_mask')
if reset:
flt['DQ'].data -= (flt['DQ'].data & dq_value)
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_data
flt['ERR'].data = np.sqrt(flt['ERR'].data**2+pers_data**2)
flt[0].header['SUBPERS'] = (True, 'Persistence model subtracted')
flt.flush()
flt.close()
def region_mask_from_ds9(ext=1):
"""
Get a region masks from a local DS9 window and make a table that can be sent to the
`exposure_region_mask` database table.
"""
import time
from .aws import db
from .ds9 import DS9
d = DS9()
rows = []
dataset = os.path.basename(d.get('file'))
dataset = dataset.split('[')[0]
regs = d.get('regions').split()
for reg in regs:
if reg.startswith('polygon'):
sr = utils.SRegion(reg, wrap=False)
rows.append([dataset, ext, sr.polystr()[0], time.time()])
tab = utils.GTable(rows=rows, names=['dataset','ext','region','time'])
if False:
db.send_to_database('exposure_region_mask', tab,
if_exists='append')
return tab
def apply_region_mask_from_db(flt_file, dq_value=1024, verbose=True, in_place=True):
"""
Query the `exposure_region_mask` table and apply masks
Parameters
----------
flt_file : str
Image filename
dq_value : int
Value to "OR" into the DQ extension
verbose : bool
Messaging
in_place : bool
Apply to DQ extension and resave `flt_file`
Returns
-------
region_mask : array-like
If a region mask for `flt_file` is found in the database, return a mask array
derived from the database footprint. Otherwise, return ``None``.
"""
try:
from .aws import db
except ImportError:
return False
try:
masks = db.SQL(f"""select * from exposure_region_mask
where dataset = '{os.path.basename(flt_file)}'
""")
except:
logstr = f'# prep.apply_region_mask_from_db: query failed'
utils.log_comment(utils.LOGFILE, logstr, verbose=verbose)
return None
if len(masks) == 0:
return None
with pyfits.open(flt_file, mode='update') as im:
sh = im['DQ'].data.shape
yp, xp = np.indices(sh)
coo = np.array([xp.flatten(), yp.flatten()]).T
region_mask = np.zeros(sh, dtype=bool)
for reg, ext in zip(masks['region'], masks['ext']):
logstr = f'# prep.apply_region_mask_from_db: {flt_file}[{ext}] mask {reg}'
utils.log_comment(utils.LOGFILE, logstr, verbose=verbose)
sr = utils.SRegion(reg, wrap=False)
region_mask |= sr.path[0].contains_points(coo).reshape(sh)
if in_place:
im['DQ',ext].data |= (region_mask*dq_value).astype(im['DQ',ext].data.dtype)
im.flush()
return region_mask
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 a FLT exposure. The function searches for region files
with filenames like
>>> mask_file = flt_file.replace('_flt.fits','.{ext}.mask.reg')
where ``{ext}`` is an integer referring to the SCI extension in the
FLT file (1 for WFC3/IR, 1 or 2 for ACS/WFC and WFC3/UVIS).
dq_value : int
DQ bit to flip for affected pixels
Returns
-------
Nothing, but updates the ``DQ`` extension of `flt_file` if a mask file
is found
"""
from regions import Regions
mask_files = glob.glob('_'.join(flt_file.split('_')[:-1]) + '.*.mask.reg')
if len(mask_files) == 0:
return True
logstr = '# Region mask for {0}: {1}'.format(flt_file, mask_files)
utils.log_comment(utils.LOGFILE, logstr, verbose=verbose)
flt = pyfits.open(flt_file, mode='update')
for mask_file in mask_files:
ext = int(mask_file.split('.')[-3])
try:
hdu = flt['SCI', ext]
reg = Regions.read(mask_file, format='ds9')[0]
reg_pix = reg.to_pixel(wcs=pywcs.WCS(hdu.header))
shape = hdu.data.shape
mask = reg_pix.to_mask().to_image(shape=shape).astype(bool)
except:
# Above fails for lookup-table distortion (ACS / UVIS)
# Here just assume the region file is defined in image coords
reg = Regions.read(mask_file, format='ds9')[0]
shape = flt['SCI', ext].data.shape
mask = reg.to_mask().to_image(shape=shape).astype(bool)
flt['DQ', ext].data[mask] |= dq_value
flt.flush()
return True
def apply_saturated_mask(flt_file, dq_value=1024, verbose=True):
"""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()
logstr = '# {0}: flagged {1:d} pixels affected by saturation pulldown'
logstr = logstr.format(flt_file, NSAT)
utils.log_comment(utils.LOGFILE, logstr, verbose=verbose)
if NSAT > 0:
flt['DQ'].data[sat_mask > 0] |= dq_value
flt.flush()
def clip_lists(input, output, clip=20):
"""Clip [x,y] arrays of objects that don't have a match within `clip` pixels in either direction
Parameters
----------
input : (array, array)
Input pixel/array coordinates
output : (array, array)
Output pixel/array coordinates
clip : float
Matching distance
Returns
-------
in_clip, out_clip : (array, array)
Clipped coordinate lists
"""
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_clip = output[ok]
if ok.sum() == 0:
print('No matches within `clip={0:f}`'.format(clip))
return False
# Backward
tree = scipy.spatial.cKDTree(out_clip, 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_clip = input[ok]
return in_clip, out_clip
def match_lists(input, output, transform=None, scl=3600., simple=True,
outlier_threshold=5, toler=5, triangle_size_limit=[5, 800],
triangle_ba_max=0.9, assume_close=False):
"""Compute matched objects and transformation between two (x,y) lists.
Parameters
----------
input : (array, array)
Input pixel/array coordinates
output : (array, array)
Output pixel/array coordinates
transform : None, `skimage.transform` object
Coordinate transformation model. If None, use
`skimage.transform.EuclideanTransform`, i.e., shift & rotation
scl : float
Not used
simple : bool
Find matches manually within `outlier_threshold`. If False, find
matches with `skimage.measure.ransac` and the specified `transform`
outlier_threshold : float
Match threshold for ``simple=False``
triangle_size_limit : (float, float)
Size limit of matching triangles, generally set to something of order
of the detector size
triangle_ba_max : float
Maximum length/height ratio of matching triangles
assume_close : bool
Not used
Returns
-------
input_ix : (array, array)
Array indices of matches from `input`
output_ix : (array, array)
Array indices of matches from `output`
outliers : (array, array)
Array indices of outliers
model : transform
Instance of the `transform` object based on the matches
"""
import copy
from astropy.table import Table
import skimage.transform
from skimage.measure import ransac
import stsci.stimage
try:
import tristars
from tristars.match import match_catalog_tri
except ImportError:
print("""
Couldn't `import tristars`. Get it from https://github.com/gbrammer/tristars to enable improved blind astrometric matching with triangle asterisms.
""")
if transform is None:
transform = skimage.transform.EuclideanTransform
# print 'xyxymatch'
if (len(output) == 0) | (len(input) == 0):
print('No entries!')
return input, output, None, transform()
try:
pair_ix = match_catalog_tri(input, output, maxKeep=10, auto_keep=3,
auto_transform=transform,
auto_limit=outlier_threshold,
size_limit=triangle_size_limit,
ignore_rot=False, ignore_scale=True,
ba_max=triangle_ba_max)
input_ix = pair_ix[:, 0]
output_ix = pair_ix[:, 1]
msg = ' tristars.match: Nin={0}, Nout={1}, match={2}'
print(msg.format(len(input), len(output), len(output_ix)))
# if False:
# fig = match.match_diagnostic_plot(input, output, pair_ix, tf=None, new_figure=True)
# fig.savefig('/tmp/xtristars.png')
# plt.close(fig)
#
# tform = get_transform(input, output, pair_ix, transform=transform, use_ransac=True)
except:
utils.log_exception(utils.LOGFILE, traceback)
utils.log_comment(utils.LOGFILE, "# ! tristars failed")
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
print(' xyxymatch.match: Nin={0}, Nout={1}, match={2}'.format(len(input), len(output), len(output_ix)))
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=3, max_trials=100)
# Iterate
if inliers.sum() > 2:
m_i, in_i = ransac((input[input_ix[inliers], :],
output[output_ix[inliers], :]),
transform, min_samples=3,
residual_threshold=3, max_trials=100)
if in_i.sum() > 2:
model = m_i
inliers[np.arange(len(inliers), dtype=np.int32)[inliers][in_i]] = False
outliers = ~inliers
mout = model(input[input_ix, :])
dx = mout - output[output_ix]
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],
simple=True,
rms_limit=2,
use_guess=False,
triangle_size_limit=[5, 1800],
max_sources=200,
triangle_ba_max=0.9,
max_err_percentile=99,
catalog_mask_pad=0.05,
min_flux_radius=1.,
min_nexp=2,
match_catalog_density=None,
assume_close=False,
ref_border=100,
transform=None,
refine_final_niter=8):
"""Pipeline for astrometric alignment of drizzled image products
1. Generate source catalog from image mosaics
2. Trim catalog lists
3. Find matches and compute (shift, rot, scale) transform
Parameters
----------
root : str
Image product rootname, passed to `~grizli.prep.make_SEP_catalog`
mag_limits : (float, float)
AB magnitude limits of objects in the image catalog to use for
the alignment
radec : str or (array, array)
Reference catalog positions (ra, dec). If `str`, will read from a
file with `np.loadtxt`, assuming just two columns
NITER : int
Number of matching/transform iterations to perform
clip : float
If positive, then coordinate arrays will be clipped with
`~grizli.prep.clip_lists`.
log : bool
Write results to `wcs.log` file and make a diagnostic figure
verbose : bool
Print status message to console
guess : list
Initial guess for alignment:
>>> guess = [0., 0., 0., 1]
>>> guess = [xshift, yshift, rot, scale]
use_guess : bool
Use the `guess`
rms_limit : float
If transform RMS exceeds this threshold, use null [0,0,0,1] transform
simple : bool
Parameter for `~grizli.prep.match_lists`
outlier_threshold : float
Parameter for `~grizli.prep.match_lists`
triangle_size_limit : (float, float)
Parameter for `~grizli.prep.match_lists`
triangle_ba_max : float
Parameter for `~grizli.prep.match_lists`
max_sources : int
Maximum number of sources to use for the matches. Triangle matching
combinatorics become slow for hundreds of sources
max_err_percentile : float
Only use sources where weight image is greater than this percentile
to try to limit spurious sources in low-weight regions
(`~grizli.utils.catalog_mask`)
catalog_mask_pad : float
Mask sources outside of this fractional size of the image dimensions
to try to limit spurius sources (`~grizli.utils.catalog_mask`)
match_catalog_density : bool, None
Try to roughly match the surface density of the reference and target
source lists, where the latter is sorted by brightness to try to
reduce spurious triangle matches
assume_close : bool
not used
ref_border : float
Only include reference sources within `ref_border` pixels of the
target image, as calculated from the original image WCS
transform : None, `skimage.transform` object
Coordinate transformation model. If None, use
`skimage.transform.EuclideanTransform`, i.e., shift & rotation
refine_final_niter : int
Number of final alignment iterations to derive the transform from simple
nearest neighbor matches after the initial `tristars` pattern matching
Returns
-------
orig_wcs : `~astropy.wcs.WCS`
Original WCS
drz_wcs : `~astropy.wcs.WCS`
Transformed WCS
out_shift : (float, float)
Translation, pixels
out_rot : float
Rotation (degrees)
out_scale : float
Scale
"""
import skimage.transform
from skimage.measure import ransac
frame = inspect.currentframe()
utils.log_function_arguments(utils.LOGFILE, frame,
'prep.align_drizzled_image')
if not os.path.exists('{0}.cat.fits'.format(root)):
#cat = make_drz_catalog(root=root)
cat = make_SEP_catalog(root=root)
else:
cat = utils.read_catalog('{0}.cat.fits'.format(root))
if hasattr(radec, 'upper'):
rd_ref = np.loadtxt(radec)
radec_comment = radec
if match_catalog_density is None:
match_catalog_density = '.cat.radec' not in radec