forked from rflrob/YildizLabCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyfits.py
executable file
·9837 lines (8026 loc) · 384 KB
/
pyfits.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
#!/usr/bin/env python
# $Id: NP_pyfits.py 505 2009-10-12 20:01:05Z jtaylor2 $
from __future__ import division
"""
A module for reading and writing FITS files and manipulating their contents.
A module for reading and writing Flexible Image Transport System
(FITS) files. This file format was endorsed by the International
Astronomical Union in 1999 and mandated by NASA as the standard format
for storing high energy astrophysics data. For details of the FITS
standard, see the NASA/Science Office of Standards and Technology
publication, NOST 100-2.0.
License: http://www.stsci.edu/resources/software_hardware/pyraf/LICENSE
For detailed examples of usage, see the I{PyFITS User's Manual} available from
U{http://www.stsci.edu/resources/software_hardware/pyfits/Users_Manual1.pdf}
Epydoc markup used for all docstrings in this module.
@group Header-related Classes: Card, CardList, _Card_with_continue,
Header, _Hierarch
@group HDU Classes: _AllHDU, BinTableHDU, _CorruptedHDU, _ExtensionHDU,
GroupsHDU, ImageHDU, _ImageBaseHDU, PrimaryHDU, TableHDU,
_TableBaseHDU, _TempHDU, _ValidHDU
@group Table-related Classes: ColDefs, Column, FITS_rec, _FormatP,
_FormatX, _VLF
"""
"""
Do you mean: "Profits"?
- Google Search, when asked for "PyFITS"
"""
import re, os, tempfile, exceptions
import operator
import __builtin__
import urllib
import tempfile
import gzip
import zipfile
import numpy as np
from numpy import char as chararray
import rec
from numpy import memmap as Memmap
from string import maketrans
import string
import types
import signal
import threading
import sys
import warnings
import weakref
import datetime
try:
import pyfitsComp
compressionSupported = 1
except:
compressionSupported = 0
# Module variables
_blockLen = 2880 # the FITS block size
_python_mode = {'readonly':'rb', 'copyonwrite':'rb', 'update':'rb+', 'append':'ab+'} # open modes
_memmap_mode = {'readonly':'r', 'copyonwrite':'c', 'update':'r+'}
TRUE = True # deprecated
FALSE = False # deprecated
_INDENT = " "
DELAYED = "delayed" # used for lazy instantiation of data
ASCIITNULL = 0 # value for ASCII table cell with value = TNULL
# this can be reset by user.
_isInt = "isinstance(val, (int, long, np.integer))"
# The following variable and function are used to support case sensitive
# values for the value of a EXTNAME card in an extension header. By default,
# pyfits converts the value of EXTNAME cards to upper case when reading from
# a file. By calling setExtensionNameCaseSensitive() the user may circumvent
# this process so that the EXTNAME value remains in the same case as it is
# in the file.
_extensionNameCaseSensitive = False
def setExtensionNameCaseSensitive(value=True):
global _extensionNameCaseSensitive
_extensionNameCaseSensitive = value
# Warnings routines
_showwarning = warnings.showwarning
def showwarning(message, category, filename, lineno, file=None, line=None):
if file is None:
file = sys.stdout
_showwarning(message, category, filename, lineno, file)
def formatwarning(message, category, filename, lineno, line=None):
return str(message)+'\n'
warnings.showwarning = showwarning
warnings.formatwarning = formatwarning
warnings.filterwarnings('always',category=UserWarning,append=True)
# Functions
def _padLength(stringLen):
"""Bytes needed to pad the input stringLen to the next FITS block."""
return (_blockLen - stringLen%_blockLen) % _blockLen
def _tmpName(input):
"""Create a temporary file name which should not already exist.
Use the directory of the input file and the base name of the mktemp()
output.
"""
dirName = os.path.dirname(input)
if dirName != '':
dirName += '/'
_name = dirName + os.path.basename(tempfile.mktemp())
if not os.path.exists(_name):
return _name
else:
raise _name, "exists"
def _fromfile(infile, dtype, count, sep):
if isinstance(infile, file):
return np.fromfile(infile, dtype=dtype, count=count, sep=sep)
else: # treat as file-like object with "read" method
read_size=np.dtype(dtype).itemsize * count
str=infile.read(read_size)
return np.fromstring(str, dtype=dtype, count=count, sep=sep)
def _tofile(arr, outfile):
if isinstance(outfile, file):
arr.tofile(outfile)
else: # treat as file-like object with "read" method
str=arr.tostring()
outfile.write(str)
class VerifyError(exceptions.Exception):
"""Verify exception class."""
pass
class _ErrList(list):
"""Verification errors list class. It has a nested list structure
constructed by error messages generated by verifications at different
class levels.
"""
def __init__(self, val, unit="Element"):
list.__init__(self, val)
self.unit = unit
def __str__(self, tab=0):
"""Print out nested structure with corresponding indentations.
A tricky use of __str__, since normally __str__ has only one
argument.
"""
result = ""
element = 0
# go through the list twice, first time print out all top level messages
for item in self:
if not isinstance(item, _ErrList):
result += _INDENT*tab+"%s\n" % item
# second time go through the next level items, each of the next level
# must present, even it has nothing.
for item in self:
if isinstance(item, _ErrList):
_dummy = item.__str__(tab=tab+1)
# print out a message only if there is something
if _dummy.strip():
if self.unit:
result += _INDENT*tab+"%s %s:\n" % (self.unit, element)
result += _dummy
element += 1
return result
class _Verify(object):
"""Shared methods for verification."""
def run_option(self, option="warn", err_text="", fix_text="Fixed.", fix = "pass", fixable=1):
"""Execute the verification with selected option."""
_text = err_text
if not fixable:
option = 'unfixable'
if option in ['warn', 'exception']:
#raise VerifyError, _text
#elif option == 'warn':
pass
# fix the value
elif option == 'unfixable':
_text = "Unfixable error: %s" % _text
else:
exec(fix)
#if option != 'silentfix':
_text += ' ' + fix_text
return _text
def verify (self, option='warn'):
"""Wrapper for _verify."""
_option = option.lower()
if _option not in ['fix', 'silentfix', 'ignore', 'warn', 'exception']:
raise ValueError, 'Option %s not recognized.' % option
if (_option == "ignore"):
return
x = str(self._verify(_option)).rstrip()
if _option in ['fix', 'silentfix'] and x.find('Unfixable') != -1:
raise VerifyError, '\n'+x
if (_option != "silentfix"and _option != 'exception') and x:
warnings.warn('Output verification result:')
warnings.warn(x)
if _option == 'exception' and x:
raise VerifyError, '\n'+x
def _pad(input):
"""Pad balnk space to the input string to be multiple of 80."""
_len = len(input)
if _len == Card.length:
return input
elif _len > Card.length:
strlen = _len % Card.length
if strlen == 0:
return input
else:
return input + ' ' * (Card.length-strlen)
# minimum length is 80
else:
strlen = _len % Card.length
return input + ' ' * (Card.length-strlen)
def _floatFormat(value):
"""Format the floating number to make sure it gets the decimal point."""
valueStr = "%.16G" % value
if "." not in valueStr and "E" not in valueStr:
valueStr += ".0"
return valueStr
class Undefined:
"""Undefined value."""
pass
class Delayed:
"""Delayed file-reading data."""
def __init__(self, hdu=None, field=None):
self.hdu = weakref.ref(hdu)
self.field = field
# translation table for floating value string
_fix_table = maketrans('de', 'DE')
_fix_table2 = maketrans('dD', 'eE')
class Card(_Verify):
# string length of a card
length = 80
# String for a FITS standard compliant (FSC) keyword.
_keywd_FSC = r'[A-Z0-9_-]* *$'
_keywd_FSC_RE = re.compile(_keywd_FSC)
# A number sub-string, either an integer or a float in fixed or
# scientific notation. One for FSC and one for non-FSC (NFSC) format:
# NFSC allows lower case of DE for exponent, allows space between sign,
# digits, exponent sign, and exponents
_digits_FSC = r'(\.\d+|\d+(\.\d*)?)([DE][+-]?\d+)?'
_digits_NFSC = r'(\.\d+|\d+(\.\d*)?) *([deDE] *[+-]? *\d+)?'
_numr_FSC = r'[+-]?' + _digits_FSC
_numr_NFSC = r'[+-]? *' + _digits_NFSC
# This regex helps delete leading zeros from numbers, otherwise
# Python might evaluate them as octal values.
_number_FSC_RE = re.compile(r'(?P<sign>[+-])?0*(?P<digt>' + _digits_FSC+')')
_number_NFSC_RE = re.compile(r'(?P<sign>[+-])? *0*(?P<digt>' + _digits_NFSC + ')')
# FSC commentary card string which must contain printable ASCII characters.
_ASCII_text = r'[ -~]*$'
_comment_FSC_RE = re.compile(_ASCII_text)
# Checks for a valid value/comment string. It returns a match object
# for a valid value/comment string.
# The valu group will return a match if a FITS string, boolean,
# number, or complex value is found, otherwise it will return
# None, meaning the keyword is undefined. The comment field will
# return a match if the comment separator is found, though the
# comment maybe an empty string.
_value_FSC_RE = re.compile(
r'(?P<valu_field> *'
r'(?P<valu>'
# The <strg> regex is not correct for all cases, but
# it comes pretty darn close. It appears to find the
# end of a string rather well, but will accept
# strings with an odd number of single quotes,
# instead of issuing an error. The FITS standard
# appears vague on this issue and only states that a
# string should not end with two single quotes,
# whereas it should not end with an even number of
# quotes to be precise.
#
# Note that a non-greedy match is done for a string,
# since a greedy match will find a single-quote after
# the comment separator resulting in an incorrect
# match.
r'\'(?P<strg>([ -~]+?|\'\'|)) *?\'(?=$|/| )|'
r'(?P<bool>[FT])|'
r'(?P<numr>' + _numr_FSC + ')|'
r'(?P<cplx>\( *'
r'(?P<real>' + _numr_FSC + ') *, *(?P<imag>' + _numr_FSC + ') *\))'
r')? *)'
r'(?P<comm_field>'
r'(?P<sepr>/ *)'
r'(?P<comm>[!-~][ -~]*)?'
r')?$')
_value_NFSC_RE = re.compile(
r'(?P<valu_field> *'
r'(?P<valu>'
r'\'(?P<strg>([ -~]+?|\'\'|)) *?\'(?=$|/| )|'
r'(?P<bool>[FT])|'
r'(?P<numr>' + _numr_NFSC + ')|'
r'(?P<cplx>\( *'
r'(?P<real>' + _numr_NFSC + ') *, *(?P<imag>' + _numr_NFSC + ') *\))'
r')? *)'
r'(?P<comm_field>'
r'(?P<sepr>/ *)'
r'(?P<comm>.*)'
r')?$')
# keys of commentary cards
_commentaryKeys = ['', 'COMMENT', 'HISTORY']
def __init__(self, key='', value='', comment=''):
"""Construct a card from key, value, and (optionally) comment.
Any specifed arguments, except defaults, must be compliant to
FITS standard.
key: keyword name, default=''.
value: keyword value, default=''.
comment: comment, default=''.
"""
if key != '' or value != '' or comment != '':
self._setkey(key)
self._setvalue(value)
self._setcomment(comment)
# for commentary cards, value can only be strings and there
# is no comment
if self.key in Card._commentaryKeys:
if not isinstance(self.value, str):
raise ValueError, 'Value in a commentary card must be a string'
else:
self.__dict__['_cardimage'] = ' '*80
def __repr__(self):
return self._cardimage
def __getattr__(self, name):
""" instanciate specified attribute object."""
if name == '_cardimage':
self.ascardimage()
elif name == 'key':
self._extractKey()
elif name in ['value', 'comment']:
self._extractValueComment(name)
else:
raise AttributeError, name
return getattr(self, name)
def _setkey(self, val):
"""Set the key attribute, surrogate for the __setattr__ key case."""
if isinstance(val, str):
val = val.strip()
if len(val) <= 8:
val = val.upper()
if val == 'END':
raise ValueError, "keyword 'END' not allowed"
self._checkKey(val)
else:
if val[:8].upper() == 'HIERARCH':
val = val[8:].strip()
self.__class__ = _Hierarch
else:
raise ValueError, 'keyword name %s is too long (> 8), use HIERARCH.' % val
else:
raise ValueError, 'keyword name %s is not a string' % val
self.__dict__['key'] = val
def _setvalue(self, val):
"""Set the value attribute."""
if isinstance(val, (str, int, long, float, complex, bool, Undefined,
np.floating, np.integer, np.complexfloating)):
if isinstance(val, str):
self._checkText(val)
self.__dict__['_valueModified'] = 1
else:
raise ValueError, 'Illegal value %s' % str(val)
self.__dict__['value'] = val
def _setcomment(self, val):
"""Set the comment attribute."""
if isinstance(val,str):
self._checkText(val)
else:
if val is not None:
raise ValueError, 'comment %s is not a string' % val
self.__dict__['comment'] = val
def __setattr__(self, name, val):
if name == 'key':
raise SyntaxError, 'keyword name cannot be reset.'
elif name == 'value':
self._setvalue(val)
elif name == 'comment':
self._setcomment(val)
elif name == '__class__':
_Verify.__setattr__(self, name, val)
return
else:
raise AttributeError, name
# When an attribute (value or comment) is changed, will reconstructe
# the card image.
self._ascardimage()
def ascardimage(self, option='silentfix'):
"""Generate a (new) card image from the attributes: key, value,
and comment, or from raw string.
option: verification option, default=silentfix.
"""
# Only if the card image already exist (to avoid infinite loop),
# fix it first.
if self.__dict__.has_key('_cardimage'):
self._check(option)
self._ascardimage()
return self.__dict__['_cardimage']
def _ascardimage(self):
"""Generate a (new) card image from the attributes: key, value,
and comment. Core code for ascardimage.
"""
# keyword string
if self.__dict__.has_key('key') or self.__dict__.has_key('_cardimage'):
if isinstance(self, _Hierarch):
keyStr = 'HIERARCH %s ' % self.key
else:
keyStr = '%-8s' % self.key
else:
keyStr = ' '*8
# value string
# check if both value and _cardimage attributes are missing,
# to avoid infinite loops
if not (self.__dict__.has_key('value') or self.__dict__.has_key('_cardimage')):
valStr = ''
# string value should occupies at least 8 columns, unless it is
# a null string
elif isinstance(self.value, str):
if self.value == '':
valStr = "''"
else:
_expValStr = self.value.replace("'","''")
valStr = "'%-8s'" % _expValStr
valStr = '%-20s' % valStr
# must be before int checking since bool is also int
elif isinstance(self.value ,(bool,np.bool_)):
valStr = '%20s' % `self.value`[0]
elif isinstance(self.value , (int, long, np.integer)):
valStr = '%20d' % self.value
# XXX need to consider platform dependence of the format (e.g. E-009 vs. E-09)
elif isinstance(self.value, (float, np.floating)):
if self._valueModified:
valStr = '%20s' % _floatFormat(self.value)
else:
valStr = '%20s' % self._valuestring
elif isinstance(self.value, (complex,np.complexfloating)):
if self._valueModified:
_tmp = '(' + _floatFormat(self.value.real) + ', ' + _floatFormat(self.value.imag) + ')'
valStr = '%20s' % _tmp
else:
valStr = '%20s' % self._valuestring
elif isinstance(self.value, Undefined):
valStr = ''
# conserve space for HIERARCH cards
if isinstance(self, _Hierarch):
valStr = valStr.strip()
# comment string
if keyStr.strip() in Card._commentaryKeys: # do NOT use self.key
commentStr = ''
elif self.__dict__.has_key('comment') or self.__dict__.has_key('_cardimage'):
if self.comment in [None, '']:
commentStr = ''
else:
commentStr = ' / ' + self.comment
else:
commentStr = ''
# equal sign string
eqStr = '= '
if keyStr.strip() in Card._commentaryKeys: # not using self.key
eqStr = ''
if self.__dict__.has_key('value'):
valStr = str(self.value)
# put all parts together
output = keyStr + eqStr + valStr + commentStr
# need this in case card-with-continue's value is shortened
if not isinstance(self, _Hierarch) and \
not isinstance(self, RecordValuedKeywordCard):
self.__class__ = Card
else:
# does not support CONTINUE for HIERARCH
if len(keyStr + eqStr + valStr) > Card.length:
raise ValueError, "The keyword %s with its value is too long." % self.key
if len(output) <= Card.length:
output = "%-80s" % output
# longstring case (CONTINUE card)
else:
# try not to use CONTINUE if the string value can fit in one line.
# Instead, just truncate the comment
if isinstance(self.value, str) and len(valStr) > (Card.length-10):
self.__class__ = _Card_with_continue
output = self._breakup_strings()
else:
warnings.warn('card is too long, comment is truncated.')
output = output[:Card.length]
self.__dict__['_cardimage'] = output
def _checkText(self, val):
"""Verify val to be printable ASCII text."""
if Card._comment_FSC_RE.match(val) is None:
self.__dict__['_err_text'] = 'Unprintable string %s' % repr(val)
self.__dict__['_fixable'] = 0
raise ValueError, self._err_text
def _checkKey(self, val):
"""Verify the keyword to be FITS standard."""
# use repr (not str) in case of control character
if Card._keywd_FSC_RE.match(val) is None:
self.__dict__['_err_text'] = 'Illegal keyword name %s' % repr(val)
self.__dict__['_fixable'] = 0
raise ValueError, self._err_text
def _extractKey(self):
"""Returns the keyword name parsed from the card image."""
head = self._getKeyString()
if isinstance(self, _Hierarch):
self.__dict__['key'] = head.strip()
else:
self.__dict__['key'] = head.strip().upper()
def _extractValueComment(self, name):
"""Extract the keyword value or comment from the card image."""
# for commentary cards, no need to parse further
if self.key in Card._commentaryKeys:
self.__dict__['value'] = self._cardimage[8:].rstrip()
self.__dict__['comment'] = ''
return
valu = self._check(option='parse')
if name == 'value':
if valu is None:
raise ValueError, "Unparsable card (" + self.key + \
"), fix it first with .verify('fix')."
if valu.group('bool') != None:
_val = valu.group('bool')=='T'
elif valu.group('strg') != None:
_val = re.sub("''", "'", valu.group('strg'))
elif valu.group('numr') != None:
# Check for numbers with leading 0s.
numr = Card._number_NFSC_RE.match(valu.group('numr'))
_digt = numr.group('digt').translate(_fix_table2, ' ')
if numr.group('sign') == None:
_val = eval(_digt)
else:
_val = eval(numr.group('sign')+_digt)
elif valu.group('cplx') != None:
# Check for numbers with leading 0s.
real = Card._number_NFSC_RE.match(valu.group('real'))
_rdigt = real.group('digt').translate(_fix_table2, ' ')
if real.group('sign') == None:
_val = eval(_rdigt)
else:
_val = eval(real.group('sign')+_rdigt)
imag = Card._number_NFSC_RE.match(valu.group('imag'))
_idigt = imag.group('digt').translate(_fix_table2, ' ')
if imag.group('sign') == None:
_val += eval(_idigt)*1j
else:
_val += eval(imag.group('sign') + _idigt)*1j
else:
_val = UNDEFINED
self.__dict__['value'] = _val
if '_valuestring' not in self.__dict__:
self.__dict__['_valuestring'] = valu.group('valu')
if '_valueModified' not in self.__dict__:
self.__dict__['_valueModified'] = 0
elif name == 'comment':
self.__dict__['comment'] = ''
if valu is not None:
_comm = valu.group('comm')
if isinstance(_comm, str):
self.__dict__['comment'] = _comm.rstrip()
def _fixValue(self, input):
"""Fix the card image for fixable non-standard compliance."""
_valStr = None
# for the unparsable case
if input is None:
_tmp = self._getValueCommentString()
try:
slashLoc = _tmp.index("/")
self.__dict__['value'] = _tmp[:slashLoc].strip()
self.__dict__['comment'] = _tmp[slashLoc+1:].strip()
except:
self.__dict__['value'] = _tmp.strip()
elif input.group('numr') != None:
numr = Card._number_NFSC_RE.match(input.group('numr'))
_valStr = numr.group('digt').translate(_fix_table, ' ')
if numr.group('sign') is not None:
_valStr = numr.group('sign')+_valStr
elif input.group('cplx') != None:
real = Card._number_NFSC_RE.match(input.group('real'))
_realStr = real.group('digt').translate(_fix_table, ' ')
if real.group('sign') is not None:
_realStr = real.group('sign')+_realStr
imag = Card._number_NFSC_RE.match(input.group('imag'))
_imagStr = imag.group('digt').translate(_fix_table, ' ')
if imag.group('sign') is not None:
_imagStr = imag.group('sign') + _imagStr
_valStr = '(' + _realStr + ', ' + _imagStr + ')'
self.__dict__['_valuestring'] = _valStr
self._ascardimage()
def _locateEq(self):
"""Locate the equal sign in the card image before column 10 and
return its location. It returns None if equal sign is not present,
or it is a commentary card.
"""
# no equal sign for commentary cards (i.e. part of the string value)
_key = self._cardimage[:8].strip().upper()
if _key in Card._commentaryKeys:
eqLoc = None
else:
if _key == 'HIERARCH':
_limit = Card.length
else:
_limit = 10
try:
eqLoc = self._cardimage[:_limit].index("=")
except:
eqLoc = None
return eqLoc
def _getKeyString(self):
"""Locate the equal sign in the card image and return the string
before the equal sign. If there is no equal sign, return the
string before column 9.
"""
eqLoc = self._locateEq()
if eqLoc is None:
eqLoc = 8
_start = 0
if self._cardimage[:8].upper() == 'HIERARCH':
_start = 8
self.__class__ = _Hierarch
return self._cardimage[_start:eqLoc]
def _getValueCommentString(self):
"""Locate the equal sign in the card image and return the string
after the equal sign. If there is no equal sign, return the
string after column 8.
"""
eqLoc = self._locateEq()
if eqLoc is None:
eqLoc = 7
return self._cardimage[eqLoc+1:]
def _check(self, option='ignore'):
"""Verify the card image with the specified option. """
self.__dict__['_err_text'] = ''
self.__dict__['_fix_text'] = ''
self.__dict__['_fixable'] = 1
if option == 'ignore':
return
elif option == 'parse':
# check the value only, no need to check key and comment for 'parse'
result = Card._value_NFSC_RE.match(self._getValueCommentString())
# if not parsable (i.e. everything else) result = None
return result
else:
# verify the equal sign position
if self.key not in Card._commentaryKeys and self._cardimage.find('=') != 8:
if option in ['exception', 'warn']:
self.__dict__['_err_text'] = 'Card image is not FITS standard (equal sign not at column 8).'
raise ValueError, self._err_text + '\n%s' % self._cardimage
elif option in ['fix', 'silentfix']:
result = self._check('parse')
self._fixValue(result)
if option == 'fix':
self.__dict__['_fix_text'] = 'Fixed card to be FITS standard.: %s' % self.key
# verify the key, it is never fixable
# always fix silently the case where "=" is before column 9,
# since there is no way to communicate back to the _keylist.
self._checkKey(self.key)
# verify the value, it may be fixable
result = Card._value_FSC_RE.match(self._getValueCommentString())
if result is not None or self.key in Card._commentaryKeys:
return result
else:
if option in ['fix', 'silentfix']:
result = self._check('parse')
self._fixValue(result)
if option == 'fix':
self.__dict__['_fix_text'] = 'Fixed card to be FITS standard.: %s' % self.key
else:
self.__dict__['_err_text'] = 'Card image is not FITS standard (unparsable value string).'
raise ValueError, self._err_text + '\n%s' % self._cardimage
# verify the comment (string), it is never fixable
if result is not None:
_str = result.group('comm')
if _str is not None:
self._checkText(_str)
def fromstring(self, input):
"""Construct a Card object from a (raw) string. It will pad the
string if it is not the length of a card image (80 columns).
If the card image is longer than 80, assume it contains CONTINUE
card(s).
"""
self.__dict__['_cardimage'] = _pad(input)
if self._cardimage[:8].upper() == 'HIERARCH':
self.__class__ = _Hierarch
# for card image longer than 80, assume it contains CONTINUE card(s).
elif len(self._cardimage) > Card.length:
self.__class__ = _Card_with_continue
# remove the key/value/comment attributes, some of them may not exist
for name in ['key', 'value', 'comment', '_valueModified']:
if self.__dict__.has_key(name):
delattr(self, name)
return self
def _ncards(self):
return len(self._cardimage) // Card.length
def _verify(self, option='warn'):
"""Card class verification method."""
_err = _ErrList([])
try:
self._check(option)
except ValueError:
# Trapping the ValueError raised by _check method. Want execution to continue while printing
# exception message.
pass
_err.append(self.run_option(option, err_text=self._err_text, fix_text=self._fix_text, fixable=self._fixable))
return _err
class RecordValuedKeywordCard(Card):
"""
Class to manage record-valued keyword cards as described in the FITS WCS
Paper IV proposal for representing a more general distortion model.
Record-valued Keyword cards are string-valued cards where the string is
interpreted as a definition giving a record field name, and its floating
point value. In a FITS header they have the following syntax:
keyword= 'field-specifier: float'
where keyword is a standard eight-character FITS keyword name, float is the
standard FITS ASCII representation of a floating point number, and these
are separated by a colon followed by a single blank. The grammar for
field-specifier is:
field-specifier:
field
field-specifier.field
field:
identifier
identifier.index
where identifier is a sequence of letters (upper or lower case),
underscores, and digits of which the first character must not be a digit,
and index is a sequence of digits. No blank characters may occur in the
field-specifier. The index is provided primarily for defining array
elements though it need not be used for that purpose.
Multiple record-valued keywords of the same name but differing values may
be present in a FITS header. The field-specifier may be viewed as part
of the keyword name.
Some examples follow:
DP1 = 'NAXIS: 2'
DP1 = 'AXIS.1: 1'
DP1 = 'AXIS.2: 2'
DP1 = 'NAUX: 2'
DP1 = 'AUX.1.COEFF.0: 0'
DP1 = 'AUX.1.POWER.0: 1'
DP1 = 'AUX.1.COEFF.1: 0.00048828125'
DP1 = 'AUX.1.POWER.1: 1'
"""
#
# A group of class level regular expression definitions that allow the
# extraction of the key, field-specifier, value, and comment from a
# card string.
#
identifier = r'[a-zA-Z_]\w*'
field = identifier + r'(\.\d+)?'
field_specifier_s = field + r'(\.' + field + r')*'
field_specifier_val = r'(?P<keyword>' + field_specifier_s + r'): (?P<val>' \
+ Card._numr_FSC + r'\s*)'
field_specifier_NFSC_val = r'(?P<keyword>' + field_specifier_s + \
r'): (?P<val>' + Card._numr_NFSC + r'\s*)'
keyword_val = r'\'' + field_specifier_val + r'\''
keyword_NFSC_val = r'\'' + field_specifier_NFSC_val + r'\''
keyword_val_comm = r' +' + keyword_val + r' *(/ *(?P<comm>[ -~]*))?$'
keyword_NFSC_val_comm = r' +' + keyword_NFSC_val + \
r' *(/ *(?P<comm>[ -~]*))?$'
#
# regular expression to extract the field specifier and value from
# a card image (ex. 'AXIS.1: 2'), the value may not be FITS Standard
# Complient
#
field_specifier_NFSC_image_RE = re.compile(field_specifier_NFSC_val)
#
# regular expression to extract the field specifier and value from
# a card value; the value may not be FITS Standard Complient
# (ex. 'AXIS.1: 2.0e5')
#
field_specifier_NFSC_val_RE = re.compile(field_specifier_NFSC_val+'$')
#
# regular expression to extract the key and the field specifier from a
# string that is being used to index into a card list that contains
# record value keyword cards (ex. 'DP1.AXIS.1')
#
keyword_name_RE = re.compile(r'(?P<key>' + identifier + r')\.' + \
r'(?P<field_spec>' + field_specifier_s + r')$')
#
# regular expression to extract the field specifier and value and comment
# from the string value of a record value keyword card
# (ex "'AXIS.1: 1' / a comment")
#
keyword_val_comm_RE = re.compile(keyword_val_comm)
#
# regular expression to extract the field specifier and value and comment
# from the string value of a record value keyword card that is not FITS
# Standard Complient (ex "'AXIS.1: 1.0d12' / a comment")
#
keyword_NFSC_val_comm_RE = re.compile(keyword_NFSC_val_comm)
#
# class method definitins
#
def coerce(cls,card):
"""
Class method to coerce an input Card object to a
RecordValuedKeywordCard object if the value of the card meets the
requirements of this type of card.
:Parameters:
card: A Card object to coerec
:Returns:
Input card coercable: a new RecordValuedKeywordCard constructed
from the key, value, and comment of the
input card
Input card not coercable: the input card
"""
mo = cls.field_specifier_NFSC_val_RE.match(card.value)
if mo:
return cls(card.key, card.value, card.comment)
else:
return card
coerce = classmethod(coerce)
def upperKey(cls, key):
"""
Class method to convert a keyword value that may contain a
field-specifier to upper case. The effect is to raise the
key to upper case and leave the field specifier in its original
case.
:Parameters:
key: A keyword value that could be an integer, a key, or
a key.field-specifier value
:Returns:
Integer input: the original integer key
String input: the converted string
"""
if isinstance(key, (int, long,np.integer)):
return key
mo = cls.keyword_name_RE.match(key)
if mo:
return mo.group('key').strip().upper() + '.' + \
mo.group('field_spec')
else:
return key.strip().upper()
upperKey = classmethod(upperKey)
def validKeyValue(cls, key, value=0):
"""
Class method that will determine if the input key and value can
be used to form a valid RecordValuedKeywordCard object. The
key parameter may contain the key only or both the key and
field-specifier. The value may be the value only or the
field-specifier and the value together. The value parameter
is optional, in which case the key parameter must contain both
the key and the field specifier. Some examples follow:
validKeyValue('DP1','AXIS.1: 2')
validKeyValue('DP1.AXIS.1', 2)
validKeyValue('DP1.AXIS.1')
:Parameters:
key: string - The key to parse
value: string or something that may be converted to a float -
The value to parse
:Returns:
valid input - A list containing the key, field-specifier, value
invalid input - An empty list
"""
rtnKey = rtnFieldSpec = rtnValue = ''
myKey = cls.upperKey(key)
if isinstance(myKey, str):
validKey = cls.keyword_name_RE.match(myKey)
if validKey: