forked from glentner/SLiPy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fits.py
executable file
·437 lines (364 loc) · 13.8 KB
/
Fits.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
#!/usr/bin/env python
# Copyright (c) Geoffrey Lentner 2015. All Rights Reserved.
# See LICENSE (GPLv3)
# slipy/SLiPy/Fits.py
"""
Fits - FITS file handling module.
"""
import os, sys, fnmatch
from astropy.io import fits as pyfits
from numbers import Number
from .. import SlipyError
from ..Framework.Command import Parse, CommandError
from ..Framework.Options import Options, OptionsError
from ..Framework.Display import Monitor, DisplayError
from .Spectrum import Spectrum, SpectrumError
from .Simbad import Position, Distance, Sptype, IDList, SimbadError
class FitsError(SlipyError):
"""
Exception for Fits module.
"""
pass
def Find(toplevel = './', pattern = '*.fits'):
"""
Search for file paths below `toplevel` fitting `pattern`.
"""
if not os.path.isdir(toplevel):
raise FitsError('`{}` does not name a directory.'.format(toplevel))
return [ os.path.join(toplevel, filename)
for filename in fnmatch.filter(os.listdir(toplevel), pattern) ]
def RFind(toplevel = './', pattern = '*.fits'):
"""
Recursively search for paths below `toplevel` fitting `pattern`.
"""
if not os.path.isdir(toplevel):
raise FitsError('`{}` does not name a directory.'.format(toplevel))
return [ os.path.join(dirpath, filename)
for dirpath, dirnames, filenames in os.walk(toplevel)
for filename in fnmatch.filter(filenames, pattern) ]
def GetData( *files, **kwargs ):
"""
Import data from FITS `files`.
kwargs = {
verbose : True , # display messages, progress
toplevel : '' , # request import from directory `toplevel`
pattern : '*.fits', # pattern matching with `toplevel`
recursive : False , # search recursively below `toplevel`
wavecal : True , # fit wavelength vector to data
crpix1 : 'crpix1', # reference pixel header keyword
crval1 : 'crval1', # value at reference pixel
cdelt1 : 'cdelt1', # resolution (delta lambda)
}
"""
try:
# convert `files` to list
files = list(files)
# available key word arguments
options = Options( kwargs,
{
'verbose' : True , # display messages, progress
'toplevel' : '' , # request import from `toplevel` dir
'pattern' : '*.fits', # pattern matching with `toplevel`
'recursive': False , # search recursively below `toplevel`
'wavecal' : True , # fit wavelength vector to data
'crpix1' : 'crpix1', # reference pixel header keyword
'crval1' : 'crval1', # value at reference pixel
'cdelt1' : 'cdelt1', # resolution (delta lambda)
})
# assignment options
verbose = options('verbose')
toplevel = options('toplevel')
pattern = options('pattern')
recursive = options('recursive')
wavecal = options('wavecal')
crpix1 = options('crpix1')
crval1 = options('crval1')
cdelt1 = options('cdelt1')
if toplevel:
# search for files matching `pattern`
find = RFind if recursive else Find
files += find( toplevel, pattern )
if verbose:
# import iteratively, displaying progress
display = Monitor()
nfiles = len(files)
data = []
print(' Importing data from {} Fits files ...'.format(nfiles) )
for a, filename in enumerate(files):
display.progress(a, nfiles)
data.append( Spectrum(filename, wavecal=wavecal,
crpix1=crpix1, crval1=crval1, cdelt1=cdelt1) )
display.complete()
return data
# import spectra 'silently'
return [ Spectrum(filename, wavecal=wavecal, crpix1=crpix1,
crval1=crval1, cdelt1=cdelt1) for filename in files ]
except OptionsError as err:
print(' --> OptionsError:', err)
raise FitsError('Data retrieval failure.')
except SpectrumError as err:
print(' --> SpectrumError:', err)
raise FitsError('Failed to construct spectrum.')
def Header( filename, keyword = None, **kwargs ):
"""
Retrieve `keyword` from FITS header in `filename`. If not provided a
keyword, the entire header object is returned.
"""
try:
options = Options( kwargs,
{
'is_main' : False # reserved for calls from Main()
})
is_main = options('is_main')
with pyfits.open(filename) as hdulist:
header = hdulist[0].header
if keyword: header = header[keyword]
if is_main:
print( header )
return
else:
return header
except OptionsError as err:
print(' --> OptionsError:', err)
raise FitsError('Failed keyword assignment in Header().')
except KeyError as key:
raise FitsError('Header element `{}` was not accessible '
'from `{}`'.format(keyword, filename))
def Search( *files, **kwargs ):
"""
Exctract object names from Fits `files` and use Simbad.py
to resolve the `attribute` (a required keyword argument)
from the SIMBAD astronomical database.
kwargs = {
verbose : True , # display messages, progress
toplevel : '' , # search under `toplevel` directory
pattern : '*.fits', # for files under `toplevel`
recursive : False , # search recusively under `toplevel`
attribute : '' , # attribute to search for (no default)
}
"""
try:
# convert `files` to list
files = list(files)
# available keyword arguments
options = Options( kwargs,
{
'verbose' : True , # display messages, progress
'toplevel' : '' , # search under `toplevel` directory
'pattern' : '*.fits', # for files under `toplevel`
'recursive' : False , # search recusively under `toplevel`
'attribute' : '' , # attribute to search for (no default)
'is_main' : False # reserved for calls from Main()
})
# assign parameters
verbose = options('verbose')
toplevel = options('toplevel')
pattern = options('pattern')
recursive = options('recursive')
attribute = options('attribute')
is_main = options('is_main')
# Available search functions from Simbad.py
SimbadSearch = {
'Position': Position, # ra, dec (degrees)
'Distance': Distance, # in parsecs
'Sptype' : Sptype , # spectral type
'IDList' : IDList # alternate IDs
}
if not attribute:
raise FitsError('An `attribute` must be specified for Search().')
if attribute not in SimbadSearch:
raise FitsError('`{}` is not an available search criteria.'
.format(attribute))
if toplevel:
# search for files in `toplevel` directory
find = RFind if recursive else Find
files += find(toplevel, pattern)
nfiles = len(files)
display = Monitor()
if verbose:
# read object names iteratively
print(' Reading object names for {} Fits files ...'.format(nfiles))
obj_ids = []
for a, name in enumerate(files):
display.progress(a, nfiles)
obj_ids.append( Header(name, 'object') )
display.complete()
else: obj_ids = [ Header(name, 'object') for name in files ]
if verbose:
# query for `attribute` iteratively
print(' Searching for `{}`s with SIMBAD ...'.format(attribute))
results = []
for a, obj in enumerate(obj_ids):
display.progress(a, nfiles)
results.append( SimbadSearch[attribute](obj) )
display.complete()
else: results = [ SimbadSearch[attribute](obj) for obj in obj_ids ]
if is_main:
formatted = {
'Position':'{1:.2f} {1:.2f}',
'Distance':'{0:.2f}',
'Sptype' : '{}'
}
for item in results:
if type(item) is list:
print( formatted[attribute].format(*item))
else:
print( formatted[attribute].format(item))
else: return results
except OptionsError as err:
print(' --> OptionsError:', err)
raise FitsError('Failed assignment for Search().')
except SimbadError as err:
print(' --> SimbadError:', err)
raise FitsError('Simbad failed.')
def PositionSort( center, radius, *files, **kwargs ):
"""
Return a list of files from `files` that lie in a `radius` (in degrees)
from `center`, based on the `ra` (right ascension) and `dec` (declination).
kwargs = {
'ra' : 'pos1' , # header element for right ascension
'dec' : 'pos2' , # header element for declination
'obj' : 'object', # header element for object id
'raconvert': True , # convert decimal hours to decimal degrees
'verbose' : True , # display messages, progress
'toplevel' : '' , # `toplevel` directory to look for files in
'recursive': False , # search `recursive`ly below `toplevel`
'pattern' : '*.fits', # glob `pattern` for file search
'useSimbad': False # use Simbad instead of header elements
}
"""
try:
# function parameter defaults
options = Options( kwargs,
{
'ra' : 'pos1' , # header element for right ascension
'dec' : 'pos2' , # header element for declination
'obj' : 'object', # header element for object id
'raconvert': True , # convert decimal hours to decimal degrees
'verbose' : True , # display messages, progress
'toplevel' : '' , # `toplevel` directory for file search
'recursive': False , # search `recursive`ly below `toplevel`
'pattern' : '*.fits', # glob `pattern` for file search
'useSimbad': False # use Simbad instead of header elements
})
# function parameter assignments
ra = options('ra')
dec = options('dec')
obj = options('obj')
raconvert = options('raconvert')
verbose = options('verbose')
toplevel = options('toplevel')
recursive = options('recursive')
pattern = options('pattern')
useSimbad = options('useSimbad')
except OptionsError as err:
print(' --> OptionsError:', err)
raise FitsError('Failed keyword assignment in PositionSort().')
# check arguments
if not hasattr( center, '__iter__'):
raise FitsError('PositionSort() expects `center` argument to be '
'`iterable` and have two elements.')
if len(center) != 2:
raise FitsError('PositionSort() expects `center` argument to have '
'exactly two elements.')
if not isinstance( radius, Number ):
raise FitsError('PositionSort() expects `radius` argument to '
'be a `Number`.')
for a, f in enumerate(files):
if not isinstance(f, str):
raise FitsError('PositionSort() expects `str` like arguments '
'for all `files` (from argument {})'.format(a))
# convert `files` to list type
files = list(files)
# look under `toplevel` if requested
if toplevel:
find = RFind if recursive else Find
files += find(toplevel, pattern)
if verbose:
# create display object
display = Monitor()
nfiles = len(files)
# initialize blank lists
pos1, pos2 = [], []
if not useSimbad:
if verbose: print(' Retrieving position information from {} files ... '.format(nfiles))
# check file headers for requested information
for a, fitsfile in enumerate(files):
try:
alpha = Header(fitsfile, ra)
delta = Header(fitsfile, dec)
if raconvert: alpha *= 180 / 12
pos1.append(alpha)
pos2.append(delta)
except FitsError as err:
# attempt to get info from SIMBAD instead
print('\n Failed to retrieve position from file {}, contacted SIMBAD ...'.format(a))
pos = Position( Header(fitsfile, obj) )
print('\033[A\r\033[K\033[2A')
pos1.append( pos[0] )
pos2.append( pos[1] )
if verbose: display.progress(a + 1, nfiles)
else:
# use the Simbad module to search for positions
if verbose: print(' Retrieving {} positions from SIMBAD ... '.format(nfiles))
for a, fitsfile in enumerate(files):
pos = Position( Header(fitsfile, obj) )
pos1.append( pos[0] )
pos2.append( pos[1] )
if verbose: display.progress(a, nfiles)
# erase progress bar
if verbose:
display.complete()
print('\r\033[K Compiling list of files ... ')
# keep files for targets within range
keepers = [ f for p1, p2, f in zip(pos1, pos2, files)
if abs(p1 - center[0]) < radius and abs(p2 - center[1]) < radius ]
# account for p1 ~ 0 && center ~ 360 like comparisons
keepers += [ f for p1, p2, f in zip(pos1, pos2, files)
if abs(p1 + 360 - center[0]) < radius and abs(p2 - center[1]) < radius ]
# account for p1 ~ 360 && center ~ 0 like comparisons
keepers += [ f for p1, p2, f in zip(pos1, pos2, files)
if abs(p1 - center[0] - 360) < radius and abs(p2 - center[1]) < radius ]
if verbose: print('\033[A\r\033[K Compiling list of files ... done')
# exclude any potential double countings
return list(set(keepers))
def Main( clargs ):
"""
Main function. See __doc__ for details.
"""
if len(clargs) < 2:
# show usage
print( __doc__ )
return 0
# Available functions for execution
executable = {
'Header' : Header, # Header function
'Search' : Search # Search function
}
try:
# Parse command line arguments
function, args, kwargs = Parse( clargs[1:] )
if not args and not kwargs:
# show function usage
print( executable[function].__doc__ )
return 0
# run execution
executable[function]( *args, is_main=True, **kwargs )
return 0
except CommandError as err:
print(' --> CommandError:', err)
return 1
except KeyError as key:
print(' --> {} was not a recognized function.'.format(key))
return 1
except FitsError as err:
# don't let uncaught self exception pass if from main.
print(' --> FitsError:', err.msg)
return 1
except Exception as err:
print(' --> Unrecognized error from Fits module.')
print(' --> Exception: `{}`'.format(err))
return 1
if __name__ == '__main__':
# call Main function, exit 0 or 1
sys.exit( Main(sys.argv) )