-
Notifications
You must be signed in to change notification settings - Fork 2
/
goodman_astro.py
2369 lines (1989 loc) · 90.6 KB
/
goodman_astro.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 astroscrappy
import dateutil
import datetime
import matplotlib.pyplot as plt
import numpy as np
import os, shutil, tempfile, shlex, re
import statsmodels.api as sm
import sys
from astropy import units as u
from astropy import wcs
from astropy.coordinates import SkyCoord, search_around_sky
from astropy.io import fits as fits
from astropy.table import Table
from astropy.time import Time
from astropy.wcs import WCS
from astroquery.vizier import Vizier
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.stats import chi2
from scipy.stats import binned_statistic_2d
# Utils (F Navarete)
def log_message(file,message, init=False, print_time=False):
"""
Initiates a log file and append a message to it.
file (str): full path of the file to be created or to append a message to it.
message (str): message to be appended to the file.
init (bool): if True, initialize a new file.
print_time (bool): if True, will print a timestamp before the message.
"""
if init:
with open(file,'w') as f:
f.write('')
if print_time:
with open(file,'a') as f:
f.write(str(datetime.datetime.now()) + '\t' + message + '\n')
else:
with open(file,'a') as f:
f.write(message + '\n')
# (F Navarete)
def get_info(header):
"""
reads a fits header and returns specific keywords used during the execution of the codes.
header (astropy.io.fits.Header): FITS header.
returns:
fname (str): filter name
binning (int): binning factor (single element). For imaging mode, the full binning information should be 'binning'x'binning'
time (str): observing time
gain (float): gain value (e-/ADU)
rdnoise (float): read noise (e-)
satur_thresh (float): saturation threshold based on the readout mode (in ADU)
exptime (float): exposure time (in sec)
"""
# check if observations are done in imaging mode. if not, exit the code
wavmode = header.get('WAVMODE')
check_wavmode(wavmode)
# get filter keywords from header
fname1 = header.get('FILTER')
fname2 = header.get('FILTER2')
# set the name of the active filter (deal with both filter wheels in case the first one has no filter)
fname = fname1 if fname1 != "NO_FILTER" else fname2
# get binning information
binning = np.array([int(b) for b in header['CCDSUM'].split(' ')])[0]
time = get_obs_time(header, verbose=False)
gain = header.get('GAIN')
rdnoise = header.get('RDNOISE')
satur_thresh = get_saturation(gain,rdnoise)
exptime = header.get('EXPTIME')
return fname, binning, time, gain, rdnoise, satur_thresh, exptime
# (F Navarete)
def get_saturation(gain,rdnoise):
"""
Simple function to estimate the saturation threshold based on the readout mode.
gain (float): gain value (e-/ADU)
rdnoise (float): read noise (e-)
returns:
satur_thresh (float): saturation threshold based on the readout mode (in ADU)
"""
if gain == 1.54 and rdnoise == 3.45: satur_thresh = 50000 # 100kHzATTN3
elif gain == 3.48 and rdnoise == 5.88: satur_thresh = 25000 # 100kHzATTN2
elif gain == 1.48 and rdnoise == 3.89: satur_thresh = 50000 # 344kHzATTN3
elif gain == 3.87 and rdnoise == 7.05: satur_thresh = 25000 # 344kHzATTN0
elif gain == 1.47 and rdnoise == 5.27: satur_thresh = 50000 # 750kHzATTN2
elif gain == 3.77 and rdnoise == 8.99: satur_thresh = 25000 # 750kHzATTN0
else: satur_thresh = 50000
return satur_thresh
# (F Navarete)
def check_wavmode(wavmode):
"""
Simple function to check whether WAVMODE is IMAGING or not.
wavmode (str): Goodman header's keyword. Should be IMAGING or SPECTROSCOPY.
returns:
if wavmode is not IMAGING, halts the code.
"""
if wavmode != "IMAGING":
sys.exit("WAVMODE is not IMAGING. No data to process.")
print("IMAGING data.")
# (F Navarete)
def check_wcs(header):
"""
Simple function to check whether the header has a WCS solution or not.
header (astropy.io.fits.Header): FITS header.
returns:
if no WCS is present, halts the code.
"""
wcs = WCS(header)
if wcs is None or not wcs.is_celestial:
sys.exit("WCS is absent or non-celestial. Impossible to compute photometry.")
return wcs
# (F Navarete)
def check_phot(m):
"""
Simple function to check whether a dictionary is None or not.
m (dict): output from calibrate_photometry()
returns:
if 'm' is None, halts the code.
"""
if m is None:
sys.exit("Impossible to retrieve photometric results.")
# (F Navarete)
def filter_sets(fname):
"""
Simple function to define which set of filters will be used based on the Goodman filter in usage.
fname (str): Goodman filter name (from header's FILTER/FILTER2 keywords)
returns:
cat_filter (str): Gaia filter to be retrieved
phot_mag (str): will convert the Gaia filter magnitude to the following filter
TODO: Right now, the function works for SDSS filters only.
Needs to add Bessel UBVRI, Johnson UBV, stromgren ubvy, Kron-Cousins Rc.
Narrow band filters should deliver results in the same filter.
"""
# photometric filters for deriving the calibration (should be as close as possible as the filter in use.
# available filters from GaiaDR2 are:
# "Gmag,BPmag,RPmag (gaia system)
# Bmag,Vmag,Rmag,Imag,gmag,rmag,g_SDSS,r_SDSS,i_SDSS"
if fname == "u-SDSS":
cat_filter = "BPmag"
phot_mag = "u_SDSS"
#phot_color_mag1 = "u_SDSS"
#phot_color_mag2 = "g_SDSS"
elif fname == "g-SDSS":
cat_filter = "BPmag"
phot_mag = "g_SDSS"
#phot_color_mag1 = "g_SDSS"
#phot_color_mag2 = "r_SDSS"
elif fname == "r-SDSS":
cat_filter = "Gmag"
phot_mag = "r_SDSS"
#phot_color_mag1 = "g_SDSS"
#phot_color_mag2 = "r_SDSS"
elif fname == "i-SDSS" or fname == "z-SDSS":
cat_filter = "Gmag"
phot_mag = "i_SDSS"
#phot_color_mag1 = "r_SDSS"
#phot_color_mag2 = "i_SDSS"
else:
# for any other filter, use the GaiaDR2 G-band magnitudes
# TODO: add transformation for the z-SDSS filter
# TODO: add transformation for Bessel, stromgren
cat_filter = "Gmag"
phot_mag = "g_SDSS"
#phot_color_mag1 = "g_SDSS"
#phot_color_mag2 = "r_SDSS"
# no need for color term on the photometric calibration of a single filter exposure.
#return cat_filter, phot_mag, phot_color_mag1, phot_color_mag2
return cat_filter, phot_mag
# astro (F Navarete)
def goodman_wcs(header):
"""
Creates a first guess of the WCS using the telescope coordinates, the
CCDSUM (binning), position angle and plate scale.
Parameters
----------
header (astropy.io.fits.Header): Primary Header to be updated.
Returns
-------
header (astropy.io.fits.Header): Primary Header with updated WCS information.
"""
if 'EQUINOX' not in header:
header['EQUINOX'] = 2000.
if 'EPOCH' not in header:
header['EPOCH'] = 2000.
binning = np.array([int(b) for b in header['CCDSUM'].split(' ')])
header['PIXSCAL1'] = -binning[0] * 0.15 # arcsec (for Swarp)
header['PIXSCAL2'] = +binning[1] * 0.15 # arcsec (for Swarp)
if abs(header['PIXSCAL1']) != abs(header['PIXSCAL2']):
logger.warning('Pixel scales for X and Y do not mach.')
plate_scale = (abs(header['PIXSCAL1'])*u.arcsec).to('degree')
p = plate_scale.to('degree').value
w = wcs.WCS(naxis=2)
try:
coordinates = SkyCoord(ra=header['RA'], dec=header['DEC'],
unit=(u.hourangle, u.deg))
except ValueError:
logger.error(
'"RA" and "DEC" missing. Using "TELRA" and "TELDEC" instead.')
coordinates = SkyCoord(ra=header['TELRA'], dec=header['TELDEC'],
unit=(u.hourangle, u.deg))
ra = coordinates.ra.to('degree').value
dec = coordinates.dec.to('degree').value
w.wcs.crpix = [header['NAXIS2'] / 2, header['NAXIS1'] / 2]
w.wcs.cdelt = [+1.*p,+1.*p] #* binning
w.wcs.crval = [ra, dec]
w.wcs.ctype = ["RA---TAN", "DEC--TAN"]
wcs_header = w.to_header()
for key in wcs_header.keys():
header[key] = wcs_header[key]
return header
# (F Navarete)
def mask_fov(image, binning):
"""
Mask out the edges of the FOV of the Goodman images.
Parameters
----------
image (numpy.ndarray): Image from fits file.
binning (int): binning of the data (1, 2, 3...) from get_info()
Returns
-------
mask_fov (numpy.ndarray): Boolean mask with the same dimension as 'image' (1/0 for good/masked pixels, respectively)
"""
# define center of the FOV for binning 1, 2, and 3
if binning == 1:
center_x, center_y, radius = 1520, 1570, 1550
elif binning == 2:
center_x, center_y, radius = 770, 800, 775
elif binning == 3:
center_x, center_y, radius = 510, 540, 515
# if any other binning value is provided, it will use the center of the image as a reference
else:
center_x, center_y, radius = image.shape[0]/2., image.shape[1]/2., image.shape[0]/2.
# create a grid of pixel coordinates
x, y = np.meshgrid( np.arange(image.shape[1]), np.arange(image.shape[0]) )
# calculate the distance of each pixel from the center of the FOV
distance = np.sqrt( (x - center_x)**2 + (y - center_y)**2 )
mask_fov = distance > radius
return mask_fov
# (F Navarete)
def bpm_mask(image, saturation, binning):
"""
Creates a complete bad pixel mask, masking out saturated sources, cosmic rays and pixels outside the circular FOV.
Mask out the edges of the FOV of the Goodman images.
Parameters
----------
image (numpy.ndarray): Image from fits file.
saturation (int): Saturation threshold from get_saturation()
binning (int): binning of the data (1, 2, 3...) from get_info()
Returns
-------
mask_fov (numpy.ndarray): Boolean mask with the same dimension as 'image' (1/0 for good/masked pixels, respectively)
"""
# Masks out saturated pixels
mask = image > saturation
# Identify and masks out cosmic rays
cmask, cimage = astroscrappy.detect_cosmics(image, mask, verbose=False)
mask |= cmask
# mask out edge of the fov
mask |= mask_fov(image, binning)
return mask
# (STDPipe)
def spherical_distance(ra1, dec1, ra2, dec2):
"""
Evaluates the spherical distance between two sets of coordinates.
:param ra1: First point or set of points RA
:param dec1: First point or set of points Dec
:param ra2: Second point or set of points RA
:param dec2: Second point or set of points Dec
:returns: Spherical distance in degrees
"""
x = np.sin(np.deg2rad((ra1 - ra2) / 2))
x *= x
y = np.sin(np.deg2rad((dec1 - dec2) / 2))
y *= y
z = np.cos(np.deg2rad((dec1 + dec2) / 2))
z *= z
return np.rad2deg(2 * np.arcsin(np.sqrt(x * (z - y) + y)))
# (STDPipe)
def spherical_match(ra1, dec1, ra2, dec2, sr=1 / 3600):
"""
Positional match on the sphere for two lists of coordinates.
Aimed to be a direct replacement for :func:`esutil.htm.HTM.match` method with :code:`maxmatch=0`.
:param ra1: First set of points RA
:param dec1: First set of points Dec
:param ra2: Second set of points RA
:param dec2: Second set of points Dec
:param sr: Maximal acceptable pair distance to be considered a match, in degrees
:returns: Two parallel sets of indices corresponding to matches from first and second lists, along with the pairwise distances in degrees
"""
# Ensure that inputs are arrays
ra1 = np.atleast_1d(ra1)
dec1 = np.atleast_1d(dec1)
ra2 = np.atleast_1d(ra2)
dec2 = np.atleast_1d(dec2)
idx1, idx2, dist, _ = search_around_sky(
SkyCoord(ra1, dec1, unit='deg'), SkyCoord(ra2, dec2, unit='deg'), sr * u.deg
)
dist = dist.deg # convert to degrees
return idx1, idx2, dist
# astrometry (STDPipe)
def get_frame_center(filename=None, header=None, wcs=None, width=None, height=None, shape=None):
"""
Returns image center RA, Dec, and radius in degrees.
Accepts either filename, or FITS header, or WCS structure
"""
if not wcs:
if header:
wcs = WCS(header)
elif filename:
header = fits.getheader(filename, -1)
wcs = WCS(header)
if width is None or height is None:
if header is not None:
width = header['NAXIS1']
height = header['NAXIS2']
elif shape is not None:
height, width = shape
if not wcs or not wcs.is_celestial:
return None, None, None
#ra1, dec1 = wcs.all_pix2world(0, 0, 0)
# Goodman has a circular FOV, so we need to set the origin at the center of the x-axis to estimate the radius of the FOV, not x=0.
ra1, dec1 = wcs.all_pix2world(width / 2, 0, 0)
ra0, dec0 = wcs.all_pix2world(width / 2, height / 2, 0)
sr = spherical_distance(ra0, dec0, ra1, dec1)
return ra0.item(), dec0.item(), sr.item()
# phot (STDPipe)
def get_objects_sextractor(image,
header=None,
mask=None,
err=None,
thresh=2.0,
aper=3.0,
r0=0.0,
gain=1,
edge=0,
minarea=5,
wcs=None,
sn=3.0,
bg_size=None,
sort=True,
reject_negative=True,
checkimages=[],
extra_params=[],
extra={},
psf=None,
catfile=None,
_workdir=None,
_tmpdir=None,
_exe=None,
verbose=False):
"""Thin wrapper around SExtractor binary.
It processes the image taking into account optional mask and noise map, and returns the list of detected objects and optionally a set of SExtractor-produced checkimages.
You may check the SExtractor documentation at https://sextractor.readthedocs.io/en/latest/ for more details about possible parameters and general principles of its operation.
E.g. detection flags (returned in `flags` column of results table) are documented at https://sextractor.readthedocs.io/en/latest/Flagging.html#extraction-flags-flags . In addition to these flags, any object having pixels masked by the input `mask` in its footprint will have :code:`0x100` flag set.
:param image: Input image as a NumPy array
:param header: Image header, optional
:param mask: Image mask as a boolean array (True values will be masked), optional
:param err: Image noise map as a NumPy array, optional
:param thresh: Detection threshold, in sigmas above local background, to be used for `DETECT_THRESH` parameter of SExtractor call
:param aper: Circular aperture radius in pixels, to be used for flux measurement. May also be list - then flux will be measured for all apertures from that list.
:param r0: Smoothing kernel size (sigma, or FWHM/2.355) to be used for improving object detection
:param gain: Image gain, e/ADU
:param edge: Reject all detected objects closer to image edge than this parameter
:param minarea: Minimal number of pixels in the object to be considered a detection (`DETECT_MINAREA` parameter of SExtractor)
:param wcs: Astrometric solution to be used for assigning sky coordinates (`ra`/`dec`) to detected objects
:param sn: Minimal S/N ratio for the object to be considered a detection
:param bg_size: Background grid size in pixels (`BACK_SIZE` SExtractor parameter)
:param sort: Whether to sort the detections in decreasing brightness or not
:param reject_negative: Whether to reject the detections with negative fluxes
:param checkimages: List of SExtractor checkimages to return along with detected objects. Any SExtractor checkimage type may be used here (e.g. `BACKGROUND`, `BACKGROUND_RMS`, `MINIBACKGROUND`, `MINIBACK_RMS`, `-BACKGROUND`, `FILTERED`, `OBJECTS`, `-OBJECTS`, `SEGMENTATION`, `APERTURES`). Optional.
:param extra_params: List of extra object parameters to return for the detection. See :code:`sex -dp` for the full list.
:param extra: Dictionary of extra configuration parameters to be passed to SExtractor call, with keys as parameter names. See :code:`sex -dd` for the full list.
:param psf: Path to PSFEx-made PSF model file to be used for PSF photometry. If provided, a set of PSF-measured parameters (`FLUX_PSF`, `MAG_PSF` etc) are added to detected objects. Optional
:param catfile: If provided, output SExtractor catalogue file will be copied to this location, to be reused by external codes. Optional.
:param _workdir: If specified, all temporary files will be created in this directory, and will be kept intact after running SExtractor. May be used for debugging exact inputs and outputs of the executable. Optional
:param _tmpdir: If specified, all temporary files will be created in a dedicated directory (that will be deleted after running the executable) inside this path.
:param _exe: Full path to SExtractor executable. If not provided, the code tries to locate it automatically in your :envvar:`PATH`.
:param verbose: Whether to show verbose messages during the run of the function or not. May be either boolean, or a `print`-like function.
:returns: Either the astropy.table.Table object with detected objects, or a list with table of objects (first element) and checkimages (consecutive elements), if checkimages are requested.
"""
# Simple wrapper around print for logging in verbose mode only
log = (
(verbose if callable(verbose) else print)
if verbose
else lambda *args, **kwargs: None
)
# Find the binary
binname = None
if _exe is not None:
# Check user-provided binary path, and fail if not found
if os.path.isfile(_exe):
binname = _exe
else:
# Find SExtractor binary in common paths
for exe in ['sex', 'sextractor', 'source-extractor']:
binname = shutil.which(exe)
if binname is not None:
break
if binname is None:
log("Can't find SExtractor binary")
return None
# else:
# log("Using SExtractor binary at", binname)
workdir = (
_workdir
if _workdir is not None
else tempfile.mkdtemp(prefix='sex', dir=_tmpdir)
)
obj = None
if mask is None:
# Create minimal mask
mask = ~np.isfinite(image)
else:
# Ensure the mask is boolean array
mask = mask.astype(bool)
# now mask the bad pixels and region outside FOV
image = image.copy()
image[mask] = np.nan
# Prepare
if type(image) == str:
# FIXME: this mode of operation is currently broken!
imagename = image
else:
imagename = os.path.join(workdir, 'image.fits')
fits.writeto(imagename, image, header, overwrite=True)
# Dummy config filename, to prevent loading from current dir
confname = os.path.join(workdir, 'empty.conf')
file_write(confname)
opts = {
'c': confname,
'VERBOSE_TYPE': 'QUIET',
'DETECT_MINAREA': minarea,
'GAIN': gain,
'DETECT_THRESH': thresh,
'WEIGHT_TYPE': 'BACKGROUND',
'MASK_TYPE': 'NONE', # both 'CORRECT' and 'BLANK' seem to cause systematics?
'SATUR_LEVEL': np.nanmax(image[~mask]) + 1 # Saturation should be handled in external mask
}
if bg_size is not None:
opts['BACK_SIZE'] = bg_size
if err is not None:
# User-provided noise model
err = err.copy().astype(np.double)
err[~np.isfinite(err)] = 1e30
err[err == 0] = 1e30
errname = os.path.join(workdir, 'errors.fits')
fits.writeto(errname, err, overwrite=True)
opts['WEIGHT_IMAGE'] = errname
opts['WEIGHT_TYPE'] = 'MAP_RMS'
flagsname = os.path.join(workdir, 'flags.fits')
fits.writeto(flagsname, mask.astype(np.int16), overwrite=True)
opts['FLAG_IMAGE'] = flagsname
if np.isscalar(aper):
opts['PHOT_APERTURES'] = aper * 2 # SExtractor expects diameters, not radii
size = ''
else:
opts['PHOT_APERTURES'] = ','.join([str(_ * 2) for _ in aper])
size = '[%d]' % len(aper)
checknames = [
os.path.join(workdir, _.replace('-', 'M_') + '.fits') for _ in checkimages
]
if checkimages:
opts['CHECKIMAGE_TYPE'] = ','.join(checkimages)
opts['CHECKIMAGE_NAME'] = ','.join(checknames)
params = [
'MAG_APER' + size,
'MAGERR_APER' + size,
'FLUX_APER' + size,
'FLUXERR_APER' + size,
'X_IMAGE',
'Y_IMAGE',
'ERRX2_IMAGE',
'ERRY2_IMAGE',
'A_IMAGE',
'B_IMAGE',
'THETA_IMAGE',
'FLUX_RADIUS',
'FWHM_IMAGE',
'FLAGS',
'IMAFLAGS_ISO',
'BACKGROUND',
]
params += extra_params
if psf is not None:
opts['PSF_NAME'] = psf
params += [
'MAG_PSF',
'MAGERR_PSF',
'FLUX_PSF',
'FLUXERR_PSF',
'XPSF_IMAGE',
'YPSF_IMAGE',
'SPREAD_MODEL',
'SPREADERR_MODEL',
'CHI2_PSF',
]
paramname = os.path.join(workdir, 'cfg.param')
with open(paramname, 'w') as paramfile:
paramfile.write("\n".join(params))
opts['PARAMETERS_NAME'] = paramname
catname = os.path.join(workdir, 'out.cat')
opts['CATALOG_NAME'] = catname
opts['CATALOG_TYPE'] = 'FITS_LDAC'
if not r0:
opts['FILTER'] = 'N'
else:
kernel = make_kernel(r0, ext=2.0)
kernelname = os.path.join(workdir, 'kernel.txt')
np.savetxt(
kernelname,
kernel / np.sum(kernel),
fmt=b'%.6f',
header='CONV NORM',
comments='',
)
opts['FILTER'] = 'Y'
opts['FILTER_NAME'] = kernelname
opts.update(extra)
# Build the command line
cmd = (
binname
+ ' '
+ shlex.quote(imagename)
+ ' '
+ format_astromatic_opts(opts)
)
if not verbose:
cmd += ' > /dev/null 2>/dev/null'
log('Will run SExtractor like that:')
log(cmd)
# Run the command!
res = os.system(cmd)
if res == 0 and os.path.exists(catname):
log('SExtractor run succeeded')
obj = Table.read(catname, hdu=2)
obj.meta.clear() # Remove unnecessary entries from the metadata
idx = (obj['X_IMAGE'] > edge) & (obj['X_IMAGE'] < image.shape[1] - edge)
idx &= (obj['Y_IMAGE'] > edge) & (obj['Y_IMAGE'] < image.shape[0] - edge)
if np.isscalar(aper):
if sn:
idx &= obj['MAGERR_APER'] < 1.0 / sn
if reject_negative:
idx &= obj['FLUX_APER'] > 0
else:
if sn:
idx &= np.all(obj['MAGERR_APER'] < 1.0 / sn, axis=1)
if reject_negative:
idx &= np.all(obj['FLUX_APER'] > 0, axis=1)
obj = obj[idx]
if wcs is None and header is not None:
wcs = WCS(header)
if wcs is not None:
obj['ra'], obj['dec'] = wcs.all_pix2world(obj['X_IMAGE'], obj['Y_IMAGE'], 1)
else:
obj['ra'], obj['dec'] = (
np.zeros_like(obj['X_IMAGE']),
np.zeros_like(obj['Y_IMAGE']),
)
obj['FLAGS'][obj['IMAFLAGS_ISO'] > 0] |= 0x100 # Masked pixels in the footprint
obj.remove_column('IMAFLAGS_ISO') # We do not need this column
# Convert variances to rms
obj['ERRX2_IMAGE'] = np.sqrt(obj['ERRX2_IMAGE'])
obj['ERRY2_IMAGE'] = np.sqrt(obj['ERRY2_IMAGE'])
for _, __ in [
['X_IMAGE', 'x'],
['Y_IMAGE', 'y'],
['ERRX2_IMAGE', 'xerr'],
['ERRY2_IMAGE', 'yerr'],
['FLUX_APER', 'flux'],
['FLUXERR_APER', 'fluxerr'],
['MAG_APER', 'mag'],
['MAGERR_APER', 'magerr'],
['BACKGROUND', 'bg'],
['FLAGS', 'flags'],
['FWHM_IMAGE', 'fwhm'],
['A_IMAGE', 'a'],
['B_IMAGE', 'b'],
['THETA_IMAGE', 'theta'],
]:
obj.rename_column(_, __)
if psf:
for _, __ in [
['XPSF_IMAGE', 'x_psf'],
['YPSF_IMAGE', 'y_psf'],
['MAG_PSF', 'mag_psf'],
['MAGERR_PSF', 'magerr_psf'],
['FLUX_PSF', 'flux_psf'],
['FLUXERR_PSF', 'fluxerr_psf'],
['CHI2_PSF', 'chi2_psf'],
['SPREAD_MODEL', 'spread_model'],
['SPREADERR_MODEL', 'spreaderr_model'],
]:
if _ in obj.keys():
obj.rename_column(_, __)
if 'mag' in __:
obj[__][obj[__] == 99] = np.nan # TODO: use masked column here?
# SExtractor uses 1-based pixel coordinates
obj['x'] -= 1
obj['y'] -= 1
if 'x_psf' in obj.keys():
obj['x_psf'] -= 1
obj['y_psf'] -= 1
obj.meta['aper'] = aper
if sort:
if np.isscalar(aper):
obj.sort('flux', reverse=True)
else:
# Table sorting by vector columns seems to be broken?..
obj = obj[np.argsort(-obj['flux'][:, 0])]
if catfile is not None:
shutil.copyfile(catname, catfile)
log("Catalogue stored to", catfile)
else:
log("Error", res, "running SExtractor")
result = obj
if checkimages:
result = [result]
for name in checknames:
if os.path.exists(name):
result.append(fits.getdata(name))
else:
log("Cannot find requested output checkimage file", name)
result.append(None)
if _workdir is None:
shutil.rmtree(workdir)
return result
# phot (STDPipe)
def make_kernel(r0=1.0, ext=1.0):
x, y = np.mgrid[
np.floor(-ext * r0) : np.ceil(ext * r0 + 1),
np.floor(-ext * r0) : np.ceil(ext * r0 + 1),
]
r = np.hypot(x, y)
image = np.exp(-r ** 2 / 2 / r0 ** 2)
return image
# phot (F Navarete)
def dq_results(dq_obj):
"""
Reads output from get_objects_sextractor() and evaluates Data Quality results.
dq_obj (astropy.table.Table): output from get_objects_sextractor()
Returns:
fwhm (float): median FWHM of the sources (in pixels)
fwhm_error (float): median absolute error of the FWHM values (in pixels)
ell (float): median ellipticity of the sources
ell_error (float): median absolute error of the ellipticity values
"""
# get FWHM from detections (using median and median absolute deviation as error)
fwhm = np.median(dq_obj['fwhm'])
fwhm_error = np.median(np.absolute(dq_obj['fwhm'] - np.median(dq_obj['fwhm'])))
# estimate median ellipticity of the sources (ell = 1 - b/a)
med_a = np.median(dq_obj['a']) # major axis
med_b = np.median(dq_obj['b']) # minor axis
med_a_error = np.median(np.absolute(dq_obj['a'] - np.median(dq_obj['a'])))
med_b_error = np.median(np.absolute(dq_obj['b'] - np.median(dq_obj['b'])))
ell = 1 - med_b / med_a
ell_error = ell * np.sqrt( (med_a_error/med_a)**2 + (med_b_error/med_b)**2 )
return fwhm, fwhm_error, ell, ell_error
# Utils (STDPipe)
def file_write(filename, contents=None, append=False):
"""
Simple utility for writing some contents into file.
"""
with open(filename, 'a' if append else 'w') as f:
if contents is not None:
f.write(contents)
# utils (STDPipe)
def table_get(table, colname, default=0):
"""
Simple wrapper to get table column, or default value if it is not present
"""
if colname in table.colnames:
return table[colname]
elif default is None:
return None
elif hasattr(default, '__len__'):
# default value is array, return it
return default
else:
# Broadcast scalar to proper length
return default * np.ones(len(table), dtype=int)
# utils (STDPipe)
def get_obs_time(header=None, filename=None, string=None, get_datetime=False, verbose=False):
"""
Extract date and time of observations from FITS headers of common formats, or from a string.
Will try various FITS keywords that may contain the time information - `DATE_OBS`, `DATE`, `TIME_OBS`, `UT`, 'MJD', 'JD'.
:param header: FITS header containing the information on time of observations
:param filename: If `header` is not set, the FITS header will be loaded from the file with this name
:param string: If provided, the time will be parsed from the string instead of FITS header
:param get_datetime: Whether to return the time as a standard Python :class:`datetime.datetime` object instead of Astropy Time
:param verbose: Whether to show verbose messages during the run of the function or not. May be either boolean, or a `print`-like function.
:returns: :class:`astropy.time.Time` object corresponding to the time of observations, or a :class:`datetime.datetime` object if :code:`get_datetime=True`
"""
# Simple wrapper around print for logging in verbose mode only
log = (
(verbose if callable(verbose) else print)
if verbose
else lambda *args, **kwargs: None
)
# Simple wrapper to display parsed value and convert it as necessary
def convert_time(time):
if isinstance(time, float):
# Try to parse floating-point value as MJD or JD, depending on the value
if time > 0 and time < 100000:
log('Assuming it is MJD')
time = Time(time, format='mjd')
elif time > 2400000 and time < 2500000:
log('Assuming it is JD')
time = Time(time, format='jd')
else:
# Then it is probably an Unix time?..
log('Assuming it is Unix time')
time = Time(time, format='unix')
else:
time = Time(time)
log('Time parsed as:', time.iso)
if get_datetime:
return time.datetime
else:
return time
if string:
log('Parsing user-provided time string:', string)
try:
return convert_time(dateutil.parser.parse(string))
except dateutil.parser.ParserError as err:
log('Could not parse user-provided string:', err)
return None
if header is None:
log('Loading FITS header from', filename)
header = fits.getheader(filename)
for dkey in ['DATE-OBS', 'DATE', 'TIME-OBS', 'UT', 'MJD', 'JD']:
if dkey in header:
log('Found ' + dkey + ':', header[dkey])
# First try to parse standard ISO time
try:
return convert_time(header[dkey])
except:
log('Could not parse ' + dkey + ' using Astropy parser')
for tkey in ['TIME-OBS', 'UT']:
if tkey in header:
log('Found ' + tkey + ':', header[tkey])
try:
return convert_time(
dateutil.parser.parse(header[dkey] + ' ' + header[tkey])
)
except dateutil.parser.ParserError as err:
log('Could not parse ' + dkey + ' + ' + tkey + ':', err)
log('Unsupported FITS header time format')
return None
# Utils (STDPipe)
def format_astromatic_opts(opts):
"""
Auxiliary function to format dictionary of options into Astromatic compatible command-line string.
Booleans are converted to Y/N, arrays to comma separated lists, strings are quoted when necessary
"""
result = []
for key in opts.keys():
if opts[key] is None:
pass
elif type(opts[key]) == bool:
result.append('-%s %s' % (key, 'Y' if opts[key] else 'N'))
else:
value = opts[key]
if type(value) == str:
value = shlex.quote(value)
elif hasattr(value, '__len__'):
value = ','.join([str(_) for _ in value])
result.append('-%s %s' % (key, value))
result = ' '.join(result)
return result
# plots (STDPipe)
def imgshow(image, wcs=None, qq=(0.01,0.99), cmap='Blues_r', px=None, py=None, plot_wcs=False, pmarker='r.', psize=2, title=None, figsize=None, show_grid=False, output=None, dpi=300):
"""
Wrapper for matplotlib imshow, can plot datapoints and use the available WCS.
"""
if figsize is None:
plt.figure()
else:
plt.figure(figsize=figsize)
# show WCS if available
if wcs is not None:
ax = plt.subplot(projection=wcs)
else:
ax = plt.subplot()
# define 1 and 99-th percentile for plotting the data
quant = np.nanquantile(image,qq)
if quant[0] < 0 :
quant[0] = 0
# now plot
img = ax.imshow(image, origin='lower', vmin=quant[0], vmax=quant[1], interpolation='nearest', cmap=cmap) # STDpipe
if show_grid:
ax.grid(color='white', ls='--')
if wcs is not None:
ax.set_xlabel('Right Ascension (J2000)')
ax.set_ylabel('Declination (J2000)')
# add colorbar
plt.colorbar(img)
# add datapoints
if px is not None and py is not None:
if plot_wcs:
ax.plot(px, py, pmarker, ms=psize, transform=ax.get_transform('fk5'))
else:
plt.plot(px, py, pmarker, ms=psize)
# add title
plt.title(title)
plt.tight_layout()
if output is not None:
plt.savefig(output, dpi=dpi)
# plots (STDPipe)
def colorbar(obj=None, ax=None, size="5%", pad=0.1):
should_restore = False
if obj is not None:
ax = obj.axes
elif ax is None:
ax = plt.gca()
# should_restore = True
# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size=size, pad=pad)
ax.get_figure().colorbar(obj, cax=cax)
# if should_restore:
ax.get_figure().sca(ax)