forked from mommermi/photometrypipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
catalog.py
1611 lines (1351 loc) · 68.4 KB
/
catalog.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 _pp_conf
from pandas import read_sql
"""
CATALOG - class structure for dealing with astronomical catalogs,
FITS_LDAC files, and sqlite databases.
version 0.9, 2016-01-27, [email protected]
"""
# Photometry Pipeline
# Copyright (C) 2016-2018 Michael Mommert, [email protected]
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <http://www.gnu.org/licenses/>.
import os
import sys
import logging
import numpy as np
import sqlite3 as sql
import astropy.units as u
import astropy.coordinates as coord
from astropy.table import Table, Column
from astropy import __version__ as astropyversion
from astropy.io import fits
import scipy.optimize as optimization
import warnings
warnings.simplefilter("ignore", UserWarning)
try:
from scipy import spatial
except ImportError:
print('Module scipy not found. Please install with: pip install scipy')
sys.exit()
try:
from astroquery.vizier import Vizier
from astroquery.sdss import SDSS
except ImportError:
print('Module astroquery not found. Please install with: pip install '
'astroquery')
sys.exit()
# translates numpy datatypes to sql-readable datatypes
sql.register_adapter(np.float64, float)
sql.register_adapter(np.float32, float)
sql.register_adapter(np.int64, int)
sql.register_adapter(np.int32, int)
# import pp modules
# setup logging
logging.basicConfig(filename=_pp_conf.log_filename,
level=_pp_conf.log_level,
format=_pp_conf.log_formatline,
datefmt=_pp_conf.log_datefmt)
class catalog(object):
def __init__(self, catalogname, display=False):
self.data = None # will be an astropy table
self.catalogname = catalogname
self.obstime = [None, None] # observation midtime (JD) +
# duration
self.obj = None # header target name
self.origin = '' # where does the data come from?
self.history = '' # catalog history
self.magsys = '' # [AB|Vega|instrumental]
self.display = display
self.filtername = None
# data access functions
@property
def shape(self):
"""
return: tuple of number of sources and fields
"""
try:
return (len(self.data), len(self.fields))
except AttributeError:
return (len(self.data), len(self.data.columns))
@property
def fields(self):
"""
return: array of all available fields
"""
return self.data.columns
def __getitem__(self, ident):
"""
return: source or field
"""
return self.data[ident]
# data manipulation functions
def reject_sources_other_than(self, condition):
"""
reject sources based on condition
input: condition
return: number of sources left
"""
n_raw = self.shape[0]
self.data = self.data[condition]
logging.info('{:s}:reject {:d} sources'.format(self.catalogname,
n_raw-self.shape[0]))
return len(self.data)
def reject_sources_with(self, condition):
"""
reject sources based on condition
input: condition
return: number of sources left
"""
n_raw = self.shape[0]
self.data = self.data[~condition]
logging.info('{:s}:reject {:d} sources'.format(self.catalogname,
n_raw-self.shape[0]))
return n_raw - len(self.data)
def add_field(self, field_name, field_array, field_type=None):
"""
single-field wrapper for add_fields
"""
if field_type is not None:
return self.data.add_column(Column(field_array, name=field_name,
format=field_type))
else:
return self.data.add_column(Column(field_array, name=field_name))
def add_fields(self, field_names, field_arrays, field_types=None):
"""
add fields to self.data
input: field_names, field_arrays, field_types
output: number of added fields
"""
assert len(field_names) == len(field_arrays)
if self.data is None:
self.data = Table()
for i in range(len(field_names)):
if field_types is None:
self.data.add_column(Column(np.array(field_arrays[i]),
name=field_names[i]))
else:
self.data.add_column(Column(np.array(field_arrays[i]),
name=field_names[i],
format=field_types[i]))
return len(field_arrays)
# data io
# online catalog access
def download_catalog(self, ra_deg, dec_deg, rad_deg,
max_sources, save_catalog=False,
max_mag=21, use_all_stars=False):
"""
download existing catalog from VIZIER server using self.catalogname
input: ra_deg, dec_deg, rad_deg, max_sources, (display_progress),
(sort=['ascending', 'descending', None])
return: number of sources downloaded
astrometric catalogs: ra_deg, dec_deg, e_ra_deg, e_dec_deg,
mag, e_mag, [epoch_jd, Gaia only]
photometric catalogs: ra_deg, dec_deg, e_ra_deg, e_dec_deg,
[mags], [e_mags], epoch_jd
"""
# setup Vizier query
# note: column filters uses original Vizier column names
# -> green column names in Vizier
if self.display:
print(('query Vizier for {:s} at {:7.3f}/{:+.3f} in '
+ 'a {:.2f} deg radius').format(self.catalogname,
ra_deg, dec_deg,
rad_deg),
end=' ', flush=True)
logging.info(('query Vizier for {:s} at {:7.3f}/{:+.3f} in '
+ 'a {:.2f} deg radius').format(self.catalogname,
ra_deg, dec_deg,
rad_deg))
field = coord.SkyCoord(ra=ra_deg, dec=dec_deg, unit=(u.deg, u.deg),
frame='icrs')
# -----------------------------------------------------------------
# use vizier query for Pan-STARRS
if self.catalogname == 'PANSTARRS':
vquery = Vizier(columns=['objID', 'RAJ2000', 'DEJ2000',
'e_RAJ2000', 'e_DEJ2000',
'gmag', 'e_gmag',
'rmag', 'e_rmag',
'imag', 'e_imag',
'zmag', 'e_zmag',
'ymag', 'e_ymag'],
column_filters={"rmag":
("<{:f}".format(max_mag))},
row_limit=max_sources,
timeout=300)
try:
self.data = vquery.query_region(field,
radius=rad_deg*u.deg,
catalog="II/349/ps1",
cache=False)[0]
except IndexError:
if self.display:
print('no data available from {:s}'.format(
self.catalogname))
logging.error('no data available from {:s}'.format(
self.catalogname))
return 0
# rename column names using PP conventions
self.data.rename_column('objID', 'ident')
self.data.rename_column('RAJ2000', 'ra_deg')
self.data.rename_column('DEJ2000', 'dec_deg')
self.data.rename_column('e_RAJ2000', 'e_ra_deg')
self.data['e_ra_deg'].convert_unit_to(u.deg)
self.data.rename_column('e_DEJ2000', 'e_dec_deg')
self.data['e_dec_deg'].convert_unit_to(u.deg)
self.data.rename_column('gmag', 'gp1mag')
self.data.rename_column('e_gmag', 'e_gp1mag')
self.data.rename_column('rmag', 'rp1mag')
self.data.rename_column('e_rmag', 'e_rp1mag')
self.data.rename_column('imag', 'ip1mag')
self.data.rename_column('e_imag', 'e_ip1mag')
self.data.rename_column('zmag', 'zp1mag')
self.data.rename_column('e_zmag', 'e_zp1mag')
self.data.rename_column('ymag', 'yp1mag')
self.data.rename_column('e_ymag', 'e_yp1mag')
self.data['mag'] = self.data['rp1mag'] # use rmag for astrometry
# clip self.data to enforce magnitude error limits
if not use_all_stars:
self.data = self.data[self.data['e_rp1mag'] <= 0.03]
# --------------------------------------------------------------------
# use astroquery vizier query for SkyMapper
elif self.catalogname == 'SkyMapper':
vquery = Vizier(columns=['all'],
column_filters={"rPSF":
("<{:f}".format(max_mag))},
row_limit=max_sources,
timeout=300)
try:
self.data = vquery.query_region(field,
radius=rad_deg*u.deg,
catalog="II/358/smss",
cache=False)[0]
except IndexError:
if self.display:
print('no data available from {:s}'.format(
self.catalogname))
logging.error('no data available from {:s}'.format(
self.catalogname))
return 0
# throw out columns we don't need
new_data = Table(self.data)
for col in self.data.columns:
if col not in ['ObjectId', 'RAICRS', 'DEICRS',
'e_RAICRS', 'e_DEICRS',
'uPSF', 'e_uPSF',
'vPSF', 'e_vPSF',
'gPSF', 'e_gPSF',
'rPSF', 'e_rPSF',
'zPSF', 'e_zPSF',
'iPSF', 'e_iPSF']:
new_data.remove_column(col)
self.data = new_data
# rename column names using PP conventions
self.data.rename_column('ObjectId', 'ident')
self.data.rename_column('RAICRS', 'ra_deg')
self.data.rename_column('DEICRS', 'dec_deg')
self.data.rename_column('e_RAICRS', 'e_ra_deg')
self.data['e_ra_deg'].convert_unit_to(u.deg)
self.data.rename_column('e_DEICRS', 'e_dec_deg')
self.data['e_dec_deg'].convert_unit_to(u.deg)
#self.data.rename_column('uPSF', 'umag')
#self.data.rename_column('e_uPSF', 'e_umag')
self.data.rename_column('vPSF', 'vmag')
self.data.rename_column('e_vPSF', 'e_vmag')
self.data.rename_column('gPSF', 'gmag')
self.data.rename_column('e_gPSF', 'e_gmag')
self.data.rename_column('rPSF', 'rmag')
self.data.rename_column('e_rPSF', 'e_rmag')
self.data.rename_column('iPSF', 'imag')
self.data.rename_column('e_iPSF', 'e_imag')
self.data.rename_column('zPSF', 'zmag')
self.data.rename_column('e_zPSF', 'e_zmag')
if not use_all_stars:
self.data = self.data[self.data['e_rmag'] <= 0.03]
# --------------------------------------------------------------------
elif self.catalogname == 'GAIA':
# astrometric and photometric catalog (as of DR2)
vquery = Vizier(columns=['Source', 'RA_ICRS', 'DE_ICRS',
'e_RA_ICRS', 'e_DE_ICRS', 'pmRA',
'pmDE', 'Epoch',
'Gmag', 'e_Gmag',
'BPmag', 'e_BPmag',
'RPmag', 'eRPmag'],
column_filters={"phot_g_mean_mag":
("<{:f}".format(max_mag))},
row_limit=max_sources,
timeout=300)
try:
self.data = vquery.query_region(field,
radius=rad_deg*u.deg,
catalog="I/345/gaia2",
cache=False)[0]
except IndexError:
if self.display:
print('no data available from {:s}'.format(
self.catalogname))
logging.error('no data available from {:s}'.format(
self.catalogname))
return 0
# rename column names using PP conventions
self.data.rename_column('Source', 'ident')
self.data.rename_column('RA_ICRS', 'ra_deg')
self.data.rename_column('DE_ICRS', 'dec_deg')
self.data.rename_column('e_RA_ICRS', 'e_ra_deg')
self.data['e_ra_deg'].convert_unit_to(u.deg)
self.data.rename_column('e_DE_ICRS', 'e_dec_deg')
self.data['e_dec_deg'].convert_unit_to(u.deg)
self.data.rename_column('Epoch', 'epoch_yr')
self.data['mag'] = self.data['Gmag'] # required for scamp
# TBD:
# - implement proper error ellipse handling
# - implement propor motion handling for DR2
# --------------------------------------------------------------------
elif self.catalogname == 'USNO-B1':
# astrometric and photometric catalog
vquery = Vizier(columns=['USNO-B1.0', 'RAJ2000', 'DEJ2000',
'e_RAJ2000', 'e_DEJ2000',
'R2mag'],
column_filters={"R2mag":
("<{:f}".format(max_mag))},
row_limit=max_sources,
timeout=300)
try:
self.data = vquery.query_region(field,
radius=rad_deg*u.deg,
catalog="I/284/out",
cache=False)[0]
except IndexError:
if self.display:
print('no data available from {:s}'.format(
self.catalogname))
logging.error('no data available from {:s}'.format(
self.catalogname))
return 0
# rename column names using PP conventions
self.data.rename_column('USNO-B1.0', 'ident')
self.data.rename_column('RAJ2000', 'ra_deg')
self.data.rename_column('DEJ2000', 'dec_deg')
self.data.rename_column('e_RAJ2000', 'e_ra_deg')
self.data['e_ra_deg'].convert_unit_to(u.deg)
self.data.rename_column('e_DEJ2000', 'e_dec_deg')
self.data['e_dec_deg'].convert_unit_to(u.deg)
self.data['mag'] = self.data['R2mag'] # required for scamp
# --------------------------------------------------------------------
elif self.catalogname == 'TGAS':
# astrometric catalog
vquery = Vizier(columns=['Source', 'RA_ICRS', 'DE_ICRS',
'e_RA_ICRS', 'e_DE_ICRS', 'pmRA',
'pmDE', 'phot_g_mean_mag'],
column_filters={"phot_g_mean_mag":
("<{:f}".format(max_mag))},
row_limit=max_sources,
timeout=300)
try:
self.data = vquery.query_region(field,
radius=rad_deg*u.deg,
catalog="I/337/tgas",
cache=False)[0]
except IndexError:
if self.display:
print('no data available from {:s}'.format(
self.catalogname))
logging.error('no data available from {:s}'.format(
self.catalogname))
return 0
# rename column names using PP conventions
self.data.rename_column('Source', 'ident')
self.data.rename_column('RA_ICRS', 'ra_deg')
self.data.rename_column('DE_ICRS', 'dec_deg')
self.data.rename_column('e_RA_ICRS', 'e_ra_deg')
self.data['e_ra_deg'].convert_unit_to(u.deg)
self.data.rename_column('e_DE_ICRS', 'e_dec_deg')
self.data['e_dec_deg'].convert_unit_to(u.deg)
self.data.rename_column('__Gmag_', 'mag')
self.data.add_column(Column(np.ones(len(self.data))*2457023.5,
name='epoch_jd', unit=u.day))
# TBD:
# - implement pm progragation
# - implement proper error ellipse handling
elif self.catalogname == '2MASS':
# photometric catalog
vquery = Vizier(columns=['2MASS', 'RAJ2000', 'DEJ2000', 'errMaj',
'errMin', 'errPA', 'Jmag', 'e_Jmag',
'Hmag', 'e_Hmag', 'Kmag', 'e_Kmag',
'Qflg', 'Rflg'],
column_filters={"Jmag":
("<{:f}".format(max_mag))},
row_limit=max_sources)
try:
self.data = vquery.query_region(field,
radius=rad_deg*u.deg,
catalog="II/246/out",
cache=False)[0]
except IndexError:
if self.display:
print('no data available from {:s}'.format(
self.catalogname))
logging.error('no data available from {:s}'.format(
self.catalogname))
return 0
# filter columns to only have really good detections
# see the Vizier webpage for a description of what the flags mean
if not use_all_stars:
Qflags = set('ABC') # only A, B, or C flagged detections
qmask = [True if not set(item).difference(Qflags) else False
for item in self.data['Qflg']]
# filter columns to only have really good detections
self.data = self.data[qmask]
# rename column names using PP conventions
self.data.rename_column('_2MASS', 'ident')
self.data.rename_column('RAJ2000', 'ra_deg')
self.data.rename_column('DEJ2000', 'dec_deg')
self.data.rename_column('Kmag', 'Ksmag')
self.data.rename_column('e_Kmag', 'e_Ksmag')
self.data['mag'] = self.data['Jmag'] # use J as default mag
# determine RA and Dec positional uncertainties and
# add respective columns
self.data['errPA'][self.data['errPA'] == 0] = 1 # workaround
arc_xopt = np.arctan(-self.data['errMin']/self.data['errMaj'] *
np.tan(self.data['errPA'].to(u.rad)))
ra_err = abs(self.data['errMaj']*np.cos(arc_xopt) *
np.cos(self.data['errPA'].to(u.rad)) -
self.data['errMin']*np.sin(arc_xopt) *
np.sin(self.data['errPA'].to(u.rad)))
self.data.add_column(Column(data=ra_err*1000,
name='e_ra_deg', unit=u.mas),
index=2)
arc_yopt = np.arctan(self.data['errMin']/self.data['errMaj'] *
np.cos(self.data['errPA'].to(u.rad)) /
np.sin(self.data['errPA'].to(u.rad)))
dec_err = abs(self.data['errMaj']*np.cos(arc_yopt) *
np.sin(self.data['errPA'].to(u.rad)) +
self.data['errMin']*np.sin(arc_yopt) *
np.cos(self.data['errPA'].to(u.rad)))
self.data.add_column(Column(data=dec_err*1000,
name='e_dec_deg', unit=u.mas), index=3)
# remove error ellipse columns
self.data.remove_column('errMaj')
self.data.remove_column('errMin')
self.data.remove_column('errPA')
elif self.catalogname == 'URAT-1':
# astrometric catalog
vquery = Vizier(columns=['URAT1', 'RAJ2000', 'DEJ2000',
'sigm', 'f.mag', 'e_f.mag', ],
column_filters={"f.mag":
("<{:f}".format(max_mag))},
row_limit=max_sources)
try:
self.data = vquery.query_region(field,
radius=rad_deg*u.deg,
catalog="I/329/urat1",
cache=False)[0]
except IndexError:
if self.display:
print('no data available from {:s}'.format(
self.catalogname))
logging.error('no data available from {:s}'.format(
self.catalogname))
return 0
# rename column names using PP conventions
self.data.rename_column('URAT1', 'ident')
self.data.rename_column('RAJ2000', 'ra_deg')
self.data.rename_column('DEJ2000', 'dec_deg')
self.data.rename_column('f.mag', 'mag')
self.data.rename_column('e_f.mag', 'e_mag')
self.data.add_column(Column(data=self.data['sigm'].data,
name='e_ra_deg',
unit=self.data['sigm'].unit),
index=2)
self.data.add_column(Column(data=self.data['sigm'].data,
name='e_dec_deg',
unit=self.data['sigm'].unit),
index=4)
self.data.remove_column('sigm')
elif self.catalogname == 'APASS9':
# photometric catalog
vquery = Vizier(columns=['recno', 'RAJ2000', 'DEJ2000',
'e_RAJ2000',
'e_DEJ2000', 'Vmag', 'e_Vmag',
'Bmag', 'e_Bmag', "g'mag", "e_g'mag",
"r'mag", "e_r'mag", "i'mag", "e_i'mag"],
column_filters={"Vmag":
("<{:f}".format(max_mag))},
row_limit=max_sources)
try:
self.data = vquery.query_region(field,
radius=rad_deg*u.deg,
catalog="II/336/apass9",
cache=False)[0]
except IndexError:
if self.display:
print('no data available from {:s}'.format(
self.catalogname))
logging.error('no data available from {:s}'.format(
self.catalogname))
return 0
# rename column names using PP conventions
self.data.rename_column('recno', 'ident')
self.data.rename_column('RAJ2000', 'ra_deg')
self.data.rename_column('DEJ2000', 'dec_deg')
self.data.rename_column('e_RAJ2000', 'e_ra_deg')
self.data.rename_column('e_DEJ2000', 'e_dec_deg')
self.data.rename_column('g_mag', 'gmag')
self.data.rename_column('e_g_mag', 'e_gmag')
self.data.rename_column('r_mag', 'rmag')
self.data.rename_column('e_r_mag', 'e_rmag')
self.data.rename_column('i_mag', 'imag')
self.data.rename_column('e_i_mag', 'e_imag')
elif self.catalogname == 'SDSS-R9':
vquery = Vizier(columns=['SDSS9', 'RA_ICRS', 'DE_ICRS',
'e_RA_ICRS',
'e_DE_ICRS', 'umag', 'e_umag',
'gmag', 'e_gmag', 'rmag', 'e_rmag',
'imag', 'e_imag', 'zmag', 'e_zmag'],
column_filters={"gmag":
("<{:f}".format(max_mag)),
"mode": "1",
"q_mode": "+"},
row_limit=max_sources)
try:
self.data = vquery.query_region(field,
radius=rad_deg*u.deg,
catalog="V/139/sdss9",
cache=False)[0]
except IndexError:
if self.display:
print('no data available from {:s}'.format(
self.catalogname))
logging.error('no data available from {:s}'.format(
self.catalogname))
return 0
# rename column names using PP conventions
self.data.rename_column('SDSS9', 'ident')
self.data.rename_column('RA_ICRS', 'ra_deg')
self.data.rename_column('DE_ICRS', 'dec_deg')
self.data.rename_column('e_RA_ICRS', 'e_ra_deg')
self.data.rename_column('e_DE_ICRS', 'e_dec_deg')
# perform correction to AB system for SDSS
# http://www.sdss3.org/dr8/algorithms/fluxcal.php#SDSStoAB
self.data['umag'] -= 0.04
self.data['zmag'] += 0.02
self.data['mag'] = self.data['rmag'] # use rmag for astrometry
elif self.catalogname == 'SDSS-R13':
try:
self.data = SDSS.query_region(
field,
radius=("{:f}d".format(rad_deg)),
photoobj_fields=['objID', 'ra',
'dec',
'raErr',
'decErr',
'fiberMag_u',
'fiberMagErr_u',
'fiberMag_g',
'fiberMagErr_g',
'fiberMag_r',
'fiberMagErr_r',
'fiberMag_i',
'fiberMagErr_i',
'fiberMag_z',
'fiberMagErr_z',
'mode',
'clean',
'type'],
timeout=180,
data_release=13,
cache=False)
except IndexError:
if self.display:
print('no data available from {:s}'.format(
self.catalogname))
logging.error('no data available from {:s}'.format(
self.catalogname))
return 0
# apply some quality masks
if not use_all_stars:
try:
mask_primary = self.data['mode'] == 1
mask_clean = self.data['clean'] == 1
mask_star = self.data['type'] == 6
mask_bright = self.data['fiberMag_g'] < max_mag
mask = mask_primary & mask_clean & mask_star & mask_bright
except TypeError:
if self.display:
print('no data available from {:s}'.format(
self.catalogname))
logging.error('no data available from {:s}'.format(
self.catalogname))
return 0
self.data = self.data[mask]
# rename column names using PP conventions
self.data.rename_column('objID', 'ident')
self.data.rename_column('ra', 'ra_deg')
self.data.rename_column('dec', 'dec_deg')
self.data.rename_column('raErr', 'e_ra_deg')
self.data.rename_column('decErr', 'e_dec_deg')
self.data.rename_column('fiberMag_u', 'umag')
self.data.rename_column('fiberMagErr_u', 'e_umag')
self.data.rename_column('fiberMag_g', 'gmag')
self.data.rename_column('fiberMagErr_g', 'e_gmag')
self.data.rename_column('fiberMag_r', 'rmag')
self.data.rename_column('fiberMagErr_r', 'e_rmag')
self.data.rename_column('fiberMag_i', 'imag')
self.data.rename_column('fiberMagErr_i', 'e_imag')
self.data.rename_column('fiberMag_z', 'zmag')
self.data.rename_column('fiberMagErr_z', 'e_zmag')
self.data['mag'] = self.data['rmag'] # use rmag for astrometry
# perform correction to AB system for SDSS
# http://www.sdss3.org/dr8/algorithms/fluxcal.php#SDSStoAB
self.data['umag'] -= 0.04
self.data['zmag'] += 0.02
# make sure our RA/DEC errors have units
self.data['e_ra_deg'] = self.data['e_ra_deg'] * u.arcsec
self.data['e_dec_deg'] = self.data['e_dec_deg'] * u.arcsec
else:
if self.display:
print('catalog {:s} not available.'.format(
self.catalogname))
logging.error('catalog {:s} not available.'.format(
self.catalogname))
return 0
if self.display:
print('{:d} sources retrieved.'.format(len(self.data)))
logging.info('{:d} sources retrieved'.format(len(self.data)))
self.history = '{:d} sources downloaded'.format(len(self.data))
# convert all coordinate uncertainties to degrees
self.data['e_ra_deg'] = self.data['e_ra_deg'].to(u.deg)
self.data['e_dec_deg'] = self.data['e_dec_deg'].to(u.deg)
# set catalog magnitude system
self.magsystem = _pp_conf.allcatalogs_magsys[self.catalogname]
# write ldac catalog
if save_catalog:
self.write_ldac(self.catalogname+'.cat')
return self.shape[0]
# FITS/LDAC interface
def read_ldac(self, filename, fits_filename=None, maxflag=None,
time_keyword='MIDTIMJD', exptime_keyword='EXPTIME',
object_keyword='OBJECT', telescope_keyword='TEL_KEYW'):
"""
read in FITS_LDAC file
input: LDAC filename
return: (number of sources, number of fields)
"""
# load LDAC file
hdulist = fits.open(filename, ignore_missing_end=True)
if len(hdulist) < 3:
print(('ERROR: {:s} seems to be empty; check LOG file if ' +
'Source Extractor ran properly').format(filename))
logging.error(('ERROR: {:s} seems to be empty; '
'check LOG file if ' +
'Source Extractor ran properly').format(
filename))
return None
# load data array
self.data = Table(hdulist[2].data)
# set other properties
telescope = ''
for line in hdulist[1].data[0][0]:
if telescope_keyword in line:
telescope = line.split('\'')[1]
self.catalogname = filename
if fits_filename is not None:
self.origin = '{:s};{:s}'.format(telescope.strip(), fits_filename)
else:
self.origin = '{:s};'.format(telescope.strip())
self.magsys = 'instrumental'
# reject flagged sources (if requested)
if maxflag is not None:
self.reject_sources_other_than(self.data['FLAGS'] <= maxflag)
# FLAGS <= 3: allow for blending and nearby sources
# read data from image header, if requested
if fits_filename is not None:
fitsheader = fits.open(fits_filename,
ignore_missing_end=True)[0].header
self.obstime[0] = float(fitsheader[time_keyword])
self.obstime[1] = float(fitsheader[exptime_keyword])
self.obj = fitsheader[object_keyword]
# rename columns
if 'XWIN_WORLD' in self.fields:
self.data.rename_column('XWIN_WORLD', 'ra_deg')
if 'YWIN_WORLD' in self.fields:
self.data.rename_column('YWIN_WORLD', 'dec_deg')
# force positive RA values
flip_idc = np.where(self.data['ra_deg'] < 0)[0]
self.data['ra_deg'][flip_idc] += 360
logging.info(('read {:d} sources in {:d} columns '
'from LDAC file {:s}').format(
self.shape[0], self.shape[1], filename))
hdulist.close()
return self.shape
def write_ldac(self, ldac_filename):
"""
write data in new FITS_LDAC file (mainly for use in SCAMP)
input: filename, ra/dec field names, projection_type
return: number of sources written to file
"""
# create primary header (empty)
primaryhdu = fits.PrimaryHDU(header=fits.Header())
# create header table
hdr_col = fits.Column(name='Field Header Card', format='1680A',
array=["obtained through Vizier"])
hdrhdu = fits.BinTableHDU.from_columns(fits.ColDefs([hdr_col]))
hdrhdu.header['EXTNAME'] = ('LDAC_IMHEAD')
# hdrhdu.header['TDIM1'] = ('(80, 36)') # remove?
# create data table
colname_dic = {'ra_deg': 'XWIN_WORLD', 'dec_deg': 'YWIN_WORLD',
'e_ra_deg': 'ERRAWIN_WORLD',
'e_dec_deg': 'ERRBWIN_WORLD',
'mag': 'MAG'}
format_dic = {'ra_deg': '1D', 'dec_deg': '1D',
'e_ra_deg': '1E',
'e_dec_deg': '1E',
'mag': '1E'}
disp_dic = {'ra_deg': 'E15', 'dec_deg': 'E15',
'e_ra_deg': 'E12',
'e_dec_deg': 'E12',
'mag': 'F8.4'}
unit_dic = {'ra_deg': 'deg', 'dec_deg': 'deg',
'e_ra_deg': 'deg',
'e_dec_deg': 'deg',
'mag': 'mag'}
data_cols = []
for col_name in self.data.columns:
if not col_name in list(colname_dic.keys()):
continue
data_cols.append(fits.Column(name=colname_dic[col_name],
format=format_dic[col_name],
array=self.data[col_name],
unit=unit_dic[col_name],
disp=disp_dic[col_name]))
data_cols.append(fits.Column(name='MAGERR',
disp='F8.4',
format='1E',
unit='mag',
array=np.ones(len(self.data))*0.01))
data_cols.append(fits.Column(name='OBSDATE',
disp='F13.8',
format='1D',
unit='yr',
array=np.ones(len(self.data))*2015.0))
datahdu = fits.BinTableHDU.from_columns(fits.ColDefs(data_cols))
datahdu.header['EXTNAME'] = ('LDAC_OBJECTS')
nsrc = len(self.data)
# # combine HDUs and write file
hdulist = fits.HDUList([primaryhdu, hdrhdu, datahdu])
if float(astropyversion.split('.')[0]) > 1:
hdulist.writeto(ldac_filename, overwrite=True)
elif float(astropyversion.split('.')[1]) >= 3:
hdulist.writeto(ldac_filename, overwrite=True)
else:
hdulist.writeto(ldac_filename, clobber=True)
logging.info('wrote {:d} sources from {:s} to LDAC file'.format(
nsrc, ldac_filename))
return nsrc
# ascii interface
def write_table(self, filename, format='ascii'):
"""
write catalog to file using astropy.table.Table.write
input: target filename, file format
return: number of sources written to file
"""
# write data into file
self.data.write(filename, format=format)
logging.info('wrote %d sources from %s to file %s' %
(self.shape[0], self.catalogname, filename))
return self.shape[0]
# SQLite interface
def write_database(self, filename):
"""
write catalog object to SQLite database file
input: target filename
output: number of sources written to file
"""
# open database file (delete existing ones)
os.remove(filename) if os.path.exists(filename) else None
db_conn = sql.connect(filename)
db = db_conn.cursor()
from copy import deepcopy
write_table = deepcopy(self.data)
# rename Johnson filternames to avoid collisions with SDSS
for filtername in ['B', 'V', 'R', 'I']:
if '_'+filtername+'mag' in list(write_table.columns):
write_table.rename_column(
'_{:s}mag'.format(filtername),
'_{:s}Johnsonmag'.format(filtername))
write_table.rename_column(
'_e_{:s}mag'.format(filtername),
'_e_{:s}Johnsonmag'.format(filtername))
elif filtername+'mag' in list(write_table.columns):
write_table.rename_column(
'{:s}mag'.format(filtername),
'{:s}Johnsonmag'.format(filtername))
write_table.rename_column(
'e_{:s}mag'.format(filtername),
'e_{:s}Johnsonmag'.format(filtername))
# create header and write to database
header = Table([[self.catalogname], [self.origin], [self.history],
[self.magsys], [self.obstime[0]], [self.obstime[1]],
[self.obj], [self.filtername]],
names=['name', 'origin', 'description',
'magsys', 'obstime', 'exptime', 'obj',
'filtername'])
header.to_pandas().to_sql('header', db_conn, index=False)
# write data to database
write_table.to_pandas().to_sql('data', db_conn, index=False)
db_conn.commit()
# return number of objects written to database
db.execute(
"SELECT COUNT(DISTINCT {:s}) FROM data".format(
self.fields[0].name))
n_obj = db.fetchall()[0][0]
logging.info(('wrote {:d} sources from catalog {:s} '
'to database file {:s}'.format(
n_obj,
" | ".join([self.catalogname,
self.origin,
self.history]),
filename)))
db_conn.close()
return n_obj
def read_database(self, filename):
""" read in photometry database into catalog """
# open database file
try:
db_conn = sql.connect(filename)
db = db_conn.cursor()
except:
if self.display:
print('ERROR: could not find database', filename)
logging.error('ERROR: could not find database', filename)
return []
# reader in header information
header = read_sql('SELECT * FROM header', db_conn)
self.catalogname = header['name'][0]
self.origin = header['origin'][0]
self.history = header['description'][0]
self.magsys = header['magsys'][0]
self.obstime[0] = header['obstime'][0]
self.obstime[1] = header['exptime'][0]
self.obj = header['obj'][0]
self.filtername = header['filtername'][0]
# read in data table
self.data = Table.from_pandas(read_sql('SELECT * FROM data',
db_conn))
# rename Johnson filternames
for filtername in ['B', 'V', 'R', 'I']:
if '_'+filtername+'Johnsonmag' in list(self.data.columns):
self.data.rename_column(
'_{:s}Johnsonmag'.format(filtername),
'_{:s}mag'.format(filtername))
self.data.rename_column(
'_e_{:s}Johnsonmag'.format(filtername),
'_e_{:s}mag'.format(filtername))