forked from gbrammer/grizli
/
utils.py
9925 lines (7580 loc) · 312 KB
/
utils.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
"""
Dumping ground for general utilities
"""
import os
import shutil
import glob
import inspect
from collections import OrderedDict
import warnings
import itertools
import logging
import astropy.io.fits as pyfits
import astropy.wcs as pywcs
import astropy.table
import numpy as np
import astropy.units as u
from sregion import SRegion, patch_from_polygon
from . import GRIZLI_PATH
KMS = u.km/u.s
FLAMBDA_CGS = u.erg/u.s/u.cm**2/u.angstrom
FNU_CGS = u.erg/u.s/u.cm**2/u.Hz
# character to skip clearing line on STDOUT printing
NO_NEWLINE = '\x1b[1A\x1b[1M'
# R_V for Galactic extinction
MW_RV = 3.1
MPL_COLORS = {'b': '#1f77b4', 'orange': '#ff7f0e', 'g': '#2ca02c', 'r': '#d62728', 'purple': '#9467bd', 'brown': '#8c564b', 'pink': '#e377c2', 'gray': '#7f7f7f', 'olive': '#bcbd22', 'cyan': '#17becf'}
# sns.color_palette("husl", 8)
SNS_HUSL = {'r': (0.9677975592919913, 0.44127456009157356, 0.5358103155058701),
'orange': (0.8087954113106306, 0.5634700050056693, 0.19502642696727285),
'olive': (0.5920891529639701, 0.6418467016378244, 0.1935069134991043),
'g': (0.19783576093349015, 0.6955516966063037, 0.3995301037444499),
'sea': (0.21044753832183283, 0.6773105080456748, 0.6433941168468681),
'b': (0.22335772267769388, 0.6565792317435265, 0.8171355503265633),
'purple': (0.6423044349219739, 0.5497680051256467, 0.9582651433656727),
'pink': (0.9603888539940703, 0.3814317878772117, 0.8683117650835491)}
GRISM_COLORS = {'G800L': (0.0, 0.4470588235294118, 0.6980392156862745),
'G102': (0.0, 0.6196078431372549, 0.45098039215686275),
'G141': (0.8352941176470589, 0.3686274509803922, 0.0),
'none': (0.8, 0.4745098039215686, 0.6549019607843137),
'G150': 'k',
'F277W': (0.0, 0.6196078431372549, 0.45098039215686275),
'F356W': (0.8352941176470589, 0.3686274509803922, 0.0),
'F444W': (0.8, 0.4745098039215686, 0.6549019607843137),
'F250M': 'lightblue',
'F300M': 'steelblue',
'F335M': 'cornflowerblue',
'F360M': 'royalblue',
'F410M': (0.0, 0.4470588235294118, 0.6980392156862745),
'F430M': 'sandybrown',
'F460M': 'lightsalmon',
'F480M': 'coral',
'G280': 'purple',
'F090W': (0.0, 0.4470588235294118, 0.6980392156862745),
'F115W': (0.0, 0.6196078431372549, 0.45098039215686275),
'F150W': (0.8352941176470589, 0.3686274509803922, 0.0),
'F140M': (0.8352941176470589, 0.3686274509803922, 0.0),
'F158M': (0.8352941176470589, 0.3686274509803922, 0.0),
'F200W': (0.8, 0.4745098039215686, 0.6549019607843137),
'F140M': 'orange',
'BLUE': '#1f77b4', # Euclid
'RED': '#d62728',
'CLEARP': 'b'}
GRISM_MAJOR = {'G102': 0.1, 'G141': 0.1, # WFC3/IR
'G800L': 0.1, # ACS/WFC
'F090W': 0.1, 'F115W': 0.1, 'F150W': 0.1, # NIRISS
'F140M': 0.1, 'F158M': 0.1, 'F200W': 0.1,
'F277W': 0.2, 'F356W': 0.2, 'F444W': 0.2, # NIRCam
'F250M':0.1,'F300M': 0.1, 'F335M':0.1, 'F360M':0.1,
'F410M': 0.1,'F430M': 0.1,'F460M': 0.1,'F480M': 0.1,
'BLUE': 0.1, 'RED': 0.1, # Euclid
'GRISM':0.1, 'G150':0.1 # Roman
}
GRISM_LIMITS = {'G800L': [0.545, 1.02, 40.], # ACS/WFC
'G280': [0.2, 0.4, 14], # WFC3/UVIS
'G102': [0.77, 1.18, 23.], # WFC3/IR
'G141': [1.06, 1.73, 46.0],
'GRISM': [0.98, 1.98, 11.], # WFIRST/Roman
'G150': [0.98, 1.98, 11.],
'F090W': [0.76, 1.04, 45.0], # NIRISS
'F115W': [0.97, 1.32, 45.0],
'F140M': [1.28, 1.52, 45.0],
'F158M': [1.28, 1.72, 45.0],
'F150W': [1.28, 1.72, 45.0],
'F200W': [1.68, 2.30, 45.0],
'F140M': [1.20, 1.60, 45.0],
'CLEARP': [0.76, 2.3, 45.0],
'F277W': [2.5, 3.2, 20.], # NIRCAM
'F356W': [3.05, 4.1, 20.],
'F444W': [3.82, 5.08, 20],
'F250M': [2.4, 2.65, 20],
'F300M': [2.77, 3.23, 20],
'F335M': [3.1, 3.6, 20],
'F360M': [3.4, 3.85, 20],
'F410M': [3.8, 4.38, 20],
'F430M': [4.1, 4.45, 20],
'F460M': [4.5, 4.8, 20],
'F480M': [4.6, 5.05, 20],
'BLUE': [0.8, 1.2, 10.], # Euclid
'RED': [1.1, 1.9, 14.]}
#DEFAULT_LINE_LIST = ['PaB', 'HeI-1083', 'SIII', 'OII-7325', 'ArIII-7138', 'SII', 'Ha+NII', 'OI-6302', 'HeI-5877', 'OIII', 'Hb', 'OIII-4363', 'Hg', 'Hd', 'H8','H9','NeIII-3867', 'OII', 'NeVI-3426', 'NeV-3346', 'MgII','CIV-1549', 'CIII-1908', 'OIII-1663', 'HeII-1640', 'NIII-1750', 'NIV-1487', 'NV-1240', 'Lya']
# Line species for determining individual line fluxes. See `load_templates`.
DEFAULT_LINE_LIST = ['BrA','BrB','BrG','PfG','PfD',
'PaA','PaB','PaG','PaD',
'HeI-1083', 'SIII', 'OII-7325', 'ArIII-7138',
'SII', 'Ha', 'OI-6302', 'HeI-5877', 'OIII', 'Hb',
'OIII-4363', 'Hg', 'Hd', 'H7', 'H8', 'H9', 'H10',
'NeIII-3867', 'OII', 'NeVI-3426', 'NeV-3346', 'MgII',
'CIV-1549', 'CIII-1906', 'CIII-1908', 'OIII-1663',
'HeII-1640', 'NIII-1750', 'NIV-1487', 'NV-1240', 'Lya']
LSTSQ_RCOND = None
def set_warnings(numpy_level='ignore', astropy_level='ignore'):
"""
Set global numpy and astropy warnings
Parameters
----------
numpy_level : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}
Numpy error level (see `~numpy.seterr`).
astropy_level : {'error', 'ignore', 'always', 'default', 'module', 'once'}
Astropy error level (see `~warnings.simplefilter`).
"""
from astropy.utils.exceptions import AstropyWarning
np.seterr(all=numpy_level)
warnings.simplefilter(astropy_level, category=AstropyWarning)
JWST_TRANSLATE = {'RA_TARG':'TARG_RA',
'DEC_TARG':'TARG_DEC',
'EXPTIME':'EFFEXPTM',
'PA_V3':'ROLL_REF'}
def get_flt_info(files=[], columns=['FILE', 'FILTER', 'PUPIL', 'INSTRUME', 'DETECTOR', 'TARGNAME', 'DATE-OBS', 'TIME-OBS', 'EXPSTART', 'EXPTIME', 'PA_V3', 'RA_TARG', 'DEC_TARG', 'POSTARG1', 'POSTARG2'], translate=JWST_TRANSLATE, defaults={'PUPIL':'---', 'TARGNAME':'indef','PA_V3':0.0}, jwst_detector=True):
"""Extract header information from a list of FLT files
Parameters
----------
files : list
List of exposure filenames.
Returns
-------
tab : `~astropy.table.Table`
Table containing header keywords
"""
import astropy.io.fits as pyfits
from astropy.table import Table
if not files:
files = glob.glob('*flt.fits')
N = len(files)
data = []
for c in columns[2:]:
if c not in translate:
translate[c] = 'xxxxxxxxxxxxxx'
targprop = []
for i in range(N):
line = [os.path.basename(files[i]).split('.gz')[0]]
if files[i].endswith('.gz'):
im = pyfits.open(files[i])
h = im[0].header.copy()
im.close()
else:
h = pyfits.Header().fromfile(files[i])
if os.path.basename(files[i]).startswith('jw0'):
with pyfits.open(files[i]) as _im:
h1 = _im['SCI'].header
if 'PA_V3' in h1:
h['PA_V3'] = h1['PA_V3']
if 'TARGPROP' in h:
targprop.append(h['TARGPROP'].lower())
else:
targprop.append('indef')
else:
targprop.append('indef')
filt = parse_filter_from_header(h, jwst_detector=jwst_detector)
line.append(filt)
has_columns = ['FILE', 'FILTER']
for key in columns[2:]:
has_columns.append(key)
if key in h:
line.append(h[key])
elif translate[key] in h:
line.append(h[translate[key]])
else:
if key in defaults:
line.append(defaults[key])
else:
line.append(np.nan)
continue
data.append(line)
tab = Table(rows=data, names=has_columns)
if 'TARGNAME' in tab.colnames:
miss = tab['TARGNAME'] == ''
targs = [t.replace(' ', '-') for t in tab['TARGNAME']]
if miss.sum() > 0:
for i in np.where(miss)[0]:
targs[i] = targprop[i] #'indef'
tab['TARGNAME'] = targs
return tab
def radec_to_targname(ra=0, dec=0, round_arcsec=(4, 60), precision=2, targstr='j{rah}{ram}{ras}{sign}{ded}{dem}', header=None):
"""Turn decimal degree coordinates into a string with rounding.
Parameters
----------
ra, dec : float
Sky coordinates in decimal degrees
round_arcsec : (scalar, scalar)
Round the coordinates to nearest value of `round`, in arcseconds.
precision : int
Sub-arcsecond precision, in `~astropy.coordinates.SkyCoord.to_string`.
targstr : string
Build `targname` with this parent string. Arguments
`rah, ram, ras, rass, sign, ded, dem, des, dess` are computed from the
(rounded) target coordinates (`ra`, `dec`) and passed to
`targstr.format`.
header : `~astropy.io.fits.Header`, None
Try to get `ra`, `dec` from header keywords, first `CRVAL` and then
`RA_TARG`, `DEC_TARG`.
Returns
-------
targname : str
Target string, see the example above.
Examples
--------
>>> # Test dec: -10d10m10.10s
>>> dec = -10. - 10./60. - 10.1/3600
>>> # Test ra: 02h02m02.20s
>>> cosd = np.cos(dec/180*np.pi)
>>> ra = 2*15 + 2./60*15 + 2.2/3600.*15
>>> # Round to nearest arcmin
>>> from grizli.utils import radec_to_targname
>>> print(radec_to_targname(ra=ra, dec=dec, round_arcsec=(4,60),
targstr='j{rah}{ram}{ras}{sign}{ded}{dem}'))
j020204m1010 # (rounded to 4 arcsec in RA)
>>> # Full precision
>>> targstr = 'j{rah}{ram}{ras}.{rass}{sign}{ded}{dem}{des}.{dess}'
>>> print(radec_to_targname(ra, dec,round_arcsec=(0.0001, 0.0001),
precision=3, targstr=targstr))
j020202.200m101010.100
"""
import astropy.coordinates
import astropy.units as u
import re
import numpy as np
if header is not None:
if 'CRVAL1' in header:
ra, dec = header['CRVAL1'], header['CRVAL2']
else:
if 'RA_TARG' in header:
ra, dec = header['RA_TARG'], header['DEC_TARG']
cosd = np.cos(dec/180*np.pi)
scl = np.array(round_arcsec)/3600*np.array([360/24, 1])
dec_scl = int(np.round(dec/scl[1]))*scl[1]
ra_scl = int(np.round(ra/scl[0]))*scl[0]
coo = astropy.coordinates.SkyCoord(ra=ra_scl*u.deg, dec=dec_scl*u.deg,
frame='icrs')
cstr = re.split('[hmsd.]', coo.to_string('hmsdms', precision=precision))
# targname = ('j{0}{1}'.format(''.join(cstr[0:3]), ''.join(cstr[4:7])))
# targname = targname.replace(' ', '').replace('+','p').replace('-','m')
rah, ram, ras, rass = cstr[0:4]
ded, dem, des, dess = cstr[4:8]
sign = 'p' if ded[1] == '+' else 'm'
targname = targstr.format(rah=rah, ram=ram, ras=ras, rass=rass,
ded=ded[2:], dem=dem, des=des, dess=dess,
sign=sign)
return targname
def blot_nearest_exact(in_data, in_wcs, out_wcs, verbose=True, stepsize=-1,
scale_by_pixel_area=False, wcs_mask=True,
fill_value=0):
"""
Own blot function for blotting exact pixels without rescaling for input
and output pixel size
test
Parameters
----------
in_data : `~numpy.ndarray`
Input data to blot.
in_wcs : `~astropy.wcs.WCS`
Input WCS. Must have _naxis1, _naxis2 or pixel_shape attributes.
out_wcs : `~astropy.wcs.WCS`
Output WCS. Must have _naxis1, _naxis2 or pixel_shape attributes.
scale_by_pixel_area : bool
If True, then scale the output image by the square of the image pixel
scales (out**2/in**2), i.e., the pixel areas.
wcs_mask : bool
Use fast WCS masking. If False, use ``regions``.
fill_value : int/float
Value in `out_data` not covered by `in_data`.
Returns
-------
out_data : `~numpy.ndarray`
Blotted data.
"""
from regions import Regions
from shapely.geometry import Polygon
import scipy.ndimage as nd
from drizzlepac import cdriz
try:
from .utils_c.interp import pixel_map_c
except:
from grizli.utils_c.interp import pixel_map_c
# Shapes, in numpy array convention (y, x)
if hasattr(in_wcs, 'pixel_shape'):
in_sh = in_wcs.pixel_shape[::-1]
elif hasattr(in_wcs, 'array_shape'):
in_sh = in_wcs.array_shape
else:
in_sh = (in_wcs._naxis2, in_wcs._naxis1)
if hasattr(out_wcs, 'pixel_shape'):
out_sh = out_wcs.pixel_shape[::-1]
elif hasattr(out_wcs, 'array_shape'):
out_sh = out_wcs.array_shape
else:
out_sh = (out_wcs._naxis2, out_wcs._naxis1)
in_px = in_wcs.calc_footprint()
in_poly = Polygon(in_px).buffer(5./3600.)
out_px = out_wcs.calc_footprint()
out_poly = Polygon(out_px).buffer(5./3600)
olap = in_poly.intersection(out_poly)
if olap.area == 0:
if verbose:
print('No overlap')
return np.zeros(out_sh)
# Region mask for speedup
if np.isclose(olap.area, out_poly.area, 0.01):
mask = np.ones(out_sh, dtype=bool)
elif wcs_mask:
# Use wcs / Path
from matplotlib.path import Path
out_xy = out_wcs.all_world2pix(np.array(in_poly.exterior.xy).T, 0)-0.5
out_xy_path = Path(out_xy)
yp, xp = np.indices(out_sh)
pts = np.array([xp.flatten(), yp.flatten()]).T
mask = out_xy_path.contains_points(pts).reshape(out_sh)
else:
olap_poly = np.array(olap.exterior.xy)
poly_reg = "fk5\npolygon("+','.join(['{0}'.format(p + 1) for p in olap_poly.T.flatten()])+')\n'
reg = Regions.parse(poly_reg, format='ds9')[0]
mask = reg.to_mask().to_image(shape=out_sh)
#yp, xp = np.indices(in_data.shape)
#xi, yi = xp[mask], yp[mask]
yo, xo = np.where(mask > 0)
if stepsize <= 1:
rd = out_wcs.all_pix2world(xo, yo, 0)
xf, yf = in_wcs.all_world2pix(rd[0], rd[1], 0)
else:
# Seems backwards and doesn't quite agree with above
blot_wcs = out_wcs
source_wcs = in_wcs
if hasattr(blot_wcs, 'pixel_shape'):
nx, ny = blot_wcs.pixel_shape
else:
nx, ny = int(blot_wcs._naxis1), int(blot_wcs._naxis2)
mapping = cdriz.DefaultWCSMapping(blot_wcs, source_wcs, nx, ny,
stepsize)
xf, yf = mapping(xo, yo)
xi, yi = np.cast[int](np.round(xf)), np.cast[int](np.round(yf))
m2 = (xi >= 0) & (yi >= 0) & (xi < in_sh[1]) & (yi < in_sh[0])
xi, yi, xf, yf, xo, yo = xi[m2], yi[m2], xf[m2], yf[m2], xo[m2], yo[m2]
out_data = np.ones(out_sh, dtype=np.float64)*fill_value
status = pixel_map_c(np.cast[np.float64](in_data), xi, yi, out_data, xo, yo)
# Fill empty
func = nd.maximum_filter
fill = out_data == 0
filtered = func(out_data, size=5)
out_data[fill] = filtered[fill]
if scale_by_pixel_area:
in_scale = get_wcs_pscale(in_wcs)
out_scale = get_wcs_pscale(out_wcs)
out_data *= out_scale**2/in_scale**2
return out_data.astype(in_data.dtype)
def _slice_ndfilter(data, filter_func, slices, args, size, footprint, kwargs):
"""
Helper function passing image slices to `scipy.ndimage` filters that is
pickleable for threading with `multiprocessing`
Parameters
----------
data, filter_func, args, size, footprint :
See `multiprocessing_ndfilter`
slices : (slice, slice, slice, slice)
Array slices for insert a cutout back into a larger parent array
Returns
-------
filtered : array-like
Filtered data
slices : tuple
`slices` as input
"""
filtered = filter_func(data, *args,
size=size, footprint=footprint,
**kwargs)
return filtered, slices
def multiprocessing_ndfilter(data, filter_func, filter_args=(), size=None, footprint=None, cutout_size=256, n_proc=4, timeout=90, mask=None, verbose=True, **kwargs):
"""
Cut up a large array and send slices to `scipy.ndimage` filters
Parameters
----------
data : array-like
Main image array
filter_func : function
Filtering function, e.g., `scipy.ndimage.median_filter`
filter_args : tuple
Arguments to pass to `filter_func`
size, footprint : int, array-like
Filter size or footprint, see, e.g., `scipy.ndimage.median_filter`
cutout_size : int
Size of subimage cutouts
n_proc : int
Number of `multiprocessing` processes to use
timeout : float
`multiprocessing` timeout (seconds)
mask : array-like
Array multiplied to `data` that can zero-out regions to ignore
verbose : bool
Print status messages
kwargs : dict
Keyword arguments passed through to `filter_func`
Returns
-------
filtered : array-like
Filtered version of `data`
Examples
--------
>>> import time
>>> import numpy as np
>>> import scipy.ndimage as nd
>>> from grizli.utils import multiprocessing_ndfilter
>>> rnd = np.random.normal(size=(512,512))
>>> t0 = time.time()
>>> f_serial = nd.median_filter(rnd, size=10)
>>> t1 = time.time()
>>> f_mp = multiprocessing_ndfilter(rnd, nd.median_filter, size=10,
>>> cutout_size=256, n_proc=4)
>>> t2 = time.time()
>>> np.allclose(f_serial, f_mp)
True
>>> print(f' serial: {(t1-t0)*1000:.1f} ms')
>>> print(f'parallel: {(t2-t1)*1000:.1f} ms')
serial: 573.9 ms
parallel: 214.8 ms
"""
import multiprocessing as mp
try:
from tqdm import tqdm
except ImportError:
verbose = False
sh = data.shape
msg = None
if cutout_size > np.max(sh):
msg = f'cutout_size={cutout_size} greater than image dimensions, run '
msg += f'`{filter_func}` directly'
elif n_proc == 0:
msg = f'n_proc = 0, run in a single command'
if msg is not None:
if verbose:
print(msg)
filtered = filter_func(data, *filter_args,
size=size, footprint=footprint)
return filtered
# Grid size
nx = data.shape[1]//cutout_size+1
ny = data.shape[0]//cutout_size+1
# Padding
if footprint is not None:
fpsh = footprint.shape
pad = np.max(fpsh)
elif size is not None:
pad = size
else:
raise ValueError('Either size or footprint must be specified')
if n_proc < 0:
n_proc = mp.cpu_count()
n_proc = np.minimum(n_proc, mp.cpu_count())
pool = mp.Pool(processes=n_proc)
jobs = []
if mask is not None:
data_mask = data*mask
else:
data_mask = data
# Make image slices
for i in range(nx):
xmi = np.maximum(0, i*cutout_size-pad)
xma = np.minimum(sh[1], (i+1)*cutout_size+pad)
#print(i, xmi, xma)
if i == 0:
slx = slice(0, cutout_size)
x0 = 0
elif i < nx-1:
slx = slice(pad, cutout_size + pad)
x0 = i*cutout_size
else:
slx = slice(pad, cutout_size + 1)
x0 = xmi+pad
nxs = slx.stop - slx.start
oslx = slice(x0, x0+nxs)
for j in range(ny):
ymi = np.maximum(0, j*cutout_size - pad)
yma = np.minimum(sh[0], (j+1)*cutout_size + pad)
if j == 0:
sly = slice(0, cutout_size)
y0 = 0
elif j < ny-1:
sly = slice(pad, cutout_size + pad)
y0 = j*cutout_size
else:
sly = slice(pad, cutout_size + 1)
y0 = ymi+pad
nys = sly.stop - sly.start
osly = slice(y0, y0+nys)
cut = data_mask[ymi:yma, xmi:xma]
if cut.max() == 0:
#print(f'Skip {xmi} {xma} {ymi} {yma}')
continue
# Make jobs for filtering the image slices
slices = (osly, oslx, sly, slx)
_args = (cut, filter_func, slices,
filter_args, size, footprint, kwargs)
jobs.append(pool.apply_async(_slice_ndfilter, _args))
# Collect results
pool.close()
filtered = np.zeros_like(data)
if verbose:
_iter = tqdm(jobs)
else:
_iter = jobs
for res in _iter:
filtered_i, slices = res.get(timeout=timeout)
filtered[slices[:2]] += filtered_i[slices[2:]]
return filtered
def parse_flt_files(files=[], info=None, uniquename=False, use_visit=False,
get_footprint=False,
translate={'AEGIS-': 'aegis-',
'COSMOS-': 'cosmos-',
'GNGRISM': 'goodsn-',
'GOODS-SOUTH-': 'goodss-',
'UDS-': 'uds-'},
visit_split_shift=1.5, max_dt=1e9,
path='../RAW'):
"""Read header information from a list of exposures and parse out groups based on filter/target/orientation.
Parameters
----------
files : list
List of exposure filenames. If not specified, will use ``*flt.fits``.
info : None or `~astropy.table.Table`
Output from `~grizli.utils.get_flt_info`.
uniquename : bool
If True, then split everything by program ID and visit name. If
False, then just group by targname/filter/pa_v3.
use_visit : bool
For parallel observations with ``targname='ANY'``, use the filename
up to the visit ID as the target name. For example:
>>> flc = 'jbhj64d8q_flc.fits'
>>> visit_targname = flc[:6]
>>> print(visit_targname)
jbhj64
If False, generate a targname for parallel observations based on the
pointing coordinates using `radec_to_targname`. Use this keyword
for dithered parallels like 3D-HST / GLASS but set to False for
undithered parallels like WISP. Should also generally be used with
``uniquename=False`` otherwise generates names that are a bit
redundant:
+--------------+---------------------------+
| `uniquename` | Output Targname |
+==============+===========================+
| True | jbhj45-bhj-45-180.0-F814W |
+--------------+---------------------------+
| False | jbhj45-180.0-F814W |
+--------------+---------------------------+
translate : dict
Translation dictionary to modify TARGNAME keywords to some other
value. Used like:
>>> targname = 'GOODS-SOUTH-10'
>>> translate = {'GOODS-SOUTH-': 'goodss-'}
>>> for k in translate:
>>> targname = targname.replace(k, translate[k])
>>> print(targname)
goodss-10
visit_split_shift : float
Separation in ``arcmin`` beyond which exposures in a group are split
into separate visits.
path : str
PATH to search for `flt` files if ``info`` not provided
Returns
-------
output_list : dict
Dictionary split by target/filter/pa_v3. Keys are derived visit
product names and values are lists of exposure filenames corresponding
to that set. Keys are generated with the formats like:
>>> targname = 'macs1149+2223'
>>> pa_v3 = 32.0
>>> filter = 'f140w'
>>> flt_filename = 'ica521naq_flt.fits'
>>> propstr = flt_filename[1:4]
>>> visit = flt_filename[4:6]
>>> # uniquename = False
>>> print('{0}-{1:05.1f}-{2}'.format(targname, pa_v3, filter))
macs1149.6+2223-032.0-f140w
>>> # uniquename = True
>>> print('{0}-{1:3s}-{2:2s}-{3:05.1f}-{4:s}'.format(targname, propstr, visit, pa_v3, filter))
macs1149.6+2223-ca5-21-032.0-f140w
filter_list : dict
Nested dictionary split by filter and then PA_V3. This shouldn't
be used if exposures from completely disjoint pointings are stored
in the same working directory.
"""
if info is None:
if not files:
files = glob.glob(os.path.join(path), '*flt.fits')
if len(files) == 0:
return False
info = get_flt_info(files)
else:
info = info.copy()
for c in info.colnames:
if not c.islower():
info.rename_column(c, c.lower())
if 'expstart' not in info.colnames:
info['expstart'] = info['exptime']*0.
so = np.argsort(info['expstart'])
info = info[so]
#pa_v3 = np.round(info['pa_v3']*10)/10 % 360.
pa_v3 = np.round(np.round(info['pa_v3'], decimals=1)) % 360.
target_list = []
for i in range(len(info)):
# Replace ANY targets with JRhRmRs-DdDmDs
if info['targname'][i] == 'ANY':
if use_visit:
new_targname = info['file'][i][:6]
else:
new_targname = 'par-'+radec_to_targname(ra=info['ra_targ'][i],
dec=info['dec_targ'][i])
target_list.append(new_targname.lower())
else:
target_list.append(info['targname'][i])
target_list = np.array(target_list)
_prog_ids = []
visits = []
for file in info['file']:
bfile = os.path.basename(file)
if bfile.startswith('jw'):
_prog_ids.append(bfile[2:7])
visits.append(bfile[7:10])
else:
_prog_ids.append(bfile[1:4])
visits.append(bfile[4:6])
visits = np.array(visits)
info['progIDs'] = _prog_ids
progIDs = np.unique(info['progIDs'])
dates = np.array([''.join(date.split('-')[1:])
for date in info['date-obs']])
targets = np.unique(target_list)
output_list = [] # OrderedDict()
filter_list = OrderedDict()
for filter in np.unique(info['filter']):
filter_list[filter] = OrderedDict()
angles = np.unique(pa_v3[(info['filter'] == filter)])
for angle in angles:
filter_list[filter][angle] = []
for target in targets:
# 3D-HST targname translations
target_use = target
for key in translate.keys():
target_use = target_use.replace(key, translate[key])
# pad i < 10 with zero
for key in translate.keys():
if translate[key] in target_use:
spl = target_use.split('-')
try:
if (int(spl[-1]) < 10) & (len(spl[-1]) == 1):
spl[-1] = '{0:02d}'.format(int(spl[-1]))
target_use = '-'.join(spl)
except:
pass
for filter in np.unique(info['filter'][(target_list == target)]):
angles = np.unique(pa_v3[(info['filter'] == filter) &
(target_list == target)])
for angle in angles:
exposure_list = []
exposure_start = []
product = '{0}-{1:05.1f}-{2}'.format(target_use, angle, filter)
visit_match = np.unique(visits[(target_list == target) &
(info['filter'] == filter)])
this_progs = []
this_visits = []
for visit in visit_match:
ix = (visits == visit) & (target_list == target)
ix &= (info['filter'] == filter)
# this_progs.append(info['progIDs'][ix][0])
# print visit, ix.sum(), np.unique(info['progIDs'][ix])
new_progs = list(np.unique(info['progIDs'][ix]))
this_visits.extend([visit]*len(new_progs))
this_progs.extend(new_progs)
for visit, prog in zip(this_visits, this_progs):
visit_list = []
visit_start = []
_vstr = '{0}-{1}-{2}-{3:05.1f}-{4}'
visit_product = _vstr.format(target_use, prog, visit,
angle, filter)
use = (target_list == target)
use &= (info['filter'] == filter)
use &= (visits == visit)
use &= (pa_v3 == angle)
use &= (info['progIDs'] == prog)
if use.sum() == 0:
continue
for tstart, file in zip(info['expstart'][use],
info['file'][use]):
f = file.split('.gz')[0]
if f not in exposure_list:
visit_list.append(str(f))
visit_start.append(tstart)
exposure_list = np.append(exposure_list, visit_list)
exposure_start.extend(visit_start)
filter_list[filter][angle].extend(visit_list)
if uniquename:
print(visit_product, len(visit_list))
so = np.argsort(visit_start)
exposure_list = np.array(visit_list)[so]
#output_list[visit_product.lower()] = visit_list
d = OrderedDict(product=str(visit_product.lower()),
files=list(np.array(visit_list)[so]))
output_list.append(d)
if not uniquename:
print(product, len(exposure_list))
so = np.argsort(exposure_start)
exposure_list = np.array(exposure_list)[so]
#output_list[product.lower()] = exposure_list
d = OrderedDict(product=str(product.lower()),
files=list(np.array(exposure_list)[so]))
output_list.append(d)
# Split large shifts
if visit_split_shift > 0:
split_list = []
for o in output_list:
_spl = split_visit(o, path=path,
max_dt=max_dt,
visit_split_shift=visit_split_shift)
split_list.extend(_spl)
output_list = split_list
# Get visit footprint from FLT WCS
if get_footprint:
from shapely.geometry import Polygon
N = len(output_list)
for i in range(N):
for j in range(len(output_list[i]['files'])):
flt_file = output_list[i]['files'][j]
if (not os.path.exists(flt_file)):
for gzext in ['', '.gz']:
_flt_file = os.path.join(path, flt_file + gzext)
if os.path.exists(_flt_file):
flt_file = _flt_file
break
flt_j = pyfits.open(flt_file)
h = flt_j[0].header
_ext = 0
if (h['INSTRUME'] == 'WFC3'):
_ext = 1
if (h['DETECTOR'] == 'IR'):
wcs_j = pywcs.WCS(flt_j['SCI', 1])
else:
wcs_j = pywcs.WCS(flt_j['SCI', 1], fobj=flt_j)
elif (h['INSTRUME'] == 'WFPC2'):
_ext = 1
wcs_j = pywcs.WCS(flt_j['SCI', 1])
else:
_ext = 1
wcs_j = pywcs.WCS(flt_j['SCI', 1], fobj=flt_j)
if ((wcs_j.pixel_shape is None) &
('NPIX1' in flt_j['SCI',1].header)):
_h = flt_j['SCI',1].header
wcs_j.pixel_shape = (_h['NPIX1'], _h['NPIX2'])
fp_j = Polygon(wcs_j.calc_footprint())
if j == 0:
fp_i = fp_j.buffer(1./3600)
else:
fp_i = fp_i.union(fp_j.buffer(1./3600))
flt_j.close()
output_list[i]['footprint'] = fp_i
return output_list, filter_list
def split_visit(visit, visit_split_shift=1.5, max_dt=6./24, path='../RAW'):
"""
Check if files in a visit have large shifts and split them otherwise
visit : visit dictionary
visit_split_shift : split if shifts larger than `visit_split_shift` arcmin
"""
ims = []
for file in visit['files']:
for gzext in ['', '.gz']:
_file = os.path.join(path, file) + gzext
if os.path.exists(_file):
ims.append(pyfits.open(_file))
break
#ims = [pyfits.open(os.path.join(path, file)) for file in visit['files']]
crval1 = np.array([im[1].header['CRVAL1'] for im in ims])
crval2 = np.array([im[1].header['CRVAL2'] for im in ims])
expstart = np.array([im[0].header['EXPSTART'] for im in ims])
dt = np.cast[int]((expstart-expstart[0])/max_dt)