-
Notifications
You must be signed in to change notification settings - Fork 1
/
hosts.py
1264 lines (1058 loc) · 43.5 KB
/
hosts.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
"""
Defines the hosts for the distant local group project
"""
from __future__ import division, print_function
import os
import sys
import numpy as np
from matplotlib import pyplot as plt
try:
import six
except ImportErrir:
from astropy.extern import six
urlopen = six.moves.urllib.request.urlopen
from astropy import units as u
from astropy.coordinates import SkyCoord
NSA_VERSION = '0.1.2' # used to find the download location/file name
NSAFILENAME = 'nsa_v{0}.fits'.format(NSA_VERSION.replace('.', '_'))
SDSS_SQL_URL = 'http://skyserver.sdss3.org/dr10/en/tools/search/x_sql.aspx'
USNOB_URL = 'http://www.nofs.navy.mil/cgi-bin/vo_cone.cgi'
TELL_IF_USING_CACHED = False # If True, show an informational message about where the NSA is coming from
class NSAHost(object):
"""
A host for targetting extracted from the Nasa-Sloan Atlas.
Parameters
----------
nsaid : int
The NSA ID# of this host
name : str or sequence of strings or None
The name of this host (or None to go with "NSA###"). If a list,
the first will be the `name` attribute, while all others will be
in `altname`
environsradius : Quantity
The distance (radius) to consider as the edge of the "environs" - can be
given as an angle, or as a physical distance.
fnsdss : str or None
The filename for the SDSS data table. If None, the default will
be used.
fnusnob : str or None
The filename for the USNO-B data table. If None, the default
will be used.
shortname : str or None
Sets the `shortname` attribute (described below) - if None, a shortname
will be created from a shortened version of the `name` attribute.
Attributes
----------
nsaid : int
The NSA ID# of this host
nsaindx : int
The index into the NSA array for this host - *not* the same as `nsaid`
ra : float
RA in degrees of the host
dec : float
Declination in degrees of the host
zdist : float
'ZDIST' field from NSA
zdisterr : float
'ZDIST_ERR' field from NSA
zspec : float
'Z' field from NSA (`z` is the photometric band)
F,N,u,g,r,i,z : float
magnitudes from the NSA
shortname : str
A name for the field that's 6 characters or less (needed for
spectrographs like IMACS that have silly character size requirements).
Notes
-----
This assumes the NSA catalog is sorted by NSAID. This is True as of
this writing but could in theory change. In that case the catalog should
be pre-sorted or something
"""
def __init__(self, nsaid, name=None, environsradius=300*u.kpc,
fnsdss=None, fnusnob=None, shortname=None):
from os import path
from astropy.coordinates import ICRS, Galactic
self.nsaid = nsaid # The NSA ID #
nsaname = 'NSA{0}'.format(self.nsaid)
if name is None:
self.name = nsaname
self.altnames = []
elif isinstance(name, six.string_types):
self.name = name
self.altnames = [nsaname]
else:
self.name = name[0]
self.altnames = name[1:]
if nsaname not in self.altnames:
self.altnames.append(nsaname)
nsa = get_nsa()
# find the object that's in the right order for the requested ID
self.nsaindx = np.searchsorted(nsa['NSAID'], nsaid)
obj = nsa[self.nsaindx]
# make sure its actually the right object
if obj['NSAID'] != nsaid:
raise ValueError('NSAID #{0} not present in the catalog'.format(nsaid))
#now populate various things
self.ra = obj['RA']
self.dec = obj['DEC']
self.zdist = obj['ZDIST']
self.zdisterr = obj['ZDIST_ERR']
self.zspec = obj['Z']
self.mstar = obj['MASS']
galcoord = ICRS(self.ra*u.deg, self.dec*u.deg).transform_to(Galactic)
self.l = galcoord.l.degree
self.b = galcoord.b.degree
for i, band in enumerate('FNugriz'):
setattr(self, band, obj['ABSMAG'][i])
if hasattr(environsradius, 'unit') and environsradius.unit.is_equivalent(u.kpc):
self.environskpc = environsradius.to(u.kpc).value
elif hasattr(environsradius, 'unit') and environsradius.unit.is_equivalent(u.arcmin):
self.environsarcmin = environsradius.to(u.arcmin).value
elif isinstance(environsradius, float) or isinstance(environsradius, int): #pre-Quantity behavior
if environsradius > 0:
self.environskpc = environsradius
else:
self.environsarcmin = -environsradius
else:
raise ValueError('invalid environsradius')
if fnsdss is None:
self.fnsdss = path.join('catalogs',
'{0}_sdss.dat'.format(self.name))
self.altfnsdss = [path.join('catalogs',
'{0}_sdss.dat'.format(nm)) for nm in self.altnames]
else:
self.fnsdss = fnsdss
self.altfnsdss = []
if fnusnob is None:
self.fnusnob = path.join('catalogs',
'{0}_usnob.dat'.format(self.name))
self.altfnusnob = [path.join('catalogs',
'{0}_usnob.dat'.format(nm)) for nm in self.altnames]
else:
self.fnusnob = fnusnob
self.altfnusnob = []
self.sdssquerymagcut = None
self.shortname = shortname
@property
def dist(self):
"""
Distance to host (given WMAP7 cosmology/H0)
"""
from astropy.cosmology import WMAP7
return WMAP7.luminosity_distance(self.zdist)
@property
def disterr(self):
"""
Distance error (given WMAP7 cosmology/H0)
"""
from astropy.cosmology import WMAP7
dist = WMAP7.luminosity_distance(self.zdist)
dp = abs(dist - WMAP7.luminosity_distance(self.zdist + self.zdisterr))
dm = abs(dist - WMAP7.luminosity_distance(self.zdist - self.zdisterr))
return (dp + dm) / 2
@property
def distmpc(self):
"""
`dist` in Mpc (for backwards-compatibility)
"""
return self.dist.to(u.Mpc).value
@property
def disterrmpc(self):
"""
`disterr` in Mpc (for backwards-compatibility)
"""
return self.disterr.to(u.Mpc).value
@property
def distmod(self):
"""
Distance modulus (mags)
"""
from math import log10
return 5 * log10(self.distmpc * 100000)
@property
def environskpc(self):
"""
The environs radius in kpc
"""
from math import radians
return radians(self._environsarcmin / 60.) * self.distmpc * 1000
@environskpc.setter
def environskpc(self, val):
from math import degrees
self._environsarcmin = degrees(val / (1000 * self.distmpc)) * 60.
@property
def environsarcmin(self):
"""
The environs radius in arcminutes
"""
return self._environsarcmin
@environsarcmin.setter
def environsarcmin(self, val):
self._environsarcmin = val
@property
def coords(self):
"""
The host's coordinates as an ICRS `SkyCoord` object.
"""
return SkyCoord(self.ra*u.deg, self.dec*u.deg, frame='icrs')
@property
def shortname(self):
if self._shortname is None:
return self.name.replace('NGC', 'N')[:6]
else:
return self._shortname
@shortname.setter
def shortname(self, value):
if value is not None and len(value) > 6:
raise ValueError('shortname must be less than 6 characters!')
self._shortname = value
def physical_to_projected(self, dist):
"""
Returns the angular distance (in arcmin) given a projected physical
distance. `distkpc` must be a Quantity.
E.g., ``physical_to_projected(30*u.arcmin)``
"""
if u.kpc.is_equivalent(dist):
dist = dist.to(u.Mpc).value
else:
raise ValueError('need to give physical_to_projected a Quantity.')
return np.degrees(dist / self.distmpc) * 60 * u.arcmin
def projected_to_physical(self, angle):
"""
Returns the projected physical distance (in kpc) given an angular
distance. `angle` must be a Quantity.
E.g., ``projected_to_physical(30*u.arcmin)``
"""
if u.degree.is_equivalent(angle):
angle = angle.to(u.degree).value
else:
raise ValueError('need to give projected_to_physical a Quantity.')
return np.radians(angle) * 1000 * self.distmpc * u.kpc
def sdss_environs_query(self, dl=False, usecas=False, magcut=None,
inclphotzs=True, applyphotflags=False,
xmatchwise=False, usepost=False):
"""
Constructs an SDSS query to get the SDSS objects around this
host and possibly downloads the catalog.
.. note ::
If you do `usecas`=True with this, be sure to put the result
in whatever file `fnsdss` points to.
Parameters
----------
dl : bool or str
If True, download the catalog to `fnsdss`. Otherwise, just
return the query. If 'overwrite', will overwrite `fnsdss` even if
it already exists.
usecas : bool
If True, includes an `INTO` in the SQL for use with casjobs.
Ignored if `dl` is True
magcut : float or None
`magcut` as accepted by `construct_sdss_query` or
None to use `self.sdssquerymagcut`
inclphotzs : bool
If True, includes a further join to add phot-zs where present
applyphotflags : bool
If True, adds photometry flags to the query (See
`construct_sdss_query` for exact flags)
xmatchwise : bool
If True, the query will also cross-match against WISE and include w1
mags.
usepost : bool
If False, uses GET, otherwise POST
Returns
-------
query : str
The SQL query if `dl` is False. Otherwise, `None` is
returned.
Raises
------
ValueError
if the requested id is not in the catalog.
"""
from os.path import exists
raddeg = self.environsarcmin / 60.
usecas = False if dl else usecas
magcut = self.sdssquerymagcut if magcut is None else magcut
intoname = self.name.replace(' ', '_') + ('_wwise' if xmatchwise else '')
query = construct_sdss_query(self.ra, self.dec, raddeg,
into=('{0}_environs'.format(intoname)) if usecas else None,
magcut=magcut, inclphotzs=inclphotzs, applyphotflags=applyphotflags,
xmatchwise=xmatchwise)
if dl:
altfns = [self.fnsdss]
altfns.extend(self.altfnsdss)
for fn in altfns:
if exists(fn):
if dl == 'overwrite':
print('File', fn, 'exists, overwriting with new download.')
else:
print('File', fn, 'exists - not downloading anything.')
break
else:
msg = 'Downloading NSA ID{0} to {1}'.format(self.nsaid, self.fnsdss)
download_sdss_query(query, fn=self.fnsdss, dlmsg=msg, usepost=usepost,
inclheader='Environs of NSA Object {0}'.format(self.nsaid))
else:
return query
def usnob_environs_query(self, dl=False):
"""
Constructs a query to get USNO-B objects around this host, and
possibly downloads the catalog.
.. note::
If `dl` is True, this also fiddles with the catalog a bit to
make the header easier to read by `astropy.io.ascii`.
Parameters
----------
dl : bool
If True, download the catalog
"""
from os.path import exists
raddeg = self.environsarcmin / 60.
usnourl = construct_usnob_query(self.ra, self.dec, raddeg, verbosity=1)
if dl:
altfns = [self.fnusnob]
altfns.extend(self.altfnusnob)
for fn in altfns:
if exists(fn):
print('File', fn, 'exists - not downloading anything.')
break
else:
u = urlopen(usnourl)
try:
with open(self.fnusnob, 'w') as fw:
download_with_progress_updates(u, fw,
msg='Downloading USNO-B to ' + self.fnusnob)
finally:
u.close()
else:
return usnourl
def get_usnob_catalog(self):
"""
Loads and retrieves the data for the USNO-B catalog associated with this
host.
Returns
-------
cat : astropy.table.Table
The USNO-B catalog
"""
if getattr(self, '_cached_usnob', None) is None:
from os.path import exists
from astropy.io import ascii
if exists(self.fnusnob):
fn = self.fnusnob
else:
for fn in self.altfnusnob:
if exists(fn):
print('Could not find file "{0}" but did find "{1}" so using that.'.format(self.fnusnob, fn))
break
else:
#didn't find one
raise IOError('Could not find file {0} nor any of {1}'.format(self.altfnusnob, self.altfnusnob))
with open(fn) as f:
for l in f:
if l.startswith('#1') and 'id' in l:
colnames = [nm.strip() for nm in l.replace('#1', '').split('|') if nm.strip() != '']
#now if there's a group of "S/G" columns, add the appropriate mag suffix
for i in range(len(colnames)):
if colnames[i] == 'S/G':
colnames[i] = colnames[i] + '_' + colnames[i - 1]
break
else:
raise ValueError('USNO-B catalog does not have header - wrong format?')
self._cached_usnob = ascii.read(fn, names=colnames, guess=False, Reader=ascii.NoHeader)
return self._cached_usnob
def get_sdss_catalog(self):
"""
Loads and retrieves the data for the SDSS environs catalog associated
with this host.
Note that this automatically converts all-upper tables to "mixed-case"
for backwards-compatibility.
Returns
-------
cat : astropy.table.Table
The SDSS catalog
"""
from os.path import exists
if getattr(self, '_cached_sdss', None) is None:
if exists(self.fnsdss):
fn = self.fnsdss
else:
for fn in self.altfnsdss:
if exists(fn):
print('Could not find file "{0}" but did find "{1}" so using that.'.format(self.fnsdss, fn))
break
else:
#didn't find one
raise IOError('Could not find file {0} nor any of {1}'.format(self.fnsdss, self.altfnsdss))
self._cached_sdss = self.load_and_reprocess_sdss_catalog(fn)
return self._cached_sdss
catalog_cases_to_convert = ['ra', 'dec', 'rhost', 'type', 'phot_sg', 'rhost_kpc', 'objID']
for band in 'ugriz':
catalog_cases_to_convert.append(band)
catalog_cases_to_convert.append('fibermag_' + band)
catalog_aliases = {nm.upper():nm for nm in catalog_cases_to_convert}
catalog_aliases['RHOST_ARCM'] = 'rhost'
catalog_aliases['PHOTPTYPE'] = 'type'
for band in 'ugriz':
catalog_aliases['EXTINCTION_' + band.upper()] = 'A' + band
catalog_aliases['PSFMAG_' + band.upper()] = 'psf_' + band
del band, catalog_cases_to_convert # clean up the namespace
def load_and_reprocess_sdss_catalog(self, fn):
from astropy.io import ascii, fits
from astropy.table import Table, Column, MaskedColumn
from astropy.coordinates import SkyCoord
if '.fits' in fn:
tab = Table(fits.getdata(fn))
else:
tab = ascii.read(fn, delimiter=',')
# if any of the upper-case versions are present, create mixed-case aliases
for real, alias in self.catalog_aliases.items():
if real in tab.colnames and alias not in tab.colnames:
tab[alias] = tab[real]
# add UBVRI converted from SDSS mags
U, B, V, R, I = sdss_to_UBVRI(*[tab[b] for b in 'ugriz'])
for b in 'UBVRI':
dat = locals()[b]
colcls = MaskedColumn if hasattr(dat, 'mask') else Column
tab.add_column(colcls(name=b, data=dat))
if 'psf_u' in tab.colnames:
pU, pB, pV, pR, pI = sdss_to_UBVRI(*[tab['psf_' + b] for b in 'ugriz'])
for b in 'UBVRI':
dat = locals()['p' + b]
colcls = MaskedColumn if hasattr(dat, 'mask') else Column
tab.add_column(colcls(name='psf_' + b, data=dat))
if 'rhost' not in tab.colnames:
tabsc = SkyCoord(u.Quantity(tab['ra'], u.deg), u.Quantity(tab['dec'], u.deg))
rhost = self.coords.separation(tabsc).degree
colcls = MaskedColumn if hasattr(rhost, 'mask') else Column
tab.add_column(colcls(name='rhost', data=rhost))
tab.add_column(colcls(name='rhost_kpc', data=np.radians(rhost)*self.distmpc*1000))
if 'type' not in tab.colnames or 'phot_sg' not in tab.colnames:
# some catalogs had 'phot_sg' as an *integer* 3/6
if 'phot_sg' in tab.colnames and tab['phot_sg'].dtype.kind == 'i':
typeint = tab['phot_sg']
tab.remove_column('phot_sg')
elif 'type' in tab.colnames and tab['type'].dtype.kind == 'i':
typeint = tab['type']
tab.remove_column('type')
else:
raise ValueError("couldn't figure out what's up with type and phot_sg")
sgstr = np.zeros(len(tab), dtype='S6')
sgstr[typeint == 3] = 'GALAXY'
sgstr[typeint == 6] = 'STAR'
tab.add_column(colcls(name='type', data=typeint))
tab.add_column(colcls(name='phot_sg', data=sgstr))
tab['coord'] = SkyCoord(tab['ra']*u.deg, tab['dec']*u.deg)
return tab
def open_on_nsasite(self):
"""
Uses `webbrowser` to open the page for this host on the NSA web site.
"""
import webbrowser
urltempl = 'http://www.nsatlas.org/getAtlas.html?search=nsaid&nsaID={0}&submit_form=Submit'
webbrowser.open(urltempl.format(self.nsaid))
def __repr__(self):
clsname = super(NSAHost, self).__repr__().split()[0][1:] # strips the "<" at the start
altnamepart = '' if len(self.altnames) == 0 else (' AKA: ' + str(self.altnames))
return "<{clsname} object w/ name '{name}'{altnamepart}>".format(clsname=clsname, name=self.name, altnamepart=altnamepart)
def sdss_image_cutout(self, savefn=None, drorurl=10, imagesize=(512, 512),
opts='', scale = '0.396127', targets=None,
raoffset=0*u.deg, decoffset=0*u.deg):
"""
Saves an SDSS image of the host, optionally with a list of targets
marked.
This requires the `requests` package (http://requests.readthedocs.org/).
Parameters
----------
savefn : None or str
The file name to save to, or None to not save
drorurl : str or int
If an int, this is the data release to use, otherwise a string URL
pointing to the image cutout URL.
imagesize : 2-tuple of its
Size of the image in (width, height)
opts : str
Options the SDSS server accepts like showing photometric objects or
scale bars or the like. Go to the finding chart tool to see
exmaples.
scale : number or angle Quantity
If a raw number, it will be taken as the image scale in arcsec per
pixel. If an angle Quantity, it's the size of the *whole* image.
targets : None or table
A table of targets to mark. Should be the same sort of table output
by `targeting.select_targets`.
raoffset : angle Quantity
How much to offset the image center in RA
decoffset : angle Quantity
How much to offset the image center in Dec
Returns
-------
imagedata
Either the image suitable for IPython if you're in IPython, or the
raw image data if not.
"""
import requests
if isinstance(drorurl, six.string_types):
url = drorurl
else:
url = 'http://skyservice.pha.jhu.edu/DR' + str(drorurl) + '/ImgCutout/getjpeg.aspx'
if u.arcsec.is_equivalent(scale):
avgimagesize = sum(imagesize) / len(imagesize)
scale = scale.to(u.arcsec).value / avgimagesize
if targets is None:
qry = ''
else:
qry = ['id ra dec']
for t in targets:
qry.append('{0} {1} {2}'.format(t['objID'], t['ra'], t['dec']))
qry = '\n'.join(qry)
res = requests.post(url, data={'ra': (self.coords.ra + raoffset).to(u.deg).value,
'dec': (self.coords.dec + decoffset).to(u.deg).value,
'width': imagesize[0],
'height': imagesize[1],
'opt': opts,
'scale': scale,
'query': qry})
if savefn:
with open(savefn, 'w') as f:
f.write(res.content)
try:
__IPYTHON__
from IPython.display import Image
return Image(data=res.content, format='jpeg')
except NameError:
return res.content
def within_environs(self, scorcat):
if isinstance(scorcat, SkyCoord):
sc = scorcat
else:
try:
sc = SkyCoord.guess_from_table(scorcat)
except u.UnitsError:
sc = SkyCoord.guess_from_table(scorcat, unit=u.deg)
return sc.separation(self.coords) < self.environsarcmin * u.arcmin
def download_with_progress_updates(u, fw, nreports=100, msg=None, outstream=sys.stdout):
"""
Download a file and give progress updates on the download.
Parameters
----------
u : result of `urlopen`
The file-like object to read from
fw : writeable file-like object
The file object to fill with the content of the download.
nreports : int
The number of times to update the download percentage if size available
msg : str or None
A message to print when the download stars or None for no message
outstream : file-like
The stream to write the updates to
"""
nreports = int(nreports)
if 'content-length' in u.headers:
l = int(u.headers['content-length']) # bytes
else:
l = None
if msg is not None:
outstream.write(msg)
if l is None:
outstream.write('\nUnknown Size\n')
else:
outstream.write('\nSize: {0} kB\n'.format(l / 1024.))
outstream.flush()
else:
outstream.write('\n') # prepare for the percentage report
if l is None:
i = 0
buf = 'notempty'
while buf:
buf = u.read(1024)
fw.write(buf)
outstream.write('\r{0} kB downloaded'.format(i + 1))
outstream.flush()
i += 1
else:
for i in range(nreports):
fw.write(u.read(int(l / nreports)))
outstream.write('\r{0}%'.format((i + 1) * 100 / nreports))
outstream.flush()
outstream.write('\n') # leave the 100% part
outstream.flush()
#get the little bit that might be left over due to rounding
end = u.read()
if end != '':
fw.write(end)
def load_all_hosts(hostsfile='hosts.dat', existinghosts='globals', usedlgname=False, keyonname=False):
"""
Loads all the hosts in the specified host file and resturns them
as a dictionary.
If `existinghosts` is 'globals', it will be taken from from the global
variable named 'hosts' if it exists. Otherwise it is a list with all
the existing NSA hosts
"""
d = {}
if existinghosts == 'globals':
existinghosts = globals().get('hosts', None)
ids = []
if existinghosts is not None:
for h in existinghosts:
if isinstance(h, NSAHost):
ids.append(h.nsaid)
i = 1
with open(hostsfile) as f:
f.readline() # header
for l in f:
while i in ids:
i += 1
nsanum, ra, dec, z = l.split()
nsanum = int(nsanum)
hnm = 'h' + str(i)
d[hnm] = NSAHost(nsanum, 'DLG' + str(i) if usedlgname else None)
if keyonname:
h = d[hnm]
d[h.name] = h
del d[hnm]
i += 1
return d
_cachednsa={}
def get_nsa(fn=None):
"""
Download the NASA Sloan Atlas if it hasn't been already, open it, and
return the data.
Parameters
----------
fn : str or None
The name of the file to load (or to save as if its not present). If
None, the convention from the NSA web site will be used.
Returns
-------
nsadata
The data as an `astropy.io.fits` record array.
"""
import os
from astropy.io import fits
from hosts import download_with_progress_updates
if fn is None:
fn = NSAFILENAME
if fn in _cachednsa:
if TELL_IF_USING_CACHED:
print('Using cached NSA for file', fn)
return _cachednsa[fn]
if os.path.exists(fn):
if TELL_IF_USING_CACHED:
print('Loading NSA from local file', fn)
else:
# download the file if it hasn't been already
NSAurl = 'http://sdss.physics.nyu.edu/mblanton/v0/' + NSAFILENAME
with open(fn, 'w') as fw:
msg = 'Downloading NSA from ' + NSAurl + ' to ' + fn
u = urlopen(NSAurl)
try:
download_with_progress_updates(u, fw, msg=msg)
finally:
u.close()
# use pyfits from astropy to load the data
res = fits.getdata(fn, 1)
_cachednsa[fn] = res
return res
def construct_sdss_query(ra, dec, radius=1*u.deg, into=None, magcut=None,
inclphotzs=True, applyphotflags=False, xmatchwise=False):
"""
Generates the query to send to the SDSS to get the full SDSS catalog around
a target.
Parameters
----------
ra : `Quantity` or float
The center/host RA (in degrees if float)
dec : `Quantity` or float
The center/host Dec (in degrees if float)
radius : `Quantity` or float
The radius to search out to (in degrees if float)
into : str or None
The name of the table to construct in your `mydb` if you want to use
this with CasJobs, or None to have no "into" in the SQL. This also
adjust other parts of the query a little to work with CasJobs instead
of the direct query.
magcut : 2-tuple or None
if not None, adds a magnitude cutoff. Should be a 2-tuple
('magname', faintlimit). Ignored if None.
inclphotzs : bool
If True, includes a further join to add phot-zs where present
applyphotflags: bool
If True, the query will some basic photometric flags (see the code for
the exact flags)
xmatchwise : bool
If True, the query will also cross-match against WISE and include w1
mags.
Returns
-------
query : str
The SQL query to send to the SDSS skyserver
"""
from textwrap import dedent
query_template = dedent("""
SELECT p.objId as objID,
p.ra, p.dec, p.type, p.flags, p.specObjID, dbo.fPhotoTypeN(p.type) as phot_sg,
p.modelMag_u as u, p.modelMag_g as g, p.modelMag_r as r,p.modelMag_i as i,p.modelMag_z as z,
p.modelMagErr_u as u_err, p.modelMagErr_g as g_err, p.modelMagErr_r as r_err,p.modelMagErr_i as i_err,p.modelMagErr_z as z_err,
p.psfMag_u as psf_u, p.psfMag_g as psf_g, p.psfMag_r as psf_r, p.psfMag_i as psf_i, p.psfMag_z as psf_z,
p.fibermag_r, p.fiber2mag_r,
p.petroMag_r + 2.5*log10(2*PI()*p.petroR50_r*p.petroR50_r) as sb_petro_r,
p.expMag_r, p.expMag_r + 2.5*log10(2*PI()*p.expRad_r*p.expRad_r + 1e-20) as sb_exp_r,
p.deVMag_r, p.deVMag_r + 2.5*log10(2*PI()*p.deVRad_r*p.deVRad_r + 1e-20) as sb_deV_r,
p.lnLExp_r, p.lnLDeV_r, p.lnLStar_r,
p.extinction_u as Au, p.extinction_g as Ag, p.extinction_r as Ar, p.extinction_i as Ai, p.extinction_z as Az,
ISNULL(s.z, -1) as spec_z, ISNULL(s.zErr, -1) as spec_z_err, ISNULL(s.zWarning, -1) as spec_z_warn, s.class as spec_class,
s.subclass as spec_subclass{photzdata}{wisedata}
{intostr}
FROM {funcprefix}fGetNearbyObjEq({ra}, {dec}, {radarcmin}) n, PhotoPrimary p
{wisejoins}
LEFT JOIN SpecObj s ON p.specObjID = s.specObjID
{photzjoins}WHERE n.objID = p.objID{magcutwhere}
{photflags}
""")
#if using casjobs, functions need 'dbo' in front of them for some reason
if into is None:
intostr = ''
funcprefix = 'dbo.'
else:
intostr = 'INTO MyDB.' + into
funcprefix = ''
intostr = '' if into is None else ('INTO MyDB.' + into)
if magcut is None:
magcutwhere = ''
else:
magcutwhere = ' and p.{0} < {1}'.format(*magcut)
if inclphotzs:
photzdata = ', ISNULL(pz.z,-1) as photz,ISNULL(pz.zerr,-1) as photz_err'
photzjoins = 'LEFT JOIN PhotoZ pz ON p.ObjID = pz.ObjID\n'
else:
photzdata = photzjoins = ''
if xmatchwise:
#wisedata = ', ISNULL(W.w1mpro,-99) as w1, ISNULL(W.w1sigmpro, -99) as w1_err'
wisedata = ', ' + dedent("""
ISNULL(w.j_m_2mass,9999) as J, ISNULL(w.j_msig_2mass,9999) as Jerr,
ISNULL(w.H_m_2mass,9999) as H, ISNULL(w.h_msig_2mass,9999) as Herr,
ISNULL(w.k_m_2mass,9999) as K, ISNULL(w.k_msig_2mass,9999) as Kerr,
ISNULL(w.w1mpro,9999) as w1, ISNULL(w.w1sigmpro,9999) as w1err,
ISNULL(w.w2mpro,9999) as w2, ISNULL(w.w2sigmpro,9999) as w2err,
ISNULL(w.w3mpro,9999) as w3, ISNULL(w.w3sigmpro,9999) as w3err,
ISNULL(w.w4mpro,9999) as w4, ISNULL(w.w4sigmpro,9999) as w4err""")
wisejoins = ('LEFT JOIN WISE_xmatch X ON p.objid = X.sdss_objid\n'
'LEFT JOIN wise_allsky W ON x.wise_cntr = W.cntr')
else:
wisejoins = wisedata = ''
if applyphotflags:
photflags = dedent("""
AND (flags & dbo.fPhotoFlags('BINNED1')) != 0
AND (flags & dbo.fPhotoFlags('SATURATED')) = 0
AND (flags & dbo.fPhotoFlags('BAD_COUNTS_ERROR')) = 0 -- "interpolation affected many pixels; PSF flux error is inaccurate and likely underestimated."
"""[1:-1])
# these were considered, but found to sometimes remove *maybe* galaxies
#AND (flags & 0x8100000c00a0) == 0 -- not NOPROFILE, PEAKCENTER, NOTCHECKED, PSF_FLUX_INTERP, SATURATED, or BAD_COUNTS_ERROR
#AND ((flags & 0x400000000000) == 0) | (psfmagerr_g <= 0.2) -- DEBLEND_NOPEAK on faint ones
else:
photflags = ''
if isinstance(ra, float):
ra = ra*u.deg
ra = ra.to(u.deg).value
if isinstance(dec, float):
dec = dec*u.deg
dec = dec.to(u.deg).value
if isinstance(radius, float):
radius = radius*u.deg
radarcmin = radius.to(u.arcmin).value
# ``**locals()`` means "use the local variable names to fill the template"
return query_template.format(**locals())
def construct_usnob_query(ra, dec, radius=1*u.deg, verbosity=1, votable=False, baseurl=USNOB_URL):
"""
Generate a USNO-B query for the area around a target.
Parameters
----------
ra : `Quantity` or float
The center/host RA (in degrees if float)
dec : `Quantity` or float
The center/host Dec (in degrees if float)
radius : `Quantity` or float
The radius to search out to (in degrees if float)
verbosity : int
The USNO verbosity level
votable : bool
If True, query gets a VOTable, otherwise ASCII
Returns
-------
url : str
The url to query to get the catalog.
"""
from urllib import urlencode
if isinstance(ra, float):
ra = ra*u.deg
if isinstance(dec, float):
dec = dec*u.deg
if isinstance(radius, float):
radius = radius*u.deg
parameters = urlencode([('CAT', 'USNO-B1'),
('RA', ra.to(u.deg).value),
('DEC', dec.to(u.deg).value),
('SR', radius.to(u.deg).value),
('VERB', verbosity),
('cftype', 'XML/VO' if votable else 'ASCII'),
('slf', 'ddd.ddd/dd.ddd'),
('skey', 'Mag')])
return baseurl + '?' + parameters
def download_sdss_query(query, fn=None, sdssurl=SDSS_SQL_URL, format='csv',
dlmsg='Downloading...', inclheader=True, usepost=False):
"""
Runs the provided query on the given SDSS `url`, and either returns the
result or saves it as a file.
Parameters
----------
query : str
The SQL query string.
fn : str or None
The filename to save the result to or None to return it from
this function.
sdssurl : str
The URL to send the query to - defaults to whatever
`SDSS_SQL_URL` is (defined at the top of this file)
format : str
The format to return the query. As far as I know, SDSS only
accepts 'csv', 'xml', and 'html'
dlmsg : str or None
A string to print when the download begins. If None, there will
also be no progress updates on the download.
inclheader : bool or str
Whether or not to include a header with information about the query
in the resulting file. If a string, that will be at the end of the
header.
usepost : bool
If False, uses GET, otherwise POST
Returns
-------
result : str, optional
If `fn` is None, this will contain the result of the query.
Raises
------
ValueError
If the SQL query results in an error or returns no rows
Notes
-----
This way of querying the SDSS has time and # of row limits - if
you exceed them you'll get an error and