hc99 commited on
Commit
7ffff7d
·
verified ·
1 Parent(s): 56d74b6

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/astropy__astropy/astropy/io/__init__.py +5 -0
  2. testbed/astropy__astropy/astropy/io/fits/__init__.py +89 -0
  3. testbed/astropy__astropy/astropy/io/fits/_utils.pyx +65 -0
  4. testbed/astropy__astropy/astropy/io/fits/card.py +1292 -0
  5. testbed/astropy__astropy/astropy/io/fits/column.py +2615 -0
  6. testbed/astropy__astropy/astropy/io/fits/connect.py +401 -0
  7. testbed/astropy__astropy/astropy/io/fits/convenience.py +1086 -0
  8. testbed/astropy__astropy/astropy/io/fits/diff.py +1512 -0
  9. testbed/astropy__astropy/astropy/io/fits/file.py +631 -0
  10. testbed/astropy__astropy/astropy/io/fits/fitsrec.py +1338 -0
  11. testbed/astropy__astropy/astropy/io/fits/fitstime.py +576 -0
  12. testbed/astropy__astropy/astropy/io/fits/header.py +2306 -0
  13. testbed/astropy__astropy/astropy/io/fits/scripts/fitscheck.py +211 -0
  14. testbed/astropy__astropy/astropy/io/fits/scripts/fitsheader.py +452 -0
  15. testbed/astropy__astropy/astropy/io/fits/setup_package.py +68 -0
  16. testbed/astropy__astropy/astropy/io/fits/src/compressionmodule.c +1323 -0
  17. testbed/astropy__astropy/astropy/io/fits/src/compressionmodule.h +56 -0
  18. testbed/astropy__astropy/astropy/io/fits/tests/__init__.py +60 -0
  19. testbed/astropy__astropy/astropy/io/fits/tests/cfitsio_verify.c +74 -0
  20. testbed/astropy__astropy/astropy/io/fits/tests/data/blank.fits +0 -0
  21. testbed/astropy__astropy/astropy/io/fits/tests/data/compressed_float_bzero.fits +0 -0
  22. testbed/astropy__astropy/astropy/io/fits/tests/data/history_header.fits +1 -0
  23. testbed/astropy__astropy/astropy/io/fits/tests/data/memtest.fits +1 -0
  24. testbed/astropy__astropy/astropy/io/fits/tests/data/o4sp040b0_raw.fits +1 -0
  25. testbed/astropy__astropy/astropy/io/fits/tests/data/random_groups.fits +8 -0
  26. testbed/astropy__astropy/astropy/io/fits/tests/data/stddata.fits +0 -0
  27. testbed/astropy__astropy/astropy/io/fits/tests/data/table.fits +0 -0
  28. testbed/astropy__astropy/astropy/io/fits/tests/data/tb.fits +0 -0
  29. testbed/astropy__astropy/astropy/io/fits/tests/data/tdim.fits +0 -0
  30. testbed/astropy__astropy/astropy/io/fits/tests/data/test0.fits +1 -0
  31. testbed/astropy__astropy/astropy/io/fits/tests/data/variable_length_table.fits +0 -0
  32. testbed/astropy__astropy/astropy/io/fits/tests/data/zerowidth.fits +27 -0
  33. testbed/astropy__astropy/astropy/io/fits/tests/test_checksum.py +457 -0
  34. testbed/astropy__astropy/astropy/io/fits/tests/test_compression_failures.py +138 -0
  35. testbed/astropy__astropy/astropy/io/fits/tests/test_connect.py +696 -0
  36. testbed/astropy__astropy/astropy/io/fits/tests/test_convenience.py +203 -0
  37. testbed/astropy__astropy/astropy/io/fits/tests/test_core.py +1389 -0
  38. testbed/astropy__astropy/astropy/io/fits/tests/test_division.py +42 -0
  39. testbed/astropy__astropy/astropy/io/fits/tests/test_fitscheck.py +77 -0
  40. testbed/astropy__astropy/astropy/io/fits/tests/test_fitsdiff.py +313 -0
  41. testbed/astropy__astropy/astropy/io/fits/tests/test_fitsheader.py +136 -0
  42. testbed/astropy__astropy/astropy/io/fits/tests/test_fitsinfo.py +31 -0
  43. testbed/astropy__astropy/astropy/io/fits/tests/test_fitstime.py +440 -0
  44. testbed/astropy__astropy/astropy/io/fits/tests/test_groups.py +211 -0
  45. testbed/astropy__astropy/astropy/io/fits/tests/test_hdulist.py +1055 -0
  46. testbed/astropy__astropy/astropy/io/fits/tests/test_header.py +0 -0
  47. testbed/astropy__astropy/astropy/io/fits/tests/test_image.py +1968 -0
  48. testbed/astropy__astropy/astropy/io/fits/tests/test_nonstandard.py +69 -0
  49. testbed/astropy__astropy/astropy/io/fits/tests/test_structured.py +101 -0
  50. testbed/astropy__astropy/astropy/io/fits/tests/test_table.py +0 -0
testbed/astropy__astropy/astropy/io/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+ """
3
+ This subpackage contains modules and packages for interpreting data storage
4
+ formats used by and in astropy.
5
+ """
testbed/astropy__astropy/astropy/io/fits/__init__.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ """
4
+ A package for reading and writing FITS files and manipulating their
5
+ contents.
6
+
7
+ A module for reading and writing Flexible Image Transport System
8
+ (FITS) files. This file format was endorsed by the International
9
+ Astronomical Union in 1999 and mandated by NASA as the standard format
10
+ for storing high energy astrophysics data. For details of the FITS
11
+ standard, see the NASA/Science Office of Standards and Technology
12
+ publication, NOST 100-2.0.
13
+ """
14
+
15
+ from astropy import config as _config
16
+
17
+ # Set module-global boolean variables
18
+ # TODO: Make it possible to set these variables via environment variables
19
+ # again, once support for that is added to Astropy
20
+
21
+
22
+ class Conf(_config.ConfigNamespace):
23
+ """
24
+ Configuration parameters for `astropy.io.fits`.
25
+ """
26
+
27
+ enable_record_valued_keyword_cards = _config.ConfigItem(
28
+ True,
29
+ 'If True, enable support for record-valued keywords as described by '
30
+ 'FITS WCS distortion paper. Otherwise they are treated as normal '
31
+ 'keywords.',
32
+ aliases=['astropy.io.fits.enabled_record_valued_keyword_cards'])
33
+ extension_name_case_sensitive = _config.ConfigItem(
34
+ False,
35
+ 'If True, extension names (i.e. the ``EXTNAME`` keyword) should be '
36
+ 'treated as case-sensitive.')
37
+ strip_header_whitespace = _config.ConfigItem(
38
+ True,
39
+ 'If True, automatically remove trailing whitespace for string values in '
40
+ 'headers. Otherwise the values are returned verbatim, with all '
41
+ 'whitespace intact.')
42
+ use_memmap = _config.ConfigItem(
43
+ True,
44
+ 'If True, use memory-mapped file access to read/write the data in '
45
+ 'FITS files. This generally provides better performance, especially '
46
+ 'for large files, but may affect performance in I/O-heavy '
47
+ 'applications.')
48
+ lazy_load_hdus = _config.ConfigItem(
49
+ True,
50
+ 'If True, use lazy loading of HDUs when opening FITS files by '
51
+ 'default; that is fits.open() will only seek for and read HDUs on '
52
+ 'demand rather than reading all HDUs at once. See the documentation '
53
+ 'for fits.open() for more datails.')
54
+ enable_uint = _config.ConfigItem(
55
+ True,
56
+ 'If True, default to recognizing the convention for representing '
57
+ 'unsigned integers in FITS--if an array has BITPIX > 0, BSCALE = 1, '
58
+ 'and BZERO = 2**BITPIX, represent the data as unsigned integers '
59
+ 'per this convention.')
60
+
61
+
62
+ conf = Conf()
63
+
64
+
65
+ # Public API compatibility imports
66
+ # These need to come after the global config variables, as some of the
67
+ # submodules use them
68
+ from . import card
69
+ from . import column
70
+ from . import convenience
71
+ from . import hdu
72
+ from .card import *
73
+ from .column import *
74
+ from .convenience import *
75
+ from .diff import *
76
+ from .fitsrec import FITS_record, FITS_rec
77
+ from .hdu import *
78
+
79
+ from .hdu.groups import GroupData
80
+ from .hdu.hdulist import fitsopen as open
81
+ from .hdu.image import Section
82
+ from .header import Header
83
+ from .verify import VerifyError
84
+
85
+
86
+ __all__ = (['Conf', 'conf'] + card.__all__ + column.__all__ +
87
+ convenience.__all__ + hdu.__all__ +
88
+ ['FITS_record', 'FITS_rec', 'GroupData', 'open', 'Section',
89
+ 'Header', 'VerifyError', 'conf'])
testbed/astropy__astropy/astropy/io/fits/_utils.pyx ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+ from collections import OrderedDict
3
+
4
+ cdef Py_ssize_t BLOCK_SIZE = 2880 # the FITS block size
5
+ cdef Py_ssize_t CARD_LENGTH = 80
6
+ cdef str VALUE_INDICATOR = '= ' # The standard FITS value indicator
7
+ cdef str END_CARD = 'END' + ' ' * 77
8
+
9
+
10
+ def parse_header(fileobj):
11
+ """Fast (and incomplete) parser for FITS headers.
12
+
13
+ This parser only reads the standard 8 character keywords, and ignores the
14
+ CONTINUE, COMMENT, HISTORY and HIERARCH cards. The goal is to find quickly
15
+ the structural keywords needed to build the HDU objects.
16
+
17
+ The implementation is straightforward: first iterate on the 2880-bytes
18
+ blocks, then iterate on the 80-bytes cards, find the value separator, and
19
+ store the parsed (keyword, card image) in a dictionary.
20
+
21
+ """
22
+
23
+ cards = OrderedDict()
24
+ cdef list read_blocks = []
25
+ cdef int found_end = 0
26
+ cdef bytes block
27
+ cdef str header_str, block_str, card_image, keyword
28
+ cdef Py_ssize_t idx, end_idx, sep_idx
29
+
30
+ while found_end == 0:
31
+ # iterate on blocks
32
+ block = fileobj.read(BLOCK_SIZE)
33
+ if not block or len(block) < BLOCK_SIZE:
34
+ # header looks incorrect, raising exception to fall back to
35
+ # the full Header parsing
36
+ raise Exception
37
+
38
+ block_str = block.decode('ascii')
39
+ read_blocks.append(block_str)
40
+ idx = 0
41
+ while idx < BLOCK_SIZE:
42
+ # iterate on cards
43
+ end_idx = idx + CARD_LENGTH
44
+ card_image = block_str[idx:end_idx]
45
+ idx = end_idx
46
+
47
+ # We are interested only in standard keyword, so we skip
48
+ # other cards, e.g. CONTINUE, HIERARCH, COMMENT.
49
+ if card_image[8:10] == VALUE_INDICATOR:
50
+ # ok, found standard keyword
51
+ keyword = card_image[:8].strip()
52
+ cards[keyword.upper()] = card_image
53
+ else:
54
+ sep_idx = card_image.find(VALUE_INDICATOR, 0, 8)
55
+ if sep_idx > 0:
56
+ keyword = card_image[:sep_idx]
57
+ cards[keyword.upper()] = card_image
58
+ elif card_image == END_CARD:
59
+ found_end = 1
60
+ break
61
+
62
+ # we keep the full header string as it may be needed later to
63
+ # create a Header object
64
+ header_str = ''.join(read_blocks)
65
+ return header_str, cards
testbed/astropy__astropy/astropy/io/fits/card.py ADDED
@@ -0,0 +1,1292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import re
4
+ import warnings
5
+
6
+ import numpy as np
7
+
8
+ from .util import _str_to_num, _is_int, translate, _words_group
9
+ from .verify import _Verify, _ErrList, VerifyError, VerifyWarning
10
+
11
+ from . import conf
12
+ from astropy.utils.exceptions import AstropyUserWarning
13
+
14
+
15
+ __all__ = ['Card', 'Undefined']
16
+
17
+
18
+ FIX_FP_TABLE = str.maketrans('de', 'DE')
19
+ FIX_FP_TABLE2 = str.maketrans('dD', 'eE')
20
+
21
+
22
+ CARD_LENGTH = 80
23
+ BLANK_CARD = ' ' * CARD_LENGTH
24
+ KEYWORD_LENGTH = 8 # The max length for FITS-standard keywords
25
+
26
+ VALUE_INDICATOR = '= ' # The standard FITS value indicator
27
+ VALUE_INDICATOR_LEN = len(VALUE_INDICATOR)
28
+ HIERARCH_VALUE_INDICATOR = '=' # HIERARCH cards may use a shortened indicator
29
+
30
+
31
+ class Undefined:
32
+ """Undefined value."""
33
+
34
+ def __init__(self):
35
+ # This __init__ is required to be here for Sphinx documentation
36
+ pass
37
+
38
+
39
+ UNDEFINED = Undefined()
40
+
41
+
42
+ class Card(_Verify):
43
+
44
+ length = CARD_LENGTH
45
+ """The length of a Card image; should always be 80 for valid FITS files."""
46
+
47
+ # String for a FITS standard compliant (FSC) keyword.
48
+ _keywd_FSC_RE = re.compile(r'^[A-Z0-9_-]{0,%d}$' % KEYWORD_LENGTH)
49
+ # This will match any printable ASCII character excluding '='
50
+ _keywd_hierarch_RE = re.compile(r'^(?:HIERARCH +)?(?:^[ -<>-~]+ ?)+$',
51
+ re.I)
52
+
53
+ # A number sub-string, either an integer or a float in fixed or
54
+ # scientific notation. One for FSC and one for non-FSC (NFSC) format:
55
+ # NFSC allows lower case of DE for exponent, allows space between sign,
56
+ # digits, exponent sign, and exponents
57
+ _digits_FSC = r'(\.\d+|\d+(\.\d*)?)([DE][+-]?\d+)?'
58
+ _digits_NFSC = r'(\.\d+|\d+(\.\d*)?) *([deDE] *[+-]? *\d+)?'
59
+ _numr_FSC = r'[+-]?' + _digits_FSC
60
+ _numr_NFSC = r'[+-]? *' + _digits_NFSC
61
+
62
+ # This regex helps delete leading zeros from numbers, otherwise
63
+ # Python might evaluate them as octal values (this is not-greedy, however,
64
+ # so it may not strip leading zeros from a float, which is fine)
65
+ _number_FSC_RE = re.compile(r'(?P<sign>[+-])?0*?(?P<digt>{})'.format(
66
+ _digits_FSC))
67
+ _number_NFSC_RE = re.compile(r'(?P<sign>[+-])? *0*?(?P<digt>{})'.format(
68
+ _digits_NFSC))
69
+
70
+ # FSC commentary card string which must contain printable ASCII characters.
71
+ # Note: \Z matches the end of the string without allowing newlines
72
+ _ascii_text_re = re.compile(r'[ -~]*\Z')
73
+
74
+ # Checks for a valid value/comment string. It returns a match object
75
+ # for a valid value/comment string.
76
+ # The valu group will return a match if a FITS string, boolean,
77
+ # number, or complex value is found, otherwise it will return
78
+ # None, meaning the keyword is undefined. The comment field will
79
+ # return a match if the comment separator is found, though the
80
+ # comment maybe an empty string.
81
+ _value_FSC_RE = re.compile(
82
+ r'(?P<valu_field> *'
83
+ r'(?P<valu>'
84
+
85
+ # The <strg> regex is not correct for all cases, but
86
+ # it comes pretty darn close. It appears to find the
87
+ # end of a string rather well, but will accept
88
+ # strings with an odd number of single quotes,
89
+ # instead of issuing an error. The FITS standard
90
+ # appears vague on this issue and only states that a
91
+ # string should not end with two single quotes,
92
+ # whereas it should not end with an even number of
93
+ # quotes to be precise.
94
+ #
95
+ # Note that a non-greedy match is done for a string,
96
+ # since a greedy match will find a single-quote after
97
+ # the comment separator resulting in an incorrect
98
+ # match.
99
+ r'\'(?P<strg>([ -~]+?|\'\'|)) *?\'(?=$|/| )|'
100
+ r'(?P<bool>[FT])|'
101
+ r'(?P<numr>' + _numr_FSC + r')|'
102
+ r'(?P<cplx>\( *'
103
+ r'(?P<real>' + _numr_FSC + r') *, *'
104
+ r'(?P<imag>' + _numr_FSC + r') *\))'
105
+ r')? *)'
106
+ r'(?P<comm_field>'
107
+ r'(?P<sepr>/ *)'
108
+ r'(?P<comm>[!-~][ -~]*)?'
109
+ r')?$')
110
+
111
+ _value_NFSC_RE = re.compile(
112
+ r'(?P<valu_field> *'
113
+ r'(?P<valu>'
114
+ r'\'(?P<strg>([ -~]+?|\'\'|) *?)\'(?=$|/| )|'
115
+ r'(?P<bool>[FT])|'
116
+ r'(?P<numr>' + _numr_NFSC + r')|'
117
+ r'(?P<cplx>\( *'
118
+ r'(?P<real>' + _numr_NFSC + r') *, *'
119
+ r'(?P<imag>' + _numr_NFSC + r') *\))'
120
+ r')? *)'
121
+ r'(?P<comm_field>'
122
+ r'(?P<sepr>/ *)'
123
+ r'(?P<comm>(.|\n)*)'
124
+ r')?$')
125
+
126
+ _rvkc_identifier = r'[a-zA-Z_]\w*'
127
+ _rvkc_field = _rvkc_identifier + r'(\.\d+)?'
128
+ _rvkc_field_specifier_s = r'{}(\.{})*'.format(_rvkc_field, _rvkc_field)
129
+ _rvkc_field_specifier_val = (r'(?P<keyword>{}): (?P<val>{})'.format(
130
+ _rvkc_field_specifier_s, _numr_FSC))
131
+ _rvkc_keyword_val = r'\'(?P<rawval>{})\''.format(_rvkc_field_specifier_val)
132
+ _rvkc_keyword_val_comm = (r' *{} *(/ *(?P<comm>[ -~]*))?$'.format(
133
+ _rvkc_keyword_val))
134
+
135
+ _rvkc_field_specifier_val_RE = re.compile(_rvkc_field_specifier_val + '$')
136
+
137
+ # regular expression to extract the key and the field specifier from a
138
+ # string that is being used to index into a card list that contains
139
+ # record value keyword cards (ex. 'DP1.AXIS.1')
140
+ _rvkc_keyword_name_RE = (
141
+ re.compile(r'(?P<keyword>{})\.(?P<field_specifier>{})$'.format(
142
+ _rvkc_identifier, _rvkc_field_specifier_s)))
143
+
144
+ # regular expression to extract the field specifier and value and comment
145
+ # from the string value of a record value keyword card
146
+ # (ex "'AXIS.1: 1' / a comment")
147
+ _rvkc_keyword_val_comm_RE = re.compile(_rvkc_keyword_val_comm)
148
+
149
+ _commentary_keywords = {'', 'COMMENT', 'HISTORY', 'END'}
150
+ _special_keywords = _commentary_keywords.union(['CONTINUE'])
151
+
152
+ # The default value indicator; may be changed if required by a convention
153
+ # (namely HIERARCH cards)
154
+ _value_indicator = VALUE_INDICATOR
155
+
156
+ def __init__(self, keyword=None, value=None, comment=None, **kwargs):
157
+ # For backwards compatibility, support the 'key' keyword argument:
158
+ if keyword is None and 'key' in kwargs:
159
+ keyword = kwargs['key']
160
+
161
+ self._keyword = None
162
+ self._value = None
163
+ self._comment = None
164
+ self._valuestring = None
165
+ self._image = None
166
+
167
+ # This attribute is set to False when creating the card from a card
168
+ # image to ensure that the contents of the image get verified at some
169
+ # point
170
+ self._verified = True
171
+
172
+ # A flag to conveniently mark whether or not this was a valid HIERARCH
173
+ # card
174
+ self._hierarch = False
175
+
176
+ # If the card could not be parsed according the the FITS standard or
177
+ # any recognized non-standard conventions, this will be True
178
+ self._invalid = False
179
+
180
+ self._field_specifier = None
181
+
182
+ # These are used primarily only by RVKCs
183
+ self._rawkeyword = None
184
+ self._rawvalue = None
185
+
186
+ if not (keyword is not None and value is not None and
187
+ self._check_if_rvkc(keyword, value)):
188
+ # If _check_if_rvkc passes, it will handle setting the keyword and
189
+ # value
190
+ if keyword is not None:
191
+ self.keyword = keyword
192
+ if value is not None:
193
+ self.value = value
194
+
195
+ if comment is not None:
196
+ self.comment = comment
197
+
198
+ self._modified = False
199
+ self._valuemodified = False
200
+
201
+ def __repr__(self):
202
+ return repr((self.keyword, self.value, self.comment))
203
+
204
+ def __str__(self):
205
+ return self.image
206
+
207
+ def __len__(self):
208
+ return 3
209
+
210
+ def __getitem__(self, index):
211
+ return (self.keyword, self.value, self.comment)[index]
212
+
213
+ @property
214
+ def keyword(self):
215
+ """Returns the keyword name parsed from the card image."""
216
+ if self._keyword is not None:
217
+ return self._keyword
218
+ elif self._image:
219
+ self._keyword = self._parse_keyword()
220
+ return self._keyword
221
+ else:
222
+ self.keyword = ''
223
+ return ''
224
+
225
+ @keyword.setter
226
+ def keyword(self, keyword):
227
+ """Set the key attribute; once set it cannot be modified."""
228
+ if self._keyword is not None:
229
+ raise AttributeError(
230
+ 'Once set, the Card keyword may not be modified')
231
+ elif isinstance(keyword, str):
232
+ # Be nice and remove trailing whitespace--some FITS code always
233
+ # pads keywords out with spaces; leading whitespace, however,
234
+ # should be strictly disallowed.
235
+ keyword = keyword.rstrip()
236
+ keyword_upper = keyword.upper()
237
+ if (len(keyword) <= KEYWORD_LENGTH and
238
+ self._keywd_FSC_RE.match(keyword_upper)):
239
+ # For keywords with length > 8 they will be HIERARCH cards,
240
+ # and can have arbitrary case keywords
241
+ if keyword_upper == 'END':
242
+ raise ValueError("Keyword 'END' not allowed.")
243
+ keyword = keyword_upper
244
+ elif self._keywd_hierarch_RE.match(keyword):
245
+ # In prior versions of PyFITS (*) HIERARCH cards would only be
246
+ # created if the user-supplied keyword explicitly started with
247
+ # 'HIERARCH '. Now we will create them automatically for long
248
+ # keywords, but we still want to support the old behavior too;
249
+ # the old behavior makes it possible to create HEIRARCH cards
250
+ # that would otherwise be recognized as RVKCs
251
+ # (*) This has never affected Astropy, because it was changed
252
+ # before PyFITS was merged into Astropy!
253
+ self._hierarch = True
254
+ self._value_indicator = HIERARCH_VALUE_INDICATOR
255
+
256
+ if keyword_upper[:9] == 'HIERARCH ':
257
+ # The user explicitly asked for a HIERARCH card, so don't
258
+ # bug them about it...
259
+ keyword = keyword[9:].strip()
260
+ else:
261
+ # We'll gladly create a HIERARCH card, but a warning is
262
+ # also displayed
263
+ warnings.warn(
264
+ 'Keyword name {!r} is greater than 8 characters or '
265
+ 'contains characters not allowed by the FITS '
266
+ 'standard; a HIERARCH card will be created.'.format(
267
+ keyword), VerifyWarning)
268
+ else:
269
+ raise ValueError('Illegal keyword name: {!r}.'.format(keyword))
270
+ self._keyword = keyword
271
+ self._modified = True
272
+ else:
273
+ raise ValueError('Keyword name {!r} is not a string.'.format(keyword))
274
+
275
+ @property
276
+ def value(self):
277
+ """The value associated with the keyword stored in this card."""
278
+
279
+ if self.field_specifier:
280
+ return float(self._value)
281
+
282
+ if self._value is not None:
283
+ value = self._value
284
+ elif self._valuestring is not None or self._image:
285
+ value = self._value = self._parse_value()
286
+ else:
287
+ if self._keyword == '':
288
+ self._value = value = ''
289
+ else:
290
+ self._value = value = UNDEFINED
291
+
292
+ if conf.strip_header_whitespace and isinstance(value, str):
293
+ value = value.rstrip()
294
+
295
+ return value
296
+
297
+ @value.setter
298
+ def value(self, value):
299
+ if self._invalid:
300
+ raise ValueError(
301
+ 'The value of invalid/unparseable cards cannot set. Either '
302
+ 'delete this card from the header or replace it.')
303
+
304
+ if value is None:
305
+ value = UNDEFINED
306
+
307
+ try:
308
+ oldvalue = self.value
309
+ except VerifyError:
310
+ # probably a parsing error, falling back to the internal _value
311
+ # which should be None. This may happen while calling _fix_value.
312
+ oldvalue = self._value
313
+
314
+ if oldvalue is None:
315
+ oldvalue = UNDEFINED
316
+
317
+ if not isinstance(value,
318
+ (str, int, float, complex, bool, Undefined,
319
+ np.floating, np.integer, np.complexfloating,
320
+ np.bool_)):
321
+ raise ValueError('Illegal value: {!r}.'.format(value))
322
+
323
+ if isinstance(value, float) and (np.isnan(value) or np.isinf(value)):
324
+ raise ValueError("Floating point {!r} values are not allowed "
325
+ "in FITS headers.".format(value))
326
+
327
+ elif isinstance(value, str):
328
+ m = self._ascii_text_re.match(value)
329
+ if not m:
330
+ raise ValueError(
331
+ 'FITS header values must contain standard printable ASCII '
332
+ 'characters; {!r} contains characters not representable in '
333
+ 'ASCII or non-printable characters.'.format(value))
334
+ elif isinstance(value, bytes):
335
+ # Allow str, but only if they can be decoded to ASCII text; note
336
+ # this is not even allowed on Python 3 since the `bytes` type is
337
+ # not included in `str`. Presently we simply don't
338
+ # allow bytes to be assigned to headers, as doing so would too
339
+ # easily mask potential user error
340
+ valid = True
341
+ try:
342
+ text_value = value.decode('ascii')
343
+ except UnicodeDecodeError:
344
+ valid = False
345
+ else:
346
+ # Check against the printable characters regexp as well
347
+ m = self._ascii_text_re.match(text_value)
348
+ valid = m is not None
349
+
350
+ if not valid:
351
+ raise ValueError(
352
+ 'FITS header values must contain standard printable ASCII '
353
+ 'characters; {!r} contains characters/bytes that do not '
354
+ 'represent printable characters in ASCII.'.format(value))
355
+ elif isinstance(value, np.bool_):
356
+ value = bool(value)
357
+
358
+ if (conf.strip_header_whitespace and
359
+ (isinstance(oldvalue, str) and isinstance(value, str))):
360
+ # Ignore extra whitespace when comparing the new value to the old
361
+ different = oldvalue.rstrip() != value.rstrip()
362
+ elif isinstance(oldvalue, bool) or isinstance(value, bool):
363
+ different = oldvalue is not value
364
+ else:
365
+ different = (oldvalue != value or
366
+ not isinstance(value, type(oldvalue)))
367
+
368
+ if different:
369
+ self._value = value
370
+ self._rawvalue = None
371
+ self._modified = True
372
+ self._valuestring = None
373
+ self._valuemodified = True
374
+ if self.field_specifier:
375
+ try:
376
+ self._value = _int_or_float(self._value)
377
+ except ValueError:
378
+ raise ValueError('value {} is not a float'.format(
379
+ self._value))
380
+
381
+ @value.deleter
382
+ def value(self):
383
+ if self._invalid:
384
+ raise ValueError(
385
+ 'The value of invalid/unparseable cards cannot deleted. '
386
+ 'Either delete this card from the header or replace it.')
387
+
388
+ if not self.field_specifier:
389
+ self.value = ''
390
+ else:
391
+ raise AttributeError('Values cannot be deleted from record-valued '
392
+ 'keyword cards')
393
+
394
+ @property
395
+ def rawkeyword(self):
396
+ """On record-valued keyword cards this is the name of the standard <= 8
397
+ character FITS keyword that this RVKC is stored in. Otherwise it is
398
+ the card's normal keyword.
399
+ """
400
+
401
+ if self._rawkeyword is not None:
402
+ return self._rawkeyword
403
+ elif self.field_specifier is not None:
404
+ self._rawkeyword = self.keyword.split('.', 1)[0]
405
+ return self._rawkeyword
406
+ else:
407
+ return self.keyword
408
+
409
+ @property
410
+ def rawvalue(self):
411
+ """On record-valued keyword cards this is the raw string value in
412
+ the ``<field-specifier>: <value>`` format stored in the card in order
413
+ to represent a RVKC. Otherwise it is the card's normal value.
414
+ """
415
+
416
+ if self._rawvalue is not None:
417
+ return self._rawvalue
418
+ elif self.field_specifier is not None:
419
+ self._rawvalue = '{}: {}'.format(self.field_specifier, self.value)
420
+ return self._rawvalue
421
+ else:
422
+ return self.value
423
+
424
+ @property
425
+ def comment(self):
426
+ """Get the comment attribute from the card image if not already set."""
427
+
428
+ if self._comment is not None:
429
+ return self._comment
430
+ elif self._image:
431
+ self._comment = self._parse_comment()
432
+ return self._comment
433
+ else:
434
+ self._comment = ''
435
+ return ''
436
+
437
+ @comment.setter
438
+ def comment(self, comment):
439
+ if self._invalid:
440
+ raise ValueError(
441
+ 'The comment of invalid/unparseable cards cannot set. Either '
442
+ 'delete this card from the header or replace it.')
443
+
444
+ if comment is None:
445
+ comment = ''
446
+
447
+ if isinstance(comment, str):
448
+ m = self._ascii_text_re.match(comment)
449
+ if not m:
450
+ raise ValueError(
451
+ 'FITS header comments must contain standard printable '
452
+ 'ASCII characters; {!r} contains characters not '
453
+ 'representable in ASCII or non-printable characters.'
454
+ .format(comment))
455
+
456
+ try:
457
+ oldcomment = self.comment
458
+ except VerifyError:
459
+ # probably a parsing error, falling back to the internal _comment
460
+ # which should be None.
461
+ oldcomment = self._comment
462
+
463
+ if oldcomment is None:
464
+ oldcomment = ''
465
+ if comment != oldcomment:
466
+ self._comment = comment
467
+ self._modified = True
468
+
469
+ @comment.deleter
470
+ def comment(self):
471
+ if self._invalid:
472
+ raise ValueError(
473
+ 'The comment of invalid/unparseable cards cannot deleted. '
474
+ 'Either delete this card from the header or replace it.')
475
+
476
+ self.comment = ''
477
+
478
+ @property
479
+ def field_specifier(self):
480
+ """
481
+ The field-specifier of record-valued keyword cards; always `None` on
482
+ normal cards.
483
+ """
484
+
485
+ # Ensure that the keyword exists and has been parsed--the will set the
486
+ # internal _field_specifier attribute if this is a RVKC.
487
+ if self.keyword:
488
+ return self._field_specifier
489
+ else:
490
+ return None
491
+
492
+ @field_specifier.setter
493
+ def field_specifier(self, field_specifier):
494
+ if not field_specifier:
495
+ raise ValueError('The field-specifier may not be blank in '
496
+ 'record-valued keyword cards.')
497
+ elif not self.field_specifier:
498
+ raise AttributeError('Cannot coerce cards to be record-valued '
499
+ 'keyword cards by setting the '
500
+ 'field_specifier attribute')
501
+ elif field_specifier != self.field_specifier:
502
+ self._field_specifier = field_specifier
503
+ # The keyword need also be updated
504
+ keyword = self._keyword.split('.', 1)[0]
505
+ self._keyword = '.'.join([keyword, field_specifier])
506
+ self._modified = True
507
+
508
+ @field_specifier.deleter
509
+ def field_specifier(self):
510
+ raise AttributeError('The field_specifier attribute may not be '
511
+ 'deleted from record-valued keyword cards.')
512
+
513
+ @property
514
+ def image(self):
515
+ """
516
+ The card "image", that is, the 80 byte character string that represents
517
+ this card in an actual FITS header.
518
+ """
519
+
520
+ if self._image and not self._verified:
521
+ self.verify('fix+warn')
522
+ if self._image is None or self._modified:
523
+ self._image = self._format_image()
524
+ return self._image
525
+
526
+ @property
527
+ def is_blank(self):
528
+ """
529
+ `True` if the card is completely blank--that is, it has no keyword,
530
+ value, or comment. It appears in the header as 80 spaces.
531
+
532
+ Returns `False` otherwise.
533
+ """
534
+
535
+ if not self._verified:
536
+ # The card image has not been parsed yet; compare directly with the
537
+ # string representation of a blank card
538
+ return self._image == BLANK_CARD
539
+
540
+ # If the keyword, value, and comment are all empty (for self.value
541
+ # explicitly check that it is a string value, since a blank value is
542
+ # returned as '')
543
+ return (not self.keyword and
544
+ (isinstance(self.value, str) and not self.value) and
545
+ not self.comment)
546
+
547
+ @classmethod
548
+ def fromstring(cls, image):
549
+ """
550
+ Construct a `Card` object from a (raw) string. It will pad the string
551
+ if it is not the length of a card image (80 columns). If the card
552
+ image is longer than 80 columns, assume it contains ``CONTINUE``
553
+ card(s).
554
+ """
555
+
556
+ card = cls()
557
+ if isinstance(image, bytes):
558
+ # FITS supports only ASCII, but decode as latin1 and just take all
559
+ # bytes for now; if it results in mojibake due to e.g. UTF-8
560
+ # encoded data in a FITS header that's OK because it shouldn't be
561
+ # there in the first place
562
+ image = image.decode('latin1')
563
+
564
+ card._image = _pad(image)
565
+ card._verified = False
566
+ return card
567
+
568
+ @classmethod
569
+ def normalize_keyword(cls, keyword):
570
+ """
571
+ `classmethod` to convert a keyword value that may contain a
572
+ field-specifier to uppercase. The effect is to raise the key to
573
+ uppercase and leave the field specifier in its original case.
574
+
575
+ Parameters
576
+ ----------
577
+ keyword : or str
578
+ A keyword value or a ``keyword.field-specifier`` value
579
+ """
580
+
581
+ # Test first for the most common case: a standard FITS keyword provided
582
+ # in standard all-caps
583
+ if (len(keyword) <= KEYWORD_LENGTH and
584
+ cls._keywd_FSC_RE.match(keyword)):
585
+ return keyword
586
+
587
+ # Test if this is a record-valued keyword
588
+ match = cls._rvkc_keyword_name_RE.match(keyword)
589
+
590
+ if match:
591
+ return '.'.join((match.group('keyword').strip().upper(),
592
+ match.group('field_specifier')))
593
+ elif len(keyword) > 9 and keyword[:9].upper() == 'HIERARCH ':
594
+ # Remove 'HIERARCH' from HIERARCH keywords; this could lead to
595
+ # ambiguity if there is actually a keyword card containing
596
+ # "HIERARCH HIERARCH", but shame on you if you do that.
597
+ return keyword[9:].strip().upper()
598
+ else:
599
+ # A normal FITS keyword, but provided in non-standard case
600
+ return keyword.strip().upper()
601
+
602
+ def _check_if_rvkc(self, *args):
603
+ """
604
+ Determine whether or not the card is a record-valued keyword card.
605
+
606
+ If one argument is given, that argument is treated as a full card image
607
+ and parsed as such. If two arguments are given, the first is treated
608
+ as the card keyword (including the field-specifier if the card is
609
+ intended as a RVKC), and the second as the card value OR the first value
610
+ can be the base keyword, and the second value the 'field-specifier:
611
+ value' string.
612
+
613
+ If the check passes the ._keyword, ._value, and .field_specifier
614
+ keywords are set.
615
+
616
+ Examples
617
+ --------
618
+
619
+ ::
620
+
621
+ self._check_if_rvkc('DP1', 'AXIS.1: 2')
622
+ self._check_if_rvkc('DP1.AXIS.1', 2)
623
+ self._check_if_rvkc('DP1 = AXIS.1: 2')
624
+ """
625
+
626
+ if not conf.enable_record_valued_keyword_cards:
627
+ return False
628
+
629
+ if len(args) == 1:
630
+ return self._check_if_rvkc_image(*args)
631
+ elif len(args) == 2:
632
+ keyword, value = args
633
+ if not isinstance(keyword, str):
634
+ return False
635
+ if keyword in self._commentary_keywords:
636
+ return False
637
+ match = self._rvkc_keyword_name_RE.match(keyword)
638
+ if match and isinstance(value, (int, float)):
639
+ self._init_rvkc(match.group('keyword'),
640
+ match.group('field_specifier'), None, value)
641
+ return True
642
+
643
+ # Testing for ': ' is a quick way to avoid running the full regular
644
+ # expression, speeding this up for the majority of cases
645
+ if isinstance(value, str) and value.find(': ') > 0:
646
+ match = self._rvkc_field_specifier_val_RE.match(value)
647
+ if match and self._keywd_FSC_RE.match(keyword):
648
+ self._init_rvkc(keyword, match.group('keyword'), value,
649
+ match.group('val'))
650
+ return True
651
+
652
+ def _check_if_rvkc_image(self, *args):
653
+ """
654
+ Implements `Card._check_if_rvkc` for the case of an unparsed card
655
+ image. If given one argument this is the full intact image. If given
656
+ two arguments the card has already been split between keyword and
657
+ value+comment at the standard value indicator '= '.
658
+ """
659
+
660
+ if len(args) == 1:
661
+ image = args[0]
662
+ eq_idx = image.find(VALUE_INDICATOR)
663
+ if eq_idx < 0 or eq_idx > 9:
664
+ return False
665
+ keyword = image[:eq_idx]
666
+ rest = image[eq_idx + VALUE_INDICATOR_LEN:]
667
+ else:
668
+ keyword, rest = args
669
+
670
+ rest = rest.lstrip()
671
+
672
+ # This test allows us to skip running the full regular expression for
673
+ # the majority of cards that do not contain strings or that definitely
674
+ # do not contain RVKC field-specifiers; it's very much a
675
+ # micro-optimization but it does make a measurable difference
676
+ if not rest or rest[0] != "'" or rest.find(': ') < 2:
677
+ return False
678
+
679
+ match = self._rvkc_keyword_val_comm_RE.match(rest)
680
+ if match:
681
+ self._init_rvkc(keyword, match.group('keyword'),
682
+ match.group('rawval'), match.group('val'))
683
+ return True
684
+
685
+ def _init_rvkc(self, keyword, field_specifier, field, value):
686
+ """
687
+ Sort of addendum to Card.__init__ to set the appropriate internal
688
+ attributes if the card was determined to be a RVKC.
689
+ """
690
+
691
+ keyword_upper = keyword.upper()
692
+ self._keyword = '.'.join((keyword_upper, field_specifier))
693
+ self._rawkeyword = keyword_upper
694
+ self._field_specifier = field_specifier
695
+ self._value = _int_or_float(value)
696
+ self._rawvalue = field
697
+
698
+ def _parse_keyword(self):
699
+ keyword = self._image[:KEYWORD_LENGTH].strip()
700
+ keyword_upper = keyword.upper()
701
+
702
+ if keyword_upper in self._special_keywords:
703
+ return keyword_upper
704
+ elif (keyword_upper == 'HIERARCH' and self._image[8] == ' ' and
705
+ HIERARCH_VALUE_INDICATOR in self._image):
706
+ # This is valid HIERARCH card as described by the HIERARCH keyword
707
+ # convention:
708
+ # http://fits.gsfc.nasa.gov/registry/hierarch_keyword.html
709
+ self._hierarch = True
710
+ self._value_indicator = HIERARCH_VALUE_INDICATOR
711
+ keyword = self._image.split(HIERARCH_VALUE_INDICATOR, 1)[0][9:]
712
+ return keyword.strip()
713
+ else:
714
+ val_ind_idx = self._image.find(VALUE_INDICATOR)
715
+ if 0 <= val_ind_idx <= KEYWORD_LENGTH:
716
+ # The value indicator should appear in byte 8, but we are
717
+ # flexible and allow this to be fixed
718
+ if val_ind_idx < KEYWORD_LENGTH:
719
+ keyword = keyword[:val_ind_idx]
720
+ keyword_upper = keyword_upper[:val_ind_idx]
721
+
722
+ rest = self._image[val_ind_idx + VALUE_INDICATOR_LEN:]
723
+
724
+ # So far this looks like a standard FITS keyword; check whether
725
+ # the value represents a RVKC; if so then we pass things off to
726
+ # the RVKC parser
727
+ if self._check_if_rvkc_image(keyword, rest):
728
+ return self._keyword
729
+
730
+ return keyword_upper
731
+ else:
732
+ warnings.warn(
733
+ 'The following header keyword is invalid or follows an '
734
+ 'unrecognized non-standard convention:\n{}'
735
+ .format(self._image), AstropyUserWarning)
736
+ self._invalid = True
737
+ return keyword
738
+
739
+ def _parse_value(self):
740
+ """Extract the keyword value from the card image."""
741
+
742
+ # for commentary cards, no need to parse further
743
+ # Likewise for invalid cards
744
+ if self.keyword.upper() in self._commentary_keywords or self._invalid:
745
+ return self._image[KEYWORD_LENGTH:].rstrip()
746
+
747
+ if self._check_if_rvkc(self._image):
748
+ return self._value
749
+
750
+ if len(self._image) > self.length:
751
+ values = []
752
+ for card in self._itersubcards():
753
+ value = card.value.rstrip().replace("''", "'")
754
+ if value and value[-1] == '&':
755
+ value = value[:-1]
756
+ values.append(value)
757
+
758
+ value = ''.join(values)
759
+
760
+ self._valuestring = value
761
+ return value
762
+
763
+ m = self._value_NFSC_RE.match(self._split()[1])
764
+
765
+ if m is None:
766
+ raise VerifyError("Unparsable card ({}), fix it first with "
767
+ ".verify('fix').".format(self.keyword))
768
+
769
+ if m.group('bool') is not None:
770
+ value = m.group('bool') == 'T'
771
+ elif m.group('strg') is not None:
772
+ value = re.sub("''", "'", m.group('strg'))
773
+ elif m.group('numr') is not None:
774
+ # Check for numbers with leading 0s.
775
+ numr = self._number_NFSC_RE.match(m.group('numr'))
776
+ digt = translate(numr.group('digt'), FIX_FP_TABLE2, ' ')
777
+ if numr.group('sign') is None:
778
+ sign = ''
779
+ else:
780
+ sign = numr.group('sign')
781
+ value = _str_to_num(sign + digt)
782
+
783
+ elif m.group('cplx') is not None:
784
+ # Check for numbers with leading 0s.
785
+ real = self._number_NFSC_RE.match(m.group('real'))
786
+ rdigt = translate(real.group('digt'), FIX_FP_TABLE2, ' ')
787
+ if real.group('sign') is None:
788
+ rsign = ''
789
+ else:
790
+ rsign = real.group('sign')
791
+ value = _str_to_num(rsign + rdigt)
792
+ imag = self._number_NFSC_RE.match(m.group('imag'))
793
+ idigt = translate(imag.group('digt'), FIX_FP_TABLE2, ' ')
794
+ if imag.group('sign') is None:
795
+ isign = ''
796
+ else:
797
+ isign = imag.group('sign')
798
+ value += _str_to_num(isign + idigt) * 1j
799
+ else:
800
+ value = UNDEFINED
801
+
802
+ if not self._valuestring:
803
+ self._valuestring = m.group('valu')
804
+ return value
805
+
806
+ def _parse_comment(self):
807
+ """Extract the keyword value from the card image."""
808
+
809
+ # for commentary cards, no need to parse further
810
+ # likewise for invalid/unparseable cards
811
+ if self.keyword in Card._commentary_keywords or self._invalid:
812
+ return ''
813
+
814
+ if len(self._image) > self.length:
815
+ comments = []
816
+ for card in self._itersubcards():
817
+ if card.comment:
818
+ comments.append(card.comment)
819
+ comment = '/ ' + ' '.join(comments).rstrip()
820
+ m = self._value_NFSC_RE.match(comment)
821
+ else:
822
+ m = self._value_NFSC_RE.match(self._split()[1])
823
+
824
+ if m is not None:
825
+ comment = m.group('comm')
826
+ if comment:
827
+ return comment.rstrip()
828
+ return ''
829
+
830
+ def _split(self):
831
+ """
832
+ Split the card image between the keyword and the rest of the card.
833
+ """
834
+
835
+ if self._image is not None:
836
+ # If we already have a card image, don't try to rebuild a new card
837
+ # image, which self.image would do
838
+ image = self._image
839
+ else:
840
+ image = self.image
841
+
842
+ if self.keyword in self._special_keywords:
843
+ keyword, valuecomment = image.split(' ', 1)
844
+ else:
845
+ try:
846
+ delim_index = image.index(self._value_indicator)
847
+ except ValueError:
848
+ delim_index = None
849
+
850
+ # The equal sign may not be any higher than column 10; anything
851
+ # past that must be considered part of the card value
852
+ if delim_index is None:
853
+ keyword = image[:KEYWORD_LENGTH]
854
+ valuecomment = image[KEYWORD_LENGTH:]
855
+ elif delim_index > 10 and image[:9] != 'HIERARCH ':
856
+ keyword = image[:8]
857
+ valuecomment = image[8:]
858
+ else:
859
+ keyword, valuecomment = image.split(self._value_indicator, 1)
860
+ return keyword.strip(), valuecomment.strip()
861
+
862
+ def _fix_keyword(self):
863
+ if self.field_specifier:
864
+ keyword, field_specifier = self._keyword.split('.', 1)
865
+ self._keyword = '.'.join([keyword.upper(), field_specifier])
866
+ else:
867
+ self._keyword = self._keyword.upper()
868
+ self._modified = True
869
+
870
+ def _fix_value(self):
871
+ """Fix the card image for fixable non-standard compliance."""
872
+
873
+ value = None
874
+ keyword, valuecomment = self._split()
875
+ m = self._value_NFSC_RE.match(valuecomment)
876
+
877
+ # for the unparsable case
878
+ if m is None:
879
+ try:
880
+ value, comment = valuecomment.split('/', 1)
881
+ self.value = value.strip()
882
+ self.comment = comment.strip()
883
+ except (ValueError, IndexError):
884
+ self.value = valuecomment
885
+ self._valuestring = self._value
886
+ return
887
+ elif m.group('numr') is not None:
888
+ numr = self._number_NFSC_RE.match(m.group('numr'))
889
+ value = translate(numr.group('digt'), FIX_FP_TABLE, ' ')
890
+ if numr.group('sign') is not None:
891
+ value = numr.group('sign') + value
892
+
893
+ elif m.group('cplx') is not None:
894
+ real = self._number_NFSC_RE.match(m.group('real'))
895
+ rdigt = translate(real.group('digt'), FIX_FP_TABLE, ' ')
896
+ if real.group('sign') is not None:
897
+ rdigt = real.group('sign') + rdigt
898
+
899
+ imag = self._number_NFSC_RE.match(m.group('imag'))
900
+ idigt = translate(imag.group('digt'), FIX_FP_TABLE, ' ')
901
+ if imag.group('sign') is not None:
902
+ idigt = imag.group('sign') + idigt
903
+ value = '({}, {})'.format(rdigt, idigt)
904
+ self._valuestring = value
905
+ # The value itself has not been modified, but its serialized
906
+ # representation (as stored in self._valuestring) has been changed, so
907
+ # still set this card as having been modified (see ticket #137)
908
+ self._modified = True
909
+
910
+ def _format_keyword(self):
911
+ if self.keyword:
912
+ if self.field_specifier:
913
+ return '{:{len}}'.format(self.keyword.split('.', 1)[0],
914
+ len=KEYWORD_LENGTH)
915
+ elif self._hierarch:
916
+ return 'HIERARCH {} '.format(self.keyword)
917
+ else:
918
+ return '{:{len}}'.format(self.keyword, len=KEYWORD_LENGTH)
919
+ else:
920
+ return ' ' * KEYWORD_LENGTH
921
+
922
+ def _format_value(self):
923
+ # value string
924
+ float_types = (float, np.floating, complex, np.complexfloating)
925
+
926
+ # Force the value to be parsed out first
927
+ value = self.value
928
+ # But work with the underlying raw value instead (to preserve
929
+ # whitespace, for now...)
930
+ value = self._value
931
+
932
+ if self.keyword in self._commentary_keywords:
933
+ # The value of a commentary card must be just a raw unprocessed
934
+ # string
935
+ value = str(value)
936
+ elif (self._valuestring and not self._valuemodified and
937
+ isinstance(self.value, float_types)):
938
+ # Keep the existing formatting for float/complex numbers
939
+ value = '{:>20}'.format(self._valuestring)
940
+ elif self.field_specifier:
941
+ value = _format_value(self._value).strip()
942
+ value = "'{}: {}'".format(self.field_specifier, value)
943
+ else:
944
+ value = _format_value(value)
945
+
946
+ # For HIERARCH cards the value should be shortened to conserve space
947
+ if not self.field_specifier and len(self.keyword) > KEYWORD_LENGTH:
948
+ value = value.strip()
949
+
950
+ return value
951
+
952
+ def _format_comment(self):
953
+ if not self.comment:
954
+ return ''
955
+ else:
956
+ return ' / {}'.format(self._comment)
957
+
958
+ def _format_image(self):
959
+ keyword = self._format_keyword()
960
+
961
+ value = self._format_value()
962
+ is_commentary = keyword.strip() in self._commentary_keywords
963
+ if is_commentary:
964
+ comment = ''
965
+ else:
966
+ comment = self._format_comment()
967
+
968
+ # equal sign string
969
+ # by default use the standard value indicator even for HIERARCH cards;
970
+ # later we may abbreviate it if necessary
971
+ delimiter = VALUE_INDICATOR
972
+ if is_commentary:
973
+ delimiter = ''
974
+
975
+ # put all parts together
976
+ output = ''.join([keyword, delimiter, value, comment])
977
+
978
+ # For HIERARCH cards we can save a bit of space if necessary by
979
+ # removing the space between the keyword and the equals sign; I'm
980
+ # guessing this is part of the HIEARCH card specification
981
+ keywordvalue_length = len(keyword) + len(delimiter) + len(value)
982
+ if (keywordvalue_length > self.length and
983
+ keyword.startswith('HIERARCH')):
984
+ if (keywordvalue_length == self.length + 1 and keyword[-1] == ' '):
985
+ output = ''.join([keyword[:-1], delimiter, value, comment])
986
+ else:
987
+ # I guess the HIERARCH card spec is incompatible with CONTINUE
988
+ # cards
989
+ raise ValueError('The header keyword {!r} with its value is '
990
+ 'too long'.format(self.keyword))
991
+
992
+ if len(output) <= self.length:
993
+ output = '{:80}'.format(output)
994
+ else:
995
+ # longstring case (CONTINUE card)
996
+ # try not to use CONTINUE if the string value can fit in one line.
997
+ # Instead, just truncate the comment
998
+ if (isinstance(self.value, str) and
999
+ len(value) > (self.length - 10)):
1000
+ output = self._format_long_image()
1001
+ else:
1002
+ warnings.warn('Card is too long, comment will be truncated.',
1003
+ VerifyWarning)
1004
+ output = output[:Card.length]
1005
+ return output
1006
+
1007
+ def _format_long_image(self):
1008
+ """
1009
+ Break up long string value/comment into ``CONTINUE`` cards.
1010
+ This is a primitive implementation: it will put the value
1011
+ string in one block and the comment string in another. Also,
1012
+ it does not break at the blank space between words. So it may
1013
+ not look pretty.
1014
+ """
1015
+
1016
+ if self.keyword in Card._commentary_keywords:
1017
+ return self._format_long_commentary_image()
1018
+
1019
+ value_length = 67
1020
+ comment_length = 64
1021
+ output = []
1022
+
1023
+ # do the value string
1024
+ value = self._value.replace("'", "''")
1025
+ words = _words_group(value, value_length)
1026
+ for idx, word in enumerate(words):
1027
+ if idx == 0:
1028
+ headstr = '{:{len}}= '.format(self.keyword, len=KEYWORD_LENGTH)
1029
+ else:
1030
+ headstr = 'CONTINUE '
1031
+
1032
+ # If this is the final CONTINUE remove the '&'
1033
+ if not self.comment and idx == len(words) - 1:
1034
+ value_format = "'{}'"
1035
+ else:
1036
+ value_format = "'{}&'"
1037
+
1038
+ value = value_format.format(word)
1039
+
1040
+ output.append('{:80}'.format(headstr + value))
1041
+
1042
+ # do the comment string
1043
+ comment_format = "{}"
1044
+
1045
+ if self.comment:
1046
+ words = _words_group(self.comment, comment_length)
1047
+ for idx, word in enumerate(words):
1048
+ # If this is the final CONTINUE remove the '&'
1049
+ if idx == len(words) - 1:
1050
+ headstr = "CONTINUE '' / "
1051
+ else:
1052
+ headstr = "CONTINUE '&' / "
1053
+
1054
+ comment = headstr + comment_format.format(word)
1055
+ output.append('{:80}'.format(comment))
1056
+
1057
+ return ''.join(output)
1058
+
1059
+ def _format_long_commentary_image(self):
1060
+ """
1061
+ If a commentary card's value is too long to fit on a single card, this
1062
+ will render the card as multiple consecutive commentary card of the
1063
+ same type.
1064
+ """
1065
+
1066
+ maxlen = Card.length - KEYWORD_LENGTH
1067
+ value = self._format_value()
1068
+ output = []
1069
+ idx = 0
1070
+ while idx < len(value):
1071
+ output.append(str(Card(self.keyword, value[idx:idx + maxlen])))
1072
+ idx += maxlen
1073
+ return ''.join(output)
1074
+
1075
+ def _verify(self, option='warn'):
1076
+ self._verified = True
1077
+
1078
+ errs = _ErrList([])
1079
+ fix_text = ('Fixed {!r} card to meet the FITS '
1080
+ 'standard.'.format(self.keyword))
1081
+
1082
+ # Don't try to verify cards that already don't meet any recognizable
1083
+ # standard
1084
+ if self._invalid:
1085
+ return errs
1086
+
1087
+ # verify the equal sign position
1088
+ if (self.keyword not in self._commentary_keywords and
1089
+ (self._image and self._image[:9].upper() != 'HIERARCH ' and
1090
+ self._image.find('=') != 8)):
1091
+ errs.append(self.run_option(
1092
+ option,
1093
+ err_text='Card {!r} is not FITS standard (equal sign not '
1094
+ 'at column 8).'.format(self.keyword),
1095
+ fix_text=fix_text,
1096
+ fix=self._fix_value))
1097
+
1098
+ # verify the key, it is never fixable
1099
+ # always fix silently the case where "=" is before column 9,
1100
+ # since there is no way to communicate back to the _keys.
1101
+ if ((self._image and self._image[:8].upper() == 'HIERARCH') or
1102
+ self._hierarch):
1103
+ pass
1104
+ else:
1105
+ if self._image:
1106
+ # PyFITS will auto-uppercase any standard keyword, so lowercase
1107
+ # keywords can only occur if they came from the wild
1108
+ keyword = self._split()[0]
1109
+ if keyword != keyword.upper():
1110
+ # Keyword should be uppercase unless it's a HIERARCH card
1111
+ errs.append(self.run_option(
1112
+ option,
1113
+ err_text='Card keyword {!r} is not upper case.'.format(
1114
+ keyword),
1115
+ fix_text=fix_text,
1116
+ fix=self._fix_keyword))
1117
+
1118
+ keyword = self.keyword
1119
+ if self.field_specifier:
1120
+ keyword = keyword.split('.', 1)[0]
1121
+
1122
+ if not self._keywd_FSC_RE.match(keyword):
1123
+ errs.append(self.run_option(
1124
+ option,
1125
+ err_text='Illegal keyword name {!r}'.format(keyword),
1126
+ fixable=False))
1127
+
1128
+ # verify the value, it may be fixable
1129
+ keyword, valuecomment = self._split()
1130
+ if self.keyword in self._commentary_keywords:
1131
+ # For commentary keywords all that needs to be ensured is that it
1132
+ # contains only printable ASCII characters
1133
+ if not self._ascii_text_re.match(valuecomment):
1134
+ errs.append(self.run_option(
1135
+ option,
1136
+ err_text='Unprintable string {!r}; commentary cards may '
1137
+ 'only contain printable ASCII characters'.format(
1138
+ valuecomment),
1139
+ fixable=False))
1140
+ else:
1141
+ m = self._value_FSC_RE.match(valuecomment)
1142
+ if not m:
1143
+ errs.append(self.run_option(
1144
+ option,
1145
+ err_text='Card {!r} is not FITS standard (invalid value '
1146
+ 'string: {!r}).'.format(self.keyword, valuecomment),
1147
+ fix_text=fix_text,
1148
+ fix=self._fix_value))
1149
+
1150
+ # verify the comment (string), it is never fixable
1151
+ m = self._value_NFSC_RE.match(valuecomment)
1152
+ if m is not None:
1153
+ comment = m.group('comm')
1154
+ if comment is not None:
1155
+ if not self._ascii_text_re.match(comment):
1156
+ errs.append(self.run_option(
1157
+ option,
1158
+ err_text=('Unprintable string {!r}; header comments '
1159
+ 'may only contain printable ASCII '
1160
+ 'characters'.format(comment)),
1161
+ fixable=False))
1162
+
1163
+ return errs
1164
+
1165
+ def _itersubcards(self):
1166
+ """
1167
+ If the card image is greater than 80 characters, it should consist of a
1168
+ normal card followed by one or more CONTINUE card. This method returns
1169
+ the subcards that make up this logical card.
1170
+ """
1171
+
1172
+ ncards = len(self._image) // Card.length
1173
+
1174
+ for idx in range(0, Card.length * ncards, Card.length):
1175
+ card = Card.fromstring(self._image[idx:idx + Card.length])
1176
+ if idx > 0 and card.keyword.upper() != 'CONTINUE':
1177
+ raise VerifyError(
1178
+ 'Long card images must have CONTINUE cards after '
1179
+ 'the first card.')
1180
+
1181
+ if not isinstance(card.value, str):
1182
+ raise VerifyError('CONTINUE cards must have string values.')
1183
+
1184
+ yield card
1185
+
1186
+
1187
+ def _int_or_float(s):
1188
+ """
1189
+ Converts an a string to an int if possible, or to a float.
1190
+
1191
+ If the string is neither a string or a float a value error is raised.
1192
+ """
1193
+
1194
+ if isinstance(s, float):
1195
+ # Already a float so just pass through
1196
+ return s
1197
+
1198
+ try:
1199
+ return int(s)
1200
+ except (ValueError, TypeError):
1201
+ try:
1202
+ return float(s)
1203
+ except (ValueError, TypeError) as e:
1204
+ raise ValueError(str(e))
1205
+
1206
+
1207
+ def _format_value(value):
1208
+ """
1209
+ Converts a card value to its appropriate string representation as
1210
+ defined by the FITS format.
1211
+ """
1212
+
1213
+ # string value should occupies at least 8 columns, unless it is
1214
+ # a null string
1215
+ if isinstance(value, str):
1216
+ if value == '':
1217
+ return "''"
1218
+ else:
1219
+ exp_val_str = value.replace("'", "''")
1220
+ val_str = "'{:8}'".format(exp_val_str)
1221
+ return '{:20}'.format(val_str)
1222
+
1223
+ # must be before int checking since bool is also int
1224
+ elif isinstance(value, (bool, np.bool_)):
1225
+ return '{:>20}'.format(repr(value)[0]) # T or F
1226
+
1227
+ elif _is_int(value):
1228
+ return '{:>20d}'.format(value)
1229
+
1230
+ elif isinstance(value, (float, np.floating)):
1231
+ return '{:>20}'.format(_format_float(value))
1232
+
1233
+ elif isinstance(value, (complex, np.complexfloating)):
1234
+ val_str = '({}, {})'.format(_format_float(value.real),
1235
+ _format_float(value.imag))
1236
+ return '{:>20}'.format(val_str)
1237
+
1238
+ elif isinstance(value, Undefined):
1239
+ return ''
1240
+ else:
1241
+ return ''
1242
+
1243
+
1244
+ def _format_float(value):
1245
+ """Format a floating number to make sure it gets the decimal point."""
1246
+
1247
+ value_str = '{:.16G}'.format(value)
1248
+ if '.' not in value_str and 'E' not in value_str:
1249
+ value_str += '.0'
1250
+ elif 'E' in value_str:
1251
+ # On some Windows builds of Python (and possibly other platforms?) the
1252
+ # exponent is zero-padded out to, it seems, three digits. Normalize
1253
+ # the format to pad only to two digits.
1254
+ significand, exponent = value_str.split('E')
1255
+ if exponent[0] in ('+', '-'):
1256
+ sign = exponent[0]
1257
+ exponent = exponent[1:]
1258
+ else:
1259
+ sign = ''
1260
+ value_str = '{}E{}{:02d}'.format(significand, sign, int(exponent))
1261
+
1262
+ # Limit the value string to at most 20 characters.
1263
+ str_len = len(value_str)
1264
+
1265
+ if str_len > 20:
1266
+ idx = value_str.find('E')
1267
+
1268
+ if idx < 0:
1269
+ value_str = value_str[:20]
1270
+ else:
1271
+ value_str = value_str[:20 - (str_len - idx)] + value_str[idx:]
1272
+
1273
+ return value_str
1274
+
1275
+
1276
+ def _pad(input):
1277
+ """Pad blank space to the input string to be multiple of 80."""
1278
+
1279
+ _len = len(input)
1280
+ if _len == Card.length:
1281
+ return input
1282
+ elif _len > Card.length:
1283
+ strlen = _len % Card.length
1284
+ if strlen == 0:
1285
+ return input
1286
+ else:
1287
+ return input + ' ' * (Card.length - strlen)
1288
+
1289
+ # minimum length is 80
1290
+ else:
1291
+ strlen = _len % Card.length
1292
+ return input + ' ' * (Card.length - strlen)
testbed/astropy__astropy/astropy/io/fits/column.py ADDED
@@ -0,0 +1,2615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import copy
4
+ import operator
5
+ import re
6
+ import sys
7
+ import warnings
8
+ import weakref
9
+ import numbers
10
+
11
+ from functools import reduce
12
+ from collections import OrderedDict
13
+ from contextlib import suppress
14
+
15
+ import numpy as np
16
+ from numpy import char as chararray
17
+
18
+ from .card import Card, CARD_LENGTH
19
+ from .util import (pairwise, _is_int, _convert_array, encode_ascii, cmp,
20
+ NotifierMixin)
21
+ from .verify import VerifyError, VerifyWarning
22
+
23
+ from astropy.utils import lazyproperty, isiterable, indent
24
+ from astropy.utils.exceptions import AstropyUserWarning
25
+
26
+ __all__ = ['Column', 'ColDefs', 'Delayed']
27
+
28
+
29
+ # mapping from TFORM data type to numpy data type (code)
30
+ # L: Logical (Boolean)
31
+ # B: Unsigned Byte
32
+ # I: 16-bit Integer
33
+ # J: 32-bit Integer
34
+ # K: 64-bit Integer
35
+ # E: Single-precision Floating Point
36
+ # D: Double-precision Floating Point
37
+ # C: Single-precision Complex
38
+ # M: Double-precision Complex
39
+ # A: Character
40
+ FITS2NUMPY = {'L': 'i1', 'B': 'u1', 'I': 'i2', 'J': 'i4', 'K': 'i8', 'E': 'f4',
41
+ 'D': 'f8', 'C': 'c8', 'M': 'c16', 'A': 'a'}
42
+
43
+ # the inverse dictionary of the above
44
+ NUMPY2FITS = {val: key for key, val in FITS2NUMPY.items()}
45
+ # Normally booleans are represented as ints in Astropy, but if passed in a numpy
46
+ # boolean array, that should be supported
47
+ NUMPY2FITS['b1'] = 'L'
48
+ # Add unsigned types, which will be stored as signed ints with a TZERO card.
49
+ NUMPY2FITS['u2'] = 'I'
50
+ NUMPY2FITS['u4'] = 'J'
51
+ NUMPY2FITS['u8'] = 'K'
52
+ # Add half precision floating point numbers which will be up-converted to
53
+ # single precision.
54
+ NUMPY2FITS['f2'] = 'E'
55
+
56
+ # This is the order in which values are converted to FITS types
57
+ # Note that only double precision floating point/complex are supported
58
+ FORMATORDER = ['L', 'B', 'I', 'J', 'K', 'D', 'M', 'A']
59
+
60
+ # Convert single precision floating point/complex to double precision.
61
+ FITSUPCONVERTERS = {'E': 'D', 'C': 'M'}
62
+
63
+ # mapping from ASCII table TFORM data type to numpy data type
64
+ # A: Character
65
+ # I: Integer (32-bit)
66
+ # J: Integer (64-bit; non-standard)
67
+ # F: Float (64-bit; fixed decimal notation)
68
+ # E: Float (64-bit; exponential notation)
69
+ # D: Float (64-bit; exponential notation, always 64-bit by convention)
70
+ ASCII2NUMPY = {'A': 'a', 'I': 'i4', 'J': 'i8', 'F': 'f8', 'E': 'f8', 'D': 'f8'}
71
+
72
+ # Maps FITS ASCII column format codes to the appropriate Python string
73
+ # formatting codes for that type.
74
+ ASCII2STR = {'A': '', 'I': 'd', 'J': 'd', 'F': 'f', 'E': 'E', 'D': 'E'}
75
+
76
+ # For each ASCII table format code, provides a default width (and decimal
77
+ # precision) for when one isn't given explicitly in the column format
78
+ ASCII_DEFAULT_WIDTHS = {'A': (1, 0), 'I': (10, 0), 'J': (15, 0),
79
+ 'E': (15, 7), 'F': (16, 7), 'D': (25, 17)}
80
+
81
+ # TDISPn for both ASCII and Binary tables
82
+ TDISP_RE_DICT = {}
83
+ TDISP_RE_DICT['F'] = re.compile(r'(?:(?P<formatc>[F])(?:(?P<width>[0-9]+)\.{1}'
84
+ r'(?P<precision>[0-9])+)+)|')
85
+ TDISP_RE_DICT['A'] = TDISP_RE_DICT['L'] = \
86
+ re.compile(r'(?:(?P<formatc>[AL])(?P<width>[0-9]+)+)|')
87
+ TDISP_RE_DICT['I'] = TDISP_RE_DICT['B'] = \
88
+ TDISP_RE_DICT['O'] = TDISP_RE_DICT['Z'] = \
89
+ re.compile(r'(?:(?P<formatc>[IBOZ])(?:(?P<width>[0-9]+)'
90
+ r'(?:\.{0,1}(?P<precision>[0-9]+))?))|')
91
+ TDISP_RE_DICT['E'] = TDISP_RE_DICT['G'] = \
92
+ TDISP_RE_DICT['D'] = \
93
+ re.compile(r'(?:(?P<formatc>[EGD])(?:(?P<width>[0-9]+)\.'
94
+ r'(?P<precision>[0-9]+))+)'
95
+ r'(?:E{0,1}(?P<exponential>[0-9]+)?)|')
96
+ TDISP_RE_DICT['EN'] = TDISP_RE_DICT['ES'] = \
97
+ re.compile(r'(?:(?P<formatc>E[NS])(?:(?P<width>[0-9]+)\.{1}'
98
+ r'(?P<precision>[0-9])+)+)')
99
+
100
+ # mapping from TDISP format to python format
101
+ # A: Character
102
+ # L: Logical (Boolean)
103
+ # I: 16-bit Integer
104
+ # Can't predefine zero padding and space padding before hand without
105
+ # knowing the value being formatted, so grabbing precision and using that
106
+ # to zero pad, ignoring width. Same with B, O, and Z
107
+ # B: Binary Integer
108
+ # O: Octal Integer
109
+ # Z: Hexadecimal Integer
110
+ # F: Float (64-bit; fixed decimal notation)
111
+ # EN: Float (engineering fortran format, exponential multiple of thee
112
+ # ES: Float (scientific, same as EN but non-zero leading digit
113
+ # E: Float, exponential notation
114
+ # Can't get exponential restriction to work without knowing value
115
+ # before hand, so just using width and precision, same with D, G, EN, and
116
+ # ES formats
117
+ # D: Double-precision Floating Point with exponential
118
+ # (E but for double precision)
119
+ # G: Double-precision Floating Point, may or may not show exponent
120
+ TDISP_FMT_DICT = {'I' : '{{:{width}d}}',
121
+ 'B' : '{{:{width}b}}',
122
+ 'O' : '{{:{width}o}}',
123
+ 'Z' : '{{:{width}x}}',
124
+ 'F' : '{{:{width}.{precision}f}}',
125
+ 'G' : '{{:{width}.{precision}g}}'}
126
+ TDISP_FMT_DICT['A'] = TDISP_FMT_DICT['L'] = '{{:>{width}}}'
127
+ TDISP_FMT_DICT['E'] = TDISP_FMT_DICT['D'] = \
128
+ TDISP_FMT_DICT['EN'] = TDISP_FMT_DICT['ES'] ='{{:{width}.{precision}e}}'
129
+
130
+ # tuple of column/field definition common names and keyword names, make
131
+ # sure to preserve the one-to-one correspondence when updating the list(s).
132
+ # Use lists, instead of dictionaries so the names can be displayed in a
133
+ # preferred order.
134
+ KEYWORD_NAMES = ('TTYPE', 'TFORM', 'TUNIT', 'TNULL', 'TSCAL', 'TZERO',
135
+ 'TDISP', 'TBCOL', 'TDIM', 'TCTYP', 'TCUNI', 'TCRPX',
136
+ 'TCRVL', 'TCDLT', 'TRPOS')
137
+ KEYWORD_ATTRIBUTES = ('name', 'format', 'unit', 'null', 'bscale', 'bzero',
138
+ 'disp', 'start', 'dim', 'coord_type', 'coord_unit',
139
+ 'coord_ref_point', 'coord_ref_value', 'coord_inc',
140
+ 'time_ref_pos')
141
+ """This is a list of the attributes that can be set on `Column` objects."""
142
+
143
+
144
+ KEYWORD_TO_ATTRIBUTE = OrderedDict(zip(KEYWORD_NAMES, KEYWORD_ATTRIBUTES))
145
+
146
+ ATTRIBUTE_TO_KEYWORD = OrderedDict(zip(KEYWORD_ATTRIBUTES, KEYWORD_NAMES))
147
+
148
+
149
+ # TODO: Define a list of default comments to associate with each table keyword
150
+
151
+ # TFORMn regular expression
152
+ TFORMAT_RE = re.compile(r'(?P<repeat>^[0-9]*)(?P<format>[LXBIJKAEDCMPQ])'
153
+ r'(?P<option>[!-~]*)', re.I)
154
+
155
+ # TFORMn for ASCII tables; two different versions depending on whether
156
+ # the format is floating-point or not; allows empty values for width
157
+ # in which case defaults are used
158
+ TFORMAT_ASCII_RE = re.compile(r'(?:(?P<format>[AIJ])(?P<width>[0-9]+)?)|'
159
+ r'(?:(?P<formatf>[FED])'
160
+ r'(?:(?P<widthf>[0-9]+)\.'
161
+ r'(?P<precision>[0-9]+))?)')
162
+
163
+ TTYPE_RE = re.compile(r'[0-9a-zA-Z_]+')
164
+ """
165
+ Regular expression for valid table column names. See FITS Standard v3.0 section
166
+ 7.2.2.
167
+ """
168
+
169
+ # table definition keyword regular expression
170
+ TDEF_RE = re.compile(r'(?P<label>^T[A-Z]*)(?P<num>[1-9][0-9 ]*$)')
171
+
172
+ # table dimension keyword regular expression (fairly flexible with whitespace)
173
+ TDIM_RE = re.compile(r'\(\s*(?P<dims>(?:\d+,\s*)+\s*\d+)\s*\)\s*')
174
+
175
+ # value for ASCII table cell with value = TNULL
176
+ # this can be reset by user.
177
+ ASCIITNULL = 0
178
+
179
+ # The default placeholder to use for NULL values in ASCII tables when
180
+ # converting from binary to ASCII tables
181
+ DEFAULT_ASCII_TNULL = '---'
182
+
183
+
184
+ class Delayed:
185
+ """Delayed file-reading data."""
186
+
187
+ def __init__(self, hdu=None, field=None):
188
+ self.hdu = weakref.proxy(hdu)
189
+ self.field = field
190
+
191
+ def __getitem__(self, key):
192
+ # This forces the data for the HDU to be read, which will replace
193
+ # the corresponding Delayed objects in the Tables Columns to be
194
+ # transformed into ndarrays. It will also return the value of the
195
+ # requested data element.
196
+ return self.hdu.data[key][self.field]
197
+
198
+
199
+ class _BaseColumnFormat(str):
200
+ """
201
+ Base class for binary table column formats (just called _ColumnFormat)
202
+ and ASCII table column formats (_AsciiColumnFormat).
203
+ """
204
+
205
+ def __eq__(self, other):
206
+ if not other:
207
+ return False
208
+
209
+ if isinstance(other, str):
210
+ if not isinstance(other, self.__class__):
211
+ try:
212
+ other = self.__class__(other)
213
+ except ValueError:
214
+ return False
215
+ else:
216
+ return False
217
+
218
+ return self.canonical == other.canonical
219
+
220
+ def __hash__(self):
221
+ return hash(self.canonical)
222
+
223
+ @lazyproperty
224
+ def dtype(self):
225
+ """
226
+ The Numpy dtype object created from the format's associated recformat.
227
+ """
228
+
229
+ return np.dtype(self.recformat)
230
+
231
+ @classmethod
232
+ def from_column_format(cls, format):
233
+ """Creates a column format object from another column format object
234
+ regardless of their type.
235
+
236
+ That is, this can convert a _ColumnFormat to an _AsciiColumnFormat
237
+ or vice versa at least in cases where a direct translation is possible.
238
+ """
239
+
240
+ return cls.from_recformat(format.recformat)
241
+
242
+
243
+ class _ColumnFormat(_BaseColumnFormat):
244
+ """
245
+ Represents a FITS binary table column format.
246
+
247
+ This is an enhancement over using a normal string for the format, since the
248
+ repeat count, format code, and option are available as separate attributes,
249
+ and smart comparison is used. For example 1J == J.
250
+ """
251
+
252
+ def __new__(cls, format):
253
+ self = super().__new__(cls, format)
254
+ self.repeat, self.format, self.option = _parse_tformat(format)
255
+ self.format = self.format.upper()
256
+ if self.format in ('P', 'Q'):
257
+ # TODO: There should be a generic factory that returns either
258
+ # _FormatP or _FormatQ as appropriate for a given TFORMn
259
+ if self.format == 'P':
260
+ recformat = _FormatP.from_tform(format)
261
+ else:
262
+ recformat = _FormatQ.from_tform(format)
263
+ # Format of variable length arrays
264
+ self.p_format = recformat.format
265
+ else:
266
+ self.p_format = None
267
+ return self
268
+
269
+ @classmethod
270
+ def from_recformat(cls, recformat):
271
+ """Creates a column format from a Numpy record dtype format."""
272
+
273
+ return cls(_convert_format(recformat, reverse=True))
274
+
275
+ @lazyproperty
276
+ def recformat(self):
277
+ """Returns the equivalent Numpy record format string."""
278
+
279
+ return _convert_format(self)
280
+
281
+ @lazyproperty
282
+ def canonical(self):
283
+ """
284
+ Returns a 'canonical' string representation of this format.
285
+
286
+ This is in the proper form of rTa where T is the single character data
287
+ type code, a is the optional part, and r is the repeat. If repeat == 1
288
+ (the default) it is left out of this representation.
289
+ """
290
+
291
+ if self.repeat == 1:
292
+ repeat = ''
293
+ else:
294
+ repeat = str(self.repeat)
295
+
296
+ return '{}{}{}'.format(repeat, self.format, self.option)
297
+
298
+
299
+ class _AsciiColumnFormat(_BaseColumnFormat):
300
+ """Similar to _ColumnFormat but specifically for columns in ASCII tables.
301
+
302
+ The formats of ASCII table columns and binary table columns are inherently
303
+ incompatible in FITS. They don't support the same ranges and types of
304
+ values, and even reuse format codes in subtly different ways. For example
305
+ the format code 'Iw' in ASCII columns refers to any integer whose string
306
+ representation is at most w characters wide, so 'I' can represent
307
+ effectively any integer that will fit in a FITS columns. Whereas for
308
+ binary tables 'I' very explicitly refers to a 16-bit signed integer.
309
+
310
+ Conversions between the two column formats can be performed using the
311
+ ``to/from_binary`` methods on this class, or the ``to/from_ascii``
312
+ methods on the `_ColumnFormat` class. But again, not all conversions are
313
+ possible and may result in a `ValueError`.
314
+ """
315
+
316
+ def __new__(cls, format, strict=False):
317
+ self = super().__new__(cls, format)
318
+ self.format, self.width, self.precision = \
319
+ _parse_ascii_tformat(format, strict)
320
+
321
+ # This is to support handling logical (boolean) data from binary tables
322
+ # in an ASCII table
323
+ self._pseudo_logical = False
324
+ return self
325
+
326
+ @classmethod
327
+ def from_column_format(cls, format):
328
+ inst = cls.from_recformat(format.recformat)
329
+ # Hack
330
+ if format.format == 'L':
331
+ inst._pseudo_logical = True
332
+ return inst
333
+
334
+ @classmethod
335
+ def from_recformat(cls, recformat):
336
+ """Creates a column format from a Numpy record dtype format."""
337
+
338
+ return cls(_convert_ascii_format(recformat, reverse=True))
339
+
340
+ @lazyproperty
341
+ def recformat(self):
342
+ """Returns the equivalent Numpy record format string."""
343
+
344
+ return _convert_ascii_format(self)
345
+
346
+ @lazyproperty
347
+ def canonical(self):
348
+ """
349
+ Returns a 'canonical' string representation of this format.
350
+
351
+ This is in the proper form of Tw.d where T is the single character data
352
+ type code, w is the width in characters for this field, and d is the
353
+ number of digits after the decimal place (for format codes 'E', 'F',
354
+ and 'D' only).
355
+ """
356
+
357
+ if self.format in ('E', 'F', 'D'):
358
+ return '{}{}.{}'.format(self.format, self.width, self.precision)
359
+
360
+ return '{}{}'.format(self.format, self.width)
361
+
362
+
363
+ class _FormatX(str):
364
+ """For X format in binary tables."""
365
+
366
+ def __new__(cls, repeat=1):
367
+ nbytes = ((repeat - 1) // 8) + 1
368
+ # use an array, even if it is only ONE u1 (i.e. use tuple always)
369
+ obj = super().__new__(cls, repr((nbytes,)) + 'u1')
370
+ obj.repeat = repeat
371
+ return obj
372
+
373
+ def __getnewargs__(self):
374
+ return (self.repeat,)
375
+
376
+ @property
377
+ def tform(self):
378
+ return '{}X'.format(self.repeat)
379
+
380
+
381
+ # TODO: Table column formats need to be verified upon first reading the file;
382
+ # as it is, an invalid P format will raise a VerifyError from some deep,
383
+ # unexpected place
384
+ class _FormatP(str):
385
+ """For P format in variable length table."""
386
+
387
+ # As far as I can tell from my reading of the FITS standard, a type code is
388
+ # *required* for P and Q formats; there is no default
389
+ _format_re_template = (r'(?P<repeat>\d+)?{}(?P<dtype>[LXBIJKAEDCM])'
390
+ r'(?:\((?P<max>\d*)\))?')
391
+ _format_code = 'P'
392
+ _format_re = re.compile(_format_re_template.format(_format_code))
393
+ _descriptor_format = '2i4'
394
+
395
+ def __new__(cls, dtype, repeat=None, max=None):
396
+ obj = super().__new__(cls, cls._descriptor_format)
397
+ obj.format = NUMPY2FITS[dtype]
398
+ obj.dtype = dtype
399
+ obj.repeat = repeat
400
+ obj.max = max
401
+ return obj
402
+
403
+ def __getnewargs__(self):
404
+ return (self.dtype, self.repeat, self.max)
405
+
406
+ @classmethod
407
+ def from_tform(cls, format):
408
+ m = cls._format_re.match(format)
409
+ if not m or m.group('dtype') not in FITS2NUMPY:
410
+ raise VerifyError('Invalid column format: {}'.format(format))
411
+ repeat = m.group('repeat')
412
+ array_dtype = m.group('dtype')
413
+ max = m.group('max')
414
+ if not max:
415
+ max = None
416
+ return cls(FITS2NUMPY[array_dtype], repeat=repeat, max=max)
417
+
418
+ @property
419
+ def tform(self):
420
+ repeat = '' if self.repeat is None else self.repeat
421
+ max = '' if self.max is None else self.max
422
+ return '{}{}{}({})'.format(repeat, self._format_code, self.format, max)
423
+
424
+
425
+ class _FormatQ(_FormatP):
426
+ """Carries type description of the Q format for variable length arrays.
427
+
428
+ The Q format is like the P format but uses 64-bit integers in the array
429
+ descriptors, allowing for heaps stored beyond 2GB into a file.
430
+ """
431
+
432
+ _format_code = 'Q'
433
+ _format_re = re.compile(_FormatP._format_re_template.format(_format_code))
434
+ _descriptor_format = '2i8'
435
+
436
+
437
+ class ColumnAttribute:
438
+ """
439
+ Descriptor for attributes of `Column` that are associated with keywords
440
+ in the FITS header and describe properties of the column as specified in
441
+ the FITS standard.
442
+
443
+ Each `ColumnAttribute` may have a ``validator`` method defined on it.
444
+ This validates values set on this attribute to ensure that they meet the
445
+ FITS standard. Invalid values will raise a warning and will not be used in
446
+ formatting the column. The validator should take two arguments--the
447
+ `Column` it is being assigned to, and the new value for the attribute, and
448
+ it must raise an `AssertionError` if the value is invalid.
449
+
450
+ The `ColumnAttribute` itself is a decorator that can be used to define the
451
+ ``validator`` for each column attribute. For example::
452
+
453
+ @ColumnAttribute('TTYPE')
454
+ def name(col, name):
455
+ if not isinstance(name, str):
456
+ raise AssertionError
457
+
458
+ The actual object returned by this decorator is the `ColumnAttribute`
459
+ instance though, not the ``name`` function. As such ``name`` is not a
460
+ method of the class it is defined in.
461
+
462
+ The setter for `ColumnAttribute` also updates the header of any table
463
+ HDU this column is attached to in order to reflect the change. The
464
+ ``validator`` should ensure that the value is valid for inclusion in a FITS
465
+ header.
466
+ """
467
+
468
+ def __init__(self, keyword):
469
+ self._keyword = keyword
470
+ self._validator = None
471
+
472
+ # The name of the attribute associated with this keyword is currently
473
+ # determined from the KEYWORD_NAMES/ATTRIBUTES lists. This could be
474
+ # make more flexible in the future, for example, to support custom
475
+ # column attributes.
476
+ self._attr = '_' + KEYWORD_TO_ATTRIBUTE[self._keyword]
477
+
478
+ def __get__(self, obj, objtype=None):
479
+ if obj is None:
480
+ return self
481
+ else:
482
+ return getattr(obj, self._attr)
483
+
484
+ def __set__(self, obj, value):
485
+ if self._validator is not None:
486
+ self._validator(obj, value)
487
+
488
+ old_value = getattr(obj, self._attr, None)
489
+ setattr(obj, self._attr, value)
490
+ obj._notify('column_attribute_changed', obj, self._attr[1:], old_value,
491
+ value)
492
+
493
+ def __call__(self, func):
494
+ """
495
+ Set the validator for this column attribute.
496
+
497
+ Returns ``self`` so that this can be used as a decorator, as described
498
+ in the docs for this class.
499
+ """
500
+
501
+ self._validator = func
502
+
503
+ return self
504
+
505
+ def __repr__(self):
506
+ return "{0}('{1}')".format(self.__class__.__name__, self._keyword)
507
+
508
+
509
+ class Column(NotifierMixin):
510
+ """
511
+ Class which contains the definition of one column, e.g. ``ttype``,
512
+ ``tform``, etc. and the array containing values for the column.
513
+ """
514
+
515
+ def __init__(self, name=None, format=None, unit=None, null=None,
516
+ bscale=None, bzero=None, disp=None, start=None, dim=None,
517
+ array=None, ascii=None, coord_type=None, coord_unit=None,
518
+ coord_ref_point=None, coord_ref_value=None, coord_inc=None,
519
+ time_ref_pos=None):
520
+ """
521
+ Construct a `Column` by specifying attributes. All attributes
522
+ except ``format`` can be optional; see :ref:`column_creation` and
523
+ :ref:`creating_ascii_table` for more information regarding
524
+ ``TFORM`` keyword.
525
+
526
+ Parameters
527
+ ----------
528
+ name : str, optional
529
+ column name, corresponding to ``TTYPE`` keyword
530
+
531
+ format : str
532
+ column format, corresponding to ``TFORM`` keyword
533
+
534
+ unit : str, optional
535
+ column unit, corresponding to ``TUNIT`` keyword
536
+
537
+ null : str, optional
538
+ null value, corresponding to ``TNULL`` keyword
539
+
540
+ bscale : int-like, optional
541
+ bscale value, corresponding to ``TSCAL`` keyword
542
+
543
+ bzero : int-like, optional
544
+ bzero value, corresponding to ``TZERO`` keyword
545
+
546
+ disp : str, optional
547
+ display format, corresponding to ``TDISP`` keyword
548
+
549
+ start : int, optional
550
+ column starting position (ASCII table only), corresponding
551
+ to ``TBCOL`` keyword
552
+
553
+ dim : str, optional
554
+ column dimension corresponding to ``TDIM`` keyword
555
+
556
+ array : iterable, optional
557
+ a `list`, `numpy.ndarray` (or other iterable that can be used to
558
+ initialize an ndarray) providing initial data for this column.
559
+ The array will be automatically converted, if possible, to the data
560
+ format of the column. In the case were non-trivial ``bscale``
561
+ and/or ``bzero`` arguments are given, the values in the array must
562
+ be the *physical* values--that is, the values of column as if the
563
+ scaling has already been applied (the array stored on the column
564
+ object will then be converted back to its storage values).
565
+
566
+ ascii : bool, optional
567
+ set `True` if this describes a column for an ASCII table; this
568
+ may be required to disambiguate the column format
569
+
570
+ coord_type : str, optional
571
+ coordinate/axis type corresponding to ``TCTYP`` keyword
572
+
573
+ coord_unit : str, optional
574
+ coordinate/axis unit corresponding to ``TCUNI`` keyword
575
+
576
+ coord_ref_point : int-like, optional
577
+ pixel coordinate of the reference point corresponding to ``TCRPX``
578
+ keyword
579
+
580
+ coord_ref_value : int-like, optional
581
+ coordinate value at reference point corresponding to ``TCRVL``
582
+ keyword
583
+
584
+ coord_inc : int-like, optional
585
+ coordinate increment at reference point corresponding to ``TCDLT``
586
+ keyword
587
+
588
+ time_ref_pos : str, optional
589
+ reference position for a time coordinate column corresponding to
590
+ ``TRPOS`` keyword
591
+ """
592
+
593
+ if format is None:
594
+ raise ValueError('Must specify format to construct Column.')
595
+
596
+ # any of the input argument (except array) can be a Card or just
597
+ # a number/string
598
+ kwargs = {'ascii': ascii}
599
+ for attr in KEYWORD_ATTRIBUTES:
600
+ value = locals()[attr] # get the argument's value
601
+
602
+ if isinstance(value, Card):
603
+ value = value.value
604
+
605
+ kwargs[attr] = value
606
+
607
+ valid_kwargs, invalid_kwargs = self._verify_keywords(**kwargs)
608
+
609
+ if invalid_kwargs:
610
+ msg = ['The following keyword arguments to Column were invalid:']
611
+
612
+ for val in invalid_kwargs.values():
613
+ msg.append(indent(val[1]))
614
+
615
+ raise VerifyError('\n'.join(msg))
616
+
617
+ for attr in KEYWORD_ATTRIBUTES:
618
+ setattr(self, attr, valid_kwargs.get(attr))
619
+
620
+ # TODO: Try to eliminate the following two special cases
621
+ # for recformat and dim:
622
+ # This is not actually stored as an attribute on columns for some
623
+ # reason
624
+ recformat = valid_kwargs['recformat']
625
+
626
+ # The 'dim' keyword's original value is stored in self.dim, while
627
+ # *only* the tuple form is stored in self._dims.
628
+ self._dims = self.dim
629
+ self.dim = dim
630
+
631
+ # Awful hack to use for now to keep track of whether the column holds
632
+ # pseudo-unsigned int data
633
+ self._pseudo_unsigned_ints = False
634
+
635
+ # if the column data is not ndarray, make it to be one, i.e.
636
+ # input arrays can be just list or tuple, not required to be ndarray
637
+ # does not include Object array because there is no guarantee
638
+ # the elements in the object array are consistent.
639
+ if not isinstance(array,
640
+ (np.ndarray, chararray.chararray, Delayed)):
641
+ try: # try to convert to a ndarray first
642
+ if array is not None:
643
+ array = np.array(array)
644
+ except Exception:
645
+ try: # then try to convert it to a strings array
646
+ itemsize = int(recformat[1:])
647
+ array = chararray.array(array, itemsize=itemsize)
648
+ except ValueError:
649
+ # then try variable length array
650
+ # Note: This includes _FormatQ by inheritance
651
+ if isinstance(recformat, _FormatP):
652
+ array = _VLF(array, dtype=recformat.dtype)
653
+ else:
654
+ raise ValueError('Data is inconsistent with the '
655
+ 'format `{}`.'.format(format))
656
+
657
+ array = self._convert_to_valid_data_type(array)
658
+
659
+ # We have required (through documentation) that arrays passed in to
660
+ # this constructor are already in their physical values, so we make
661
+ # note of that here
662
+ if isinstance(array, np.ndarray):
663
+ self._physical_values = True
664
+ else:
665
+ self._physical_values = False
666
+
667
+ self._parent_fits_rec = None
668
+ self.array = array
669
+
670
+ def __repr__(self):
671
+ text = ''
672
+ for attr in KEYWORD_ATTRIBUTES:
673
+ value = getattr(self, attr)
674
+ if value is not None:
675
+ text += attr + ' = ' + repr(value) + '; '
676
+ return text[:-2]
677
+
678
+ def __eq__(self, other):
679
+ """
680
+ Two columns are equal if their name and format are the same. Other
681
+ attributes aren't taken into account at this time.
682
+ """
683
+
684
+ # According to the FITS standard column names must be case-insensitive
685
+ a = (self.name.lower(), self.format)
686
+ b = (other.name.lower(), other.format)
687
+ return a == b
688
+
689
+ def __hash__(self):
690
+ """
691
+ Like __eq__, the hash of a column should be based on the unique column
692
+ name and format, and be case-insensitive with respect to the column
693
+ name.
694
+ """
695
+
696
+ return hash((self.name.lower(), self.format))
697
+
698
+ @property
699
+ def array(self):
700
+ """
701
+ The Numpy `~numpy.ndarray` associated with this `Column`.
702
+
703
+ If the column was instantiated with an array passed to the ``array``
704
+ argument, this will return that array. However, if the column is
705
+ later added to a table, such as via `BinTableHDU.from_columns` as
706
+ is typically the case, this attribute will be updated to reference
707
+ the associated field in the table, which may no longer be the same
708
+ array.
709
+ """
710
+
711
+ # Ideally the .array attribute never would have existed in the first
712
+ # place, or would have been internal-only. This is a legacy of the
713
+ # older design from Astropy that needs to have continued support, for
714
+ # now.
715
+
716
+ # One of the main problems with this design was that it created a
717
+ # reference cycle. When the .array attribute was updated after
718
+ # creating a FITS_rec from the column (as explained in the docstring) a
719
+ # reference cycle was created. This is because the code in BinTableHDU
720
+ # (and a few other places) does essentially the following:
721
+ #
722
+ # data._coldefs = columns # The ColDefs object holding this Column
723
+ # for col in columns:
724
+ # col.array = data.field(col.name)
725
+ #
726
+ # This way each columns .array attribute now points to the field in the
727
+ # table data. It's actually a pretty confusing interface (since it
728
+ # replaces the array originally pointed to by .array), but it's the way
729
+ # things have been for a long, long time.
730
+ #
731
+ # However, this results, in *many* cases, in a reference cycle.
732
+ # Because the array returned by data.field(col.name), while sometimes
733
+ # an array that owns its own data, is usually like a slice of the
734
+ # original data. It has the original FITS_rec as the array .base.
735
+ # This results in the following reference cycle (for the n-th column):
736
+ #
737
+ # data -> data._coldefs -> data._coldefs[n] ->
738
+ # data._coldefs[n].array -> data._coldefs[n].array.base -> data
739
+ #
740
+ # Because ndarray objects do not handled by Python's garbage collector
741
+ # the reference cycle cannot be broken. Therefore the FITS_rec's
742
+ # refcount never goes to zero, its __del__ is never called, and its
743
+ # memory is never freed. This didn't occur in *all* cases, but it did
744
+ # occur in many cases.
745
+ #
746
+ # To get around this, Column.array is no longer a simple attribute
747
+ # like it was previously. Now each Column has a ._parent_fits_rec
748
+ # attribute which is a weakref to a FITS_rec object. Code that
749
+ # previously assigned each col.array to field in a FITS_rec (as in
750
+ # the example a few paragraphs above) is still used, however now
751
+ # array.setter checks if a reference cycle will be created. And if
752
+ # so, instead of saving directly to the Column's __dict__, it creates
753
+ # the ._prent_fits_rec weakref, and all lookups of the column's .array
754
+ # go through that instead.
755
+ #
756
+ # This alone does not fully solve the problem. Because
757
+ # _parent_fits_rec is a weakref, if the user ever holds a reference to
758
+ # the Column, but deletes all references to the underlying FITS_rec,
759
+ # the .array attribute would suddenly start returning None instead of
760
+ # the array data. This problem is resolved on FITS_rec's end. See the
761
+ # note in the FITS_rec._coldefs property for the rest of the story.
762
+
763
+ # If the Columns's array is not a reference to an existing FITS_rec,
764
+ # then it is just stored in self.__dict__; otherwise check the
765
+ # _parent_fits_rec reference if it 's still available.
766
+ if 'array' in self.__dict__:
767
+ return self.__dict__['array']
768
+ elif self._parent_fits_rec is not None:
769
+ parent = self._parent_fits_rec()
770
+ if parent is not None:
771
+ return parent[self.name]
772
+ else:
773
+ return None
774
+
775
+ @array.setter
776
+ def array(self, array):
777
+ # The following looks over the bases of the given array to check if it
778
+ # has a ._coldefs attribute (i.e. is a FITS_rec) and that that _coldefs
779
+ # contains this Column itself, and would create a reference cycle if we
780
+ # stored the array directly in self.__dict__.
781
+ # In this case it instead sets up the _parent_fits_rec weakref to the
782
+ # underlying FITS_rec, so that array.getter can return arrays through
783
+ # self._parent_fits_rec().field(self.name), rather than storing a
784
+ # hard reference to the field like it used to.
785
+ base = array
786
+ while True:
787
+ if (hasattr(base, '_coldefs') and
788
+ isinstance(base._coldefs, ColDefs)):
789
+ for col in base._coldefs:
790
+ if col is self and self._parent_fits_rec is None:
791
+ self._parent_fits_rec = weakref.ref(base)
792
+
793
+ # Just in case the user already set .array to their own
794
+ # array.
795
+ if 'array' in self.__dict__:
796
+ del self.__dict__['array']
797
+ return
798
+
799
+ if getattr(base, 'base', None) is not None:
800
+ base = base.base
801
+ else:
802
+ break
803
+
804
+ self.__dict__['array'] = array
805
+
806
+ @array.deleter
807
+ def array(self):
808
+ try:
809
+ del self.__dict__['array']
810
+ except KeyError:
811
+ pass
812
+
813
+ self._parent_fits_rec = None
814
+
815
+ @ColumnAttribute('TTYPE')
816
+ def name(col, name):
817
+ if name is None:
818
+ # Allow None to indicate deleting the name, or to just indicate an
819
+ # unspecified name (when creating a new Column).
820
+ return
821
+
822
+ # Check that the name meets the recommended standard--other column
823
+ # names are *allowed*, but will be discouraged
824
+ if isinstance(name, str) and not TTYPE_RE.match(name):
825
+ warnings.warn(
826
+ 'It is strongly recommended that column names contain only '
827
+ 'upper and lower-case ASCII letters, digits, or underscores '
828
+ 'for maximum compatibility with other software '
829
+ '(got {0!r}).'.format(name), VerifyWarning)
830
+
831
+ # This ensures that the new name can fit into a single FITS card
832
+ # without any special extension like CONTINUE cards or the like.
833
+ if (not isinstance(name, str)
834
+ or len(str(Card('TTYPE', name))) != CARD_LENGTH):
835
+ raise AssertionError(
836
+ 'Column name must be a string able to fit in a single '
837
+ 'FITS card--typically this means a maximum of 68 '
838
+ 'characters, though it may be fewer if the string '
839
+ 'contains special characters like quotes.')
840
+
841
+ @ColumnAttribute('TCTYP')
842
+ def coord_type(col, coord_type):
843
+ if coord_type is None:
844
+ return
845
+
846
+ if (not isinstance(coord_type, str)
847
+ or len(coord_type) > 8):
848
+ raise AssertionError(
849
+ 'Coordinate/axis type must be a string of atmost 8 '
850
+ 'characters.')
851
+
852
+ @ColumnAttribute('TCUNI')
853
+ def coord_unit(col, coord_unit):
854
+ if (coord_unit is not None
855
+ and not isinstance(coord_unit, str)):
856
+ raise AssertionError(
857
+ 'Coordinate/axis unit must be a string.')
858
+
859
+ @ColumnAttribute('TCRPX')
860
+ def coord_ref_point(col, coord_ref_point):
861
+ if (coord_ref_point is not None
862
+ and not isinstance(coord_ref_point, numbers.Real)):
863
+ raise AssertionError(
864
+ 'Pixel coordinate of the reference point must be '
865
+ 'real floating type.')
866
+
867
+ @ColumnAttribute('TCRVL')
868
+ def coord_ref_value(col, coord_ref_value):
869
+ if (coord_ref_value is not None
870
+ and not isinstance(coord_ref_value, numbers.Real)):
871
+ raise AssertionError(
872
+ 'Coordinate value at reference point must be real '
873
+ 'floating type.')
874
+
875
+ @ColumnAttribute('TCDLT')
876
+ def coord_inc(col, coord_inc):
877
+ if (coord_inc is not None
878
+ and not isinstance(coord_inc, numbers.Real)):
879
+ raise AssertionError(
880
+ 'Coordinate increment must be real floating type.')
881
+
882
+ @ColumnAttribute('TRPOS')
883
+ def time_ref_pos(col, time_ref_pos):
884
+ if (time_ref_pos is not None
885
+ and not isinstance(time_ref_pos, str)):
886
+ raise AssertionError(
887
+ 'Time reference position must be a string.')
888
+
889
+ format = ColumnAttribute('TFORM')
890
+ unit = ColumnAttribute('TUNIT')
891
+ null = ColumnAttribute('TNULL')
892
+ bscale = ColumnAttribute('TSCAL')
893
+ bzero = ColumnAttribute('TZERO')
894
+ disp = ColumnAttribute('TDISP')
895
+ start = ColumnAttribute('TBCOL')
896
+ dim = ColumnAttribute('TDIM')
897
+
898
+ @lazyproperty
899
+ def ascii(self):
900
+ """Whether this `Column` represents a column in an ASCII table."""
901
+
902
+ return isinstance(self.format, _AsciiColumnFormat)
903
+
904
+ @lazyproperty
905
+ def dtype(self):
906
+ return self.format.dtype
907
+
908
+ def copy(self):
909
+ """
910
+ Return a copy of this `Column`.
911
+ """
912
+ tmp = Column(format='I') # just use a throw-away format
913
+ tmp.__dict__ = self.__dict__.copy()
914
+ return tmp
915
+
916
+ @staticmethod
917
+ def _convert_format(format, cls):
918
+ """The format argument to this class's initializer may come in many
919
+ forms. This uses the given column format class ``cls`` to convert
920
+ to a format of that type.
921
+
922
+ TODO: There should be an abc base class for column format classes
923
+ """
924
+
925
+ # Short circuit in case we're already a _BaseColumnFormat--there is at
926
+ # least one case in which this can happen
927
+ if isinstance(format, _BaseColumnFormat):
928
+ return format, format.recformat
929
+
930
+ if format in NUMPY2FITS:
931
+ with suppress(VerifyError):
932
+ # legit recarray format?
933
+ recformat = format
934
+ format = cls.from_recformat(format)
935
+
936
+ try:
937
+ # legit FITS format?
938
+ format = cls(format)
939
+ recformat = format.recformat
940
+ except VerifyError:
941
+ raise VerifyError('Illegal format `{}`.'.format(format))
942
+
943
+ return format, recformat
944
+
945
+ @classmethod
946
+ def _verify_keywords(cls, name=None, format=None, unit=None, null=None,
947
+ bscale=None, bzero=None, disp=None, start=None,
948
+ dim=None, ascii=None, coord_type=None, coord_unit=None,
949
+ coord_ref_point=None, coord_ref_value=None,
950
+ coord_inc=None, time_ref_pos=None):
951
+ """
952
+ Given the keyword arguments used to initialize a Column, specifically
953
+ those that typically read from a FITS header (so excluding array),
954
+ verify that each keyword has a valid value.
955
+
956
+ Returns a 2-tuple of dicts. The first maps valid keywords to their
957
+ values. The second maps invalid keywords to a 2-tuple of their value,
958
+ and a message explaining why they were found invalid.
959
+ """
960
+
961
+ valid = {}
962
+ invalid = {}
963
+
964
+ format, recformat = cls._determine_formats(format, start, dim, ascii)
965
+ valid.update(format=format, recformat=recformat)
966
+
967
+ # Currently we don't have any validation for name, unit, bscale, or
968
+ # bzero so include those by default
969
+ # TODO: Add validation for these keywords, obviously
970
+ for k, v in [('name', name), ('unit', unit), ('bscale', bscale),
971
+ ('bzero', bzero)]:
972
+ if v is not None and v != '':
973
+ valid[k] = v
974
+
975
+ # Validate null option
976
+ # Note: Enough code exists that thinks empty strings are sensible
977
+ # inputs for these options that we need to treat '' as None
978
+ if null is not None and null != '':
979
+ msg = None
980
+ if isinstance(format, _AsciiColumnFormat):
981
+ null = str(null)
982
+ if len(null) > format.width:
983
+ msg = (
984
+ "ASCII table null option (TNULLn) is longer than "
985
+ "the column's character width and will be truncated "
986
+ "(got {!r}).".format(null))
987
+ else:
988
+ tnull_formats = ('B', 'I', 'J', 'K')
989
+
990
+ if not _is_int(null):
991
+ # Make this an exception instead of a warning, since any
992
+ # non-int value is meaningless
993
+ msg = (
994
+ 'Column null option (TNULLn) must be an integer for '
995
+ 'binary table columns (got {!r}). The invalid value '
996
+ 'will be ignored for the purpose of formatting '
997
+ 'the data in this column.'.format(null))
998
+
999
+ elif not (format.format in tnull_formats or
1000
+ (format.format in ('P', 'Q') and
1001
+ format.p_format in tnull_formats)):
1002
+ # TODO: We should also check that TNULLn's integer value
1003
+ # is in the range allowed by the column's format
1004
+ msg = (
1005
+ 'Column null option (TNULLn) is invalid for binary '
1006
+ 'table columns of type {!r} (got {!r}). The invalid '
1007
+ 'value will be ignored for the purpose of formatting '
1008
+ 'the data in this column.'.format(format, null))
1009
+
1010
+ if msg is None:
1011
+ valid['null'] = null
1012
+ else:
1013
+ invalid['null'] = (null, msg)
1014
+
1015
+ # Validate the disp option
1016
+ # TODO: Add full parsing and validation of TDISPn keywords
1017
+ if disp is not None and disp != '':
1018
+ msg = None
1019
+ if not isinstance(disp, str):
1020
+ msg = (
1021
+ 'Column disp option (TDISPn) must be a string (got {!r}).'
1022
+ 'The invalid value will be ignored for the purpose of '
1023
+ 'formatting the data in this column.'.format(disp))
1024
+
1025
+ elif (isinstance(format, _AsciiColumnFormat) and
1026
+ disp[0].upper() == 'L'):
1027
+ # disp is at least one character long and has the 'L' format
1028
+ # which is not recognized for ASCII tables
1029
+ msg = (
1030
+ "Column disp option (TDISPn) may not use the 'L' format "
1031
+ "with ASCII table columns. The invalid value will be "
1032
+ "ignored for the purpose of formatting the data in this "
1033
+ "column.")
1034
+
1035
+ if msg is None:
1036
+ valid['disp'] = disp
1037
+ else:
1038
+ invalid['disp'] = (disp, msg)
1039
+
1040
+ # Validate the start option
1041
+ if start is not None and start != '':
1042
+ msg = None
1043
+ if not isinstance(format, _AsciiColumnFormat):
1044
+ # The 'start' option only applies to ASCII columns
1045
+ msg = (
1046
+ 'Column start option (TBCOLn) is not allowed for binary '
1047
+ 'table columns (got {!r}). The invalid keyword will be '
1048
+ 'ignored for the purpose of formatting the data in this '
1049
+ 'column.'.format(start))
1050
+ else:
1051
+ try:
1052
+ start = int(start)
1053
+ except (TypeError, ValueError):
1054
+ pass
1055
+
1056
+ if not _is_int(start) or start < 1:
1057
+ msg = (
1058
+ 'Column start option (TBCOLn) must be a positive integer '
1059
+ '(got {!r}). The invalid value will be ignored for the '
1060
+ 'purpose of formatting the data in this column.'.format(start))
1061
+
1062
+ if msg is None:
1063
+ valid['start'] = start
1064
+ else:
1065
+ invalid['start'] = (start, msg)
1066
+
1067
+ # Process TDIMn options
1068
+ # ASCII table columns can't have a TDIMn keyword associated with it;
1069
+ # for now we just issue a warning and ignore it.
1070
+ # TODO: This should be checked by the FITS verification code
1071
+ if dim is not None and dim != '':
1072
+ msg = None
1073
+ dims_tuple = tuple()
1074
+ # NOTE: If valid, the dim keyword's value in the the valid dict is
1075
+ # a tuple, not the original string; if invalid just the original
1076
+ # string is returned
1077
+ if isinstance(format, _AsciiColumnFormat):
1078
+ msg = (
1079
+ 'Column dim option (TDIMn) is not allowed for ASCII table '
1080
+ 'columns (got {!r}). The invalid keyword will be ignored '
1081
+ 'for the purpose of formatting this column.'.format(dim))
1082
+
1083
+ elif isinstance(dim, str):
1084
+ dims_tuple = _parse_tdim(dim)
1085
+ elif isinstance(dim, tuple):
1086
+ dims_tuple = dim
1087
+ else:
1088
+ msg = (
1089
+ "`dim` argument must be a string containing a valid value "
1090
+ "for the TDIMn header keyword associated with this column, "
1091
+ "or a tuple containing the C-order dimensions for the "
1092
+ "column. The invalid value will be ignored for the purpose "
1093
+ "of formatting this column.")
1094
+
1095
+ if dims_tuple:
1096
+ if reduce(operator.mul, dims_tuple) > format.repeat:
1097
+ msg = (
1098
+ "The repeat count of the column format {!r} for column {!r} "
1099
+ "is fewer than the number of elements per the TDIM "
1100
+ "argument {!r}. The invalid TDIMn value will be ignored "
1101
+ "for the purpose of formatting this column.".format(
1102
+ name, format, dim))
1103
+
1104
+ if msg is None:
1105
+ valid['dim'] = dims_tuple
1106
+ else:
1107
+ invalid['dim'] = (dim, msg)
1108
+
1109
+ if coord_type is not None and coord_type != '':
1110
+ msg = None
1111
+ if not isinstance(coord_type, str):
1112
+ msg = (
1113
+ "Coordinate/axis type option (TCTYPn) must be a string "
1114
+ "(got {!r}). The invalid keyword will be ignored for the "
1115
+ "purpose of formatting this column.".format(coord_type))
1116
+ elif len(coord_type) > 8:
1117
+ msg = (
1118
+ "Coordinate/axis type option (TCTYPn) must be a string "
1119
+ "of atmost 8 characters (got {!r}). The invalid keyword "
1120
+ "will be ignored for the purpose of formatting this "
1121
+ "column.".format(coord_type))
1122
+
1123
+ if msg is None:
1124
+ valid['coord_type'] = coord_type
1125
+ else:
1126
+ invalid['coord_type'] = (coord_type, msg)
1127
+
1128
+ if coord_unit is not None and coord_unit != '':
1129
+ msg = None
1130
+ if not isinstance(coord_unit, str):
1131
+ msg = (
1132
+ "Coordinate/axis unit option (TCUNIn) must be a string "
1133
+ "(got {!r}). The invalid keyword will be ignored for the "
1134
+ "purpose of formatting this column.".format(coord_unit))
1135
+
1136
+ if msg is None:
1137
+ valid['coord_unit'] = coord_unit
1138
+ else:
1139
+ invalid['coord_unit'] = (coord_unit, msg)
1140
+
1141
+ for k, v in [('coord_ref_point', coord_ref_point),
1142
+ ('coord_ref_value', coord_ref_value),
1143
+ ('coord_inc', coord_inc)]:
1144
+ if v is not None and v != '':
1145
+ msg = None
1146
+ if not isinstance(v, numbers.Real):
1147
+ msg = (
1148
+ "Column {} option ({}n) must be a real floating type (got {!r}). "
1149
+ "The invalid value will be ignored for the purpose of formatting "
1150
+ "the data in this column.".format(k, ATTRIBUTE_TO_KEYWORD[k], v))
1151
+
1152
+ if msg is None:
1153
+ valid[k] = v
1154
+ else:
1155
+ invalid[k] = (v, msg)
1156
+
1157
+ if time_ref_pos is not None and time_ref_pos != '':
1158
+ msg=None
1159
+ if not isinstance(time_ref_pos, str):
1160
+ msg = (
1161
+ "Time coordinate reference position option (TRPOSn) must be "
1162
+ "a string (got {!r}). The invalid keyword will be ignored for "
1163
+ "the purpose of formatting this column.".format(time_ref_pos))
1164
+
1165
+ if msg is None:
1166
+ valid['time_ref_pos'] = time_ref_pos
1167
+ else:
1168
+ invalid['time_ref_pos'] = (time_ref_pos, msg)
1169
+
1170
+ return valid, invalid
1171
+
1172
+ @classmethod
1173
+ def _determine_formats(cls, format, start, dim, ascii):
1174
+ """
1175
+ Given a format string and whether or not the Column is for an
1176
+ ASCII table (ascii=None means unspecified, but lean toward binary table
1177
+ where ambiguous) create an appropriate _BaseColumnFormat instance for
1178
+ the column's format, and determine the appropriate recarray format.
1179
+
1180
+ The values of the start and dim keyword arguments are also useful, as
1181
+ the former is only valid for ASCII tables and the latter only for
1182
+ BINARY tables.
1183
+ """
1184
+
1185
+ # If the given format string is unambiguously a Numpy dtype or one of
1186
+ # the Numpy record format type specifiers supported by Astropy then that
1187
+ # should take priority--otherwise assume it is a FITS format
1188
+ if isinstance(format, np.dtype):
1189
+ format, _, _ = _dtype_to_recformat(format)
1190
+
1191
+ # check format
1192
+ if ascii is None and not isinstance(format, _BaseColumnFormat):
1193
+ # We're just give a string which could be either a Numpy format
1194
+ # code, or a format for a binary column array *or* a format for an
1195
+ # ASCII column array--there may be many ambiguities here. Try our
1196
+ # best to guess what the user intended.
1197
+ format, recformat = cls._guess_format(format, start, dim)
1198
+ elif not ascii and not isinstance(format, _BaseColumnFormat):
1199
+ format, recformat = cls._convert_format(format, _ColumnFormat)
1200
+ elif ascii and not isinstance(format, _AsciiColumnFormat):
1201
+ format, recformat = cls._convert_format(format,
1202
+ _AsciiColumnFormat)
1203
+ else:
1204
+ # The format is already acceptable and unambiguous
1205
+ recformat = format.recformat
1206
+
1207
+ return format, recformat
1208
+
1209
+ @classmethod
1210
+ def _guess_format(cls, format, start, dim):
1211
+ if start and dim:
1212
+ # This is impossible; this can't be a valid FITS column
1213
+ raise ValueError(
1214
+ 'Columns cannot have both a start (TCOLn) and dim '
1215
+ '(TDIMn) option, since the former is only applies to '
1216
+ 'ASCII tables, and the latter is only valid for binary '
1217
+ 'tables.')
1218
+ elif start:
1219
+ # Only ASCII table columns can have a 'start' option
1220
+ guess_format = _AsciiColumnFormat
1221
+ elif dim:
1222
+ # Only binary tables can have a dim option
1223
+ guess_format = _ColumnFormat
1224
+ else:
1225
+ # If the format is *technically* a valid binary column format
1226
+ # (i.e. it has a valid format code followed by arbitrary
1227
+ # "optional" codes), but it is also strictly a valid ASCII
1228
+ # table format, then assume an ASCII table column was being
1229
+ # requested (the more likely case, after all).
1230
+ with suppress(VerifyError):
1231
+ format = _AsciiColumnFormat(format, strict=True)
1232
+
1233
+ # A safe guess which reflects the existing behavior of previous
1234
+ # Astropy versions
1235
+ guess_format = _ColumnFormat
1236
+
1237
+ try:
1238
+ format, recformat = cls._convert_format(format, guess_format)
1239
+ except VerifyError:
1240
+ # For whatever reason our guess was wrong (for example if we got
1241
+ # just 'F' that's not a valid binary format, but it an ASCII format
1242
+ # code albeit with the width/precision omitted
1243
+ guess_format = (_AsciiColumnFormat
1244
+ if guess_format is _ColumnFormat
1245
+ else _ColumnFormat)
1246
+ # If this fails too we're out of options--it is truly an invalid
1247
+ # format, or at least not supported
1248
+ format, recformat = cls._convert_format(format, guess_format)
1249
+
1250
+ return format, recformat
1251
+
1252
+ def _convert_to_valid_data_type(self, array):
1253
+ # Convert the format to a type we understand
1254
+ if isinstance(array, Delayed):
1255
+ return array
1256
+ elif array is None:
1257
+ return array
1258
+ else:
1259
+ format = self.format
1260
+ dims = self._dims
1261
+
1262
+ if dims:
1263
+ shape = dims[:-1] if 'A' in format else dims
1264
+ shape = (len(array),) + shape
1265
+ array = array.reshape(shape)
1266
+
1267
+ if 'P' in format or 'Q' in format:
1268
+ return array
1269
+ elif 'A' in format:
1270
+ if array.dtype.char in 'SU':
1271
+ if dims:
1272
+ # The 'last' dimension (first in the order given
1273
+ # in the TDIMn keyword itself) is the number of
1274
+ # characters in each string
1275
+ fsize = dims[-1]
1276
+ else:
1277
+ fsize = np.dtype(format.recformat).itemsize
1278
+ return chararray.array(array, itemsize=fsize, copy=False)
1279
+ else:
1280
+ return _convert_array(array, np.dtype(format.recformat))
1281
+ elif 'L' in format:
1282
+ # boolean needs to be scaled back to storage values ('T', 'F')
1283
+ if array.dtype == np.dtype('bool'):
1284
+ return np.where(array == np.False_, ord('F'), ord('T'))
1285
+ else:
1286
+ return np.where(array == 0, ord('F'), ord('T'))
1287
+ elif 'X' in format:
1288
+ return _convert_array(array, np.dtype('uint8'))
1289
+ else:
1290
+ # Preserve byte order of the original array for now; see #77
1291
+ numpy_format = array.dtype.byteorder + format.recformat
1292
+
1293
+ # Handle arrays passed in as unsigned ints as pseudo-unsigned
1294
+ # int arrays; blatantly tacked in here for now--we need columns
1295
+ # to have explicit knowledge of whether they treated as
1296
+ # pseudo-unsigned
1297
+ bzeros = {2: np.uint16(2**15), 4: np.uint32(2**31),
1298
+ 8: np.uint64(2**63)}
1299
+ if (array.dtype.kind == 'u' and
1300
+ array.dtype.itemsize in bzeros and
1301
+ self.bscale in (1, None, '') and
1302
+ self.bzero == bzeros[array.dtype.itemsize]):
1303
+ # Basically the array is uint, has scale == 1.0, and the
1304
+ # bzero is the appropriate value for a pseudo-unsigned
1305
+ # integer of the input dtype, then go ahead and assume that
1306
+ # uint is assumed
1307
+ numpy_format = numpy_format.replace('i', 'u')
1308
+ self._pseudo_unsigned_ints = True
1309
+
1310
+ # The .base here means we're dropping the shape information,
1311
+ # which is only used to format recarray fields, and is not
1312
+ # useful for converting input arrays to the correct data type
1313
+ dtype = np.dtype(numpy_format).base
1314
+
1315
+ return _convert_array(array, dtype)
1316
+
1317
+
1318
+ class ColDefs(NotifierMixin):
1319
+ """
1320
+ Column definitions class.
1321
+
1322
+ It has attributes corresponding to the `Column` attributes
1323
+ (e.g. `ColDefs` has the attribute ``names`` while `Column`
1324
+ has ``name``). Each attribute in `ColDefs` is a list of
1325
+ corresponding attribute values from all `Column` objects.
1326
+ """
1327
+
1328
+ _padding_byte = '\x00'
1329
+ _col_format_cls = _ColumnFormat
1330
+
1331
+ def __new__(cls, input, ascii=False):
1332
+ klass = cls
1333
+
1334
+ if (hasattr(input, '_columns_type') and
1335
+ issubclass(input._columns_type, ColDefs)):
1336
+ klass = input._columns_type
1337
+ elif (hasattr(input, '_col_format_cls') and
1338
+ issubclass(input._col_format_cls, _AsciiColumnFormat)):
1339
+ klass = _AsciiColDefs
1340
+
1341
+ if ascii: # force ASCII if this has been explicitly requested
1342
+ klass = _AsciiColDefs
1343
+
1344
+ return object.__new__(klass)
1345
+
1346
+ def __getnewargs__(self):
1347
+ return (self._arrays,)
1348
+
1349
+ def __init__(self, input, ascii=False):
1350
+ """
1351
+ Parameters
1352
+ ----------
1353
+
1354
+ input : sequence of `Column`, `ColDefs`, other
1355
+ An existing table HDU, an existing `ColDefs`, or any multi-field
1356
+ Numpy array or `numpy.recarray`.
1357
+
1358
+ ascii : bool
1359
+ Use True to ensure that ASCII table columns are used.
1360
+
1361
+ """
1362
+ from .hdu.table import _TableBaseHDU
1363
+ from .fitsrec import FITS_rec
1364
+
1365
+ if isinstance(input, ColDefs):
1366
+ self._init_from_coldefs(input)
1367
+ elif (isinstance(input, FITS_rec) and hasattr(input, '_coldefs') and
1368
+ input._coldefs):
1369
+ # If given a FITS_rec object we can directly copy its columns, but
1370
+ # only if its columns have already been defined, otherwise this
1371
+ # will loop back in on itself and blow up
1372
+ self._init_from_coldefs(input._coldefs)
1373
+ elif isinstance(input, np.ndarray) and input.dtype.fields is not None:
1374
+ # Construct columns from the fields of a record array
1375
+ self._init_from_array(input)
1376
+ elif isiterable(input):
1377
+ # if the input is a list of Columns
1378
+ self._init_from_sequence(input)
1379
+ elif isinstance(input, _TableBaseHDU):
1380
+ # Construct columns from fields in an HDU header
1381
+ self._init_from_table(input)
1382
+ else:
1383
+ raise TypeError('Input to ColDefs must be a table HDU, a list '
1384
+ 'of Columns, or a record/field array.')
1385
+
1386
+ # Listen for changes on all columns
1387
+ for col in self.columns:
1388
+ col._add_listener(self)
1389
+
1390
+ def _init_from_coldefs(self, coldefs):
1391
+ """Initialize from an existing ColDefs object (just copy the
1392
+ columns and convert their formats if necessary).
1393
+ """
1394
+
1395
+ self.columns = [self._copy_column(col) for col in coldefs]
1396
+
1397
+ def _init_from_sequence(self, columns):
1398
+ for idx, col in enumerate(columns):
1399
+ if not isinstance(col, Column):
1400
+ raise TypeError('Element {} in the ColDefs input is not a '
1401
+ 'Column.'.format(idx))
1402
+
1403
+ self._init_from_coldefs(columns)
1404
+
1405
+ def _init_from_array(self, array):
1406
+ self.columns = []
1407
+ for idx in range(len(array.dtype)):
1408
+ cname = array.dtype.names[idx]
1409
+ ftype = array.dtype.fields[cname][0]
1410
+ format = self._col_format_cls.from_recformat(ftype)
1411
+
1412
+ # Determine the appropriate dimensions for items in the column
1413
+ # (typically just 1D)
1414
+ dim = array.dtype[idx].shape[::-1]
1415
+ if dim and (len(dim) > 1 or 'A' in format):
1416
+ if 'A' in format:
1417
+ # n x m string arrays must include the max string
1418
+ # length in their dimensions (e.g. l x n x m)
1419
+ dim = (array.dtype[idx].base.itemsize,) + dim
1420
+ dim = repr(dim).replace(' ', '')
1421
+ else:
1422
+ dim = None
1423
+
1424
+ # Check for unsigned ints.
1425
+ bzero = None
1426
+ if ftype.base.kind == 'u':
1427
+ if 'I' in format:
1428
+ bzero = np.uint16(2**15)
1429
+ elif 'J' in format:
1430
+ bzero = np.uint32(2**31)
1431
+ elif 'K' in format:
1432
+ bzero = np.uint64(2**63)
1433
+
1434
+ c = Column(name=cname, format=format,
1435
+ array=array.view(np.ndarray)[cname], bzero=bzero,
1436
+ dim=dim)
1437
+ self.columns.append(c)
1438
+
1439
+ def _init_from_table(self, table):
1440
+ hdr = table._header
1441
+ nfields = hdr['TFIELDS']
1442
+
1443
+ # go through header keywords to pick out column definition keywords
1444
+ # definition dictionaries for each field
1445
+ col_keywords = [{} for i in range(nfields)]
1446
+ for keyword, value in hdr.items():
1447
+ key = TDEF_RE.match(keyword)
1448
+ try:
1449
+ keyword = key.group('label')
1450
+ except Exception:
1451
+ continue # skip if there is no match
1452
+ if keyword in KEYWORD_NAMES:
1453
+ col = int(key.group('num'))
1454
+ if 0 < col <= nfields:
1455
+ attr = KEYWORD_TO_ATTRIBUTE[keyword]
1456
+ if attr == 'format':
1457
+ # Go ahead and convert the format value to the
1458
+ # appropriate ColumnFormat container now
1459
+ value = self._col_format_cls(value)
1460
+ col_keywords[col - 1][attr] = value
1461
+
1462
+ # Verify the column keywords and display any warnings if necessary;
1463
+ # we only want to pass on the valid keywords
1464
+ for idx, kwargs in enumerate(col_keywords):
1465
+ valid_kwargs, invalid_kwargs = Column._verify_keywords(**kwargs)
1466
+ for val in invalid_kwargs.values():
1467
+ warnings.warn(
1468
+ 'Invalid keyword for column {}: {}'.format(idx + 1, val[1]),
1469
+ VerifyWarning)
1470
+ # Special cases for recformat and dim
1471
+ # TODO: Try to eliminate the need for these special cases
1472
+ del valid_kwargs['recformat']
1473
+ if 'dim' in valid_kwargs:
1474
+ valid_kwargs['dim'] = kwargs['dim']
1475
+ col_keywords[idx] = valid_kwargs
1476
+
1477
+ # data reading will be delayed
1478
+ for col in range(nfields):
1479
+ col_keywords[col]['array'] = Delayed(table, col)
1480
+
1481
+ # now build the columns
1482
+ self.columns = [Column(**attrs) for attrs in col_keywords]
1483
+
1484
+ # Add the table HDU is a listener to changes to the columns
1485
+ # (either changes to individual columns, or changes to the set of
1486
+ # columns (add/remove/etc.))
1487
+ self._add_listener(table)
1488
+
1489
+ def __copy__(self):
1490
+ return self.__class__(self)
1491
+
1492
+ def __deepcopy__(self, memo):
1493
+ return self.__class__([copy.deepcopy(c, memo) for c in self.columns])
1494
+
1495
+ def _copy_column(self, column):
1496
+ """Utility function used currently only by _init_from_coldefs
1497
+ to help convert columns from binary format to ASCII format or vice
1498
+ versa if necessary (otherwise performs a straight copy).
1499
+ """
1500
+
1501
+ if isinstance(column.format, self._col_format_cls):
1502
+ # This column has a FITS format compatible with this column
1503
+ # definitions class (that is ascii or binary)
1504
+ return column.copy()
1505
+
1506
+ new_column = column.copy()
1507
+
1508
+ # Try to use the Numpy recformat as the equivalency between the
1509
+ # two formats; if that conversion can't be made then these
1510
+ # columns can't be transferred
1511
+ # TODO: Catch exceptions here and raise an explicit error about
1512
+ # column format conversion
1513
+ new_column.format = self._col_format_cls.from_column_format(
1514
+ column.format)
1515
+
1516
+ # Handle a few special cases of column format options that are not
1517
+ # compatible between ASCII an binary tables
1518
+ # TODO: This is sort of hacked in right now; we really need
1519
+ # separate classes for ASCII and Binary table Columns, and they
1520
+ # should handle formatting issues like these
1521
+ if not isinstance(new_column.format, _AsciiColumnFormat):
1522
+ # the column is a binary table column...
1523
+ new_column.start = None
1524
+ if new_column.null is not None:
1525
+ # We can't just "guess" a value to represent null
1526
+ # values in the new column, so just disable this for
1527
+ # now; users may modify it later
1528
+ new_column.null = None
1529
+ else:
1530
+ # the column is an ASCII table column...
1531
+ if new_column.null is not None:
1532
+ new_column.null = DEFAULT_ASCII_TNULL
1533
+ if (new_column.disp is not None and
1534
+ new_column.disp.upper().startswith('L')):
1535
+ # ASCII columns may not use the logical data display format;
1536
+ # for now just drop the TDISPn option for this column as we
1537
+ # don't have a systematic conversion of boolean data to ASCII
1538
+ # tables yet
1539
+ new_column.disp = None
1540
+
1541
+ return new_column
1542
+
1543
+ def __getattr__(self, name):
1544
+ """
1545
+ Automatically returns the values for the given keyword attribute for
1546
+ all `Column`s in this list.
1547
+
1548
+ Implements for example self.units, self.formats, etc.
1549
+ """
1550
+ cname = name[:-1]
1551
+ if cname in KEYWORD_ATTRIBUTES and name[-1] == 's':
1552
+ attr = []
1553
+ for col in self.columns:
1554
+ val = getattr(col, cname)
1555
+ attr.append(val if val is not None else '')
1556
+ return attr
1557
+ raise AttributeError(name)
1558
+
1559
+ @lazyproperty
1560
+ def dtype(self):
1561
+ # Note: This previously returned a dtype that just used the raw field
1562
+ # widths based on the format's repeat count, and did not incorporate
1563
+ # field *shapes* as provided by TDIMn keywords.
1564
+ # Now this incorporates TDIMn from the start, which makes *this* method
1565
+ # a little more complicated, but simplifies code elsewhere (for example
1566
+ # fields will have the correct shapes even in the raw recarray).
1567
+ formats = []
1568
+ offsets = [0]
1569
+
1570
+ for format_, dim in zip(self.formats, self._dims):
1571
+ dt = format_.dtype
1572
+
1573
+ if len(offsets) < len(self.formats):
1574
+ # Note: the size of the *original* format_ may be greater than
1575
+ # one would expect from the number of elements determined by
1576
+ # dim. The FITS format allows this--the rest of the field is
1577
+ # filled with undefined values.
1578
+ offsets.append(offsets[-1] + dt.itemsize)
1579
+
1580
+ if dim:
1581
+ if format_.format == 'A':
1582
+ dt = np.dtype((dt.char + str(dim[-1]), dim[:-1]))
1583
+ else:
1584
+ dt = np.dtype((dt.base, dim))
1585
+
1586
+ formats.append(dt)
1587
+
1588
+ return np.dtype({'names': self.names,
1589
+ 'formats': formats,
1590
+ 'offsets': offsets})
1591
+
1592
+ @lazyproperty
1593
+ def names(self):
1594
+ return [col.name for col in self.columns]
1595
+
1596
+ @lazyproperty
1597
+ def formats(self):
1598
+ return [col.format for col in self.columns]
1599
+
1600
+ @lazyproperty
1601
+ def _arrays(self):
1602
+ return [col.array for col in self.columns]
1603
+
1604
+ @lazyproperty
1605
+ def _recformats(self):
1606
+ return [fmt.recformat for fmt in self.formats]
1607
+
1608
+ @lazyproperty
1609
+ def _dims(self):
1610
+ """Returns the values of the TDIMn keywords parsed into tuples."""
1611
+
1612
+ return [col._dims for col in self.columns]
1613
+
1614
+ def __getitem__(self, key):
1615
+ if isinstance(key, str):
1616
+ key = _get_index(self.names, key)
1617
+
1618
+ x = self.columns[key]
1619
+ if _is_int(key):
1620
+ return x
1621
+ else:
1622
+ return ColDefs(x)
1623
+
1624
+ def __len__(self):
1625
+ return len(self.columns)
1626
+
1627
+ def __repr__(self):
1628
+ rep = 'ColDefs('
1629
+ if hasattr(self, 'columns') and self.columns:
1630
+ # The hasattr check is mostly just useful in debugging sessions
1631
+ # where self.columns may not be defined yet
1632
+ rep += '\n '
1633
+ rep += '\n '.join([repr(c) for c in self.columns])
1634
+ rep += '\n'
1635
+ rep += ')'
1636
+ return rep
1637
+
1638
+ def __add__(self, other, option='left'):
1639
+ if isinstance(other, Column):
1640
+ b = [other]
1641
+ elif isinstance(other, ColDefs):
1642
+ b = list(other.columns)
1643
+ else:
1644
+ raise TypeError('Wrong type of input.')
1645
+ if option == 'left':
1646
+ tmp = list(self.columns) + b
1647
+ else:
1648
+ tmp = b + list(self.columns)
1649
+ return ColDefs(tmp)
1650
+
1651
+ def __radd__(self, other):
1652
+ return self.__add__(other, 'right')
1653
+
1654
+ def __sub__(self, other):
1655
+ if not isinstance(other, (list, tuple)):
1656
+ other = [other]
1657
+ _other = [_get_index(self.names, key) for key in other]
1658
+ indx = list(range(len(self)))
1659
+ for x in _other:
1660
+ indx.remove(x)
1661
+ tmp = [self[i] for i in indx]
1662
+ return ColDefs(tmp)
1663
+
1664
+ def _update_column_attribute_changed(self, column, attr, old_value,
1665
+ new_value):
1666
+ """
1667
+ Handle column attribute changed notifications from columns that are
1668
+ members of this `ColDefs`.
1669
+
1670
+ `ColDefs` itself does not currently do anything with this, and just
1671
+ bubbles the notification up to any listening table HDUs that may need
1672
+ to update their headers, etc. However, this also informs the table of
1673
+ the numerical index of the column that changed.
1674
+ """
1675
+
1676
+ idx = 0
1677
+ for idx, col in enumerate(self.columns):
1678
+ if col is column:
1679
+ break
1680
+
1681
+ if attr == 'name':
1682
+ del self.names
1683
+ elif attr == 'format':
1684
+ del self.formats
1685
+
1686
+ self._notify('column_attribute_changed', column, idx, attr, old_value,
1687
+ new_value)
1688
+
1689
+ def add_col(self, column):
1690
+ """
1691
+ Append one `Column` to the column definition.
1692
+ """
1693
+
1694
+ if not isinstance(column, Column):
1695
+ raise AssertionError
1696
+
1697
+ self._arrays.append(column.array)
1698
+ # Obliterate caches of certain things
1699
+ del self.dtype
1700
+ del self._recformats
1701
+ del self._dims
1702
+ del self.names
1703
+ del self.formats
1704
+
1705
+ self.columns.append(column)
1706
+
1707
+ # Listen for changes on the new column
1708
+ column._add_listener(self)
1709
+
1710
+ # If this ColDefs is being tracked by a Table, inform the
1711
+ # table that its data is now invalid.
1712
+ self._notify('column_added', self, column)
1713
+ return self
1714
+
1715
+ def del_col(self, col_name):
1716
+ """
1717
+ Delete (the definition of) one `Column`.
1718
+
1719
+ col_name : str or int
1720
+ The column's name or index
1721
+ """
1722
+
1723
+ indx = _get_index(self.names, col_name)
1724
+ col = self.columns[indx]
1725
+
1726
+ del self._arrays[indx]
1727
+ # Obliterate caches of certain things
1728
+ del self.dtype
1729
+ del self._recformats
1730
+ del self._dims
1731
+ del self.names
1732
+ del self.formats
1733
+
1734
+ del self.columns[indx]
1735
+
1736
+ col._remove_listener(self)
1737
+
1738
+ # If this ColDefs is being tracked by a table HDU, inform the HDU (or
1739
+ # any other listeners) that the column has been removed
1740
+ # Just send a reference to self, and the index of the column that was
1741
+ # removed
1742
+ self._notify('column_removed', self, indx)
1743
+ return self
1744
+
1745
+ def change_attrib(self, col_name, attrib, new_value):
1746
+ """
1747
+ Change an attribute (in the ``KEYWORD_ATTRIBUTES`` list) of a `Column`.
1748
+
1749
+ Parameters
1750
+ ----------
1751
+ col_name : str or int
1752
+ The column name or index to change
1753
+
1754
+ attrib : str
1755
+ The attribute name
1756
+
1757
+ new_value : object
1758
+ The new value for the attribute
1759
+ """
1760
+
1761
+ setattr(self[col_name], attrib, new_value)
1762
+
1763
+ def change_name(self, col_name, new_name):
1764
+ """
1765
+ Change a `Column`'s name.
1766
+
1767
+ Parameters
1768
+ ----------
1769
+ col_name : str
1770
+ The current name of the column
1771
+
1772
+ new_name : str
1773
+ The new name of the column
1774
+ """
1775
+
1776
+ if new_name != col_name and new_name in self.names:
1777
+ raise ValueError('New name {} already exists.'.format(new_name))
1778
+ else:
1779
+ self.change_attrib(col_name, 'name', new_name)
1780
+
1781
+ def change_unit(self, col_name, new_unit):
1782
+ """
1783
+ Change a `Column`'s unit.
1784
+
1785
+ Parameters
1786
+ ----------
1787
+ col_name : str or int
1788
+ The column name or index
1789
+
1790
+ new_unit : str
1791
+ The new unit for the column
1792
+ """
1793
+
1794
+ self.change_attrib(col_name, 'unit', new_unit)
1795
+
1796
+ def info(self, attrib='all', output=None):
1797
+ """
1798
+ Get attribute(s) information of the column definition.
1799
+
1800
+ Parameters
1801
+ ----------
1802
+ attrib : str
1803
+ Can be one or more of the attributes listed in
1804
+ ``astropy.io.fits.column.KEYWORD_ATTRIBUTES``. The default is
1805
+ ``"all"`` which will print out all attributes. It forgives plurals
1806
+ and blanks. If there are two or more attribute names, they must be
1807
+ separated by comma(s).
1808
+
1809
+ output : file, optional
1810
+ File-like object to output to. Outputs to stdout by default.
1811
+ If `False`, returns the attributes as a `dict` instead.
1812
+
1813
+ Notes
1814
+ -----
1815
+ This function doesn't return anything by default; it just prints to
1816
+ stdout.
1817
+ """
1818
+
1819
+ if output is None:
1820
+ output = sys.stdout
1821
+
1822
+ if attrib.strip().lower() in ['all', '']:
1823
+ lst = KEYWORD_ATTRIBUTES
1824
+ else:
1825
+ lst = attrib.split(',')
1826
+ for idx in range(len(lst)):
1827
+ lst[idx] = lst[idx].strip().lower()
1828
+ if lst[idx][-1] == 's':
1829
+ lst[idx] = list[idx][:-1]
1830
+
1831
+ ret = {}
1832
+
1833
+ for attr in lst:
1834
+ if output:
1835
+ if attr not in KEYWORD_ATTRIBUTES:
1836
+ output.write("'{}' is not an attribute of the column "
1837
+ "definitions.\n".format(attr))
1838
+ continue
1839
+ output.write("{}:\n".format(attr))
1840
+ output.write(' {}\n'.format(getattr(self, attr + 's')))
1841
+ else:
1842
+ ret[attr] = getattr(self, attr + 's')
1843
+
1844
+ if not output:
1845
+ return ret
1846
+
1847
+
1848
+ class _AsciiColDefs(ColDefs):
1849
+ """ColDefs implementation for ASCII tables."""
1850
+
1851
+ _padding_byte = ' '
1852
+ _col_format_cls = _AsciiColumnFormat
1853
+
1854
+ def __init__(self, input, ascii=True):
1855
+ super().__init__(input)
1856
+
1857
+ # if the format of an ASCII column has no width, add one
1858
+ if not isinstance(input, _AsciiColDefs):
1859
+ self._update_field_metrics()
1860
+ else:
1861
+ for idx, s in enumerate(input.starts):
1862
+ self.columns[idx].start = s
1863
+
1864
+ self._spans = input.spans
1865
+ self._width = input._width
1866
+
1867
+ @lazyproperty
1868
+ def dtype(self):
1869
+ dtype = {}
1870
+
1871
+ for j in range(len(self)):
1872
+ data_type = 'S' + str(self.spans[j])
1873
+ dtype[self.names[j]] = (data_type, self.starts[j] - 1)
1874
+
1875
+ return np.dtype(dtype)
1876
+
1877
+ @property
1878
+ def spans(self):
1879
+ """A list of the widths of each field in the table."""
1880
+
1881
+ return self._spans
1882
+
1883
+ @lazyproperty
1884
+ def _recformats(self):
1885
+ if len(self) == 1:
1886
+ widths = []
1887
+ else:
1888
+ widths = [y - x for x, y in pairwise(self.starts)]
1889
+
1890
+ # Widths is the width of each field *including* any space between
1891
+ # fields; this is so that we can map the fields to string records in a
1892
+ # Numpy recarray
1893
+ widths.append(self._width - self.starts[-1] + 1)
1894
+ return ['a' + str(w) for w in widths]
1895
+
1896
+ def add_col(self, column):
1897
+ super().add_col(column)
1898
+ self._update_field_metrics()
1899
+
1900
+ def del_col(self, col_name):
1901
+ super().del_col(col_name)
1902
+ self._update_field_metrics()
1903
+
1904
+ def _update_field_metrics(self):
1905
+ """
1906
+ Updates the list of the start columns, the list of the widths of each
1907
+ field, and the total width of each record in the table.
1908
+ """
1909
+
1910
+ spans = [0] * len(self.columns)
1911
+ end_col = 0 # Refers to the ASCII text column, not the table col
1912
+ for idx, col in enumerate(self.columns):
1913
+ width = col.format.width
1914
+
1915
+ # Update the start columns and column span widths taking into
1916
+ # account the case that the starting column of a field may not
1917
+ # be the column immediately after the previous field
1918
+ if not col.start:
1919
+ col.start = end_col + 1
1920
+ end_col = col.start + width - 1
1921
+ spans[idx] = width
1922
+
1923
+ self._spans = spans
1924
+ self._width = end_col
1925
+
1926
+
1927
+ # Utilities
1928
+
1929
+
1930
+ class _VLF(np.ndarray):
1931
+ """Variable length field object."""
1932
+
1933
+ def __new__(cls, input, dtype='a'):
1934
+ """
1935
+ Parameters
1936
+ ----------
1937
+ input
1938
+ a sequence of variable-sized elements.
1939
+ """
1940
+
1941
+ if dtype == 'a':
1942
+ try:
1943
+ # this handles ['abc'] and [['a','b','c']]
1944
+ # equally, beautiful!
1945
+ input = [chararray.array(x, itemsize=1) for x in input]
1946
+ except Exception:
1947
+ raise ValueError(
1948
+ 'Inconsistent input data array: {0}'.format(input))
1949
+
1950
+ a = np.array(input, dtype=object)
1951
+ self = np.ndarray.__new__(cls, shape=(len(input),), buffer=a,
1952
+ dtype=object)
1953
+ self.max = 0
1954
+ self.element_dtype = dtype
1955
+ return self
1956
+
1957
+ def __array_finalize__(self, obj):
1958
+ if obj is None:
1959
+ return
1960
+ self.max = obj.max
1961
+ self.element_dtype = obj.element_dtype
1962
+
1963
+ def __setitem__(self, key, value):
1964
+ """
1965
+ To make sure the new item has consistent data type to avoid
1966
+ misalignment.
1967
+ """
1968
+
1969
+ if isinstance(value, np.ndarray) and value.dtype == self.dtype:
1970
+ pass
1971
+ elif isinstance(value, chararray.chararray) and value.itemsize == 1:
1972
+ pass
1973
+ elif self.element_dtype == 'a':
1974
+ value = chararray.array(value, itemsize=1)
1975
+ else:
1976
+ value = np.array(value, dtype=self.element_dtype)
1977
+ np.ndarray.__setitem__(self, key, value)
1978
+ self.max = max(self.max, len(value))
1979
+
1980
+
1981
+ def _get_index(names, key):
1982
+ """
1983
+ Get the index of the ``key`` in the ``names`` list.
1984
+
1985
+ The ``key`` can be an integer or string. If integer, it is the index
1986
+ in the list. If string,
1987
+
1988
+ a. Field (column) names are case sensitive: you can have two
1989
+ different columns called 'abc' and 'ABC' respectively.
1990
+
1991
+ b. When you *refer* to a field (presumably with the field
1992
+ method), it will try to match the exact name first, so in
1993
+ the example in (a), field('abc') will get the first field,
1994
+ and field('ABC') will get the second field.
1995
+
1996
+ If there is no exact name matched, it will try to match the
1997
+ name with case insensitivity. So, in the last example,
1998
+ field('Abc') will cause an exception since there is no unique
1999
+ mapping. If there is a field named "XYZ" and no other field
2000
+ name is a case variant of "XYZ", then field('xyz'),
2001
+ field('Xyz'), etc. will get this field.
2002
+ """
2003
+
2004
+ if _is_int(key):
2005
+ indx = int(key)
2006
+ elif isinstance(key, str):
2007
+ # try to find exact match first
2008
+ try:
2009
+ indx = names.index(key.rstrip())
2010
+ except ValueError:
2011
+ # try to match case-insentively,
2012
+ _key = key.lower().rstrip()
2013
+ names = [n.lower().rstrip() for n in names]
2014
+ count = names.count(_key) # occurrence of _key in names
2015
+ if count == 1:
2016
+ indx = names.index(_key)
2017
+ elif count == 0:
2018
+ raise KeyError("Key '{}' does not exist.".format(key))
2019
+ else: # multiple match
2020
+ raise KeyError("Ambiguous key name '{}'.".format(key))
2021
+ else:
2022
+ raise KeyError("Illegal key '{!r}'.".format(key))
2023
+
2024
+ return indx
2025
+
2026
+
2027
+ def _unwrapx(input, output, repeat):
2028
+ """
2029
+ Unwrap the X format column into a Boolean array.
2030
+
2031
+ Parameters
2032
+ ----------
2033
+ input
2034
+ input ``Uint8`` array of shape (`s`, `nbytes`)
2035
+
2036
+ output
2037
+ output Boolean array of shape (`s`, `repeat`)
2038
+
2039
+ repeat
2040
+ number of bits
2041
+ """
2042
+
2043
+ pow2 = np.array([128, 64, 32, 16, 8, 4, 2, 1], dtype='uint8')
2044
+ nbytes = ((repeat - 1) // 8) + 1
2045
+ for i in range(nbytes):
2046
+ _min = i * 8
2047
+ _max = min((i + 1) * 8, repeat)
2048
+ for j in range(_min, _max):
2049
+ output[..., j] = np.bitwise_and(input[..., i], pow2[j - i * 8])
2050
+
2051
+
2052
+ def _wrapx(input, output, repeat):
2053
+ """
2054
+ Wrap the X format column Boolean array into an ``UInt8`` array.
2055
+
2056
+ Parameters
2057
+ ----------
2058
+ input
2059
+ input Boolean array of shape (`s`, `repeat`)
2060
+
2061
+ output
2062
+ output ``Uint8`` array of shape (`s`, `nbytes`)
2063
+
2064
+ repeat
2065
+ number of bits
2066
+ """
2067
+
2068
+ output[...] = 0 # reset the output
2069
+ nbytes = ((repeat - 1) // 8) + 1
2070
+ unused = nbytes * 8 - repeat
2071
+ for i in range(nbytes):
2072
+ _min = i * 8
2073
+ _max = min((i + 1) * 8, repeat)
2074
+ for j in range(_min, _max):
2075
+ if j != _min:
2076
+ np.left_shift(output[..., i], 1, output[..., i])
2077
+ np.add(output[..., i], input[..., j], output[..., i])
2078
+
2079
+ # shift the unused bits
2080
+ np.left_shift(output[..., i], unused, output[..., i])
2081
+
2082
+
2083
+ def _makep(array, descr_output, format, nrows=None):
2084
+ """
2085
+ Construct the P (or Q) format column array, both the data descriptors and
2086
+ the data. It returns the output "data" array of data type `dtype`.
2087
+
2088
+ The descriptor location will have a zero offset for all columns
2089
+ after this call. The final offset will be calculated when the file
2090
+ is written.
2091
+
2092
+ Parameters
2093
+ ----------
2094
+ array
2095
+ input object array
2096
+
2097
+ descr_output
2098
+ output "descriptor" array of data type int32 (for P format arrays) or
2099
+ int64 (for Q format arrays)--must be nrows long in its first dimension
2100
+
2101
+ format
2102
+ the _FormatP object representing the format of the variable array
2103
+
2104
+ nrows : int, optional
2105
+ number of rows to create in the column; defaults to the number of rows
2106
+ in the input array
2107
+ """
2108
+
2109
+ # TODO: A great deal of this is redundant with FITS_rec._convert_p; see if
2110
+ # we can merge the two somehow.
2111
+
2112
+ _offset = 0
2113
+
2114
+ if not nrows:
2115
+ nrows = len(array)
2116
+
2117
+ data_output = _VLF([None] * nrows, dtype=format.dtype)
2118
+
2119
+ if format.dtype == 'a':
2120
+ _nbytes = 1
2121
+ else:
2122
+ _nbytes = np.array([], dtype=format.dtype).itemsize
2123
+
2124
+ for idx in range(nrows):
2125
+ if idx < len(array):
2126
+ rowval = array[idx]
2127
+ else:
2128
+ if format.dtype == 'a':
2129
+ rowval = ' ' * data_output.max
2130
+ else:
2131
+ rowval = [0] * data_output.max
2132
+ if format.dtype == 'a':
2133
+ data_output[idx] = chararray.array(encode_ascii(rowval),
2134
+ itemsize=1)
2135
+ else:
2136
+ data_output[idx] = np.array(rowval, dtype=format.dtype)
2137
+
2138
+ descr_output[idx, 0] = len(data_output[idx])
2139
+ descr_output[idx, 1] = _offset
2140
+ _offset += len(data_output[idx]) * _nbytes
2141
+
2142
+ return data_output
2143
+
2144
+
2145
+ def _parse_tformat(tform):
2146
+ """Parse ``TFORMn`` keyword for a binary table into a
2147
+ ``(repeat, format, option)`` tuple.
2148
+ """
2149
+
2150
+ try:
2151
+ (repeat, format, option) = TFORMAT_RE.match(tform.strip()).groups()
2152
+ except Exception:
2153
+ # TODO: Maybe catch this error use a default type (bytes, maybe?) for
2154
+ # unrecognized column types. As long as we can determine the correct
2155
+ # byte width somehow..
2156
+ raise VerifyError('Format {!r} is not recognized.'.format(tform))
2157
+
2158
+ if repeat == '':
2159
+ repeat = 1
2160
+ else:
2161
+ repeat = int(repeat)
2162
+
2163
+ return (repeat, format.upper(), option)
2164
+
2165
+
2166
+ def _parse_ascii_tformat(tform, strict=False):
2167
+ """
2168
+ Parse the ``TFORMn`` keywords for ASCII tables into a ``(format, width,
2169
+ precision)`` tuple (the latter is always zero unless format is one of 'E',
2170
+ 'F', or 'D').
2171
+ """
2172
+
2173
+ match = TFORMAT_ASCII_RE.match(tform.strip())
2174
+ if not match:
2175
+ raise VerifyError('Format {!r} is not recognized.'.format(tform))
2176
+
2177
+ # Be flexible on case
2178
+ format = match.group('format')
2179
+ if format is None:
2180
+ # Floating point format
2181
+ format = match.group('formatf').upper()
2182
+ width = match.group('widthf')
2183
+ precision = match.group('precision')
2184
+ if width is None or precision is None:
2185
+ if strict:
2186
+ raise VerifyError('Format {!r} is not unambiguously an ASCII '
2187
+ 'table format.')
2188
+ else:
2189
+ width = 0 if width is None else width
2190
+ precision = 1 if precision is None else precision
2191
+ else:
2192
+ format = format.upper()
2193
+ width = match.group('width')
2194
+ if width is None:
2195
+ if strict:
2196
+ raise VerifyError('Format {!r} is not unambiguously an ASCII '
2197
+ 'table format.')
2198
+ else:
2199
+ # Just use a default width of 0 if unspecified
2200
+ width = 0
2201
+ precision = 0
2202
+
2203
+ def convert_int(val):
2204
+ msg = ('Format {!r} is not valid--field width and decimal precision '
2205
+ 'must be integers.')
2206
+ try:
2207
+ val = int(val)
2208
+ except (ValueError, TypeError):
2209
+ raise VerifyError(msg.format(tform))
2210
+
2211
+ return val
2212
+
2213
+ if width and precision:
2214
+ # This should only be the case for floating-point formats
2215
+ width, precision = convert_int(width), convert_int(precision)
2216
+ elif width:
2217
+ # Just for integer/string formats; ignore precision
2218
+ width = convert_int(width)
2219
+ else:
2220
+ # For any format, if width was unspecified use the set defaults
2221
+ width, precision = ASCII_DEFAULT_WIDTHS[format]
2222
+
2223
+ if width <= 0:
2224
+ raise VerifyError("Format {!r} not valid--field width must be a "
2225
+ "positive integeter.".format(tform))
2226
+
2227
+ if precision >= width:
2228
+ raise VerifyError("Format {!r} not valid--the number of decimal digits "
2229
+ "must be less than the format's total "
2230
+ "width {}.".format(tform, width))
2231
+
2232
+ return format, width, precision
2233
+
2234
+
2235
+ def _parse_tdim(tdim):
2236
+ """Parse the ``TDIM`` value into a tuple (may return an empty tuple if
2237
+ the value ``TDIM`` value is empty or invalid).
2238
+ """
2239
+
2240
+ m = tdim and TDIM_RE.match(tdim)
2241
+ if m:
2242
+ dims = m.group('dims')
2243
+ return tuple(int(d.strip()) for d in dims.split(','))[::-1]
2244
+
2245
+ # Ignore any dim values that don't specify a multidimensional column
2246
+ return tuple()
2247
+
2248
+
2249
+ def _scalar_to_format(value):
2250
+ """
2251
+ Given a scalar value or string, returns the minimum FITS column format
2252
+ that can represent that value. 'minimum' is defined by the order given in
2253
+ FORMATORDER.
2254
+ """
2255
+
2256
+ # First, if value is a string, try to convert to the appropriate scalar
2257
+ # value
2258
+ for type_ in (int, float, complex):
2259
+ try:
2260
+ value = type_(value)
2261
+ break
2262
+ except ValueError:
2263
+ continue
2264
+
2265
+ numpy_dtype_str = np.min_scalar_type(value).str
2266
+ numpy_dtype_str = numpy_dtype_str[1:] # Strip endianness
2267
+
2268
+ try:
2269
+ fits_format = NUMPY2FITS[numpy_dtype_str]
2270
+ return FITSUPCONVERTERS.get(fits_format, fits_format)
2271
+ except KeyError:
2272
+ return "A" + str(len(value))
2273
+
2274
+
2275
+ def _cmp_recformats(f1, f2):
2276
+ """
2277
+ Compares two numpy recformats using the ordering given by FORMATORDER.
2278
+ """
2279
+
2280
+ if f1[0] == 'a' and f2[0] == 'a':
2281
+ return cmp(int(f1[1:]), int(f2[1:]))
2282
+ else:
2283
+ f1, f2 = NUMPY2FITS[f1], NUMPY2FITS[f2]
2284
+ return cmp(FORMATORDER.index(f1), FORMATORDER.index(f2))
2285
+
2286
+
2287
+ def _convert_fits2record(format):
2288
+ """
2289
+ Convert FITS format spec to record format spec.
2290
+ """
2291
+
2292
+ repeat, dtype, option = _parse_tformat(format)
2293
+
2294
+ if dtype in FITS2NUMPY:
2295
+ if dtype == 'A':
2296
+ output_format = FITS2NUMPY[dtype] + str(repeat)
2297
+ # to accommodate both the ASCII table and binary table column
2298
+ # format spec, i.e. A7 in ASCII table is the same as 7A in
2299
+ # binary table, so both will produce 'a7'.
2300
+ # Technically the FITS standard does not allow this but it's a very
2301
+ # common mistake
2302
+ if format.lstrip()[0] == 'A' and option != '':
2303
+ # make sure option is integer
2304
+ output_format = FITS2NUMPY[dtype] + str(int(option))
2305
+ else:
2306
+ repeat_str = ''
2307
+ if repeat != 1:
2308
+ repeat_str = str(repeat)
2309
+ output_format = repeat_str + FITS2NUMPY[dtype]
2310
+
2311
+ elif dtype == 'X':
2312
+ output_format = _FormatX(repeat)
2313
+ elif dtype == 'P':
2314
+ output_format = _FormatP.from_tform(format)
2315
+ elif dtype == 'Q':
2316
+ output_format = _FormatQ.from_tform(format)
2317
+ elif dtype == 'F':
2318
+ output_format = 'f8'
2319
+ else:
2320
+ raise ValueError('Illegal format `{}`.'.format(format))
2321
+
2322
+ return output_format
2323
+
2324
+
2325
+ def _convert_record2fits(format):
2326
+ """
2327
+ Convert record format spec to FITS format spec.
2328
+ """
2329
+
2330
+ recformat, kind, dtype = _dtype_to_recformat(format)
2331
+ shape = dtype.shape
2332
+ itemsize = dtype.base.itemsize
2333
+ if dtype.char == 'U':
2334
+ # Unicode dtype--itemsize is 4 times actual ASCII character length,
2335
+ # which what matters for FITS column formats
2336
+ # Use dtype.base--dtype may be a multi-dimensional dtype
2337
+ itemsize = itemsize // 4
2338
+
2339
+ option = str(itemsize)
2340
+
2341
+ ndims = len(shape)
2342
+ repeat = 1
2343
+ if ndims > 0:
2344
+ nel = np.array(shape, dtype='i8').prod()
2345
+ if nel > 1:
2346
+ repeat = nel
2347
+
2348
+ if kind == 'a':
2349
+ # This is a kludge that will place string arrays into a
2350
+ # single field, so at least we won't lose data. Need to
2351
+ # use a TDIM keyword to fix this, declaring as (slength,
2352
+ # dim1, dim2, ...) as mwrfits does
2353
+
2354
+ ntot = int(repeat) * int(option)
2355
+
2356
+ output_format = str(ntot) + 'A'
2357
+ elif recformat in NUMPY2FITS: # record format
2358
+ if repeat != 1:
2359
+ repeat = str(repeat)
2360
+ else:
2361
+ repeat = ''
2362
+ output_format = repeat + NUMPY2FITS[recformat]
2363
+ else:
2364
+ raise ValueError('Illegal format `{}`.'.format(format))
2365
+
2366
+ return output_format
2367
+
2368
+
2369
+ def _dtype_to_recformat(dtype):
2370
+ """
2371
+ Utility function for converting a dtype object or string that instantiates
2372
+ a dtype (e.g. 'float32') into one of the two character Numpy format codes
2373
+ that have been traditionally used by Astropy.
2374
+
2375
+ In particular, use of 'a' to refer to character data is long since
2376
+ deprecated in Numpy, but Astropy remains heavily invested in its use
2377
+ (something to try to get away from sooner rather than later).
2378
+ """
2379
+
2380
+ if not isinstance(dtype, np.dtype):
2381
+ dtype = np.dtype(dtype)
2382
+
2383
+ kind = dtype.base.kind
2384
+
2385
+ if kind in ('U', 'S'):
2386
+ recformat = kind = 'a'
2387
+ else:
2388
+ itemsize = dtype.base.itemsize
2389
+ recformat = kind + str(itemsize)
2390
+
2391
+ return recformat, kind, dtype
2392
+
2393
+
2394
+ def _convert_format(format, reverse=False):
2395
+ """
2396
+ Convert FITS format spec to record format spec. Do the opposite if
2397
+ reverse=True.
2398
+ """
2399
+
2400
+ if reverse:
2401
+ return _convert_record2fits(format)
2402
+ else:
2403
+ return _convert_fits2record(format)
2404
+
2405
+
2406
+ def _convert_ascii_format(format, reverse=False):
2407
+ """Convert ASCII table format spec to record format spec."""
2408
+
2409
+ if reverse:
2410
+ recformat, kind, dtype = _dtype_to_recformat(format)
2411
+ itemsize = dtype.itemsize
2412
+
2413
+ if kind == 'a':
2414
+ return 'A' + str(itemsize)
2415
+ elif NUMPY2FITS.get(recformat) == 'L':
2416
+ # Special case for logical/boolean types--for ASCII tables we
2417
+ # represent these as single character columns containing 'T' or 'F'
2418
+ # (a la the storage format for Logical columns in binary tables)
2419
+ return 'A1'
2420
+ elif kind == 'i':
2421
+ # Use for the width the maximum required to represent integers
2422
+ # of that byte size plus 1 for signs, but use a minimum of the
2423
+ # default width (to keep with existing behavior)
2424
+ width = 1 + len(str(2 ** (itemsize * 8)))
2425
+ width = max(width, ASCII_DEFAULT_WIDTHS['I'][0])
2426
+ return 'I' + str(width)
2427
+ elif kind == 'f':
2428
+ # This is tricky, but go ahead and use D if float-64, and E
2429
+ # if float-32 with their default widths
2430
+ if itemsize >= 8:
2431
+ format = 'D'
2432
+ else:
2433
+ format = 'E'
2434
+ width = '.'.join(str(w) for w in ASCII_DEFAULT_WIDTHS[format])
2435
+ return format + width
2436
+ # TODO: There may be reasonable ways to represent other Numpy types so
2437
+ # let's see what other possibilities there are besides just 'a', 'i',
2438
+ # and 'f'. If it doesn't have a reasonable ASCII representation then
2439
+ # raise an exception
2440
+ else:
2441
+ format, width, precision = _parse_ascii_tformat(format)
2442
+
2443
+ # This gives a sensible "default" dtype for a given ASCII
2444
+ # format code
2445
+ recformat = ASCII2NUMPY[format]
2446
+
2447
+ # The following logic is taken from CFITSIO:
2448
+ # For integers, if the width <= 4 we can safely use 16-bit ints for all
2449
+ # values [for the non-standard J format code just always force 64-bit]
2450
+ if format == 'I' and width <= 4:
2451
+ recformat = 'i2'
2452
+ elif format == 'A':
2453
+ recformat += str(width)
2454
+
2455
+ return recformat
2456
+
2457
+
2458
+ def _parse_tdisp_format(tdisp):
2459
+ """
2460
+ Parse the ``TDISPn`` keywords for ASCII and binary tables into a
2461
+ ``(format, width, precision, exponential)`` tuple (the TDISP values
2462
+ for ASCII and binary are identical except for 'Lw',
2463
+ which is only present in BINTABLE extensions
2464
+
2465
+ Parameters
2466
+ ----------
2467
+ tdisp: str
2468
+ TDISPn FITS Header keyword. Used to specify display formatting.
2469
+
2470
+ Returns
2471
+ -------
2472
+ formatc: str
2473
+ The format characters from TDISPn
2474
+ width: str
2475
+ The width int value from TDISPn
2476
+ precision: str
2477
+ The precision int value from TDISPn
2478
+ exponential: str
2479
+ The exponential int value from TDISPn
2480
+
2481
+ """
2482
+
2483
+ # Use appropriate regex for format type
2484
+ tdisp = tdisp.strip()
2485
+ fmt_key = tdisp[0] if tdisp[0] !='E' or tdisp[1] not in 'NS' else tdisp[:2]
2486
+ try:
2487
+ tdisp_re = TDISP_RE_DICT[fmt_key]
2488
+ except KeyError:
2489
+ raise VerifyError('Format {} is not recognized.'.format(tdisp))
2490
+
2491
+
2492
+ match = tdisp_re.match(tdisp.strip())
2493
+ if not match or match.group('formatc') is None:
2494
+ raise VerifyError('Format {} is not recognized.'.format(tdisp))
2495
+
2496
+ formatc = match.group('formatc')
2497
+ width = match.group('width')
2498
+ precision = None
2499
+ exponential = None
2500
+
2501
+ # Some formats have precision and exponential
2502
+ if tdisp[0] in ('I', 'B', 'O', 'Z', 'F', 'E', 'G', 'D'):
2503
+ precision = match.group('precision')
2504
+ if precision is None:
2505
+ precision = 1
2506
+ if tdisp[0] in ('E', 'D', 'G') and tdisp[1] not in ('N', 'S'):
2507
+ exponential = match.group('exponential')
2508
+ if exponential is None:
2509
+ exponential = 1
2510
+
2511
+ # Once parsed, check format dict to do conversion to a formatting string
2512
+ return formatc, width, precision, exponential
2513
+
2514
+
2515
+ def _fortran_to_python_format(tdisp):
2516
+ """
2517
+ Turn the TDISPn fortran format pieces into a final Python format string.
2518
+ See the format_type definitions above the TDISP_FMT_DICT. If codes is
2519
+ changed to take advantage of the exponential specification, will need to
2520
+ add it as another input parameter.
2521
+
2522
+ Parameters
2523
+ ----------
2524
+ tdisp: str
2525
+ TDISPn FITS Header keyword. Used to specify display formatting.
2526
+
2527
+ Returns
2528
+ -------
2529
+ format_string: str
2530
+ The TDISPn keyword string translated into a Python format string.
2531
+ """
2532
+ format_type, width, precision, exponential = _parse_tdisp_format(tdisp)
2533
+
2534
+ try:
2535
+ fmt = TDISP_FMT_DICT[format_type]
2536
+ return fmt.format(width=width, precision=precision)
2537
+
2538
+ except KeyError:
2539
+ raise VerifyError('Format {} is not recognized.'.format(format_type))
2540
+
2541
+
2542
+ def python_to_tdisp(format_string, logical_dtype = False):
2543
+ """
2544
+ Turn the Python format string to a TDISP FITS compliant format string. Not
2545
+ all formats convert. these will cause a Warning and return None.
2546
+
2547
+ Parameters
2548
+ ----------
2549
+ format_string: str
2550
+ TDISPn FITS Header keyword. Used to specify display formatting.
2551
+ logical_dtype: bool
2552
+ True is this format type should be a logical type, 'L'. Needs special
2553
+ handeling.
2554
+
2555
+ Returns
2556
+ -------
2557
+ tdsip_string: str
2558
+ The TDISPn keyword string translated into a Python format string.
2559
+ """
2560
+
2561
+ fmt_to_tdisp = {'a': 'A', 's': 'A', 'd': 'I', 'b': 'B', 'o': 'O', 'x': 'Z',
2562
+ 'X': 'Z', 'f': 'F', 'F': 'F', 'g': 'G', 'G': 'G', 'e': 'E',
2563
+ 'E': 'E'}
2564
+
2565
+ if format_string in [None, "", "{}"]:
2566
+ return None
2567
+
2568
+ # Strip out extra format characters that aren't a type or a width/precision
2569
+ if format_string[0] == '{' and format_string != "{}":
2570
+ fmt_str = format_string.lstrip("{:").rstrip('}')
2571
+ elif format_string[0] == '%':
2572
+ fmt_str = format_string.lstrip("%")
2573
+ else:
2574
+ fmt_str = format_string
2575
+
2576
+ precision, sep = '', ''
2577
+
2578
+ # Character format, only translate right aligned, and don't take zero fills
2579
+ if fmt_str[-1].isdigit() and fmt_str[0] == '>' and fmt_str[1] != '0':
2580
+ ftype = fmt_to_tdisp['a']
2581
+ width = fmt_str[1:]
2582
+
2583
+ elif fmt_str[-1] == 's' and fmt_str != 's':
2584
+ ftype = fmt_to_tdisp['a']
2585
+ width = fmt_str[:-1].lstrip('0')
2586
+
2587
+ # Number formats, don't take zero fills
2588
+ elif fmt_str[-1].isalpha() and len(fmt_str) > 1 and fmt_str[0] != '0':
2589
+ ftype = fmt_to_tdisp[fmt_str[-1]]
2590
+ fmt_str = fmt_str[:-1]
2591
+
2592
+ # If format has a "." split out the width and precision
2593
+ if '.' in fmt_str:
2594
+ width, precision = fmt_str.split('.')
2595
+ sep = '.'
2596
+ if width == "":
2597
+ ascii_key = ftype if ftype != 'G' else 'F'
2598
+ width = str(int(precision) + (ASCII_DEFAULT_WIDTHS[ascii_key][0] -
2599
+ ASCII_DEFAULT_WIDTHS[ascii_key][1]))
2600
+ # Otherwise we just have a width
2601
+ else:
2602
+ width = fmt_str
2603
+
2604
+ else:
2605
+ warnings.warn('Format {} cannot be mapped to the accepted '
2606
+ 'TDISPn keyword values. Format will not be '
2607
+ 'moved into TDISPn keyword.'.format(format_string),
2608
+ AstropyUserWarning)
2609
+ return None
2610
+
2611
+ # Catch logical data type, set the format type back to L in this case
2612
+ if logical_dtype:
2613
+ ftype = 'L'
2614
+
2615
+ return ftype + width + sep + precision
testbed/astropy__astropy/astropy/io/fits/connect.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+
4
+ import os
5
+ import re
6
+ import warnings
7
+ from collections import OrderedDict
8
+
9
+ from astropy.io import registry as io_registry
10
+ from astropy import units as u
11
+ from astropy.table import Table, serialize, meta, Column, MaskedColumn
12
+ from astropy.table.table import has_info_class
13
+ from astropy.time import Time
14
+ from astropy.utils.exceptions import AstropyUserWarning
15
+ from astropy.utils.data_info import MixinInfo, serialize_context_as
16
+ from . import HDUList, TableHDU, BinTableHDU, GroupsHDU
17
+ from .column import KEYWORD_NAMES, _fortran_to_python_format
18
+ from .convenience import table_to_hdu
19
+ from .hdu.hdulist import fitsopen as fits_open
20
+ from .util import first
21
+
22
+
23
+ # FITS file signature as per RFC 4047
24
+ FITS_SIGNATURE = (b"\x53\x49\x4d\x50\x4c\x45\x20\x20\x3d\x20\x20\x20\x20\x20"
25
+ b"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
26
+ b"\x20\x54")
27
+
28
+ # Keywords to remove for all tables that are read in
29
+ REMOVE_KEYWORDS = ['XTENSION', 'BITPIX', 'NAXIS', 'NAXIS1', 'NAXIS2',
30
+ 'PCOUNT', 'GCOUNT', 'TFIELDS', 'THEAP']
31
+
32
+ # Column-specific keywords regex
33
+ COLUMN_KEYWORD_REGEXP = '(' + '|'.join(KEYWORD_NAMES) + ')[0-9]+'
34
+
35
+
36
+ def is_column_keyword(keyword):
37
+ return re.match(COLUMN_KEYWORD_REGEXP, keyword) is not None
38
+
39
+
40
+ def is_fits(origin, filepath, fileobj, *args, **kwargs):
41
+ """
42
+ Determine whether `origin` is a FITS file.
43
+
44
+ Parameters
45
+ ----------
46
+ origin : str or readable file-like object
47
+ Path or file object containing a potential FITS file.
48
+
49
+ Returns
50
+ -------
51
+ is_fits : bool
52
+ Returns `True` if the given file is a FITS file.
53
+ """
54
+ if fileobj is not None:
55
+ pos = fileobj.tell()
56
+ sig = fileobj.read(30)
57
+ fileobj.seek(pos)
58
+ return sig == FITS_SIGNATURE
59
+ elif filepath is not None:
60
+ if filepath.lower().endswith(('.fits', '.fits.gz', '.fit', '.fit.gz',
61
+ '.fts', '.fts.gz')):
62
+ return True
63
+ elif isinstance(args[0], (HDUList, TableHDU, BinTableHDU, GroupsHDU)):
64
+ return True
65
+ else:
66
+ return False
67
+
68
+
69
+ def _decode_mixins(tbl):
70
+ """Decode a Table ``tbl`` that has astropy Columns + appropriate meta-data into
71
+ the corresponding table with mixin columns (as appropriate).
72
+ """
73
+ # If available read in __serialized_columns__ meta info which is stored
74
+ # in FITS COMMENTS between two sentinels.
75
+ try:
76
+ i0 = tbl.meta['comments'].index('--BEGIN-ASTROPY-SERIALIZED-COLUMNS--')
77
+ i1 = tbl.meta['comments'].index('--END-ASTROPY-SERIALIZED-COLUMNS--')
78
+ except (ValueError, KeyError):
79
+ return tbl
80
+
81
+ # The YAML data are split into COMMENT cards, with lines longer than 70
82
+ # characters being split with a continuation character \ (backslash).
83
+ # Strip the backslashes and join together.
84
+ continuation_line = False
85
+ lines = []
86
+ for line in tbl.meta['comments'][i0 + 1:i1]:
87
+ if continuation_line:
88
+ lines[-1] = lines[-1] + line[:70]
89
+ else:
90
+ lines.append(line[:70])
91
+ continuation_line = len(line) == 71
92
+
93
+ del tbl.meta['comments'][i0:i1 + 1]
94
+ if not tbl.meta['comments']:
95
+ del tbl.meta['comments']
96
+ info = meta.get_header_from_yaml(lines)
97
+
98
+ # Add serialized column information to table meta for use in constructing mixins
99
+ tbl.meta['__serialized_columns__'] = info['meta']['__serialized_columns__']
100
+
101
+ # Use the `datatype` attribute info to update column attributes that are
102
+ # NOT already handled via standard FITS column keys (name, dtype, unit).
103
+ for col in info['datatype']:
104
+ for attr in ['description', 'meta']:
105
+ if attr in col:
106
+ setattr(tbl[col['name']].info, attr, col[attr])
107
+
108
+ # Construct new table with mixins, using tbl.meta['__serialized_columns__']
109
+ # as guidance.
110
+ tbl = serialize._construct_mixins_from_columns(tbl)
111
+
112
+ return tbl
113
+
114
+
115
+ def read_table_fits(input, hdu=None, astropy_native=False, memmap=False,
116
+ character_as_bytes=True):
117
+ """
118
+ Read a Table object from an FITS file
119
+
120
+ If the ``astropy_native`` argument is ``True``, then input FITS columns
121
+ which are representations of an astropy core object will be converted to
122
+ that class and stored in the ``Table`` as "mixin columns". Currently this
123
+ is limited to FITS columns which adhere to the FITS Time standard, in which
124
+ case they will be converted to a `~astropy.time.Time` column in the output
125
+ table.
126
+
127
+ Parameters
128
+ ----------
129
+ input : str or file-like object or compatible `astropy.io.fits` HDU object
130
+ If a string, the filename to read the table from. If a file object, or
131
+ a compatible HDU object, the object to extract the table from. The
132
+ following `astropy.io.fits` HDU objects can be used as input:
133
+ - :class:`~astropy.io.fits.hdu.table.TableHDU`
134
+ - :class:`~astropy.io.fits.hdu.table.BinTableHDU`
135
+ - :class:`~astropy.io.fits.hdu.table.GroupsHDU`
136
+ - :class:`~astropy.io.fits.hdu.hdulist.HDUList`
137
+ hdu : int or str, optional
138
+ The HDU to read the table from.
139
+ astropy_native : bool, optional
140
+ Read in FITS columns as native astropy objects where possible instead
141
+ of standard Table Column objects. Default is False.
142
+ memmap : bool, optional
143
+ Whether to use memory mapping, which accesses data on disk as needed. If
144
+ you are only accessing part of the data, this is often more efficient.
145
+ If you want to access all the values in the table, and you are able to
146
+ fit the table in memory, you may be better off leaving memory mapping
147
+ off. However, if your table would not fit in memory, you should set this
148
+ to `True`.
149
+ character_as_bytes : bool, optional
150
+ If `True`, string columns are stored as Numpy byte arrays (dtype ``S``)
151
+ and are converted on-the-fly to unicode strings when accessing
152
+ individual elements. If you need to use Numpy unicode arrays (dtype
153
+ ``U``) internally, you should set this to `False`, but note that this
154
+ will use more memory. If set to `False`, string columns will not be
155
+ memory-mapped even if ``memmap`` is `True`.
156
+ """
157
+
158
+ if isinstance(input, HDUList):
159
+
160
+ # Parse all table objects
161
+ tables = OrderedDict()
162
+ for ihdu, hdu_item in enumerate(input):
163
+ if isinstance(hdu_item, (TableHDU, BinTableHDU, GroupsHDU)):
164
+ tables[ihdu] = hdu_item
165
+
166
+ if len(tables) > 1:
167
+ if hdu is None:
168
+ warnings.warn("hdu= was not specified but multiple tables"
169
+ " are present, reading in first available"
170
+ " table (hdu={0})".format(first(tables)),
171
+ AstropyUserWarning)
172
+ hdu = first(tables)
173
+
174
+ # hdu might not be an integer, so we first need to convert it
175
+ # to the correct HDU index
176
+ hdu = input.index_of(hdu)
177
+
178
+ if hdu in tables:
179
+ table = tables[hdu]
180
+ else:
181
+ raise ValueError("No table found in hdu={0}".format(hdu))
182
+
183
+ elif len(tables) == 1:
184
+ table = tables[first(tables)]
185
+ else:
186
+ raise ValueError("No table found")
187
+
188
+ elif isinstance(input, (TableHDU, BinTableHDU, GroupsHDU)):
189
+
190
+ table = input
191
+
192
+ else:
193
+
194
+ hdulist = fits_open(input, character_as_bytes=character_as_bytes,
195
+ memmap=memmap)
196
+
197
+ try:
198
+ return read_table_fits(hdulist, hdu=hdu,
199
+ astropy_native=astropy_native)
200
+ finally:
201
+ hdulist.close()
202
+
203
+ # Check if table is masked
204
+ masked = any(col.null is not None for col in table.columns)
205
+
206
+ # TODO: in future, it may make more sense to do this column-by-column,
207
+ # rather than via the structured array.
208
+
209
+ # In the loop below we access the data using data[col.name] rather than
210
+ # col.array to make sure that the data is scaled correctly if needed.
211
+ data = table.data
212
+
213
+ columns = []
214
+ for col in data.columns:
215
+
216
+ # Set column data
217
+ if masked:
218
+ column = MaskedColumn(data=data[col.name], name=col.name, copy=False)
219
+ if col.null is not None:
220
+ column.set_fill_value(col.null)
221
+ column.mask[column.data == col.null] = True
222
+ else:
223
+ column = Column(data=data[col.name], name=col.name, copy=False)
224
+
225
+ # Copy over units
226
+ if col.unit is not None:
227
+ column.unit = u.Unit(col.unit, format='fits', parse_strict='silent')
228
+
229
+ # Copy over display format
230
+ if col.disp is not None:
231
+ column.format = _fortran_to_python_format(col.disp)
232
+
233
+ columns.append(column)
234
+
235
+ # Create Table object
236
+ t = Table(columns, masked=masked, copy=False)
237
+
238
+ # TODO: deal properly with unsigned integers
239
+
240
+ hdr = table.header
241
+ if astropy_native:
242
+ # Avoid circular imports, and also only import if necessary.
243
+ from .fitstime import fits_to_time
244
+ hdr = fits_to_time(hdr, t)
245
+
246
+ for key, value, comment in hdr.cards:
247
+
248
+ if key in ['COMMENT', 'HISTORY']:
249
+ # Convert to io.ascii format
250
+ if key == 'COMMENT':
251
+ key = 'comments'
252
+
253
+ if key in t.meta:
254
+ t.meta[key].append(value)
255
+ else:
256
+ t.meta[key] = [value]
257
+
258
+ elif key in t.meta: # key is duplicate
259
+
260
+ if isinstance(t.meta[key], list):
261
+ t.meta[key].append(value)
262
+ else:
263
+ t.meta[key] = [t.meta[key], value]
264
+
265
+ elif is_column_keyword(key) or key in REMOVE_KEYWORDS:
266
+
267
+ pass
268
+
269
+ else:
270
+
271
+ t.meta[key] = value
272
+
273
+ # TODO: implement masking
274
+
275
+ # Decode any mixin columns that have been stored as standard Columns.
276
+ t = _decode_mixins(t)
277
+
278
+ return t
279
+
280
+
281
+ def _encode_mixins(tbl):
282
+ """Encode a Table ``tbl`` that may have mixin columns to a Table with only
283
+ astropy Columns + appropriate meta-data to allow subsequent decoding.
284
+ """
285
+ # Determine if information will be lost without serializing meta. This is hardcoded
286
+ # to the set difference between column info attributes and what FITS can store
287
+ # natively (name, dtype, unit). See _get_col_attributes() in table/meta.py for where
288
+ # this comes from.
289
+ info_lost = any(any(getattr(col.info, attr, None) not in (None, {})
290
+ for attr in ('description', 'meta'))
291
+ for col in tbl.itercols())
292
+
293
+ # If PyYAML is not available then check to see if there are any mixin cols
294
+ # that *require* YAML serialization. FITS already has support for Time,
295
+ # Quantity, so if those are the only mixins the proceed without doing the
296
+ # YAML bit, for backward compatibility (i.e. not requiring YAML to write
297
+ # Time or Quantity). In this case other mixin column meta (e.g.
298
+ # description or meta) will be silently dropped, consistent with astropy <=
299
+ # 2.0 behavior.
300
+ try:
301
+ import yaml # noqa
302
+ except ImportError:
303
+ for col in tbl.itercols():
304
+ if (has_info_class(col, MixinInfo) and
305
+ col.__class__ not in (u.Quantity, Time)):
306
+ raise TypeError("cannot write type {} column '{}' "
307
+ "to FITS without PyYAML installed."
308
+ .format(col.__class__.__name__, col.info.name))
309
+ else:
310
+ if info_lost:
311
+ warnings.warn("table contains column(s) with defined 'format',"
312
+ " 'description', or 'meta' info attributes. These"
313
+ " will be dropped unless you install PyYAML.",
314
+ AstropyUserWarning)
315
+ return tbl
316
+
317
+ # Convert the table to one with no mixins, only Column objects. This adds
318
+ # meta data which is extracted with meta.get_yaml_from_table. This ignores
319
+ # Time-subclass columns and leave them in the table so that the downstream
320
+ # FITS Time handling does the right thing.
321
+
322
+ with serialize_context_as('fits'):
323
+ encode_tbl = serialize.represent_mixins_as_columns(
324
+ tbl, exclude_classes=(Time,))
325
+
326
+ # If the encoded table is unchanged then there were no mixins. But if there
327
+ # is column metadata (format, description, meta) that would be lost, then
328
+ # still go through the serialized columns machinery.
329
+ if encode_tbl is tbl and not info_lost:
330
+ return tbl
331
+
332
+ # Get the YAML serialization of information describing the table columns.
333
+ # This is re-using ECSV code that combined existing table.meta with with
334
+ # the extra __serialized_columns__ key. For FITS the table.meta is handled
335
+ # by the native FITS connect code, so don't include that in the YAML
336
+ # output.
337
+ ser_col = '__serialized_columns__'
338
+
339
+ # encode_tbl might not have a __serialized_columns__ key if there were no mixins,
340
+ # but machinery below expects it to be available, so just make an empty dict.
341
+ encode_tbl.meta.setdefault(ser_col, {})
342
+
343
+ tbl_meta_copy = encode_tbl.meta.copy()
344
+ try:
345
+ encode_tbl.meta = {ser_col: encode_tbl.meta[ser_col]}
346
+ meta_yaml_lines = meta.get_yaml_from_table(encode_tbl)
347
+ finally:
348
+ encode_tbl.meta = tbl_meta_copy
349
+ del encode_tbl.meta[ser_col]
350
+
351
+ if 'comments' not in encode_tbl.meta:
352
+ encode_tbl.meta['comments'] = []
353
+ encode_tbl.meta['comments'].append('--BEGIN-ASTROPY-SERIALIZED-COLUMNS--')
354
+
355
+ for line in meta_yaml_lines:
356
+ if len(line) == 0:
357
+ lines = ['']
358
+ else:
359
+ # Split line into 70 character chunks for COMMENT cards
360
+ idxs = list(range(0, len(line) + 70, 70))
361
+ lines = [line[i0:i1] + '\\' for i0, i1 in zip(idxs[:-1], idxs[1:])]
362
+ lines[-1] = lines[-1][:-1]
363
+ encode_tbl.meta['comments'].extend(lines)
364
+
365
+ encode_tbl.meta['comments'].append('--END-ASTROPY-SERIALIZED-COLUMNS--')
366
+
367
+ return encode_tbl
368
+
369
+
370
+ def write_table_fits(input, output, overwrite=False):
371
+ """
372
+ Write a Table object to a FITS file
373
+
374
+ Parameters
375
+ ----------
376
+ input : Table
377
+ The table to write out.
378
+ output : str
379
+ The filename to write the table to.
380
+ overwrite : bool
381
+ Whether to overwrite any existing file without warning.
382
+ """
383
+
384
+ # Encode any mixin columns into standard Columns.
385
+ input = _encode_mixins(input)
386
+
387
+ table_hdu = table_to_hdu(input, character_as_bytes=True)
388
+
389
+ # Check if output file already exists
390
+ if isinstance(output, str) and os.path.exists(output):
391
+ if overwrite:
392
+ os.remove(output)
393
+ else:
394
+ raise OSError("File exists: {0}".format(output))
395
+
396
+ table_hdu.writeto(output)
397
+
398
+
399
+ io_registry.register_reader('fits', Table, read_table_fits)
400
+ io_registry.register_writer('fits', Table, write_table_fits)
401
+ io_registry.register_identifier('fits', Table, is_fits)
testbed/astropy__astropy/astropy/io/fits/convenience.py ADDED
@@ -0,0 +1,1086 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ """
4
+ Convenience functions
5
+ =====================
6
+
7
+ The functions in this module provide shortcuts for some of the most basic
8
+ operations on FITS files, such as reading and updating the header. They are
9
+ included directly in the 'astropy.io.fits' namespace so that they can be used
10
+ like::
11
+
12
+ astropy.io.fits.getheader(...)
13
+
14
+ These functions are primarily for convenience when working with FITS files in
15
+ the command-line interpreter. If performing several operations on the same
16
+ file, such as in a script, it is better to *not* use these functions, as each
17
+ one must open and re-parse the file. In such cases it is better to use
18
+ :func:`astropy.io.fits.open` and work directly with the
19
+ :class:`astropy.io.fits.HDUList` object and underlying HDU objects.
20
+
21
+ Several of the convenience functions, such as `getheader` and `getdata` support
22
+ special arguments for selecting which extension HDU to use when working with a
23
+ multi-extension FITS file. There are a few supported argument formats for
24
+ selecting the extension. See the documentation for `getdata` for an
25
+ explanation of all the different formats.
26
+
27
+ .. warning::
28
+ All arguments to convenience functions other than the filename that are
29
+ *not* for selecting the extension HDU should be passed in as keyword
30
+ arguments. This is to avoid ambiguity and conflicts with the
31
+ extension arguments. For example, to set NAXIS=1 on the Primary HDU:
32
+
33
+ Wrong::
34
+
35
+ astropy.io.fits.setval('myimage.fits', 'NAXIS', 1)
36
+
37
+ The above example will try to set the NAXIS value on the first extension
38
+ HDU to blank. That is, the argument '1' is assumed to specify an extension
39
+ HDU.
40
+
41
+ Right::
42
+
43
+ astropy.io.fits.setval('myimage.fits', 'NAXIS', value=1)
44
+
45
+ This will set the NAXIS keyword to 1 on the primary HDU (the default). To
46
+ specify the first extension HDU use::
47
+
48
+ astropy.io.fits.setval('myimage.fits', 'NAXIS', value=1, ext=1)
49
+
50
+ This complexity arises out of the attempt to simultaneously support
51
+ multiple argument formats that were used in past versions of PyFITS.
52
+ Unfortunately, it is not possible to support all formats without
53
+ introducing some ambiguity. A future Astropy release may standardize
54
+ around a single format and officially deprecate the other formats.
55
+ """
56
+
57
+
58
+ import operator
59
+ import os
60
+ import warnings
61
+
62
+ import numpy as np
63
+
64
+ from .diff import FITSDiff, HDUDiff
65
+ from .file import FILE_MODES, _File
66
+ from .hdu.base import _BaseHDU, _ValidHDU
67
+ from .hdu.hdulist import fitsopen, HDUList
68
+ from .hdu.image import PrimaryHDU, ImageHDU
69
+ from .hdu.table import BinTableHDU
70
+ from .header import Header
71
+ from .util import fileobj_closed, fileobj_name, fileobj_mode, _is_int
72
+ from astropy.utils.exceptions import AstropyUserWarning
73
+ from astropy.utils.decorators import deprecated_renamed_argument
74
+
75
+
76
+ __all__ = ['getheader', 'getdata', 'getval', 'setval', 'delval', 'writeto',
77
+ 'append', 'update', 'info', 'tabledump', 'tableload',
78
+ 'table_to_hdu', 'printdiff']
79
+
80
+
81
+ def getheader(filename, *args, **kwargs):
82
+ """
83
+ Get the header from an extension of a FITS file.
84
+
85
+ Parameters
86
+ ----------
87
+ filename : file path, file object, or file like object
88
+ File to get header from. If an opened file object, its mode
89
+ must be one of the following rb, rb+, or ab+).
90
+
91
+ ext, extname, extver
92
+ The rest of the arguments are for extension specification. See the
93
+ `getdata` documentation for explanations/examples.
94
+
95
+ kwargs
96
+ Any additional keyword arguments to be passed to
97
+ `astropy.io.fits.open`.
98
+
99
+ Returns
100
+ -------
101
+ header : `Header` object
102
+ """
103
+
104
+ mode, closed = _get_file_mode(filename)
105
+ hdulist, extidx = _getext(filename, mode, *args, **kwargs)
106
+ try:
107
+ hdu = hdulist[extidx]
108
+ header = hdu.header
109
+ finally:
110
+ hdulist.close(closed=closed)
111
+
112
+ return header
113
+
114
+
115
+ def getdata(filename, *args, header=None, lower=None, upper=None, view=None,
116
+ **kwargs):
117
+ """
118
+ Get the data from an extension of a FITS file (and optionally the
119
+ header).
120
+
121
+ Parameters
122
+ ----------
123
+ filename : file path, file object, or file like object
124
+ File to get data from. If opened, mode must be one of the
125
+ following rb, rb+, or ab+.
126
+
127
+ ext
128
+ The rest of the arguments are for extension specification.
129
+ They are flexible and are best illustrated by examples.
130
+
131
+ No extra arguments implies the primary header::
132
+
133
+ getdata('in.fits')
134
+
135
+ By extension number::
136
+
137
+ getdata('in.fits', 0) # the primary header
138
+ getdata('in.fits', 2) # the second extension
139
+ getdata('in.fits', ext=2) # the second extension
140
+
141
+ By name, i.e., ``EXTNAME`` value (if unique)::
142
+
143
+ getdata('in.fits', 'sci')
144
+ getdata('in.fits', extname='sci') # equivalent
145
+
146
+ Note ``EXTNAME`` values are not case sensitive
147
+
148
+ By combination of ``EXTNAME`` and EXTVER`` as separate
149
+ arguments or as a tuple::
150
+
151
+ getdata('in.fits', 'sci', 2) # EXTNAME='SCI' & EXTVER=2
152
+ getdata('in.fits', extname='sci', extver=2) # equivalent
153
+ getdata('in.fits', ('sci', 2)) # equivalent
154
+
155
+ Ambiguous or conflicting specifications will raise an exception::
156
+
157
+ getdata('in.fits', ext=('sci',1), extname='err', extver=2)
158
+
159
+ header : bool, optional
160
+ If `True`, return the data and the header of the specified HDU as a
161
+ tuple.
162
+
163
+ lower, upper : bool, optional
164
+ If ``lower`` or ``upper`` are `True`, the field names in the
165
+ returned data object will be converted to lower or upper case,
166
+ respectively.
167
+
168
+ view : ndarray, optional
169
+ When given, the data will be returned wrapped in the given ndarray
170
+ subclass by calling::
171
+
172
+ data.view(view)
173
+
174
+ kwargs
175
+ Any additional keyword arguments to be passed to
176
+ `astropy.io.fits.open`.
177
+
178
+ Returns
179
+ -------
180
+ array : array, record array or groups data object
181
+ Type depends on the type of the extension being referenced.
182
+
183
+ If the optional keyword ``header`` is set to `True`, this
184
+ function will return a (``data``, ``header``) tuple.
185
+ """
186
+
187
+ mode, closed = _get_file_mode(filename)
188
+
189
+ hdulist, extidx = _getext(filename, mode, *args, **kwargs)
190
+ try:
191
+ hdu = hdulist[extidx]
192
+ data = hdu.data
193
+ if data is None and extidx == 0:
194
+ try:
195
+ hdu = hdulist[1]
196
+ data = hdu.data
197
+ except IndexError:
198
+ raise IndexError('No data in this HDU.')
199
+ if data is None:
200
+ raise IndexError('No data in this HDU.')
201
+ if header:
202
+ hdr = hdu.header
203
+ finally:
204
+ hdulist.close(closed=closed)
205
+
206
+ # Change case of names if requested
207
+ trans = None
208
+ if lower:
209
+ trans = operator.methodcaller('lower')
210
+ elif upper:
211
+ trans = operator.methodcaller('upper')
212
+ if trans:
213
+ if data.dtype.names is None:
214
+ # this data does not have fields
215
+ return
216
+ if data.dtype.descr[0][0] == '':
217
+ # this data does not have fields
218
+ return
219
+ data.dtype.names = [trans(n) for n in data.dtype.names]
220
+
221
+ # allow different views into the underlying ndarray. Keep the original
222
+ # view just in case there is a problem
223
+ if isinstance(view, type) and issubclass(view, np.ndarray):
224
+ data = data.view(view)
225
+
226
+ if header:
227
+ return data, hdr
228
+ else:
229
+ return data
230
+
231
+
232
+ def getval(filename, keyword, *args, **kwargs):
233
+ """
234
+ Get a keyword's value from a header in a FITS file.
235
+
236
+ Parameters
237
+ ----------
238
+ filename : file path, file object, or file like object
239
+ Name of the FITS file, or file object (if opened, mode must be
240
+ one of the following rb, rb+, or ab+).
241
+
242
+ keyword : str
243
+ Keyword name
244
+
245
+ ext, extname, extver
246
+ The rest of the arguments are for extension specification.
247
+ See `getdata` for explanations/examples.
248
+
249
+ kwargs
250
+ Any additional keyword arguments to be passed to
251
+ `astropy.io.fits.open`.
252
+ *Note:* This function automatically specifies ``do_not_scale_image_data
253
+ = True`` when opening the file so that values can be retrieved from the
254
+ unmodified header.
255
+
256
+ Returns
257
+ -------
258
+ keyword value : str, int, or float
259
+ """
260
+
261
+ if 'do_not_scale_image_data' not in kwargs:
262
+ kwargs['do_not_scale_image_data'] = True
263
+
264
+ hdr = getheader(filename, *args, **kwargs)
265
+ return hdr[keyword]
266
+
267
+
268
+ def setval(filename, keyword, *args, value=None, comment=None, before=None,
269
+ after=None, savecomment=False, **kwargs):
270
+ """
271
+ Set a keyword's value from a header in a FITS file.
272
+
273
+ If the keyword already exists, it's value/comment will be updated.
274
+ If it does not exist, a new card will be created and it will be
275
+ placed before or after the specified location. If no ``before`` or
276
+ ``after`` is specified, it will be appended at the end.
277
+
278
+ When updating more than one keyword in a file, this convenience
279
+ function is a much less efficient approach compared with opening
280
+ the file for update, modifying the header, and closing the file.
281
+
282
+ Parameters
283
+ ----------
284
+ filename : file path, file object, or file like object
285
+ Name of the FITS file, or file object If opened, mode must be update
286
+ (rb+). An opened file object or `~gzip.GzipFile` object will be closed
287
+ upon return.
288
+
289
+ keyword : str
290
+ Keyword name
291
+
292
+ value : str, int, float, optional
293
+ Keyword value (default: `None`, meaning don't modify)
294
+
295
+ comment : str, optional
296
+ Keyword comment, (default: `None`, meaning don't modify)
297
+
298
+ before : str, int, optional
299
+ Name of the keyword, or index of the card before which the new card
300
+ will be placed. The argument ``before`` takes precedence over
301
+ ``after`` if both are specified (default: `None`).
302
+
303
+ after : str, int, optional
304
+ Name of the keyword, or index of the card after which the new card will
305
+ be placed. (default: `None`).
306
+
307
+ savecomment : bool, optional
308
+ When `True`, preserve the current comment for an existing keyword. The
309
+ argument ``savecomment`` takes precedence over ``comment`` if both
310
+ specified. If ``comment`` is not specified then the current comment
311
+ will automatically be preserved (default: `False`).
312
+
313
+ ext, extname, extver
314
+ The rest of the arguments are for extension specification.
315
+ See `getdata` for explanations/examples.
316
+
317
+ kwargs
318
+ Any additional keyword arguments to be passed to
319
+ `astropy.io.fits.open`.
320
+ *Note:* This function automatically specifies ``do_not_scale_image_data
321
+ = True`` when opening the file so that values can be retrieved from the
322
+ unmodified header.
323
+ """
324
+
325
+ if 'do_not_scale_image_data' not in kwargs:
326
+ kwargs['do_not_scale_image_data'] = True
327
+
328
+ closed = fileobj_closed(filename)
329
+ hdulist, extidx = _getext(filename, 'update', *args, **kwargs)
330
+ try:
331
+ if keyword in hdulist[extidx].header and savecomment:
332
+ comment = None
333
+ hdulist[extidx].header.set(keyword, value, comment, before, after)
334
+ finally:
335
+ hdulist.close(closed=closed)
336
+
337
+
338
+ def delval(filename, keyword, *args, **kwargs):
339
+ """
340
+ Delete all instances of keyword from a header in a FITS file.
341
+
342
+ Parameters
343
+ ----------
344
+
345
+ filename : file path, file object, or file like object
346
+ Name of the FITS file, or file object If opened, mode must be update
347
+ (rb+). An opened file object or `~gzip.GzipFile` object will be closed
348
+ upon return.
349
+
350
+ keyword : str, int
351
+ Keyword name or index
352
+
353
+ ext, extname, extver
354
+ The rest of the arguments are for extension specification.
355
+ See `getdata` for explanations/examples.
356
+
357
+ kwargs
358
+ Any additional keyword arguments to be passed to
359
+ `astropy.io.fits.open`.
360
+ *Note:* This function automatically specifies ``do_not_scale_image_data
361
+ = True`` when opening the file so that values can be retrieved from the
362
+ unmodified header.
363
+ """
364
+
365
+ if 'do_not_scale_image_data' not in kwargs:
366
+ kwargs['do_not_scale_image_data'] = True
367
+
368
+ closed = fileobj_closed(filename)
369
+ hdulist, extidx = _getext(filename, 'update', *args, **kwargs)
370
+ try:
371
+ del hdulist[extidx].header[keyword]
372
+ finally:
373
+ hdulist.close(closed=closed)
374
+
375
+
376
+ @deprecated_renamed_argument('clobber', 'overwrite', '2.0')
377
+ def writeto(filename, data, header=None, output_verify='exception',
378
+ overwrite=False, checksum=False):
379
+ """
380
+ Create a new FITS file using the supplied data/header.
381
+
382
+ Parameters
383
+ ----------
384
+ filename : file path, file object, or file like object
385
+ File to write to. If opened, must be opened in a writeable binary
386
+ mode such as 'wb' or 'ab+'.
387
+
388
+ data : array, record array, or groups data object
389
+ data to write to the new file
390
+
391
+ header : `Header` object, optional
392
+ the header associated with ``data``. If `None`, a header
393
+ of the appropriate type is created for the supplied data. This
394
+ argument is optional.
395
+
396
+ output_verify : str
397
+ Output verification option. Must be one of ``"fix"``, ``"silentfix"``,
398
+ ``"ignore"``, ``"warn"``, or ``"exception"``. May also be any
399
+ combination of ``"fix"`` or ``"silentfix"`` with ``"+ignore"``,
400
+ ``+warn``, or ``+exception" (e.g. ``"fix+warn"``). See :ref:`verify`
401
+ for more info.
402
+
403
+ overwrite : bool, optional
404
+ If ``True``, overwrite the output file if it exists. Raises an
405
+ ``OSError`` if ``False`` and the output file exists. Default is
406
+ ``False``.
407
+
408
+ .. versionchanged:: 1.3
409
+ ``overwrite`` replaces the deprecated ``clobber`` argument.
410
+
411
+ checksum : bool, optional
412
+ If `True`, adds both ``DATASUM`` and ``CHECKSUM`` cards to the
413
+ headers of all HDU's written to the file.
414
+ """
415
+
416
+ hdu = _makehdu(data, header)
417
+ if hdu.is_image and not isinstance(hdu, PrimaryHDU):
418
+ hdu = PrimaryHDU(data, header=header)
419
+ hdu.writeto(filename, overwrite=overwrite, output_verify=output_verify,
420
+ checksum=checksum)
421
+
422
+
423
+ def table_to_hdu(table, character_as_bytes=False):
424
+ """
425
+ Convert an `~astropy.table.Table` object to a FITS
426
+ `~astropy.io.fits.BinTableHDU`.
427
+
428
+ Parameters
429
+ ----------
430
+ table : astropy.table.Table
431
+ The table to convert.
432
+ character_as_bytes : bool
433
+ Whether to return bytes for string columns when accessed from the HDU.
434
+ By default this is `False` and (unicode) strings are returned, but for
435
+ large tables this may use up a lot of memory.
436
+
437
+ Returns
438
+ -------
439
+ table_hdu : `~astropy.io.fits.BinTableHDU`
440
+ The FITS binary table HDU.
441
+ """
442
+ # Avoid circular imports
443
+ from .connect import is_column_keyword, REMOVE_KEYWORDS
444
+ from .column import python_to_tdisp
445
+
446
+ # Header to store Time related metadata
447
+ hdr = None
448
+
449
+ # Not all tables with mixin columns are supported
450
+ if table.has_mixin_columns:
451
+ # Import is done here, in order to avoid it at build time as erfa is not
452
+ # yet available then.
453
+ from astropy.table.column import BaseColumn
454
+ from astropy.time import Time
455
+ from astropy.units import Quantity
456
+ from .fitstime import time_to_fits
457
+
458
+ # Only those columns which are instances of BaseColumn, Quantity or Time can
459
+ # be written
460
+ unsupported_cols = table.columns.not_isinstance((BaseColumn, Quantity, Time))
461
+ if unsupported_cols:
462
+ unsupported_names = [col.info.name for col in unsupported_cols]
463
+ raise ValueError('cannot write table with mixin column(s) {0}'
464
+ .format(unsupported_names))
465
+
466
+ time_cols = table.columns.isinstance(Time)
467
+ if time_cols:
468
+ table, hdr = time_to_fits(table)
469
+
470
+ # Create a new HDU object
471
+ if table.masked:
472
+ # float column's default mask value needs to be Nan
473
+ for column in table.columns.values():
474
+ fill_value = column.get_fill_value()
475
+ if column.dtype.kind == 'f' and np.allclose(fill_value, 1e20):
476
+ column.set_fill_value(np.nan)
477
+
478
+ # TODO: it might be better to construct the FITS table directly from
479
+ # the Table columns, rather than go via a structured array.
480
+ table_hdu = BinTableHDU.from_columns(np.array(table.filled()), header=hdr, character_as_bytes=True)
481
+ for col in table_hdu.columns:
482
+ # Binary FITS tables support TNULL *only* for integer data columns
483
+ # TODO: Determine a schema for handling non-integer masked columns
484
+ # in FITS (if at all possible)
485
+ int_formats = ('B', 'I', 'J', 'K')
486
+ if not (col.format in int_formats or
487
+ col.format.p_format in int_formats):
488
+ continue
489
+
490
+ # The astype is necessary because if the string column is less
491
+ # than one character, the fill value will be N/A by default which
492
+ # is too long, and so no values will get masked.
493
+ fill_value = table[col.name].get_fill_value()
494
+
495
+ col.null = fill_value.astype(table[col.name].dtype)
496
+ else:
497
+ table_hdu = BinTableHDU.from_columns(np.array(table.filled()), header=hdr, character_as_bytes=character_as_bytes)
498
+
499
+ # Set units and format display for output HDU
500
+ for col in table_hdu.columns:
501
+
502
+ if table[col.name].info.format is not None:
503
+ # check for boolean types, special format case
504
+ logical = table[col.name].info.dtype == bool
505
+
506
+ tdisp_format = python_to_tdisp(table[col.name].info.format,
507
+ logical_dtype=logical)
508
+ if tdisp_format is not None:
509
+ col.disp = tdisp_format
510
+
511
+ unit = table[col.name].unit
512
+ if unit is not None:
513
+ # Local imports to avoid importing units when it is not required,
514
+ # e.g. for command-line scripts
515
+ from astropy.units import Unit
516
+ from astropy.units.format.fits import UnitScaleError
517
+ try:
518
+ col.unit = unit.to_string(format='fits')
519
+ except UnitScaleError:
520
+ scale = unit.scale
521
+ raise UnitScaleError(
522
+ "The column '{0}' could not be stored in FITS format "
523
+ "because it has a scale '({1})' that "
524
+ "is not recognized by the FITS standard. Either scale "
525
+ "the data or change the units.".format(col.name, str(scale)))
526
+ except ValueError:
527
+ warnings.warn(
528
+ "The unit '{0}' could not be saved to FITS format".format(
529
+ unit.to_string()), AstropyUserWarning)
530
+
531
+ # Try creating a Unit to issue a warning if the unit is not FITS compliant
532
+ Unit(col.unit, format='fits', parse_strict='warn')
533
+
534
+ # Column-specific override keywords for coordinate columns
535
+ coord_meta = table.meta.pop('__coordinate_columns__', {})
536
+ for col_name, col_info in coord_meta.items():
537
+ col = table_hdu.columns[col_name]
538
+ # Set the column coordinate attributes from data saved earlier.
539
+ # Note: have to set all three, even if we have no data.
540
+ for attr in 'coord_type', 'coord_unit', 'time_ref_pos':
541
+ setattr(col, attr, col_info.get(attr, None))
542
+
543
+ for key, value in table.meta.items():
544
+ if is_column_keyword(key.upper()) or key.upper() in REMOVE_KEYWORDS:
545
+ warnings.warn(
546
+ "Meta-data keyword {0} will be ignored since it conflicts "
547
+ "with a FITS reserved keyword".format(key), AstropyUserWarning)
548
+
549
+ # Convert to FITS format
550
+ if key == 'comments':
551
+ key = 'comment'
552
+
553
+ if isinstance(value, list):
554
+ for item in value:
555
+ try:
556
+ table_hdu.header.append((key, item))
557
+ except ValueError:
558
+ warnings.warn(
559
+ "Attribute `{0}` of type {1} cannot be added to "
560
+ "FITS Header - skipping".format(key, type(value)),
561
+ AstropyUserWarning)
562
+ else:
563
+ try:
564
+ table_hdu.header[key] = value
565
+ except ValueError:
566
+ warnings.warn(
567
+ "Attribute `{0}` of type {1} cannot be added to FITS "
568
+ "Header - skipping".format(key, type(value)),
569
+ AstropyUserWarning)
570
+ return table_hdu
571
+
572
+
573
+ def append(filename, data, header=None, checksum=False, verify=True, **kwargs):
574
+ """
575
+ Append the header/data to FITS file if filename exists, create if not.
576
+
577
+ If only ``data`` is supplied, a minimal header is created.
578
+
579
+ Parameters
580
+ ----------
581
+ filename : file path, file object, or file like object
582
+ File to write to. If opened, must be opened for update (rb+) unless it
583
+ is a new file, then it must be opened for append (ab+). A file or
584
+ `~gzip.GzipFile` object opened for update will be closed after return.
585
+
586
+ data : array, table, or group data object
587
+ the new data used for appending
588
+
589
+ header : `Header` object, optional
590
+ The header associated with ``data``. If `None`, an appropriate header
591
+ will be created for the data object supplied.
592
+
593
+ checksum : bool, optional
594
+ When `True` adds both ``DATASUM`` and ``CHECKSUM`` cards to the header
595
+ of the HDU when written to the file.
596
+
597
+ verify : bool, optional
598
+ When `True`, the existing FITS file will be read in to verify it for
599
+ correctness before appending. When `False`, content is simply appended
600
+ to the end of the file. Setting ``verify`` to `False` can be much
601
+ faster.
602
+
603
+ kwargs
604
+ Additional arguments are passed to:
605
+
606
+ - `~astropy.io.fits.writeto` if the file does not exist or is empty.
607
+ In this case ``output_verify`` is the only possible argument.
608
+ - `~astropy.io.fits.open` if ``verify`` is True or if ``filename``
609
+ is a file object.
610
+ - Otherwise no additional arguments can be used.
611
+
612
+ """
613
+ name, closed, noexist_or_empty = _stat_filename_or_fileobj(filename)
614
+
615
+ if noexist_or_empty:
616
+ #
617
+ # The input file or file like object either doesn't exits or is
618
+ # empty. Use the writeto convenience function to write the
619
+ # output to the empty object.
620
+ #
621
+ writeto(filename, data, header, checksum=checksum, **kwargs)
622
+ else:
623
+ hdu = _makehdu(data, header)
624
+
625
+ if isinstance(hdu, PrimaryHDU):
626
+ hdu = ImageHDU(data, header)
627
+
628
+ if verify or not closed:
629
+ f = fitsopen(filename, mode='append', **kwargs)
630
+ try:
631
+ f.append(hdu)
632
+
633
+ # Set a flag in the HDU so that only this HDU gets a checksum
634
+ # when writing the file.
635
+ hdu._output_checksum = checksum
636
+ finally:
637
+ f.close(closed=closed)
638
+ else:
639
+ f = _File(filename, mode='append')
640
+ try:
641
+ hdu._output_checksum = checksum
642
+ hdu._writeto(f)
643
+ finally:
644
+ f.close()
645
+
646
+
647
+ def update(filename, data, *args, **kwargs):
648
+ """
649
+ Update the specified extension with the input data/header.
650
+
651
+ Parameters
652
+ ----------
653
+ filename : file path, file object, or file like object
654
+ File to update. If opened, mode must be update (rb+). An opened file
655
+ object or `~gzip.GzipFile` object will be closed upon return.
656
+
657
+ data : array, table, or group data object
658
+ the new data used for updating
659
+
660
+ header : `Header` object, optional
661
+ The header associated with ``data``. If `None`, an appropriate header
662
+ will be created for the data object supplied.
663
+
664
+ ext, extname, extver
665
+ The rest of the arguments are flexible: the 3rd argument can be the
666
+ header associated with the data. If the 3rd argument is not a
667
+ `Header`, it (and other positional arguments) are assumed to be the
668
+ extension specification(s). Header and extension specs can also be
669
+ keyword arguments. For example::
670
+
671
+ update(file, dat, hdr, 'sci') # update the 'sci' extension
672
+ update(file, dat, 3) # update the 3rd extension
673
+ update(file, dat, hdr, 3) # update the 3rd extension
674
+ update(file, dat, 'sci', 2) # update the 2nd SCI extension
675
+ update(file, dat, 3, header=hdr) # update the 3rd extension
676
+ update(file, dat, header=hdr, ext=5) # update the 5th extension
677
+
678
+ kwargs
679
+ Any additional keyword arguments to be passed to
680
+ `astropy.io.fits.open`.
681
+ """
682
+
683
+ # The arguments to this function are a bit trickier to deal with than others
684
+ # in this module, since the documentation has promised that the header
685
+ # argument can be an optional positional argument.
686
+ if args and isinstance(args[0], Header):
687
+ header = args[0]
688
+ args = args[1:]
689
+ else:
690
+ header = None
691
+ # The header can also be a keyword argument--if both are provided the
692
+ # keyword takes precedence
693
+ header = kwargs.pop('header', header)
694
+
695
+ new_hdu = _makehdu(data, header)
696
+
697
+ closed = fileobj_closed(filename)
698
+
699
+ hdulist, _ext = _getext(filename, 'update', *args, **kwargs)
700
+ try:
701
+ hdulist[_ext] = new_hdu
702
+ finally:
703
+ hdulist.close(closed=closed)
704
+
705
+
706
+ def info(filename, output=None, **kwargs):
707
+ """
708
+ Print the summary information on a FITS file.
709
+
710
+ This includes the name, type, length of header, data shape and type
711
+ for each extension.
712
+
713
+ Parameters
714
+ ----------
715
+ filename : file path, file object, or file like object
716
+ FITS file to obtain info from. If opened, mode must be one of
717
+ the following: rb, rb+, or ab+ (i.e. the file must be readable).
718
+
719
+ output : file, bool, optional
720
+ A file-like object to write the output to. If ``False``, does not
721
+ output to a file and instead returns a list of tuples representing the
722
+ HDU info. Writes to ``sys.stdout`` by default.
723
+
724
+ kwargs
725
+ Any additional keyword arguments to be passed to
726
+ `astropy.io.fits.open`.
727
+ *Note:* This function sets ``ignore_missing_end=True`` by default.
728
+ """
729
+
730
+ mode, closed = _get_file_mode(filename, default='readonly')
731
+ # Set the default value for the ignore_missing_end parameter
732
+ if 'ignore_missing_end' not in kwargs:
733
+ kwargs['ignore_missing_end'] = True
734
+
735
+ f = fitsopen(filename, mode=mode, **kwargs)
736
+ try:
737
+ ret = f.info(output=output)
738
+ finally:
739
+ if closed:
740
+ f.close()
741
+
742
+ return ret
743
+
744
+
745
+ def printdiff(inputa, inputb, *args, **kwargs):
746
+ """
747
+ Compare two parts of a FITS file, including entire FITS files,
748
+ FITS `HDUList` objects and FITS ``HDU`` objects.
749
+
750
+ Parameters
751
+ ----------
752
+ inputa : str, `HDUList` object, or ``HDU`` object
753
+ The filename of a FITS file, `HDUList`, or ``HDU``
754
+ object to compare to ``inputb``.
755
+
756
+ inputb : str, `HDUList` object, or ``HDU`` object
757
+ The filename of a FITS file, `HDUList`, or ``HDU``
758
+ object to compare to ``inputa``.
759
+
760
+ ext, extname, extver
761
+ Additional positional arguments are for extension specification if your
762
+ inputs are string filenames (will not work if
763
+ ``inputa`` and ``inputb`` are ``HDU`` objects or `HDUList` objects).
764
+ They are flexible and are best illustrated by examples. In addition
765
+ to using these arguments positionally you can directly call the
766
+ keyword parameters ``ext``, ``extname``.
767
+
768
+ By extension number::
769
+
770
+ printdiff('inA.fits', 'inB.fits', 0) # the primary HDU
771
+ printdiff('inA.fits', 'inB.fits', 2) # the second extension
772
+ printdiff('inA.fits', 'inB.fits', ext=2) # the second extension
773
+
774
+ By name, i.e., ``EXTNAME`` value (if unique). ``EXTNAME`` values are
775
+ not case sensitive:
776
+
777
+ printdiff('inA.fits', 'inB.fits', 'sci')
778
+ printdiff('inA.fits', 'inB.fits', extname='sci') # equivalent
779
+
780
+ By combination of ``EXTNAME`` and ``EXTVER`` as separate
781
+ arguments or as a tuple::
782
+
783
+ printdiff('inA.fits', 'inB.fits', 'sci', 2) # EXTNAME='SCI'
784
+ # & EXTVER=2
785
+ printdiff('inA.fits', 'inB.fits', extname='sci', extver=2)
786
+ # equivalent
787
+ printdiff('inA.fits', 'inB.fits', ('sci', 2)) # equivalent
788
+
789
+ Ambiguous or conflicting specifications will raise an exception::
790
+
791
+ printdiff('inA.fits', 'inB.fits',
792
+ ext=('sci', 1), extname='err', extver=2)
793
+
794
+ kwargs
795
+ Any additional keyword arguments to be passed to
796
+ `~astropy.io.fits.FITSDiff`.
797
+
798
+ Notes
799
+ -----
800
+ The primary use for the `printdiff` function is to allow quick print out
801
+ of a FITS difference report and will write to ``sys.stdout``.
802
+ To save the diff report to a file please use `~astropy.io.fits.FITSDiff`
803
+ directly.
804
+ """
805
+
806
+ # Pop extension keywords
807
+ extension = {key: kwargs.pop(key) for key in ['ext', 'extname', 'extver']
808
+ if key in kwargs}
809
+ has_extensions = args or extension
810
+
811
+ if isinstance(inputa, str) and has_extensions:
812
+ # Use handy _getext to interpret any ext keywords, but
813
+ # will need to close a if fails
814
+ modea, closeda = _get_file_mode(inputa)
815
+ modeb, closedb = _get_file_mode(inputb)
816
+
817
+ hdulista, extidxa = _getext(inputa, modea, *args, **extension)
818
+ # Have to close a if b doesn't make it
819
+ try:
820
+ hdulistb, extidxb = _getext(inputb, modeb, *args, **extension)
821
+ except Exception:
822
+ hdulista.close(closed=closeda)
823
+ raise
824
+
825
+ try:
826
+ hdua = hdulista[extidxa]
827
+ hdub = hdulistb[extidxb]
828
+ # See below print for note
829
+ print(HDUDiff(hdua, hdub, **kwargs).report())
830
+
831
+ finally:
832
+ hdulista.close(closed=closeda)
833
+ hdulistb.close(closed=closedb)
834
+
835
+ # If input is not a string, can feed HDU objects or HDUList directly,
836
+ # but can't currently handle extensions
837
+ elif isinstance(inputa, _ValidHDU) and has_extensions:
838
+ raise ValueError("Cannot use extension keywords when providing an "
839
+ "HDU object.")
840
+
841
+ elif isinstance(inputa, _ValidHDU) and not has_extensions:
842
+ print(HDUDiff(inputa, inputb, **kwargs).report())
843
+
844
+ elif isinstance(inputa, HDUList) and has_extensions:
845
+ raise NotImplementedError("Extension specification with HDUList "
846
+ "objects not implemented.")
847
+
848
+ # This function is EXCLUSIVELY for printing the diff report to screen
849
+ # in a one-liner call, hence the use of print instead of logging
850
+ else:
851
+ print(FITSDiff(inputa, inputb, **kwargs).report())
852
+
853
+
854
+ @deprecated_renamed_argument('clobber', 'overwrite', '2.0')
855
+ def tabledump(filename, datafile=None, cdfile=None, hfile=None, ext=1,
856
+ overwrite=False):
857
+ """
858
+ Dump a table HDU to a file in ASCII format. The table may be
859
+ dumped in three separate files, one containing column definitions,
860
+ one containing header parameters, and one for table data.
861
+
862
+ Parameters
863
+ ----------
864
+ filename : file path, file object or file-like object
865
+ Input fits file.
866
+
867
+ datafile : file path, file object or file-like object, optional
868
+ Output data file. The default is the root name of the input
869
+ fits file appended with an underscore, followed by the
870
+ extension number (ext), followed by the extension ``.txt``.
871
+
872
+ cdfile : file path, file object or file-like object, optional
873
+ Output column definitions file. The default is `None`,
874
+ no column definitions output is produced.
875
+
876
+ hfile : file path, file object or file-like object, optional
877
+ Output header parameters file. The default is `None`,
878
+ no header parameters output is produced.
879
+
880
+ ext : int
881
+ The number of the extension containing the table HDU to be
882
+ dumped.
883
+
884
+ overwrite : bool, optional
885
+ If ``True``, overwrite the output file if it exists. Raises an
886
+ ``OSError`` if ``False`` and the output file exists. Default is
887
+ ``False``.
888
+
889
+ .. versionchanged:: 1.3
890
+ ``overwrite`` replaces the deprecated ``clobber`` argument.
891
+
892
+ Notes
893
+ -----
894
+ The primary use for the `tabledump` function is to allow editing in a
895
+ standard text editor of the table data and parameters. The
896
+ `tableload` function can be used to reassemble the table from the
897
+ three ASCII files.
898
+ """
899
+
900
+ # allow file object to already be opened in any of the valid modes
901
+ # and leave the file in the same state (opened or closed) as when
902
+ # the function was called
903
+
904
+ mode, closed = _get_file_mode(filename, default='readonly')
905
+ f = fitsopen(filename, mode=mode)
906
+
907
+ # Create the default data file name if one was not provided
908
+ try:
909
+ if not datafile:
910
+ root, tail = os.path.splitext(f._file.name)
911
+ datafile = root + '_' + repr(ext) + '.txt'
912
+
913
+ # Dump the data from the HDU to the files
914
+ f[ext].dump(datafile, cdfile, hfile, overwrite)
915
+ finally:
916
+ if closed:
917
+ f.close()
918
+
919
+
920
+ if isinstance(tabledump.__doc__, str):
921
+ tabledump.__doc__ += BinTableHDU._tdump_file_format.replace('\n', '\n ')
922
+
923
+
924
+ def tableload(datafile, cdfile, hfile=None):
925
+ """
926
+ Create a table from the input ASCII files. The input is from up
927
+ to three separate files, one containing column definitions, one
928
+ containing header parameters, and one containing column data. The
929
+ header parameters file is not required. When the header
930
+ parameters file is absent a minimal header is constructed.
931
+
932
+ Parameters
933
+ ----------
934
+ datafile : file path, file object or file-like object
935
+ Input data file containing the table data in ASCII format.
936
+
937
+ cdfile : file path, file object or file-like object
938
+ Input column definition file containing the names, formats,
939
+ display formats, physical units, multidimensional array
940
+ dimensions, undefined values, scale factors, and offsets
941
+ associated with the columns in the table.
942
+
943
+ hfile : file path, file object or file-like object, optional
944
+ Input parameter definition file containing the header
945
+ parameter definitions to be associated with the table.
946
+ If `None`, a minimal header is constructed.
947
+
948
+ Notes
949
+ -----
950
+ The primary use for the `tableload` function is to allow the input of
951
+ ASCII data that was edited in a standard text editor of the table
952
+ data and parameters. The tabledump function can be used to create the
953
+ initial ASCII files.
954
+ """
955
+
956
+ return BinTableHDU.load(datafile, cdfile, hfile, replace=True)
957
+
958
+
959
+ if isinstance(tableload.__doc__, str):
960
+ tableload.__doc__ += BinTableHDU._tdump_file_format.replace('\n', '\n ')
961
+
962
+
963
+ def _getext(filename, mode, *args, ext=None, extname=None, extver=None,
964
+ **kwargs):
965
+ """
966
+ Open the input file, return the `HDUList` and the extension.
967
+
968
+ This supports several different styles of extension selection. See the
969
+ :func:`getdata()` documentation for the different possibilities.
970
+ """
971
+
972
+ err_msg = ('Redundant/conflicting extension arguments(s): {}'.format(
973
+ {'args': args, 'ext': ext, 'extname': extname,
974
+ 'extver': extver}))
975
+
976
+ # This code would be much simpler if just one way of specifying an
977
+ # extension were picked. But now we need to support all possible ways for
978
+ # the time being.
979
+ if len(args) == 1:
980
+ # Must be either an extension number, an extension name, or an
981
+ # (extname, extver) tuple
982
+ if _is_int(args[0]) or (isinstance(ext, tuple) and len(ext) == 2):
983
+ if ext is not None or extname is not None or extver is not None:
984
+ raise TypeError(err_msg)
985
+ ext = args[0]
986
+ elif isinstance(args[0], str):
987
+ # The first arg is an extension name; it could still be valid
988
+ # to provide an extver kwarg
989
+ if ext is not None or extname is not None:
990
+ raise TypeError(err_msg)
991
+ extname = args[0]
992
+ else:
993
+ # Take whatever we have as the ext argument; we'll validate it
994
+ # below
995
+ ext = args[0]
996
+ elif len(args) == 2:
997
+ # Must be an extname and extver
998
+ if ext is not None or extname is not None or extver is not None:
999
+ raise TypeError(err_msg)
1000
+ extname = args[0]
1001
+ extver = args[1]
1002
+ elif len(args) > 2:
1003
+ raise TypeError('Too many positional arguments.')
1004
+
1005
+ if (ext is not None and
1006
+ not (_is_int(ext) or
1007
+ (isinstance(ext, tuple) and len(ext) == 2 and
1008
+ isinstance(ext[0], str) and _is_int(ext[1])))):
1009
+ raise ValueError(
1010
+ 'The ext keyword must be either an extension number '
1011
+ '(zero-indexed) or a (extname, extver) tuple.')
1012
+ if extname is not None and not isinstance(extname, str):
1013
+ raise ValueError('The extname argument must be a string.')
1014
+ if extver is not None and not _is_int(extver):
1015
+ raise ValueError('The extver argument must be an integer.')
1016
+
1017
+ if ext is None and extname is None and extver is None:
1018
+ ext = 0
1019
+ elif ext is not None and (extname is not None or extver is not None):
1020
+ raise TypeError(err_msg)
1021
+ elif extname:
1022
+ if extver:
1023
+ ext = (extname, extver)
1024
+ else:
1025
+ ext = (extname, 1)
1026
+ elif extver and extname is None:
1027
+ raise TypeError('extver alone cannot specify an extension.')
1028
+
1029
+ hdulist = fitsopen(filename, mode=mode, **kwargs)
1030
+
1031
+ return hdulist, ext
1032
+
1033
+
1034
+ def _makehdu(data, header):
1035
+ if header is None:
1036
+ header = Header()
1037
+ hdu = _BaseHDU._from_data(data, header)
1038
+ if hdu.__class__ in (_BaseHDU, _ValidHDU):
1039
+ # The HDU type was unrecognized, possibly due to a
1040
+ # nonexistent/incomplete header
1041
+ if ((isinstance(data, np.ndarray) and data.dtype.fields is not None) or
1042
+ isinstance(data, np.recarray)):
1043
+ hdu = BinTableHDU(data, header=header)
1044
+ elif isinstance(data, np.ndarray):
1045
+ hdu = ImageHDU(data, header=header)
1046
+ else:
1047
+ raise KeyError('Data must be a numpy array.')
1048
+ return hdu
1049
+
1050
+
1051
+ def _stat_filename_or_fileobj(filename):
1052
+ closed = fileobj_closed(filename)
1053
+ name = fileobj_name(filename) or ''
1054
+
1055
+ try:
1056
+ loc = filename.tell()
1057
+ except AttributeError:
1058
+ loc = 0
1059
+
1060
+ noexist_or_empty = ((name and
1061
+ (not os.path.exists(name) or
1062
+ (os.path.getsize(name) == 0)))
1063
+ or (not name and loc == 0))
1064
+
1065
+ return name, closed, noexist_or_empty
1066
+
1067
+
1068
+ def _get_file_mode(filename, default='readonly'):
1069
+ """
1070
+ Allow file object to already be opened in any of the valid modes and
1071
+ and leave the file in the same state (opened or closed) as when
1072
+ the function was called.
1073
+ """
1074
+
1075
+ mode = default
1076
+ closed = fileobj_closed(filename)
1077
+
1078
+ fmode = fileobj_mode(filename)
1079
+ if fmode is not None:
1080
+ mode = FILE_MODES.get(fmode)
1081
+ if mode is None:
1082
+ raise OSError(
1083
+ "File mode of the input file object ({!r}) cannot be used to "
1084
+ "read/write FITS files.".format(fmode))
1085
+
1086
+ return mode, closed
testbed/astropy__astropy/astropy/io/fits/diff.py ADDED
@@ -0,0 +1,1512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+ """
3
+ Facilities for diffing two FITS files. Includes objects for diffing entire
4
+ FITS files, individual HDUs, FITS headers, or just FITS data.
5
+
6
+ Used to implement the fitsdiff program.
7
+ """
8
+ import fnmatch
9
+ import glob
10
+ import io
11
+ import operator
12
+ import os.path
13
+ import textwrap
14
+ import warnings
15
+
16
+ from collections import defaultdict
17
+ from inspect import signature
18
+ from itertools import islice
19
+
20
+ import numpy as np
21
+
22
+ from astropy import __version__
23
+
24
+ from .card import Card, BLANK_CARD
25
+ from .header import Header
26
+ from astropy.utils.decorators import deprecated_renamed_argument
27
+ # HDUList is used in one of the doctests
28
+ from .hdu.hdulist import fitsopen, HDUList # pylint: disable=W0611
29
+ from .hdu.table import _TableLikeHDU
30
+ from astropy.utils.exceptions import AstropyDeprecationWarning
31
+ from astropy.utils.diff import (report_diff_values, fixed_width_indent,
32
+ where_not_allclose, diff_values)
33
+
34
+ __all__ = ['FITSDiff', 'HDUDiff', 'HeaderDiff', 'ImageDataDiff', 'RawDataDiff',
35
+ 'TableDataDiff']
36
+
37
+ # Column attributes of interest for comparison
38
+ _COL_ATTRS = [('unit', 'units'), ('null', 'null values'),
39
+ ('bscale', 'bscales'), ('bzero', 'bzeros'),
40
+ ('disp', 'display formats'), ('dim', 'dimensions')]
41
+
42
+
43
+ class _BaseDiff:
44
+ """
45
+ Base class for all FITS diff objects.
46
+
47
+ When instantiating a FITS diff object, the first two arguments are always
48
+ the two objects to diff (two FITS files, two FITS headers, etc.).
49
+ Instantiating a ``_BaseDiff`` also causes the diff itself to be executed.
50
+ The returned ``_BaseDiff`` instance has a number of attribute that describe
51
+ the results of the diff operation.
52
+
53
+ The most basic attribute, present on all ``_BaseDiff`` instances, is
54
+ ``.identical`` which is `True` if the two objects being compared are
55
+ identical according to the diff method for objects of that type.
56
+ """
57
+
58
+ def __init__(self, a, b):
59
+ """
60
+ The ``_BaseDiff`` class does not implement a ``_diff`` method and
61
+ should not be instantiated directly. Instead instantiate the
62
+ appropriate subclass of ``_BaseDiff`` for the objects being compared
63
+ (for example, use `HeaderDiff` to compare two `Header` objects.
64
+ """
65
+
66
+ self.a = a
67
+ self.b = b
68
+
69
+ # For internal use in report output
70
+ self._fileobj = None
71
+ self._indent = 0
72
+
73
+ self._diff()
74
+
75
+ def __bool__(self):
76
+ """
77
+ A ``_BaseDiff`` object acts as `True` in a boolean context if the two
78
+ objects compared are identical. Otherwise it acts as `False`.
79
+ """
80
+
81
+ return not self.identical
82
+
83
+ @classmethod
84
+ def fromdiff(cls, other, a, b):
85
+ """
86
+ Returns a new Diff object of a specific subclass from an existing diff
87
+ object, passing on the values for any arguments they share in common
88
+ (such as ignore_keywords).
89
+
90
+ For example::
91
+
92
+ >>> from astropy.io import fits
93
+ >>> hdul1, hdul2 = fits.HDUList(), fits.HDUList()
94
+ >>> headera, headerb = fits.Header(), fits.Header()
95
+ >>> fd = fits.FITSDiff(hdul1, hdul2, ignore_keywords=['*'])
96
+ >>> hd = fits.HeaderDiff.fromdiff(fd, headera, headerb)
97
+ >>> list(hd.ignore_keywords)
98
+ ['*']
99
+ """
100
+
101
+ sig = signature(cls.__init__)
102
+ # The first 3 arguments of any Diff initializer are self, a, and b.
103
+ kwargs = {}
104
+ for arg in list(sig.parameters.keys())[3:]:
105
+ if hasattr(other, arg):
106
+ kwargs[arg] = getattr(other, arg)
107
+
108
+ return cls(a, b, **kwargs)
109
+
110
+ @property
111
+ def identical(self):
112
+ """
113
+ `True` if all the ``.diff_*`` attributes on this diff instance are
114
+ empty, implying that no differences were found.
115
+
116
+ Any subclass of ``_BaseDiff`` must have at least one ``.diff_*``
117
+ attribute, which contains a non-empty value if and only if some
118
+ difference was found between the two objects being compared.
119
+ """
120
+
121
+ return not any(getattr(self, attr) for attr in self.__dict__
122
+ if attr.startswith('diff_'))
123
+
124
+ @deprecated_renamed_argument('clobber', 'overwrite', '2.0')
125
+ def report(self, fileobj=None, indent=0, overwrite=False):
126
+ """
127
+ Generates a text report on the differences (if any) between two
128
+ objects, and either returns it as a string or writes it to a file-like
129
+ object.
130
+
131
+ Parameters
132
+ ----------
133
+ fileobj : file-like object, string, or None (optional)
134
+ If `None`, this method returns the report as a string. Otherwise it
135
+ returns `None` and writes the report to the given file-like object
136
+ (which must have a ``.write()`` method at a minimum), or to a new
137
+ file at the path specified.
138
+
139
+ indent : int
140
+ The number of 4 space tabs to indent the report.
141
+
142
+ overwrite : bool, optional
143
+ If ``True``, overwrite the output file if it exists. Raises an
144
+ ``OSError`` if ``False`` and the output file exists. Default is
145
+ ``False``.
146
+
147
+ .. versionchanged:: 1.3
148
+ ``overwrite`` replaces the deprecated ``clobber`` argument.
149
+
150
+ Returns
151
+ -------
152
+ report : str or None
153
+ """
154
+
155
+ return_string = False
156
+ filepath = None
157
+
158
+ if isinstance(fileobj, str):
159
+ if os.path.exists(fileobj) and not overwrite:
160
+ raise OSError("File {0} exists, aborting (pass in "
161
+ "overwrite=True to overwrite)".format(fileobj))
162
+ else:
163
+ filepath = fileobj
164
+ fileobj = open(filepath, 'w')
165
+ elif fileobj is None:
166
+ fileobj = io.StringIO()
167
+ return_string = True
168
+
169
+ self._fileobj = fileobj
170
+ self._indent = indent # This is used internally by _writeln
171
+
172
+ try:
173
+ self._report()
174
+ finally:
175
+ if filepath:
176
+ fileobj.close()
177
+
178
+ if return_string:
179
+ return fileobj.getvalue()
180
+
181
+ def _writeln(self, text):
182
+ self._fileobj.write(fixed_width_indent(text, self._indent) + '\n')
183
+
184
+ def _diff(self):
185
+ raise NotImplementedError
186
+
187
+ def _report(self):
188
+ raise NotImplementedError
189
+
190
+
191
+ class FITSDiff(_BaseDiff):
192
+ """Diff two FITS files by filename, or two `HDUList` objects.
193
+
194
+ `FITSDiff` objects have the following diff attributes:
195
+
196
+ - ``diff_hdu_count``: If the FITS files being compared have different
197
+ numbers of HDUs, this contains a 2-tuple of the number of HDUs in each
198
+ file.
199
+
200
+ - ``diff_hdus``: If any HDUs with the same index are different, this
201
+ contains a list of 2-tuples of the HDU index and the `HDUDiff` object
202
+ representing the differences between the two HDUs.
203
+ """
204
+
205
+ def __init__(self, a, b, ignore_hdus=[], ignore_keywords=[],
206
+ ignore_comments=[], ignore_fields=[],
207
+ numdiffs=10, rtol=0.0, atol=0.0,
208
+ ignore_blanks=True, ignore_blank_cards=True, tolerance=None):
209
+ """
210
+ Parameters
211
+ ----------
212
+ a : str or `HDUList`
213
+ The filename of a FITS file on disk, or an `HDUList` object.
214
+
215
+ b : str or `HDUList`
216
+ The filename of a FITS file on disk, or an `HDUList` object to
217
+ compare to the first file.
218
+
219
+ ignore_hdus : sequence, optional
220
+ HDU names to ignore when comparing two FITS files or HDU lists; the
221
+ presence of these HDUs and their contents are ignored. Wildcard
222
+ strings may also be included in the list.
223
+
224
+ ignore_keywords : sequence, optional
225
+ Header keywords to ignore when comparing two headers; the presence
226
+ of these keywords and their values are ignored. Wildcard strings
227
+ may also be included in the list.
228
+
229
+ ignore_comments : sequence, optional
230
+ A list of header keywords whose comments should be ignored in the
231
+ comparison. May contain wildcard strings as with ignore_keywords.
232
+
233
+ ignore_fields : sequence, optional
234
+ The (case-insensitive) names of any table columns to ignore if any
235
+ table data is to be compared.
236
+
237
+ numdiffs : int, optional
238
+ The number of pixel/table values to output when reporting HDU data
239
+ differences. Though the count of differences is the same either
240
+ way, this allows controlling the number of different values that
241
+ are kept in memory or output. If a negative value is given, then
242
+ numdiffs is treated as unlimited (default: 10).
243
+
244
+ rtol : float, optional
245
+ The relative difference to allow when comparing two float values
246
+ either in header values, image arrays, or table columns
247
+ (default: 0.0). Values which satisfy the expression
248
+
249
+ .. math::
250
+
251
+ \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right|
252
+
253
+ are considered to be different.
254
+ The underlying function used for comparison is `numpy.allclose`.
255
+
256
+ .. versionchanged:: 2.0
257
+ ``rtol`` replaces the deprecated ``tolerance`` argument.
258
+
259
+ atol : float, optional
260
+ The allowed absolute difference. See also ``rtol`` parameter.
261
+
262
+ .. versionadded:: 2.0
263
+
264
+ ignore_blanks : bool, optional
265
+ Ignore extra whitespace at the end of string values either in
266
+ headers or data. Extra leading whitespace is not ignored
267
+ (default: True).
268
+
269
+ ignore_blank_cards : bool, optional
270
+ Ignore all cards that are blank, i.e. they only contain
271
+ whitespace (default: True).
272
+ """
273
+
274
+ if isinstance(a, str):
275
+ try:
276
+ a = fitsopen(a)
277
+ except Exception as exc:
278
+ raise OSError("error opening file a ({}): {}: {}".format(
279
+ a, exc.__class__.__name__, exc.args[0]))
280
+ close_a = True
281
+ else:
282
+ close_a = False
283
+
284
+ if isinstance(b, str):
285
+ try:
286
+ b = fitsopen(b)
287
+ except Exception as exc:
288
+ raise OSError("error opening file b ({}): {}: {}".format(
289
+ b, exc.__class__.__name__, exc.args[0]))
290
+ close_b = True
291
+ else:
292
+ close_b = False
293
+
294
+ # Normalize keywords/fields to ignore to upper case
295
+ self.ignore_hdus = set(k.upper() for k in ignore_hdus)
296
+ self.ignore_keywords = set(k.upper() for k in ignore_keywords)
297
+ self.ignore_comments = set(k.upper() for k in ignore_comments)
298
+ self.ignore_fields = set(k.upper() for k in ignore_fields)
299
+
300
+ self.numdiffs = numdiffs
301
+ self.rtol = rtol
302
+ self.atol = atol
303
+
304
+ if tolerance is not None: # This should be removed in the next astropy version
305
+ warnings.warn(
306
+ '"tolerance" was deprecated in version 2.0 and will be removed in '
307
+ 'a future version. Use argument "rtol" instead.',
308
+ AstropyDeprecationWarning)
309
+ self.rtol = tolerance # when tolerance is provided *always* ignore `rtol`
310
+ # during the transition/deprecation period
311
+
312
+ self.ignore_blanks = ignore_blanks
313
+ self.ignore_blank_cards = ignore_blank_cards
314
+
315
+ # Some hdu names may be pattern wildcards. Find them.
316
+ self.ignore_hdu_patterns = set()
317
+ for name in list(self.ignore_hdus):
318
+ if name != '*' and glob.has_magic(name):
319
+ self.ignore_hdus.remove(name)
320
+ self.ignore_hdu_patterns.add(name)
321
+
322
+ self.diff_hdu_count = ()
323
+ self.diff_hdus = []
324
+
325
+ try:
326
+ super().__init__(a, b)
327
+ finally:
328
+ if close_a:
329
+ a.close()
330
+ if close_b:
331
+ b.close()
332
+
333
+ def _diff(self):
334
+ if len(self.a) != len(self.b):
335
+ self.diff_hdu_count = (len(self.a), len(self.b))
336
+
337
+ # Record filenames for use later in _report
338
+ self.filenamea = self.a.filename()
339
+ if not self.filenamea:
340
+ self.filenamea = '<{} object at {:#x}>'.format(
341
+ self.a.__class__.__name__, id(self.a))
342
+
343
+ self.filenameb = self.b.filename()
344
+ if not self.filenameb:
345
+ self.filenameb = '<{} object at {:#x}>'.format(
346
+ self.b.__class__.__name__, id(self.b))
347
+
348
+ if self.ignore_hdus:
349
+ self.a = HDUList([h for h in self.a if h.name not in self.ignore_hdus])
350
+ self.b = HDUList([h for h in self.b if h.name not in self.ignore_hdus])
351
+ if self.ignore_hdu_patterns:
352
+ a_names = [hdu.name for hdu in self.a]
353
+ b_names = [hdu.name for hdu in self.b]
354
+ for pattern in self.ignore_hdu_patterns:
355
+ self.a = HDUList([h for h in self.a if h.name not in fnmatch.filter(
356
+ a_names, pattern)])
357
+ self.b = HDUList([h for h in self.b if h.name not in fnmatch.filter(
358
+ b_names, pattern)])
359
+
360
+ # For now, just compare the extensions one by one in order.
361
+ # Might allow some more sophisticated types of diffing later.
362
+
363
+ # TODO: Somehow or another simplify the passing around of diff
364
+ # options--this will become important as the number of options grows
365
+ for idx in range(min(len(self.a), len(self.b))):
366
+ hdu_diff = HDUDiff.fromdiff(self, self.a[idx], self.b[idx])
367
+
368
+ if not hdu_diff.identical:
369
+ self.diff_hdus.append((idx, hdu_diff))
370
+
371
+ def _report(self):
372
+ wrapper = textwrap.TextWrapper(initial_indent=' ',
373
+ subsequent_indent=' ')
374
+
375
+ self._fileobj.write('\n')
376
+ self._writeln(' fitsdiff: {}'.format(__version__))
377
+ self._writeln(' a: {}\n b: {}'.format(self.filenamea, self.filenameb))
378
+
379
+ if self.ignore_hdus:
380
+ ignore_hdus = ' '.join(sorted(self.ignore_hdus))
381
+ self._writeln(' HDU(s) not to be compared:\n{}'
382
+ .format(wrapper.fill(ignore_hdus)))
383
+
384
+ if self.ignore_hdu_patterns:
385
+ ignore_hdu_patterns = ' '.join(sorted(self.ignore_hdu_patterns))
386
+ self._writeln(' HDU(s) not to be compared:\n{}'
387
+ .format(wrapper.fill(ignore_hdu_patterns)))
388
+
389
+ if self.ignore_keywords:
390
+ ignore_keywords = ' '.join(sorted(self.ignore_keywords))
391
+ self._writeln(' Keyword(s) not to be compared:\n{}'
392
+ .format(wrapper.fill(ignore_keywords)))
393
+
394
+ if self.ignore_comments:
395
+ ignore_comments = ' '.join(sorted(self.ignore_comments))
396
+ self._writeln(' Keyword(s) whose comments are not to be compared'
397
+ ':\n{}'.format(wrapper.fill(ignore_comments)))
398
+
399
+ if self.ignore_fields:
400
+ ignore_fields = ' '.join(sorted(self.ignore_fields))
401
+ self._writeln(' Table column(s) not to be compared:\n{}'
402
+ .format(wrapper.fill(ignore_fields)))
403
+
404
+ self._writeln(' Maximum number of different data values to be '
405
+ 'reported: {}'.format(self.numdiffs))
406
+ self._writeln(' Relative tolerance: {}, Absolute tolerance: {}'
407
+ .format(self.rtol, self.atol))
408
+
409
+ if self.diff_hdu_count:
410
+ self._fileobj.write('\n')
411
+ self._writeln('Files contain different numbers of HDUs:')
412
+ self._writeln(' a: {}'.format(self.diff_hdu_count[0]))
413
+ self._writeln(' b: {}'.format(self.diff_hdu_count[1]))
414
+
415
+ if not self.diff_hdus:
416
+ self._writeln('No differences found between common HDUs.')
417
+ return
418
+ elif not self.diff_hdus:
419
+ self._fileobj.write('\n')
420
+ self._writeln('No differences found.')
421
+ return
422
+
423
+ for idx, hdu_diff in self.diff_hdus:
424
+ # print out the extension heading
425
+ if idx == 0:
426
+ self._fileobj.write('\n')
427
+ self._writeln('Primary HDU:')
428
+ else:
429
+ self._fileobj.write('\n')
430
+ self._writeln('Extension HDU {}:'.format(idx))
431
+ hdu_diff.report(self._fileobj, indent=self._indent + 1)
432
+
433
+
434
+ class HDUDiff(_BaseDiff):
435
+ """
436
+ Diff two HDU objects, including their headers and their data (but only if
437
+ both HDUs contain the same type of data (image, table, or unknown).
438
+
439
+ `HDUDiff` objects have the following diff attributes:
440
+
441
+ - ``diff_extnames``: If the two HDUs have different EXTNAME values, this
442
+ contains a 2-tuple of the different extension names.
443
+
444
+ - ``diff_extvers``: If the two HDUS have different EXTVER values, this
445
+ contains a 2-tuple of the different extension versions.
446
+
447
+ - ``diff_extlevels``: If the two HDUs have different EXTLEVEL values, this
448
+ contains a 2-tuple of the different extension levels.
449
+
450
+ - ``diff_extension_types``: If the two HDUs have different XTENSION values,
451
+ this contains a 2-tuple of the different extension types.
452
+
453
+ - ``diff_headers``: Contains a `HeaderDiff` object for the headers of the
454
+ two HDUs. This will always contain an object--it may be determined
455
+ whether the headers are different through ``diff_headers.identical``.
456
+
457
+ - ``diff_data``: Contains either a `ImageDataDiff`, `TableDataDiff`, or
458
+ `RawDataDiff` as appropriate for the data in the HDUs, and only if the
459
+ two HDUs have non-empty data of the same type (`RawDataDiff` is used for
460
+ HDUs containing non-empty data of an indeterminate type).
461
+ """
462
+
463
+ def __init__(self, a, b, ignore_keywords=[], ignore_comments=[],
464
+ ignore_fields=[], numdiffs=10, rtol=0.0, atol=0.0,
465
+ ignore_blanks=True, ignore_blank_cards=True, tolerance=None):
466
+ """
467
+ Parameters
468
+ ----------
469
+ a : `HDUList`
470
+ An `HDUList` object.
471
+
472
+ b : str or `HDUList`
473
+ An `HDUList` object to compare to the first `HDUList` object.
474
+
475
+ ignore_keywords : sequence, optional
476
+ Header keywords to ignore when comparing two headers; the presence
477
+ of these keywords and their values are ignored. Wildcard strings
478
+ may also be included in the list.
479
+
480
+ ignore_comments : sequence, optional
481
+ A list of header keywords whose comments should be ignored in the
482
+ comparison. May contain wildcard strings as with ignore_keywords.
483
+
484
+ ignore_fields : sequence, optional
485
+ The (case-insensitive) names of any table columns to ignore if any
486
+ table data is to be compared.
487
+
488
+ numdiffs : int, optional
489
+ The number of pixel/table values to output when reporting HDU data
490
+ differences. Though the count of differences is the same either
491
+ way, this allows controlling the number of different values that
492
+ are kept in memory or output. If a negative value is given, then
493
+ numdiffs is treated as unlimited (default: 10).
494
+
495
+ rtol : float, optional
496
+ The relative difference to allow when comparing two float values
497
+ either in header values, image arrays, or table columns
498
+ (default: 0.0). Values which satisfy the expression
499
+
500
+ .. math::
501
+
502
+ \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right|
503
+
504
+ are considered to be different.
505
+ The underlying function used for comparison is `numpy.allclose`.
506
+
507
+ .. versionchanged:: 2.0
508
+ ``rtol`` replaces the deprecated ``tolerance`` argument.
509
+
510
+ atol : float, optional
511
+ The allowed absolute difference. See also ``rtol`` parameter.
512
+
513
+ .. versionadded:: 2.0
514
+
515
+ ignore_blanks : bool, optional
516
+ Ignore extra whitespace at the end of string values either in
517
+ headers or data. Extra leading whitespace is not ignored
518
+ (default: True).
519
+
520
+ ignore_blank_cards : bool, optional
521
+ Ignore all cards that are blank, i.e. they only contain
522
+ whitespace (default: True).
523
+ """
524
+
525
+ self.ignore_keywords = {k.upper() for k in ignore_keywords}
526
+ self.ignore_comments = {k.upper() for k in ignore_comments}
527
+ self.ignore_fields = {k.upper() for k in ignore_fields}
528
+
529
+ self.rtol = rtol
530
+ self.atol = atol
531
+
532
+ if tolerance is not None: # This should be removed in the next astropy version
533
+ warnings.warn(
534
+ '"tolerance" was deprecated in version 2.0 and will be removed in '
535
+ 'a future version. Use argument "rtol" instead.',
536
+ AstropyDeprecationWarning)
537
+ self.rtol = tolerance # when tolerance is provided *always* ignore `rtol`
538
+ # during the transition/deprecation period
539
+
540
+ self.numdiffs = numdiffs
541
+ self.ignore_blanks = ignore_blanks
542
+
543
+ self.diff_extnames = ()
544
+ self.diff_extvers = ()
545
+ self.diff_extlevels = ()
546
+ self.diff_extension_types = ()
547
+ self.diff_headers = None
548
+ self.diff_data = None
549
+
550
+ super().__init__(a, b)
551
+
552
+ def _diff(self):
553
+ if self.a.name != self.b.name:
554
+ self.diff_extnames = (self.a.name, self.b.name)
555
+
556
+ if self.a.ver != self.b.ver:
557
+ self.diff_extvers = (self.a.ver, self.b.ver)
558
+
559
+ if self.a.level != self.b.level:
560
+ self.diff_extlevels = (self.a.level, self.b.level)
561
+
562
+ if self.a.header.get('XTENSION') != self.b.header.get('XTENSION'):
563
+ self.diff_extension_types = (self.a.header.get('XTENSION'),
564
+ self.b.header.get('XTENSION'))
565
+
566
+ self.diff_headers = HeaderDiff.fromdiff(self, self.a.header.copy(),
567
+ self.b.header.copy())
568
+
569
+ if self.a.data is None or self.b.data is None:
570
+ # TODO: Perhaps have some means of marking this case
571
+ pass
572
+ elif self.a.is_image and self.b.is_image:
573
+ self.diff_data = ImageDataDiff.fromdiff(self, self.a.data,
574
+ self.b.data)
575
+ elif (isinstance(self.a, _TableLikeHDU) and
576
+ isinstance(self.b, _TableLikeHDU)):
577
+ # TODO: Replace this if/when _BaseHDU grows a .is_table property
578
+ self.diff_data = TableDataDiff.fromdiff(self, self.a.data,
579
+ self.b.data)
580
+ elif not self.diff_extension_types:
581
+ # Don't diff the data for unequal extension types that are not
582
+ # recognized image or table types
583
+ self.diff_data = RawDataDiff.fromdiff(self, self.a.data,
584
+ self.b.data)
585
+
586
+ def _report(self):
587
+ if self.identical:
588
+ self._writeln(" No differences found.")
589
+ if self.diff_extension_types:
590
+ self._writeln(" Extension types differ:\n a: {}\n "
591
+ "b: {}".format(*self.diff_extension_types))
592
+ if self.diff_extnames:
593
+ self._writeln(" Extension names differ:\n a: {}\n "
594
+ "b: {}".format(*self.diff_extnames))
595
+ if self.diff_extvers:
596
+ self._writeln(" Extension versions differ:\n a: {}\n "
597
+ "b: {}".format(*self.diff_extvers))
598
+
599
+ if self.diff_extlevels:
600
+ self._writeln(" Extension levels differ:\n a: {}\n "
601
+ "b: {}".format(*self.diff_extlevels))
602
+
603
+ if not self.diff_headers.identical:
604
+ self._fileobj.write('\n')
605
+ self._writeln(" Headers contain differences:")
606
+ self.diff_headers.report(self._fileobj, indent=self._indent + 1)
607
+
608
+ if self.diff_data is not None and not self.diff_data.identical:
609
+ self._fileobj.write('\n')
610
+ self._writeln(" Data contains differences:")
611
+ self.diff_data.report(self._fileobj, indent=self._indent + 1)
612
+
613
+
614
+ class HeaderDiff(_BaseDiff):
615
+ """
616
+ Diff two `Header` objects.
617
+
618
+ `HeaderDiff` objects have the following diff attributes:
619
+
620
+ - ``diff_keyword_count``: If the two headers contain a different number of
621
+ keywords, this contains a 2-tuple of the keyword count for each header.
622
+
623
+ - ``diff_keywords``: If either header contains one or more keywords that
624
+ don't appear at all in the other header, this contains a 2-tuple
625
+ consisting of a list of the keywords only appearing in header a, and a
626
+ list of the keywords only appearing in header b.
627
+
628
+ - ``diff_duplicate_keywords``: If a keyword appears in both headers at
629
+ least once, but contains a different number of duplicates (for example, a
630
+ different number of HISTORY cards in each header), an item is added to
631
+ this dict with the keyword as the key, and a 2-tuple of the different
632
+ counts of that keyword as the value. For example::
633
+
634
+ {'HISTORY': (20, 19)}
635
+
636
+ means that header a contains 20 HISTORY cards, while header b contains
637
+ only 19 HISTORY cards.
638
+
639
+ - ``diff_keyword_values``: If any of the common keyword between the two
640
+ headers have different values, they appear in this dict. It has a
641
+ structure similar to ``diff_duplicate_keywords``, with the keyword as the
642
+ key, and a 2-tuple of the different values as the value. For example::
643
+
644
+ {'NAXIS': (2, 3)}
645
+
646
+ means that the NAXIS keyword has a value of 2 in header a, and a value of
647
+ 3 in header b. This excludes any keywords matched by the
648
+ ``ignore_keywords`` list.
649
+
650
+ - ``diff_keyword_comments``: Like ``diff_keyword_values``, but contains
651
+ differences between keyword comments.
652
+
653
+ `HeaderDiff` objects also have a ``common_keywords`` attribute that lists
654
+ all keywords that appear in both headers.
655
+ """
656
+
657
+ def __init__(self, a, b, ignore_keywords=[], ignore_comments=[],
658
+ rtol=0.0, atol=0.0, ignore_blanks=True, ignore_blank_cards=True,
659
+ tolerance=None):
660
+ """
661
+ Parameters
662
+ ----------
663
+ a : `HDUList`
664
+ An `HDUList` object.
665
+
666
+ b : `HDUList`
667
+ An `HDUList` object to compare to the first `HDUList` object.
668
+
669
+ ignore_keywords : sequence, optional
670
+ Header keywords to ignore when comparing two headers; the presence
671
+ of these keywords and their values are ignored. Wildcard strings
672
+ may also be included in the list.
673
+
674
+ ignore_comments : sequence, optional
675
+ A list of header keywords whose comments should be ignored in the
676
+ comparison. May contain wildcard strings as with ignore_keywords.
677
+
678
+ numdiffs : int, optional
679
+ The number of pixel/table values to output when reporting HDU data
680
+ differences. Though the count of differences is the same either
681
+ way, this allows controlling the number of different values that
682
+ are kept in memory or output. If a negative value is given, then
683
+ numdiffs is treated as unlimited (default: 10).
684
+
685
+ rtol : float, optional
686
+ The relative difference to allow when comparing two float values
687
+ either in header values, image arrays, or table columns
688
+ (default: 0.0). Values which satisfy the expression
689
+
690
+ .. math::
691
+
692
+ \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right|
693
+
694
+ are considered to be different.
695
+ The underlying function used for comparison is `numpy.allclose`.
696
+
697
+ .. versionchanged:: 2.0
698
+ ``rtol`` replaces the deprecated ``tolerance`` argument.
699
+
700
+ atol : float, optional
701
+ The allowed absolute difference. See also ``rtol`` parameter.
702
+
703
+ .. versionadded:: 2.0
704
+
705
+ ignore_blanks : bool, optional
706
+ Ignore extra whitespace at the end of string values either in
707
+ headers or data. Extra leading whitespace is not ignored
708
+ (default: True).
709
+
710
+ ignore_blank_cards : bool, optional
711
+ Ignore all cards that are blank, i.e. they only contain
712
+ whitespace (default: True).
713
+ """
714
+
715
+ self.ignore_keywords = {k.upper() for k in ignore_keywords}
716
+ self.ignore_comments = {k.upper() for k in ignore_comments}
717
+
718
+ self.rtol = rtol
719
+ self.atol = atol
720
+
721
+ if tolerance is not None: # This should be removed in the next astropy version
722
+ warnings.warn(
723
+ '"tolerance" was deprecated in version 2.0 and will be removed in '
724
+ 'a future version. Use argument "rtol" instead.',
725
+ AstropyDeprecationWarning)
726
+ self.rtol = tolerance # when tolerance is provided *always* ignore `rtol`
727
+ # during the transition/deprecation period
728
+
729
+ self.ignore_blanks = ignore_blanks
730
+ self.ignore_blank_cards = ignore_blank_cards
731
+
732
+ self.ignore_keyword_patterns = set()
733
+ self.ignore_comment_patterns = set()
734
+ for keyword in list(self.ignore_keywords):
735
+ keyword = keyword.upper()
736
+ if keyword != '*' and glob.has_magic(keyword):
737
+ self.ignore_keywords.remove(keyword)
738
+ self.ignore_keyword_patterns.add(keyword)
739
+ for keyword in list(self.ignore_comments):
740
+ keyword = keyword.upper()
741
+ if keyword != '*' and glob.has_magic(keyword):
742
+ self.ignore_comments.remove(keyword)
743
+ self.ignore_comment_patterns.add(keyword)
744
+
745
+ # Keywords appearing in each header
746
+ self.common_keywords = []
747
+
748
+ # Set to the number of keywords in each header if the counts differ
749
+ self.diff_keyword_count = ()
750
+
751
+ # Set if the keywords common to each header (excluding ignore_keywords)
752
+ # appear in different positions within the header
753
+ # TODO: Implement this
754
+ self.diff_keyword_positions = ()
755
+
756
+ # Keywords unique to each header (excluding keywords in
757
+ # ignore_keywords)
758
+ self.diff_keywords = ()
759
+
760
+ # Keywords that have different numbers of duplicates in each header
761
+ # (excluding keywords in ignore_keywords)
762
+ self.diff_duplicate_keywords = {}
763
+
764
+ # Keywords common to each header but having different values (excluding
765
+ # keywords in ignore_keywords)
766
+ self.diff_keyword_values = defaultdict(list)
767
+
768
+ # Keywords common to each header but having different comments
769
+ # (excluding keywords in ignore_keywords or in ignore_comments)
770
+ self.diff_keyword_comments = defaultdict(list)
771
+
772
+ if isinstance(a, str):
773
+ a = Header.fromstring(a)
774
+ if isinstance(b, str):
775
+ b = Header.fromstring(b)
776
+
777
+ if not (isinstance(a, Header) and isinstance(b, Header)):
778
+ raise TypeError('HeaderDiff can only diff astropy.io.fits.Header '
779
+ 'objects or strings containing FITS headers.')
780
+
781
+ super().__init__(a, b)
782
+
783
+ # TODO: This doesn't pay much attention to the *order* of the keywords,
784
+ # except in the case of duplicate keywords. The order should be checked
785
+ # too, or at least it should be an option.
786
+ def _diff(self):
787
+ if self.ignore_blank_cards:
788
+ cardsa = [c for c in self.a.cards if str(c) != BLANK_CARD]
789
+ cardsb = [c for c in self.b.cards if str(c) != BLANK_CARD]
790
+ else:
791
+ cardsa = list(self.a.cards)
792
+ cardsb = list(self.b.cards)
793
+
794
+ # build dictionaries of keyword values and comments
795
+ def get_header_values_comments(cards):
796
+ values = {}
797
+ comments = {}
798
+ for card in cards:
799
+ value = card.value
800
+ if self.ignore_blanks and isinstance(value, str):
801
+ value = value.rstrip()
802
+ values.setdefault(card.keyword, []).append(value)
803
+ comments.setdefault(card.keyword, []).append(card.comment)
804
+ return values, comments
805
+
806
+ valuesa, commentsa = get_header_values_comments(cardsa)
807
+ valuesb, commentsb = get_header_values_comments(cardsb)
808
+
809
+ # Normalize all keyword to upper-case for comparison's sake;
810
+ # TODO: HIERARCH keywords should be handled case-sensitively I think
811
+ keywordsa = {k.upper() for k in valuesa}
812
+ keywordsb = {k.upper() for k in valuesb}
813
+
814
+ self.common_keywords = sorted(keywordsa.intersection(keywordsb))
815
+ if len(cardsa) != len(cardsb):
816
+ self.diff_keyword_count = (len(cardsa), len(cardsb))
817
+
818
+ # Any other diff attributes should exclude ignored keywords
819
+ keywordsa = keywordsa.difference(self.ignore_keywords)
820
+ keywordsb = keywordsb.difference(self.ignore_keywords)
821
+ if self.ignore_keyword_patterns:
822
+ for pattern in self.ignore_keyword_patterns:
823
+ keywordsa = keywordsa.difference(fnmatch.filter(keywordsa,
824
+ pattern))
825
+ keywordsb = keywordsb.difference(fnmatch.filter(keywordsb,
826
+ pattern))
827
+
828
+ if '*' in self.ignore_keywords:
829
+ # Any other differences between keywords are to be ignored
830
+ return
831
+
832
+ left_only_keywords = sorted(keywordsa.difference(keywordsb))
833
+ right_only_keywords = sorted(keywordsb.difference(keywordsa))
834
+
835
+ if left_only_keywords or right_only_keywords:
836
+ self.diff_keywords = (left_only_keywords, right_only_keywords)
837
+
838
+ # Compare count of each common keyword
839
+ for keyword in self.common_keywords:
840
+ if keyword in self.ignore_keywords:
841
+ continue
842
+ if self.ignore_keyword_patterns:
843
+ skip = False
844
+ for pattern in self.ignore_keyword_patterns:
845
+ if fnmatch.fnmatch(keyword, pattern):
846
+ skip = True
847
+ break
848
+ if skip:
849
+ continue
850
+
851
+ counta = len(valuesa[keyword])
852
+ countb = len(valuesb[keyword])
853
+ if counta != countb:
854
+ self.diff_duplicate_keywords[keyword] = (counta, countb)
855
+
856
+ # Compare keywords' values and comments
857
+ for a, b in zip(valuesa[keyword], valuesb[keyword]):
858
+ if diff_values(a, b, rtol=self.rtol, atol=self.atol):
859
+ self.diff_keyword_values[keyword].append((a, b))
860
+ else:
861
+ # If there are duplicate keywords we need to be able to
862
+ # index each duplicate; if the values of a duplicate
863
+ # are identical use None here
864
+ self.diff_keyword_values[keyword].append(None)
865
+
866
+ if not any(self.diff_keyword_values[keyword]):
867
+ # No differences found; delete the array of Nones
868
+ del self.diff_keyword_values[keyword]
869
+
870
+ if '*' in self.ignore_comments or keyword in self.ignore_comments:
871
+ continue
872
+ if self.ignore_comment_patterns:
873
+ skip = False
874
+ for pattern in self.ignore_comment_patterns:
875
+ if fnmatch.fnmatch(keyword, pattern):
876
+ skip = True
877
+ break
878
+ if skip:
879
+ continue
880
+
881
+ for a, b in zip(commentsa[keyword], commentsb[keyword]):
882
+ if diff_values(a, b):
883
+ self.diff_keyword_comments[keyword].append((a, b))
884
+ else:
885
+ self.diff_keyword_comments[keyword].append(None)
886
+
887
+ if not any(self.diff_keyword_comments[keyword]):
888
+ del self.diff_keyword_comments[keyword]
889
+
890
+ def _report(self):
891
+ if self.diff_keyword_count:
892
+ self._writeln(' Headers have different number of cards:')
893
+ self._writeln(' a: {}'.format(self.diff_keyword_count[0]))
894
+ self._writeln(' b: {}'.format(self.diff_keyword_count[1]))
895
+ if self.diff_keywords:
896
+ for keyword in self.diff_keywords[0]:
897
+ if keyword in Card._commentary_keywords:
898
+ val = self.a[keyword][0]
899
+ else:
900
+ val = self.a[keyword]
901
+ self._writeln(' Extra keyword {!r:8} in a: {!r}'.format(
902
+ keyword, val))
903
+ for keyword in self.diff_keywords[1]:
904
+ if keyword in Card._commentary_keywords:
905
+ val = self.b[keyword][0]
906
+ else:
907
+ val = self.b[keyword]
908
+ self._writeln(' Extra keyword {!r:8} in b: {!r}'.format(
909
+ keyword, val))
910
+
911
+ if self.diff_duplicate_keywords:
912
+ for keyword, count in sorted(self.diff_duplicate_keywords.items()):
913
+ self._writeln(' Inconsistent duplicates of keyword {!r:8}:'
914
+ .format(keyword))
915
+ self._writeln(' Occurs {} time(s) in a, {} times in (b)'
916
+ .format(*count))
917
+
918
+ if self.diff_keyword_values or self.diff_keyword_comments:
919
+ for keyword in self.common_keywords:
920
+ report_diff_keyword_attr(self._fileobj, 'values',
921
+ self.diff_keyword_values, keyword,
922
+ ind=self._indent)
923
+ report_diff_keyword_attr(self._fileobj, 'comments',
924
+ self.diff_keyword_comments, keyword,
925
+ ind=self._indent)
926
+
927
+ # TODO: It might be good if there was also a threshold option for percentage of
928
+ # different pixels: For example ignore if only 1% of the pixels are different
929
+ # within some threshold. There are lots of possibilities here, but hold off
930
+ # for now until specific cases come up.
931
+
932
+
933
+ class ImageDataDiff(_BaseDiff):
934
+ """
935
+ Diff two image data arrays (really any array from a PRIMARY HDU or an IMAGE
936
+ extension HDU, though the data unit is assumed to be "pixels").
937
+
938
+ `ImageDataDiff` objects have the following diff attributes:
939
+
940
+ - ``diff_dimensions``: If the two arrays contain either a different number
941
+ of dimensions or different sizes in any dimension, this contains a
942
+ 2-tuple of the shapes of each array. Currently no further comparison is
943
+ performed on images that don't have the exact same dimensions.
944
+
945
+ - ``diff_pixels``: If the two images contain any different pixels, this
946
+ contains a list of 2-tuples of the array index where the difference was
947
+ found, and another 2-tuple containing the different values. For example,
948
+ if the pixel at (0, 0) contains different values this would look like::
949
+
950
+ [(0, 0), (1.1, 2.2)]
951
+
952
+ where 1.1 and 2.2 are the values of that pixel in each array. This
953
+ array only contains up to ``self.numdiffs`` differences, for storage
954
+ efficiency.
955
+
956
+ - ``diff_total``: The total number of different pixels found between the
957
+ arrays. Although ``diff_pixels`` does not necessarily contain all the
958
+ different pixel values, this can be used to get a count of the total
959
+ number of differences found.
960
+
961
+ - ``diff_ratio``: Contains the ratio of ``diff_total`` to the total number
962
+ of pixels in the arrays.
963
+ """
964
+
965
+ def __init__(self, a, b, numdiffs=10, rtol=0.0, atol=0.0, tolerance=None):
966
+ """
967
+ Parameters
968
+ ----------
969
+ a : `HDUList`
970
+ An `HDUList` object.
971
+
972
+ b : `HDUList`
973
+ An `HDUList` object to compare to the first `HDUList` object.
974
+
975
+ numdiffs : int, optional
976
+ The number of pixel/table values to output when reporting HDU data
977
+ differences. Though the count of differences is the same either
978
+ way, this allows controlling the number of different values that
979
+ are kept in memory or output. If a negative value is given, then
980
+ numdiffs is treated as unlimited (default: 10).
981
+
982
+ rtol : float, optional
983
+ The relative difference to allow when comparing two float values
984
+ either in header values, image arrays, or table columns
985
+ (default: 0.0). Values which satisfy the expression
986
+
987
+ .. math::
988
+
989
+ \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right|
990
+
991
+ are considered to be different.
992
+ The underlying function used for comparison is `numpy.allclose`.
993
+
994
+ .. versionchanged:: 2.0
995
+ ``rtol`` replaces the deprecated ``tolerance`` argument.
996
+
997
+ atol : float, optional
998
+ The allowed absolute difference. See also ``rtol`` parameter.
999
+
1000
+ .. versionadded:: 2.0
1001
+ """
1002
+
1003
+ self.numdiffs = numdiffs
1004
+ self.rtol = rtol
1005
+ self.atol = atol
1006
+
1007
+ if tolerance is not None: # This should be removed in the next astropy version
1008
+ warnings.warn(
1009
+ '"tolerance" was deprecated in version 2.0 and will be removed in '
1010
+ 'a future version. Use argument "rtol" instead.',
1011
+ AstropyDeprecationWarning)
1012
+ self.rtol = tolerance # when tolerance is provided *always* ignore `rtol`
1013
+ # during the transition/deprecation period
1014
+
1015
+ self.diff_dimensions = ()
1016
+ self.diff_pixels = []
1017
+ self.diff_ratio = 0
1018
+
1019
+ # self.diff_pixels only holds up to numdiffs differing pixels, but this
1020
+ # self.diff_total stores the total count of differences between
1021
+ # the images, but not the different values
1022
+ self.diff_total = 0
1023
+
1024
+ super().__init__(a, b)
1025
+
1026
+ def _diff(self):
1027
+ if self.a.shape != self.b.shape:
1028
+ self.diff_dimensions = (self.a.shape, self.b.shape)
1029
+ # Don't do any further comparison if the dimensions differ
1030
+ # TODO: Perhaps we could, however, diff just the intersection
1031
+ # between the two images
1032
+ return
1033
+
1034
+ # Find the indices where the values are not equal
1035
+ # If neither a nor b are floating point (or complex), ignore rtol and
1036
+ # atol
1037
+ if not (np.issubdtype(self.a.dtype, np.inexact) or
1038
+ np.issubdtype(self.b.dtype, np.inexact)):
1039
+ rtol = 0
1040
+ atol = 0
1041
+ else:
1042
+ rtol = self.rtol
1043
+ atol = self.atol
1044
+
1045
+ diffs = where_not_allclose(self.a, self.b, atol=atol, rtol=rtol)
1046
+
1047
+ self.diff_total = len(diffs[0])
1048
+
1049
+ if self.diff_total == 0:
1050
+ # Then we're done
1051
+ return
1052
+
1053
+ if self.numdiffs < 0:
1054
+ numdiffs = self.diff_total
1055
+ else:
1056
+ numdiffs = self.numdiffs
1057
+
1058
+ self.diff_pixels = [(idx, (self.a[idx], self.b[idx]))
1059
+ for idx in islice(zip(*diffs), 0, numdiffs)]
1060
+ self.diff_ratio = float(self.diff_total) / float(len(self.a.flat))
1061
+
1062
+ def _report(self):
1063
+ if self.diff_dimensions:
1064
+ dimsa = ' x '.join(str(d) for d in
1065
+ reversed(self.diff_dimensions[0]))
1066
+ dimsb = ' x '.join(str(d) for d in
1067
+ reversed(self.diff_dimensions[1]))
1068
+ self._writeln(' Data dimensions differ:')
1069
+ self._writeln(' a: {}'.format(dimsa))
1070
+ self._writeln(' b: {}'.format(dimsb))
1071
+ # For now we don't do any further comparison if the dimensions
1072
+ # differ; though in the future it might be nice to be able to
1073
+ # compare at least where the images intersect
1074
+ self._writeln(' No further data comparison performed.')
1075
+ return
1076
+
1077
+ if not self.diff_pixels:
1078
+ return
1079
+
1080
+ for index, values in self.diff_pixels:
1081
+ index = [x + 1 for x in reversed(index)]
1082
+ self._writeln(' Data differs at {}:'.format(index))
1083
+ report_diff_values(values[0], values[1], fileobj=self._fileobj,
1084
+ indent_width=self._indent + 1)
1085
+
1086
+ if self.diff_total > self.numdiffs:
1087
+ self._writeln(' ...')
1088
+ self._writeln(' {} different pixels found ({:.2%} different).'
1089
+ .format(self.diff_total, self.diff_ratio))
1090
+
1091
+
1092
+ class RawDataDiff(ImageDataDiff):
1093
+ """
1094
+ `RawDataDiff` is just a special case of `ImageDataDiff` where the images
1095
+ are one-dimensional, and the data is treated as a 1-dimensional array of
1096
+ bytes instead of pixel values. This is used to compare the data of two
1097
+ non-standard extension HDUs that were not recognized as containing image or
1098
+ table data.
1099
+
1100
+ `ImageDataDiff` objects have the following diff attributes:
1101
+
1102
+ - ``diff_dimensions``: Same as the ``diff_dimensions`` attribute of
1103
+ `ImageDataDiff` objects. Though the "dimension" of each array is just an
1104
+ integer representing the number of bytes in the data.
1105
+
1106
+ - ``diff_bytes``: Like the ``diff_pixels`` attribute of `ImageDataDiff`
1107
+ objects, but renamed to reflect the minor semantic difference that these
1108
+ are raw bytes and not pixel values. Also the indices are integers
1109
+ instead of tuples.
1110
+
1111
+ - ``diff_total`` and ``diff_ratio``: Same as `ImageDataDiff`.
1112
+ """
1113
+
1114
+ def __init__(self, a, b, numdiffs=10):
1115
+ """
1116
+ Parameters
1117
+ ----------
1118
+ a : `HDUList`
1119
+ An `HDUList` object.
1120
+
1121
+ b : `HDUList`
1122
+ An `HDUList` object to compare to the first `HDUList` object.
1123
+
1124
+ numdiffs : int, optional
1125
+ The number of pixel/table values to output when reporting HDU data
1126
+ differences. Though the count of differences is the same either
1127
+ way, this allows controlling the number of different values that
1128
+ are kept in memory or output. If a negative value is given, then
1129
+ numdiffs is treated as unlimited (default: 10).
1130
+ """
1131
+
1132
+ self.diff_dimensions = ()
1133
+ self.diff_bytes = []
1134
+
1135
+ super().__init__(a, b, numdiffs=numdiffs)
1136
+
1137
+ def _diff(self):
1138
+ super()._diff()
1139
+ if self.diff_dimensions:
1140
+ self.diff_dimensions = (self.diff_dimensions[0][0],
1141
+ self.diff_dimensions[1][0])
1142
+
1143
+ self.diff_bytes = [(x[0], y) for x, y in self.diff_pixels]
1144
+ del self.diff_pixels
1145
+
1146
+ def _report(self):
1147
+ if self.diff_dimensions:
1148
+ self._writeln(' Data sizes differ:')
1149
+ self._writeln(' a: {} bytes'.format(self.diff_dimensions[0]))
1150
+ self._writeln(' b: {} bytes'.format(self.diff_dimensions[1]))
1151
+ # For now we don't do any further comparison if the dimensions
1152
+ # differ; though in the future it might be nice to be able to
1153
+ # compare at least where the images intersect
1154
+ self._writeln(' No further data comparison performed.')
1155
+ return
1156
+
1157
+ if not self.diff_bytes:
1158
+ return
1159
+
1160
+ for index, values in self.diff_bytes:
1161
+ self._writeln(' Data differs at byte {}:'.format(index))
1162
+ report_diff_values(values[0], values[1], fileobj=self._fileobj,
1163
+ indent_width=self._indent + 1)
1164
+
1165
+ self._writeln(' ...')
1166
+ self._writeln(' {} different bytes found ({:.2%} different).'
1167
+ .format(self.diff_total, self.diff_ratio))
1168
+
1169
+
1170
+ class TableDataDiff(_BaseDiff):
1171
+ """
1172
+ Diff two table data arrays. It doesn't matter whether the data originally
1173
+ came from a binary or ASCII table--the data should be passed in as a
1174
+ recarray.
1175
+
1176
+ `TableDataDiff` objects have the following diff attributes:
1177
+
1178
+ - ``diff_column_count``: If the tables being compared have different
1179
+ numbers of columns, this contains a 2-tuple of the column count in each
1180
+ table. Even if the tables have different column counts, an attempt is
1181
+ still made to compare any columns they have in common.
1182
+
1183
+ - ``diff_columns``: If either table contains columns unique to that table,
1184
+ either in name or format, this contains a 2-tuple of lists. The first
1185
+ element is a list of columns (these are full `Column` objects) that
1186
+ appear only in table a. The second element is a list of tables that
1187
+ appear only in table b. This only lists columns with different column
1188
+ definitions, and has nothing to do with the data in those columns.
1189
+
1190
+ - ``diff_column_names``: This is like ``diff_columns``, but lists only the
1191
+ names of columns unique to either table, rather than the full `Column`
1192
+ objects.
1193
+
1194
+ - ``diff_column_attributes``: Lists columns that are in both tables but
1195
+ have different secondary attributes, such as TUNIT or TDISP. The format
1196
+ is a list of 2-tuples: The first a tuple of the column name and the
1197
+ attribute, the second a tuple of the different values.
1198
+
1199
+ - ``diff_values``: `TableDataDiff` compares the data in each table on a
1200
+ column-by-column basis. If any different data is found, it is added to
1201
+ this list. The format of this list is similar to the ``diff_pixels``
1202
+ attribute on `ImageDataDiff` objects, though the "index" consists of a
1203
+ (column_name, row) tuple. For example::
1204
+
1205
+ [('TARGET', 0), ('NGC1001', 'NGC1002')]
1206
+
1207
+ shows that the tables contain different values in the 0-th row of the
1208
+ 'TARGET' column.
1209
+
1210
+ - ``diff_total`` and ``diff_ratio``: Same as `ImageDataDiff`.
1211
+
1212
+ `TableDataDiff` objects also have a ``common_columns`` attribute that lists
1213
+ the `Column` objects for columns that are identical in both tables, and a
1214
+ ``common_column_names`` attribute which contains a set of the names of
1215
+ those columns.
1216
+ """
1217
+
1218
+ def __init__(self, a, b, ignore_fields=[], numdiffs=10, rtol=0.0, atol=0.0,
1219
+ tolerance=None):
1220
+ """
1221
+ Parameters
1222
+ ----------
1223
+ a : `HDUList`
1224
+ An `HDUList` object.
1225
+
1226
+ b : `HDUList`
1227
+ An `HDUList` object to compare to the first `HDUList` object.
1228
+
1229
+ ignore_fields : sequence, optional
1230
+ The (case-insensitive) names of any table columns to ignore if any
1231
+ table data is to be compared.
1232
+
1233
+ numdiffs : int, optional
1234
+ The number of pixel/table values to output when reporting HDU data
1235
+ differences. Though the count of differences is the same either
1236
+ way, this allows controlling the number of different values that
1237
+ are kept in memory or output. If a negative value is given, then
1238
+ numdiffs is treated as unlimited (default: 10).
1239
+
1240
+ rtol : float, optional
1241
+ The relative difference to allow when comparing two float values
1242
+ either in header values, image arrays, or table columns
1243
+ (default: 0.0). Values which satisfy the expression
1244
+
1245
+ .. math::
1246
+
1247
+ \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right|
1248
+
1249
+ are considered to be different.
1250
+ The underlying function used for comparison is `numpy.allclose`.
1251
+
1252
+ .. versionchanged:: 2.0
1253
+ ``rtol`` replaces the deprecated ``tolerance`` argument.
1254
+
1255
+ atol : float, optional
1256
+ The allowed absolute difference. See also ``rtol`` parameter.
1257
+
1258
+ .. versionadded:: 2.0
1259
+ """
1260
+
1261
+ self.ignore_fields = set(ignore_fields)
1262
+ self.numdiffs = numdiffs
1263
+ self.rtol = rtol
1264
+ self.atol = atol
1265
+
1266
+ if tolerance is not None: # This should be removed in the next astropy version
1267
+ warnings.warn(
1268
+ '"tolerance" was deprecated in version 2.0 and will be removed in '
1269
+ 'a future version. Use argument "rtol" instead.',
1270
+ AstropyDeprecationWarning)
1271
+ self.rtol = tolerance # when tolerance is provided *always* ignore `rtol`
1272
+ # during the transition/deprecation period
1273
+
1274
+ self.common_columns = []
1275
+ self.common_column_names = set()
1276
+
1277
+ # self.diff_columns contains columns with different column definitions,
1278
+ # but not different column data. Column data is only compared in
1279
+ # columns that have the same definitions
1280
+ self.diff_rows = ()
1281
+ self.diff_column_count = ()
1282
+ self.diff_columns = ()
1283
+
1284
+ # If two columns have the same name+format, but other attributes are
1285
+ # different (such as TUNIT or such) they are listed here
1286
+ self.diff_column_attributes = []
1287
+
1288
+ # Like self.diff_columns, but just contains a list of the column names
1289
+ # unique to each table, and in the order they appear in the tables
1290
+ self.diff_column_names = ()
1291
+ self.diff_values = []
1292
+
1293
+ self.diff_ratio = 0
1294
+ self.diff_total = 0
1295
+
1296
+ super().__init__(a, b)
1297
+
1298
+ def _diff(self):
1299
+ # Much of the code for comparing columns is similar to the code for
1300
+ # comparing headers--consider refactoring
1301
+ colsa = self.a.columns
1302
+ colsb = self.b.columns
1303
+
1304
+ if len(colsa) != len(colsb):
1305
+ self.diff_column_count = (len(colsa), len(colsb))
1306
+
1307
+ # Even if the number of columns are unequal, we still do comparison of
1308
+ # any common columns
1309
+ colsa = {c.name.lower(): c for c in colsa}
1310
+ colsb = {c.name.lower(): c for c in colsb}
1311
+
1312
+ if '*' in self.ignore_fields:
1313
+ # If all columns are to be ignored, ignore any further differences
1314
+ # between the columns
1315
+ return
1316
+
1317
+ # Keep the user's original ignore_fields list for reporting purposes,
1318
+ # but internally use a case-insensitive version
1319
+ ignore_fields = {f.lower() for f in self.ignore_fields}
1320
+
1321
+ # It might be nice if there were a cleaner way to do this, but for now
1322
+ # it'll do
1323
+ for fieldname in ignore_fields:
1324
+ fieldname = fieldname.lower()
1325
+ if fieldname in colsa:
1326
+ del colsa[fieldname]
1327
+ if fieldname in colsb:
1328
+ del colsb[fieldname]
1329
+
1330
+ colsa_set = set(colsa.values())
1331
+ colsb_set = set(colsb.values())
1332
+ self.common_columns = sorted(colsa_set.intersection(colsb_set),
1333
+ key=operator.attrgetter('name'))
1334
+
1335
+ self.common_column_names = {col.name.lower()
1336
+ for col in self.common_columns}
1337
+
1338
+ left_only_columns = {col.name.lower(): col
1339
+ for col in colsa_set.difference(colsb_set)}
1340
+ right_only_columns = {col.name.lower(): col
1341
+ for col in colsb_set.difference(colsa_set)}
1342
+
1343
+ if left_only_columns or right_only_columns:
1344
+ self.diff_columns = (left_only_columns, right_only_columns)
1345
+ self.diff_column_names = ([], [])
1346
+
1347
+ if left_only_columns:
1348
+ for col in self.a.columns:
1349
+ if col.name.lower() in left_only_columns:
1350
+ self.diff_column_names[0].append(col.name)
1351
+
1352
+ if right_only_columns:
1353
+ for col in self.b.columns:
1354
+ if col.name.lower() in right_only_columns:
1355
+ self.diff_column_names[1].append(col.name)
1356
+
1357
+ # If the tables have a different number of rows, we don't compare the
1358
+ # columns right now.
1359
+ # TODO: It might be nice to optionally compare the first n rows where n
1360
+ # is the minimum of the row counts between the two tables.
1361
+ if len(self.a) != len(self.b):
1362
+ self.diff_rows = (len(self.a), len(self.b))
1363
+ return
1364
+
1365
+ # If the tables contain no rows there's no data to compare, so we're
1366
+ # done at this point. (See ticket #178)
1367
+ if len(self.a) == len(self.b) == 0:
1368
+ return
1369
+
1370
+ # Like in the old fitsdiff, compare tables on a column by column basis
1371
+ # The difficulty here is that, while FITS column names are meant to be
1372
+ # case-insensitive, Astropy still allows, for the sake of flexibility,
1373
+ # two columns with the same name but different case. When columns are
1374
+ # accessed in FITS tables, a case-sensitive is tried first, and failing
1375
+ # that a case-insensitive match is made.
1376
+ # It's conceivable that the same column could appear in both tables
1377
+ # being compared, but with different case.
1378
+ # Though it *may* lead to inconsistencies in these rare cases, this
1379
+ # just assumes that there are no duplicated column names in either
1380
+ # table, and that the column names can be treated case-insensitively.
1381
+ for col in self.common_columns:
1382
+ name_lower = col.name.lower()
1383
+ if name_lower in ignore_fields:
1384
+ continue
1385
+
1386
+ cola = colsa[name_lower]
1387
+ colb = colsb[name_lower]
1388
+
1389
+ for attr, _ in _COL_ATTRS:
1390
+ vala = getattr(cola, attr, None)
1391
+ valb = getattr(colb, attr, None)
1392
+ if diff_values(vala, valb):
1393
+ self.diff_column_attributes.append(
1394
+ ((col.name.upper(), attr), (vala, valb)))
1395
+
1396
+ arra = self.a[col.name]
1397
+ arrb = self.b[col.name]
1398
+
1399
+ if (np.issubdtype(arra.dtype, np.floating) and
1400
+ np.issubdtype(arrb.dtype, np.floating)):
1401
+ diffs = where_not_allclose(arra, arrb,
1402
+ rtol=self.rtol,
1403
+ atol=self.atol)
1404
+ elif 'P' in col.format:
1405
+ diffs = ([idx for idx in range(len(arra))
1406
+ if not np.allclose(arra[idx], arrb[idx],
1407
+ rtol=self.rtol,
1408
+ atol=self.atol)],)
1409
+ else:
1410
+ diffs = np.where(arra != arrb)
1411
+
1412
+ self.diff_total += len(set(diffs[0]))
1413
+
1414
+ if self.numdiffs >= 0:
1415
+ if len(self.diff_values) >= self.numdiffs:
1416
+ # Don't save any more diff values
1417
+ continue
1418
+
1419
+ # Add no more diff'd values than this
1420
+ max_diffs = self.numdiffs - len(self.diff_values)
1421
+ else:
1422
+ max_diffs = len(diffs[0])
1423
+
1424
+ last_seen_idx = None
1425
+ for idx in islice(diffs[0], 0, max_diffs):
1426
+ if idx == last_seen_idx:
1427
+ # Skip duplicate indices, which my occur when the column
1428
+ # data contains multi-dimensional values; we're only
1429
+ # interested in storing row-by-row differences
1430
+ continue
1431
+ last_seen_idx = idx
1432
+ self.diff_values.append(((col.name, idx),
1433
+ (arra[idx], arrb[idx])))
1434
+
1435
+ total_values = len(self.a) * len(self.a.dtype.fields)
1436
+ self.diff_ratio = float(self.diff_total) / float(total_values)
1437
+
1438
+ def _report(self):
1439
+ if self.diff_column_count:
1440
+ self._writeln(' Tables have different number of columns:')
1441
+ self._writeln(' a: {}'.format(self.diff_column_count[0]))
1442
+ self._writeln(' b: {}'.format(self.diff_column_count[1]))
1443
+
1444
+ if self.diff_column_names:
1445
+ # Show columns with names unique to either table
1446
+ for name in self.diff_column_names[0]:
1447
+ format = self.diff_columns[0][name.lower()].format
1448
+ self._writeln(' Extra column {} of format {} in a'.format(
1449
+ name, format))
1450
+ for name in self.diff_column_names[1]:
1451
+ format = self.diff_columns[1][name.lower()].format
1452
+ self._writeln(' Extra column {} of format {} in b'.format(
1453
+ name, format))
1454
+
1455
+ col_attrs = dict(_COL_ATTRS)
1456
+ # Now go through each table again and show columns with common
1457
+ # names but other property differences...
1458
+ for col_attr, vals in self.diff_column_attributes:
1459
+ name, attr = col_attr
1460
+ self._writeln(' Column {} has different {}:'.format(
1461
+ name, col_attrs[attr]))
1462
+ report_diff_values(vals[0], vals[1], fileobj=self._fileobj,
1463
+ indent_width=self._indent + 1)
1464
+
1465
+ if self.diff_rows:
1466
+ self._writeln(' Table rows differ:')
1467
+ self._writeln(' a: {}'.format(self.diff_rows[0]))
1468
+ self._writeln(' b: {}'.format(self.diff_rows[1]))
1469
+ self._writeln(' No further data comparison performed.')
1470
+ return
1471
+
1472
+ if not self.diff_values:
1473
+ return
1474
+
1475
+ # Finally, let's go through and report column data differences:
1476
+ for indx, values in self.diff_values:
1477
+ self._writeln(' Column {} data differs in row {}:'.format(*indx))
1478
+ report_diff_values(values[0], values[1], fileobj=self._fileobj,
1479
+ indent_width=self._indent + 1)
1480
+
1481
+ if self.diff_values and self.numdiffs < self.diff_total:
1482
+ self._writeln(' ...{} additional difference(s) found.'.format(
1483
+ (self.diff_total - self.numdiffs)))
1484
+
1485
+ if self.diff_total > self.numdiffs:
1486
+ self._writeln(' ...')
1487
+
1488
+ self._writeln(' {} different table data element(s) found '
1489
+ '({:.2%} different).'
1490
+ .format(self.diff_total, self.diff_ratio))
1491
+
1492
+
1493
+ def report_diff_keyword_attr(fileobj, attr, diffs, keyword, ind=0):
1494
+ """
1495
+ Write a diff between two header keyword values or comments to the specified
1496
+ file-like object.
1497
+ """
1498
+
1499
+ if keyword in diffs:
1500
+ vals = diffs[keyword]
1501
+ for idx, val in enumerate(vals):
1502
+ if val is None:
1503
+ continue
1504
+ if idx == 0:
1505
+ dup = ''
1506
+ else:
1507
+ dup = '[{}]'.format(idx + 1)
1508
+ fileobj.write(
1509
+ fixed_width_indent(' Keyword {:8}{} has different {}:\n'
1510
+ .format(keyword, dup, attr), ind))
1511
+ report_diff_values(val[0], val[1], fileobj=fileobj,
1512
+ indent_width=ind + 1)
testbed/astropy__astropy/astropy/io/fits/file.py ADDED
@@ -0,0 +1,631 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+
4
+ import bz2
5
+ import gzip
6
+ import errno
7
+ import http.client
8
+ import mmap
9
+ import operator
10
+ import pathlib
11
+ import io
12
+ import os
13
+ import sys
14
+ import tempfile
15
+ import warnings
16
+ import zipfile
17
+ import re
18
+
19
+ from functools import reduce
20
+
21
+ import numpy as np
22
+
23
+ from .util import (isreadable, iswritable, isfile, fileobj_open, fileobj_name,
24
+ fileobj_closed, fileobj_mode, _array_from_file,
25
+ _array_to_file, _write_string)
26
+ from astropy.utils.data import download_file, _is_url
27
+ from astropy.utils.decorators import classproperty, deprecated_renamed_argument
28
+ from astropy.utils.exceptions import AstropyUserWarning
29
+
30
+
31
+ # Maps astropy.io.fits-specific file mode names to the appropriate file
32
+ # modes to use for the underlying raw files
33
+ IO_FITS_MODES = {
34
+ 'readonly': 'rb',
35
+ 'copyonwrite': 'rb',
36
+ 'update': 'rb+',
37
+ 'append': 'ab+',
38
+ 'ostream': 'wb',
39
+ 'denywrite': 'rb'}
40
+
41
+ # Maps OS-level file modes to the appropriate astropy.io.fits specific mode
42
+ # to use when given file objects but no mode specified; obviously in
43
+ # IO_FITS_MODES there are overlaps; for example 'readonly' and 'denywrite'
44
+ # both require the file to be opened in 'rb' mode. But 'readonly' is the
45
+ # default behavior for such files if not otherwise specified.
46
+ # Note: 'ab' is only supported for 'ostream' which is output-only.
47
+ FILE_MODES = {
48
+ 'rb': 'readonly', 'rb+': 'update',
49
+ 'wb': 'ostream', 'wb+': 'update',
50
+ 'ab': 'ostream', 'ab+': 'append'}
51
+
52
+ # A match indicates the file was opened in text mode, which is not allowed
53
+ TEXT_RE = re.compile(r'^[rwa]((t?\+?)|(\+?t?))$')
54
+
55
+
56
+ # readonly actually uses copyonwrite for mmap so that readonly without mmap and
57
+ # with mmap still have to same behavior with regard to updating the array. To
58
+ # get a truly readonly mmap use denywrite
59
+ # the name 'denywrite' comes from a deprecated flag to mmap() on Linux--it
60
+ # should be clarified that 'denywrite' mode is not directly analogous to the
61
+ # use of that flag; it was just taken, for lack of anything better, as a name
62
+ # that means something like "read only" but isn't readonly.
63
+ MEMMAP_MODES = {'readonly': mmap.ACCESS_COPY,
64
+ 'copyonwrite': mmap.ACCESS_COPY,
65
+ 'update': mmap.ACCESS_WRITE,
66
+ 'append': mmap.ACCESS_COPY,
67
+ 'denywrite': mmap.ACCESS_READ}
68
+
69
+ # TODO: Eventually raise a warning, and maybe even later disable the use of
70
+ # 'copyonwrite' and 'denywrite' modes unless memmap=True. For now, however,
71
+ # that would generate too many warnings for too many users. If nothing else,
72
+ # wait until the new logging system is in place.
73
+
74
+ GZIP_MAGIC = b'\x1f\x8b\x08'
75
+ PKZIP_MAGIC = b'\x50\x4b\x03\x04'
76
+ BZIP2_MAGIC = b'\x42\x5a'
77
+
78
+ def _normalize_fits_mode(mode):
79
+ if mode is not None and mode not in IO_FITS_MODES:
80
+ if TEXT_RE.match(mode):
81
+ raise ValueError(
82
+ "Text mode '{}' not supported: "
83
+ "files must be opened in binary mode".format(mode))
84
+ new_mode = FILE_MODES.get(mode)
85
+ if new_mode not in IO_FITS_MODES:
86
+ raise ValueError("Mode '{}' not recognized".format(mode))
87
+ mode = new_mode
88
+ return mode
89
+
90
+ class _File:
91
+ """
92
+ Represents a FITS file on disk (or in some other file-like object).
93
+ """
94
+
95
+ @deprecated_renamed_argument('clobber', 'overwrite', '2.0')
96
+ def __init__(self, fileobj=None, mode=None, memmap=None, overwrite=False,
97
+ cache=True):
98
+ self.strict_memmap = bool(memmap)
99
+ memmap = True if memmap is None else memmap
100
+
101
+ if fileobj is None:
102
+ self._file = None
103
+ self.closed = False
104
+ self.binary = True
105
+ self.mode = mode
106
+ self.memmap = memmap
107
+ self.compression = None
108
+ self.readonly = False
109
+ self.writeonly = False
110
+ self.simulateonly = True
111
+ self.close_on_error = False
112
+ return
113
+ else:
114
+ self.simulateonly = False
115
+ # If fileobj is of type pathlib.Path
116
+ if isinstance(fileobj, pathlib.Path):
117
+ fileobj = str(fileobj)
118
+ elif isinstance(fileobj, bytes):
119
+ # Using bytes as filename is tricky, it's deprecated for Windows
120
+ # in Python 3.5 (because it could lead to false-positives) but
121
+ # was fixed and un-deprecated in Python 3.6.
122
+ # However it requires that the bytes object is encoded with the
123
+ # file system encoding.
124
+ # Probably better to error out and ask for a str object instead.
125
+ # TODO: This could be revised when Python 3.5 support is dropped
126
+ # See also: https://github.com/astropy/astropy/issues/6789
127
+ raise TypeError("names should be `str` not `bytes`.")
128
+
129
+ # Holds mmap instance for files that use mmap
130
+ self._mmap = None
131
+
132
+ if mode is not None and mode not in IO_FITS_MODES:
133
+ raise ValueError("Mode '{}' not recognized".format(mode))
134
+ if isfile(fileobj):
135
+ objmode = _normalize_fits_mode(fileobj_mode(fileobj))
136
+ if mode is not None and mode != objmode:
137
+ raise ValueError(
138
+ "Requested FITS mode '{}' not compatible with open file "
139
+ "handle mode '{}'".format(mode, objmode))
140
+ mode = objmode
141
+ if mode is None:
142
+ mode = 'readonly'
143
+
144
+ # Handle raw URLs
145
+ if (isinstance(fileobj, str) and
146
+ mode not in ('ostream', 'append', 'update') and _is_url(fileobj)):
147
+ self.name = download_file(fileobj, cache=cache)
148
+ # Handle responses from URL requests that have already been opened
149
+ elif isinstance(fileobj, http.client.HTTPResponse):
150
+ if mode in ('ostream', 'append', 'update'):
151
+ raise ValueError(
152
+ "Mode {} not supported for HTTPResponse".format(mode))
153
+ fileobj = io.BytesIO(fileobj.read())
154
+ else:
155
+ self.name = fileobj_name(fileobj)
156
+
157
+ self.closed = False
158
+ self.binary = True
159
+ self.mode = mode
160
+ self.memmap = memmap
161
+
162
+ # Underlying fileobj is a file-like object, but an actual file object
163
+ self.file_like = False
164
+
165
+ # Should the object be closed on error: see
166
+ # https://github.com/astropy/astropy/issues/6168
167
+ self.close_on_error = False
168
+
169
+ # More defaults to be adjusted below as necessary
170
+ self.compression = None
171
+ self.readonly = False
172
+ self.writeonly = False
173
+
174
+ # Initialize the internal self._file object
175
+ if isfile(fileobj):
176
+ self._open_fileobj(fileobj, mode, overwrite)
177
+ elif isinstance(fileobj, str):
178
+ self._open_filename(fileobj, mode, overwrite)
179
+ else:
180
+ self._open_filelike(fileobj, mode, overwrite)
181
+
182
+ self.fileobj_mode = fileobj_mode(self._file)
183
+
184
+ if isinstance(fileobj, gzip.GzipFile):
185
+ self.compression = 'gzip'
186
+ elif isinstance(fileobj, zipfile.ZipFile):
187
+ # Reading from zip files is supported but not writing (yet)
188
+ self.compression = 'zip'
189
+ elif isinstance(fileobj, bz2.BZ2File):
190
+ self.compression = 'bzip2'
191
+
192
+ if (mode in ('readonly', 'copyonwrite', 'denywrite') or
193
+ (self.compression and mode == 'update')):
194
+ self.readonly = True
195
+ elif (mode == 'ostream' or
196
+ (self.compression and mode == 'append')):
197
+ self.writeonly = True
198
+
199
+ # For 'ab+' mode, the pointer is at the end after the open in
200
+ # Linux, but is at the beginning in Solaris.
201
+ if (mode == 'ostream' or self.compression or
202
+ not hasattr(self._file, 'seek')):
203
+ # For output stream start with a truncated file.
204
+ # For compressed files we can't really guess at the size
205
+ self.size = 0
206
+ else:
207
+ pos = self._file.tell()
208
+ self._file.seek(0, 2)
209
+ self.size = self._file.tell()
210
+ self._file.seek(pos)
211
+
212
+ if self.memmap:
213
+ if not isfile(self._file):
214
+ self.memmap = False
215
+ elif not self.readonly and not self._mmap_available:
216
+ # Test mmap.flush--see
217
+ # https://github.com/astropy/astropy/issues/968
218
+ self.memmap = False
219
+
220
+ def __repr__(self):
221
+ return '<{}.{} {}>'.format(self.__module__, self.__class__.__name__,
222
+ self._file)
223
+
224
+ # Support the 'with' statement
225
+ def __enter__(self):
226
+ return self
227
+
228
+ def __exit__(self, type, value, traceback):
229
+ self.close()
230
+
231
+ def readable(self):
232
+ if self.writeonly:
233
+ return False
234
+ return isreadable(self._file)
235
+
236
+ def read(self, size=None):
237
+ if not hasattr(self._file, 'read'):
238
+ raise EOFError
239
+ try:
240
+ return self._file.read(size)
241
+ except OSError:
242
+ # On some versions of Python, it appears, GzipFile will raise an
243
+ # OSError if you try to read past its end (as opposed to just
244
+ # returning '')
245
+ if self.compression == 'gzip':
246
+ return ''
247
+ raise
248
+
249
+ def readarray(self, size=None, offset=0, dtype=np.uint8, shape=None):
250
+ """
251
+ Similar to file.read(), but returns the contents of the underlying
252
+ file as a numpy array (or mmap'd array if memmap=True) rather than a
253
+ string.
254
+
255
+ Usually it's best not to use the `size` argument with this method, but
256
+ it's provided for compatibility.
257
+ """
258
+
259
+ if not hasattr(self._file, 'read'):
260
+ raise EOFError
261
+
262
+ if not isinstance(dtype, np.dtype):
263
+ dtype = np.dtype(dtype)
264
+
265
+ if size and size % dtype.itemsize != 0:
266
+ raise ValueError('size {} not a multiple of {}'.format(size, dtype))
267
+
268
+ if isinstance(shape, int):
269
+ shape = (shape,)
270
+
271
+ if not (size or shape):
272
+ warnings.warn('No size or shape given to readarray(); assuming a '
273
+ 'shape of (1,)', AstropyUserWarning)
274
+ shape = (1,)
275
+
276
+ if size and not shape:
277
+ shape = (size // dtype.itemsize,)
278
+
279
+ if size and shape:
280
+ actualsize = np.prod(shape) * dtype.itemsize
281
+
282
+ if actualsize > size:
283
+ raise ValueError('size {} is too few bytes for a {} array of '
284
+ '{}'.format(size, shape, dtype))
285
+ elif actualsize < size:
286
+ raise ValueError('size {} is too many bytes for a {} array of '
287
+ '{}'.format(size, shape, dtype))
288
+
289
+ filepos = self._file.tell()
290
+
291
+ try:
292
+ if self.memmap:
293
+ if self._mmap is None:
294
+ # Instantiate Memmap array of the file offset at 0 (so we
295
+ # can return slices of it to offset anywhere else into the
296
+ # file)
297
+ access_mode = MEMMAP_MODES[self.mode]
298
+
299
+ # For reasons unknown the file needs to point to (near)
300
+ # the beginning or end of the file. No idea how close to
301
+ # the beginning or end.
302
+ # If I had to guess there is some bug in the mmap module
303
+ # of CPython or perhaps in microsoft's underlying code
304
+ # for generating the mmap.
305
+ self._file.seek(0, 0)
306
+ # This would also work:
307
+ # self._file.seek(0, 2) # moves to the end
308
+ try:
309
+ self._mmap = mmap.mmap(self._file.fileno(), 0,
310
+ access=access_mode,
311
+ offset=0)
312
+ except OSError as exc:
313
+ # NOTE: mode='readonly' results in the memory-mapping
314
+ # using the ACCESS_COPY mode in mmap so that users can
315
+ # modify arrays. However, on some systems, the OS raises
316
+ # a '[Errno 12] Cannot allocate memory' OSError if the
317
+ # address space is smaller than the file. The solution
318
+ # is to open the file in mode='denywrite', which at
319
+ # least allows the file to be opened even if the
320
+ # resulting arrays will be truly read-only.
321
+ if exc.errno == errno.ENOMEM and self.mode == 'readonly':
322
+ warnings.warn("Could not memory map array with "
323
+ "mode='readonly', falling back to "
324
+ "mode='denywrite', which means that "
325
+ "the array will be read-only",
326
+ AstropyUserWarning)
327
+ self._mmap = mmap.mmap(self._file.fileno(), 0,
328
+ access=MEMMAP_MODES['denywrite'],
329
+ offset=0)
330
+ else:
331
+ raise
332
+
333
+ return np.ndarray(shape=shape, dtype=dtype, offset=offset,
334
+ buffer=self._mmap)
335
+ else:
336
+ count = reduce(operator.mul, shape)
337
+ self._file.seek(offset)
338
+ data = _array_from_file(self._file, dtype, count)
339
+ data.shape = shape
340
+ return data
341
+ finally:
342
+ # Make sure we leave the file in the position we found it; on
343
+ # some platforms (e.g. Windows) mmaping a file handle can also
344
+ # reset its file pointer
345
+ self._file.seek(filepos)
346
+
347
+ def writable(self):
348
+ if self.readonly:
349
+ return False
350
+ return iswritable(self._file)
351
+
352
+ def write(self, string):
353
+ if hasattr(self._file, 'write'):
354
+ _write_string(self._file, string)
355
+
356
+ def writearray(self, array):
357
+ """
358
+ Similar to file.write(), but writes a numpy array instead of a string.
359
+
360
+ Also like file.write(), a flush() or close() may be needed before
361
+ the file on disk reflects the data written.
362
+ """
363
+
364
+ if hasattr(self._file, 'write'):
365
+ _array_to_file(array, self._file)
366
+
367
+ def flush(self):
368
+ if hasattr(self._file, 'flush'):
369
+ self._file.flush()
370
+
371
+ def seek(self, offset, whence=0):
372
+ if not hasattr(self._file, 'seek'):
373
+ return
374
+ self._file.seek(offset, whence)
375
+ pos = self._file.tell()
376
+ if self.size and pos > self.size:
377
+ warnings.warn('File may have been truncated: actual file length '
378
+ '({}) is smaller than the expected size ({})'
379
+ .format(self.size, pos), AstropyUserWarning)
380
+
381
+ def tell(self):
382
+ if not hasattr(self._file, 'tell'):
383
+ raise EOFError
384
+ return self._file.tell()
385
+
386
+ def truncate(self, size=None):
387
+ if hasattr(self._file, 'truncate'):
388
+ self._file.truncate(size)
389
+
390
+ def close(self):
391
+ """
392
+ Close the 'physical' FITS file.
393
+ """
394
+
395
+ if hasattr(self._file, 'close'):
396
+ self._file.close()
397
+
398
+ self._maybe_close_mmap()
399
+ # Set self._memmap to None anyways since no new .data attributes can be
400
+ # loaded after the file is closed
401
+ self._mmap = None
402
+
403
+ self.closed = True
404
+ self.close_on_error = False
405
+
406
+ def _maybe_close_mmap(self, refcount_delta=0):
407
+ """
408
+ When mmap is in use these objects hold a reference to the mmap of the
409
+ file (so there is only one, shared by all HDUs that reference this
410
+ file).
411
+
412
+ This will close the mmap if there are no arrays referencing it.
413
+ """
414
+
415
+ if (self._mmap is not None and
416
+ sys.getrefcount(self._mmap) == 2 + refcount_delta):
417
+ self._mmap.close()
418
+ self._mmap = None
419
+
420
+ def _overwrite_existing(self, overwrite, fileobj, closed):
421
+ """Overwrite an existing file if ``overwrite`` is ``True``, otherwise
422
+ raise an OSError. The exact behavior of this method depends on the
423
+ _File object state and is only meant for use within the ``_open_*``
424
+ internal methods.
425
+ """
426
+
427
+ # The file will be overwritten...
428
+ if ((self.file_like and hasattr(fileobj, 'len') and fileobj.len > 0) or
429
+ (os.path.exists(self.name) and os.path.getsize(self.name) != 0)):
430
+ if overwrite:
431
+ if self.file_like and hasattr(fileobj, 'truncate'):
432
+ fileobj.truncate(0)
433
+ else:
434
+ if not closed:
435
+ fileobj.close()
436
+ os.remove(self.name)
437
+ else:
438
+ raise OSError("File {!r} already exists.".format(self.name))
439
+
440
+ def _try_read_compressed(self, obj_or_name, magic, mode, ext=''):
441
+ """Attempt to determine if the given file is compressed"""
442
+ if ext == '.gz' or magic.startswith(GZIP_MAGIC):
443
+ if mode == 'append':
444
+ raise OSError("'append' mode is not supported with gzip files."
445
+ "Use 'update' mode instead")
446
+ # Handle gzip files
447
+ kwargs = dict(mode=IO_FITS_MODES[mode])
448
+ if isinstance(obj_or_name, str):
449
+ kwargs['filename'] = obj_or_name
450
+ else:
451
+ kwargs['fileobj'] = obj_or_name
452
+ self._file = gzip.GzipFile(**kwargs)
453
+ self.compression = 'gzip'
454
+ elif ext == '.zip' or magic.startswith(PKZIP_MAGIC):
455
+ # Handle zip files
456
+ self._open_zipfile(self.name, mode)
457
+ self.compression = 'zip'
458
+ elif ext == '.bz2' or magic.startswith(BZIP2_MAGIC):
459
+ # Handle bzip2 files
460
+ if mode in ['update', 'append']:
461
+ raise OSError("update and append modes are not supported "
462
+ "with bzip2 files")
463
+ # bzip2 only supports 'w' and 'r' modes
464
+ bzip2_mode = 'w' if mode == 'ostream' else 'r'
465
+ self._file = bz2.BZ2File(obj_or_name, mode=bzip2_mode)
466
+ self.compression = 'bzip2'
467
+ return self.compression is not None
468
+
469
+ def _open_fileobj(self, fileobj, mode, overwrite):
470
+ """Open a FITS file from a file object (including compressed files)."""
471
+
472
+ closed = fileobj_closed(fileobj)
473
+ fmode = fileobj_mode(fileobj) or IO_FITS_MODES[mode]
474
+
475
+ if mode == 'ostream':
476
+ self._overwrite_existing(overwrite, fileobj, closed)
477
+
478
+ if not closed:
479
+ self._file = fileobj
480
+ elif isfile(fileobj):
481
+ self._file = fileobj_open(self.name, IO_FITS_MODES[mode])
482
+
483
+ # Attempt to determine if the file represented by the open file object
484
+ # is compressed
485
+ try:
486
+ # We need to account for the possibility that the underlying file
487
+ # handle may have been opened with either 'ab' or 'ab+', which
488
+ # means that the current file position is at the end of the file.
489
+ if mode in ['ostream', 'append']:
490
+ self._file.seek(0)
491
+ magic = self._file.read(4)
492
+ # No matter whether the underlying file was opened with 'ab' or
493
+ # 'ab+', we need to return to the beginning of the file in order
494
+ # to properly process the FITS header (and handle the possibility
495
+ # of a compressed file).
496
+ self._file.seek(0)
497
+ except (OSError,OSError):
498
+ return
499
+
500
+ self._try_read_compressed(fileobj, magic, mode)
501
+
502
+ def _open_filelike(self, fileobj, mode, overwrite):
503
+ """Open a FITS file from a file-like object, i.e. one that has
504
+ read and/or write methods.
505
+ """
506
+
507
+ self.file_like = True
508
+ self._file = fileobj
509
+
510
+ if fileobj_closed(fileobj):
511
+ raise OSError("Cannot read from/write to a closed file-like "
512
+ "object ({!r}).".format(fileobj))
513
+
514
+ if isinstance(fileobj, zipfile.ZipFile):
515
+ self._open_zipfile(fileobj, mode)
516
+ # We can bypass any additional checks at this point since now
517
+ # self._file points to the temp file extracted from the zip
518
+ return
519
+
520
+ # If there is not seek or tell methods then set the mode to
521
+ # output streaming.
522
+ if (not hasattr(self._file, 'seek') or
523
+ not hasattr(self._file, 'tell')):
524
+ self.mode = mode = 'ostream'
525
+
526
+ if mode == 'ostream':
527
+ self._overwrite_existing(overwrite, fileobj, False)
528
+
529
+ # Any "writeable" mode requires a write() method on the file object
530
+ if (self.mode in ('update', 'append', 'ostream') and
531
+ not hasattr(self._file, 'write')):
532
+ raise OSError("File-like object does not have a 'write' "
533
+ "method, required for mode '{}'.".format(self.mode))
534
+
535
+ # Any mode except for 'ostream' requires readability
536
+ if self.mode != 'ostream' and not hasattr(self._file, 'read'):
537
+ raise OSError("File-like object does not have a 'read' "
538
+ "method, required for mode {!r}.".format(self.mode))
539
+
540
+ def _open_filename(self, filename, mode, overwrite):
541
+ """Open a FITS file from a filename string."""
542
+
543
+ if mode == 'ostream':
544
+ self._overwrite_existing(overwrite, None, True)
545
+
546
+ if os.path.exists(self.name):
547
+ with fileobj_open(self.name, 'rb') as f:
548
+ magic = f.read(4)
549
+ else:
550
+ magic = b''
551
+
552
+ ext = os.path.splitext(self.name)[1]
553
+
554
+ if not self._try_read_compressed(self.name, magic, mode, ext=ext):
555
+ self._file = fileobj_open(self.name, IO_FITS_MODES[mode])
556
+ self.close_on_error = True
557
+
558
+ # Make certain we're back at the beginning of the file
559
+ # BZ2File does not support seek when the file is open for writing, but
560
+ # when opening a file for write, bz2.BZ2File always truncates anyway.
561
+ if not (isinstance(self._file, bz2.BZ2File) and mode == 'ostream'):
562
+ self._file.seek(0)
563
+
564
+ @classproperty(lazy=True)
565
+ def _mmap_available(cls):
566
+ """Tests that mmap, and specifically mmap.flush works. This may
567
+ be the case on some uncommon platforms (see
568
+ https://github.com/astropy/astropy/issues/968).
569
+
570
+ If mmap.flush is found not to work, ``self.memmap = False`` is
571
+ set and a warning is issued.
572
+ """
573
+
574
+ tmpfd, tmpname = tempfile.mkstemp()
575
+ try:
576
+ # Windows does not allow mappings on empty files
577
+ os.write(tmpfd, b' ')
578
+ os.fsync(tmpfd)
579
+ try:
580
+ mm = mmap.mmap(tmpfd, 1, access=mmap.ACCESS_WRITE)
581
+ except OSError as exc:
582
+ warnings.warn('Failed to create mmap: {}; mmap use will be '
583
+ 'disabled'.format(str(exc)), AstropyUserWarning)
584
+ del exc
585
+ return False
586
+ try:
587
+ mm.flush()
588
+ except OSError:
589
+ warnings.warn('mmap.flush is unavailable on this platform; '
590
+ 'using mmap in writeable mode will be disabled',
591
+ AstropyUserWarning)
592
+ return False
593
+ finally:
594
+ mm.close()
595
+ finally:
596
+ os.close(tmpfd)
597
+ os.remove(tmpname)
598
+
599
+ return True
600
+
601
+ def _open_zipfile(self, fileobj, mode):
602
+ """Limited support for zipfile.ZipFile objects containing a single
603
+ a file. Allows reading only for now by extracting the file to a
604
+ tempfile.
605
+ """
606
+
607
+ if mode in ('update', 'append'):
608
+ raise OSError(
609
+ "Writing to zipped fits files is not currently "
610
+ "supported")
611
+
612
+ if not isinstance(fileobj, zipfile.ZipFile):
613
+ zfile = zipfile.ZipFile(fileobj)
614
+ close = True
615
+ else:
616
+ zfile = fileobj
617
+ close = False
618
+
619
+ namelist = zfile.namelist()
620
+ if len(namelist) != 1:
621
+ raise OSError(
622
+ "Zip files with multiple members are not supported.")
623
+ self._file = tempfile.NamedTemporaryFile(suffix='.fits')
624
+ self._file.write(zfile.read(namelist[0]))
625
+
626
+ if close:
627
+ zfile.close()
628
+ # We just wrote the contents of the first file in the archive to a new
629
+ # temp file, which now serves as our underlying file object. So it's
630
+ # necessary to reset the position back to the beginning
631
+ self._file.seek(0)
testbed/astropy__astropy/astropy/io/fits/fitsrec.py ADDED
@@ -0,0 +1,1338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import copy
4
+ import operator
5
+ import warnings
6
+ import weakref
7
+
8
+ from contextlib import suppress
9
+ from functools import reduce
10
+
11
+ import numpy as np
12
+
13
+ from numpy import char as chararray
14
+
15
+ from .column import (ASCIITNULL, FITS2NUMPY, ASCII2NUMPY, ASCII2STR, ColDefs,
16
+ _AsciiColDefs, _FormatX, _FormatP, _VLF, _get_index,
17
+ _wrapx, _unwrapx, _makep, Delayed)
18
+ from .util import decode_ascii, encode_ascii, _rstrip_inplace
19
+ from astropy.utils import lazyproperty
20
+
21
+
22
+ class FITS_record:
23
+ """
24
+ FITS record class.
25
+
26
+ `FITS_record` is used to access records of the `FITS_rec` object.
27
+ This will allow us to deal with scaled columns. It also handles
28
+ conversion/scaling of columns in ASCII tables. The `FITS_record`
29
+ class expects a `FITS_rec` object as input.
30
+ """
31
+
32
+ def __init__(self, input, row=0, start=None, end=None, step=None,
33
+ base=None, **kwargs):
34
+ """
35
+ Parameters
36
+ ----------
37
+ input : array
38
+ The array to wrap.
39
+
40
+ row : int, optional
41
+ The starting logical row of the array.
42
+
43
+ start : int, optional
44
+ The starting column in the row associated with this object.
45
+ Used for subsetting the columns of the `FITS_rec` object.
46
+
47
+ end : int, optional
48
+ The ending column in the row associated with this object.
49
+ Used for subsetting the columns of the `FITS_rec` object.
50
+ """
51
+
52
+ self.array = input
53
+ self.row = row
54
+ if base:
55
+ width = len(base)
56
+ else:
57
+ width = self.array._nfields
58
+
59
+ s = slice(start, end, step).indices(width)
60
+ self.start, self.end, self.step = s
61
+ self.base = base
62
+
63
+ def __getitem__(self, key):
64
+ if isinstance(key, str):
65
+ indx = _get_index(self.array.names, key)
66
+
67
+ if indx < self.start or indx > self.end - 1:
68
+ raise KeyError("Key '{}' does not exist.".format(key))
69
+ elif isinstance(key, slice):
70
+ return type(self)(self.array, self.row, key.start, key.stop,
71
+ key.step, self)
72
+ else:
73
+ indx = self._get_index(key)
74
+
75
+ if indx > self.array._nfields - 1:
76
+ raise IndexError('Index out of bounds')
77
+
78
+ return self.array.field(indx)[self.row]
79
+
80
+ def __setitem__(self, key, value):
81
+ if isinstance(key, str):
82
+ indx = _get_index(self.array.names, key)
83
+
84
+ if indx < self.start or indx > self.end - 1:
85
+ raise KeyError("Key '{}' does not exist.".format(key))
86
+ elif isinstance(key, slice):
87
+ for indx in range(slice.start, slice.stop, slice.step):
88
+ indx = self._get_indx(indx)
89
+ self.array.field(indx)[self.row] = value
90
+ else:
91
+ indx = self._get_index(key)
92
+ if indx > self.array._nfields - 1:
93
+ raise IndexError('Index out of bounds')
94
+
95
+ self.array.field(indx)[self.row] = value
96
+
97
+ def __len__(self):
98
+ return len(range(self.start, self.end, self.step))
99
+
100
+ def __repr__(self):
101
+ """
102
+ Display a single row.
103
+ """
104
+
105
+ outlist = []
106
+ for idx in range(len(self)):
107
+ outlist.append(repr(self[idx]))
108
+ return '({})'.format(', '.join(outlist))
109
+
110
+ def field(self, field):
111
+ """
112
+ Get the field data of the record.
113
+ """
114
+
115
+ return self.__getitem__(field)
116
+
117
+ def setfield(self, field, value):
118
+ """
119
+ Set the field data of the record.
120
+ """
121
+
122
+ self.__setitem__(field, value)
123
+
124
+ @lazyproperty
125
+ def _bases(self):
126
+ bases = [weakref.proxy(self)]
127
+ base = self.base
128
+ while base:
129
+ bases.append(base)
130
+ base = base.base
131
+ return bases
132
+
133
+ def _get_index(self, indx):
134
+ indices = np.ogrid[:self.array._nfields]
135
+ for base in reversed(self._bases):
136
+ if base.step < 1:
137
+ s = slice(base.start, None, base.step)
138
+ else:
139
+ s = slice(base.start, base.end, base.step)
140
+ indices = indices[s]
141
+ return indices[indx]
142
+
143
+
144
+ class FITS_rec(np.recarray):
145
+ """
146
+ FITS record array class.
147
+
148
+ `FITS_rec` is the data part of a table HDU's data part. This is a layer
149
+ over the `~numpy.recarray`, so we can deal with scaled columns.
150
+
151
+ It inherits all of the standard methods from `numpy.ndarray`.
152
+ """
153
+
154
+ _record_type = FITS_record
155
+ _character_as_bytes = False
156
+
157
+ def __new__(subtype, input):
158
+ """
159
+ Construct a FITS record array from a recarray.
160
+ """
161
+
162
+ # input should be a record array
163
+ if input.dtype.subdtype is None:
164
+ self = np.recarray.__new__(subtype, input.shape, input.dtype,
165
+ buf=input.data)
166
+ else:
167
+ self = np.recarray.__new__(subtype, input.shape, input.dtype,
168
+ buf=input.data, strides=input.strides)
169
+
170
+ self._init()
171
+ if self.dtype.fields:
172
+ self._nfields = len(self.dtype.fields)
173
+
174
+ return self
175
+
176
+ def __setstate__(self, state):
177
+ meta = state[-1]
178
+ column_state = state[-2]
179
+ state = state[:-2]
180
+
181
+ super().__setstate__(state)
182
+
183
+ self._col_weakrefs = weakref.WeakSet()
184
+
185
+ for attr, value in zip(meta, column_state):
186
+ setattr(self, attr, value)
187
+
188
+ def __reduce__(self):
189
+ """
190
+ Return a 3-tuple for pickling a FITS_rec. Use the super-class
191
+ functionality but then add in a tuple of FITS_rec-specific
192
+ values that get used in __setstate__.
193
+ """
194
+
195
+ reconst_func, reconst_func_args, state = super().__reduce__()
196
+
197
+ # Define FITS_rec-specific attrs that get added to state
198
+ column_state = []
199
+ meta = []
200
+
201
+ for attrs in ['_converted', '_heapoffset', '_heapsize', '_nfields',
202
+ '_gap', '_uint', 'parnames', '_coldefs']:
203
+
204
+ with suppress(AttributeError):
205
+ # _coldefs can be Delayed, and file objects cannot be
206
+ # picked, it needs to be deepcopied first
207
+ if attrs == '_coldefs':
208
+ column_state.append(self._coldefs.__deepcopy__(None))
209
+ else:
210
+ column_state.append(getattr(self, attrs))
211
+ meta.append(attrs)
212
+
213
+ state = state + (column_state, meta)
214
+
215
+ return reconst_func, reconst_func_args, state
216
+
217
+ def __array_finalize__(self, obj):
218
+ if obj is None:
219
+ return
220
+
221
+ if isinstance(obj, FITS_rec):
222
+ self._character_as_bytes = obj._character_as_bytes
223
+
224
+ if isinstance(obj, FITS_rec) and obj.dtype == self.dtype:
225
+ self._converted = obj._converted
226
+ self._heapoffset = obj._heapoffset
227
+ self._heapsize = obj._heapsize
228
+ self._col_weakrefs = obj._col_weakrefs
229
+ self._coldefs = obj._coldefs
230
+ self._nfields = obj._nfields
231
+ self._gap = obj._gap
232
+ self._uint = obj._uint
233
+ elif self.dtype.fields is not None:
234
+ # This will allow regular ndarrays with fields, rather than
235
+ # just other FITS_rec objects
236
+ self._nfields = len(self.dtype.fields)
237
+ self._converted = {}
238
+
239
+ self._heapoffset = getattr(obj, '_heapoffset', 0)
240
+ self._heapsize = getattr(obj, '_heapsize', 0)
241
+
242
+ self._gap = getattr(obj, '_gap', 0)
243
+ self._uint = getattr(obj, '_uint', False)
244
+ self._col_weakrefs = weakref.WeakSet()
245
+ self._coldefs = ColDefs(self)
246
+
247
+ # Work around chicken-egg problem. Column.array relies on the
248
+ # _coldefs attribute to set up ref back to parent FITS_rec; however
249
+ # in the above line the self._coldefs has not been assigned yet so
250
+ # this fails. This patches that up...
251
+ for col in self._coldefs:
252
+ del col.array
253
+ col._parent_fits_rec = weakref.ref(self)
254
+ else:
255
+ self._init()
256
+
257
+ def _init(self):
258
+ """Initializes internal attributes specific to FITS-isms."""
259
+
260
+ self._nfields = 0
261
+ self._converted = {}
262
+ self._heapoffset = 0
263
+ self._heapsize = 0
264
+ self._col_weakrefs = weakref.WeakSet()
265
+ self._coldefs = None
266
+ self._gap = 0
267
+ self._uint = False
268
+
269
+ @classmethod
270
+ def from_columns(cls, columns, nrows=0, fill=False, character_as_bytes=False):
271
+ """
272
+ Given a `ColDefs` object of unknown origin, initialize a new `FITS_rec`
273
+ object.
274
+
275
+ .. note::
276
+
277
+ This was originally part of the ``new_table`` function in the table
278
+ module but was moved into a class method since most of its
279
+ functionality always had more to do with initializing a `FITS_rec`
280
+ object than anything else, and much of it also overlapped with
281
+ ``FITS_rec._scale_back``.
282
+
283
+ Parameters
284
+ ----------
285
+ columns : sequence of `Column` or a `ColDefs`
286
+ The columns from which to create the table data. If these
287
+ columns have data arrays attached that data may be used in
288
+ initializing the new table. Otherwise the input columns
289
+ will be used as a template for a new table with the requested
290
+ number of rows.
291
+
292
+ nrows : int
293
+ Number of rows in the new table. If the input columns have data
294
+ associated with them, the size of the largest input column is used.
295
+ Otherwise the default is 0.
296
+
297
+ fill : bool
298
+ If `True`, will fill all cells with zeros or blanks. If
299
+ `False`, copy the data from input, undefined cells will still
300
+ be filled with zeros/blanks.
301
+ """
302
+
303
+ if not isinstance(columns, ColDefs):
304
+ columns = ColDefs(columns)
305
+
306
+ # read the delayed data
307
+ for column in columns:
308
+ arr = column.array
309
+ if isinstance(arr, Delayed):
310
+ if arr.hdu.data is None:
311
+ column.array = None
312
+ else:
313
+ column.array = _get_recarray_field(arr.hdu.data,
314
+ arr.field)
315
+ # Reset columns._arrays (which we may want to just do away with
316
+ # altogether
317
+ del columns._arrays
318
+
319
+ # use the largest column shape as the shape of the record
320
+ if nrows == 0:
321
+ for arr in columns._arrays:
322
+ if arr is not None:
323
+ dim = arr.shape[0]
324
+ else:
325
+ dim = 0
326
+ if dim > nrows:
327
+ nrows = dim
328
+
329
+ raw_data = np.empty(columns.dtype.itemsize * nrows, dtype=np.uint8)
330
+ raw_data.fill(ord(columns._padding_byte))
331
+ data = np.recarray(nrows, dtype=columns.dtype, buf=raw_data).view(cls)
332
+ data._character_as_bytes = character_as_bytes
333
+
334
+ # Make sure the data is a listener for changes to the columns
335
+ columns._add_listener(data)
336
+
337
+ # Previously this assignment was made from hdu.columns, but that's a
338
+ # bug since if a _TableBaseHDU has a FITS_rec in its .data attribute
339
+ # the _TableBaseHDU.columns property is actually returned from
340
+ # .data._coldefs, so this assignment was circular! Don't make that
341
+ # mistake again.
342
+ # All of this is an artifact of the fragility of the FITS_rec class,
343
+ # and that it can't just be initialized by columns...
344
+ data._coldefs = columns
345
+
346
+ # If fill is True we don't copy anything from the column arrays. We're
347
+ # just using them as a template, and returning a table filled with
348
+ # zeros/blanks
349
+ if fill:
350
+ return data
351
+
352
+ # Otherwise we have to fill the recarray with data from the input
353
+ # columns
354
+ for idx, column in enumerate(columns):
355
+ # For each column in the ColDef object, determine the number of
356
+ # rows in that column. This will be either the number of rows in
357
+ # the ndarray associated with the column, or the number of rows
358
+ # given in the call to this function, which ever is smaller. If
359
+ # the input FILL argument is true, the number of rows is set to
360
+ # zero so that no data is copied from the original input data.
361
+ arr = column.array
362
+
363
+ if arr is None:
364
+ array_size = 0
365
+ else:
366
+ array_size = len(arr)
367
+
368
+ n = min(array_size, nrows)
369
+
370
+ # TODO: At least *some* of this logic is mostly redundant with the
371
+ # _convert_foo methods in this class; see if we can eliminate some
372
+ # of that duplication.
373
+
374
+ if not n:
375
+ # The input column had an empty array, so just use the fill
376
+ # value
377
+ continue
378
+
379
+ field = _get_recarray_field(data, idx)
380
+ name = column.name
381
+ fitsformat = column.format
382
+ recformat = fitsformat.recformat
383
+
384
+ outarr = field[:n]
385
+ inarr = arr[:n]
386
+
387
+ if isinstance(recformat, _FormatX):
388
+ # Data is a bit array
389
+ if inarr.shape[-1] == recformat.repeat:
390
+ _wrapx(inarr, outarr, recformat.repeat)
391
+ continue
392
+ elif isinstance(recformat, _FormatP):
393
+ data._cache_field(name, _makep(inarr, field, recformat,
394
+ nrows=nrows))
395
+ continue
396
+ # TODO: Find a better way of determining that the column is meant
397
+ # to be FITS L formatted
398
+ elif recformat[-2:] == FITS2NUMPY['L'] and inarr.dtype == bool:
399
+ # column is boolean
400
+ # The raw data field should be filled with either 'T' or 'F'
401
+ # (not 0). Use 'F' as a default
402
+ field[:] = ord('F')
403
+ # Also save the original boolean array in data._converted so
404
+ # that it doesn't have to be re-converted
405
+ converted = np.zeros(field.shape, dtype=bool)
406
+ converted[:n] = inarr
407
+ data._cache_field(name, converted)
408
+ # TODO: Maybe this step isn't necessary at all if _scale_back
409
+ # will handle it?
410
+ inarr = np.where(inarr == np.False_, ord('F'), ord('T'))
411
+ elif (columns[idx]._physical_values and
412
+ columns[idx]._pseudo_unsigned_ints):
413
+ # Temporary hack...
414
+ bzero = column.bzero
415
+ converted = np.zeros(field.shape, dtype=inarr.dtype)
416
+ converted[:n] = inarr
417
+ data._cache_field(name, converted)
418
+ if n < nrows:
419
+ # Pre-scale rows below the input data
420
+ field[n:] = -bzero
421
+
422
+ inarr = inarr - bzero
423
+ elif isinstance(columns, _AsciiColDefs):
424
+ # Regardless whether the format is character or numeric, if the
425
+ # input array contains characters then it's already in the raw
426
+ # format for ASCII tables
427
+ if fitsformat._pseudo_logical:
428
+ # Hack to support converting from 8-bit T/F characters
429
+ # Normally the column array is a chararray of 1 character
430
+ # strings, but we need to view it as a normal ndarray of
431
+ # 8-bit ints to fill it with ASCII codes for 'T' and 'F'
432
+ outarr = field.view(np.uint8, np.ndarray)[:n]
433
+ elif arr.dtype.kind not in ('S', 'U'):
434
+ # Set up views of numeric columns with the appropriate
435
+ # numeric dtype
436
+ # Fill with the appropriate blanks for the column format
437
+ data._cache_field(name, np.zeros(nrows, dtype=arr.dtype))
438
+ outarr = data._converted[name][:n]
439
+
440
+ outarr[:] = inarr
441
+ continue
442
+
443
+ if inarr.shape != outarr.shape:
444
+ if (inarr.dtype.kind == outarr.dtype.kind and
445
+ inarr.dtype.kind in ('U', 'S') and
446
+ inarr.dtype != outarr.dtype):
447
+
448
+ inarr_rowsize = inarr[0].size
449
+ inarr = inarr.flatten().view(outarr.dtype)
450
+
451
+ # This is a special case to handle input arrays with
452
+ # non-trivial TDIMn.
453
+ # By design each row of the outarray is 1-D, while each row of
454
+ # the input array may be n-D
455
+ if outarr.ndim > 1:
456
+ # The normal case where the first dimension is the rows
457
+ inarr_rowsize = inarr[0].size
458
+ inarr = inarr.reshape(n, inarr_rowsize)
459
+ outarr[:, :inarr_rowsize] = inarr
460
+ else:
461
+ # Special case for strings where the out array only has one
462
+ # dimension (the second dimension is rolled up into the
463
+ # strings
464
+ outarr[:n] = inarr.ravel()
465
+ else:
466
+ outarr[:] = inarr
467
+
468
+ # Now replace the original column array references with the new
469
+ # fields
470
+ # This is required to prevent the issue reported in
471
+ # https://github.com/spacetelescope/PyFITS/issues/99
472
+ for idx in range(len(columns)):
473
+ columns._arrays[idx] = data.field(idx)
474
+
475
+ return data
476
+
477
+ def __repr__(self):
478
+ # Force use of the normal ndarray repr (rather than the new
479
+ # one added for recarray in Numpy 1.10) for backwards compat
480
+ return np.ndarray.__repr__(self)
481
+
482
+ def __getitem__(self, key):
483
+ if self._coldefs is None:
484
+ return super().__getitem__(key)
485
+
486
+ if isinstance(key, str):
487
+ return self.field(key)
488
+
489
+ # Have to view as a recarray then back as a FITS_rec, otherwise the
490
+ # circular reference fix/hack in FITS_rec.field() won't preserve
491
+ # the slice.
492
+ out = self.view(np.recarray)[key]
493
+ if type(out) is not np.recarray:
494
+ # Oops, we got a single element rather than a view. In that case,
495
+ # return a Record, which has no __getstate__ and is more efficient.
496
+ return self._record_type(self, key)
497
+
498
+ # We got a view; change it back to our class, and add stuff
499
+ out = out.view(type(self))
500
+ out._coldefs = ColDefs(self._coldefs)
501
+ arrays = []
502
+ out._converted = {}
503
+ for idx, name in enumerate(self._coldefs.names):
504
+ #
505
+ # Store the new arrays for the _coldefs object
506
+ #
507
+ arrays.append(self._coldefs._arrays[idx][key])
508
+
509
+ # Ensure that the sliced FITS_rec will view the same scaled
510
+ # columns as the original; this is one of the few cases where
511
+ # it is not necessary to use _cache_field()
512
+ if name in self._converted:
513
+ dummy = self._converted[name]
514
+ field = np.ndarray.__getitem__(dummy, key)
515
+ out._converted[name] = field
516
+
517
+ out._coldefs._arrays = arrays
518
+ return out
519
+
520
+ def __setitem__(self, key, value):
521
+ if self._coldefs is None:
522
+ return super().__setitem__(key, value)
523
+
524
+ if isinstance(key, str):
525
+ self[key][:] = value
526
+ return
527
+
528
+ if isinstance(key, slice):
529
+ end = min(len(self), key.stop or len(self))
530
+ end = max(0, end)
531
+ start = max(0, key.start or 0)
532
+ end = min(end, start + len(value))
533
+
534
+ for idx in range(start, end):
535
+ self.__setitem__(idx, value[idx - start])
536
+ return
537
+
538
+ if isinstance(value, FITS_record):
539
+ for idx in range(self._nfields):
540
+ self.field(self.names[idx])[key] = value.field(self.names[idx])
541
+ elif isinstance(value, (tuple, list, np.void)):
542
+ if self._nfields == len(value):
543
+ for idx in range(self._nfields):
544
+ self.field(idx)[key] = value[idx]
545
+ else:
546
+ raise ValueError('Input tuple or list required to have {} '
547
+ 'elements.'.format(self._nfields))
548
+ else:
549
+ raise TypeError('Assignment requires a FITS_record, tuple, or '
550
+ 'list as input.')
551
+
552
+ def _ipython_key_completions_(self):
553
+ return self.names
554
+
555
+ def copy(self, order='C'):
556
+ """
557
+ The Numpy documentation lies; `numpy.ndarray.copy` is not equivalent to
558
+ `numpy.copy`. Differences include that it re-views the copied array as
559
+ self's ndarray subclass, as though it were taking a slice; this means
560
+ ``__array_finalize__`` is called and the copy shares all the array
561
+ attributes (including ``._converted``!). So we need to make a deep
562
+ copy of all those attributes so that the two arrays truly do not share
563
+ any data.
564
+ """
565
+
566
+ new = super().copy(order=order)
567
+
568
+ new.__dict__ = copy.deepcopy(self.__dict__)
569
+ return new
570
+
571
+ @property
572
+ def columns(self):
573
+ """
574
+ A user-visible accessor for the coldefs.
575
+
576
+ See https://aeon.stsci.edu/ssb/trac/pyfits/ticket/44
577
+ """
578
+
579
+ return self._coldefs
580
+
581
+ @property
582
+ def _coldefs(self):
583
+ # This used to be a normal internal attribute, but it was changed to a
584
+ # property as a quick and transparent way to work around the reference
585
+ # leak bug fixed in https://github.com/astropy/astropy/pull/4539
586
+ #
587
+ # See the long comment in the Column.array property for more details
588
+ # on this. But in short, FITS_rec now has a ._col_weakrefs attribute
589
+ # which is a WeakSet of weakrefs to each Column in _coldefs.
590
+ #
591
+ # So whenever ._coldefs is set we also add each Column in the ColDefs
592
+ # to the weakrefs set. This is an easy way to find out if a Column has
593
+ # any references to it external to the FITS_rec (i.e. a user assigned a
594
+ # column to a variable). If the column is still in _col_weakrefs then
595
+ # there are other references to it external to this FITS_rec. We use
596
+ # that information in __del__ to save off copies of the array data
597
+ # for those columns to their Column.array property before our memory
598
+ # is freed.
599
+ return self.__dict__.get('_coldefs')
600
+
601
+ @_coldefs.setter
602
+ def _coldefs(self, cols):
603
+ self.__dict__['_coldefs'] = cols
604
+ if isinstance(cols, ColDefs):
605
+ for col in cols.columns:
606
+ self._col_weakrefs.add(col)
607
+
608
+ @_coldefs.deleter
609
+ def _coldefs(self):
610
+ try:
611
+ del self.__dict__['_coldefs']
612
+ except KeyError as exc:
613
+ raise AttributeError(exc.args[0])
614
+
615
+ def __del__(self):
616
+ try:
617
+ del self._coldefs
618
+ if self.dtype.fields is not None:
619
+ for col in self._col_weakrefs:
620
+
621
+ if col.array is not None:
622
+ col.array = col.array.copy()
623
+
624
+ # See issues #4690 and #4912
625
+ except (AttributeError, TypeError): # pragma: no cover
626
+ pass
627
+
628
+ @property
629
+ def names(self):
630
+ """List of column names."""
631
+
632
+ if self.dtype.fields:
633
+ return list(self.dtype.names)
634
+ elif getattr(self, '_coldefs', None) is not None:
635
+ return self._coldefs.names
636
+ else:
637
+ return None
638
+
639
+ @property
640
+ def formats(self):
641
+ """List of column FITS formats."""
642
+
643
+ if getattr(self, '_coldefs', None) is not None:
644
+ return self._coldefs.formats
645
+
646
+ return None
647
+
648
+ @property
649
+ def _raw_itemsize(self):
650
+ """
651
+ Returns the size of row items that would be written to the raw FITS
652
+ file, taking into account the possibility of unicode columns being
653
+ compactified.
654
+
655
+ Currently for internal use only.
656
+ """
657
+
658
+ if _has_unicode_fields(self):
659
+ total_itemsize = 0
660
+ for field in self.dtype.fields.values():
661
+ itemsize = field[0].itemsize
662
+ if field[0].kind == 'U':
663
+ itemsize = itemsize // 4
664
+ total_itemsize += itemsize
665
+ return total_itemsize
666
+ else:
667
+ # Just return the normal itemsize
668
+ return self.itemsize
669
+
670
+ def field(self, key):
671
+ """
672
+ A view of a `Column`'s data as an array.
673
+ """
674
+
675
+ # NOTE: The *column* index may not be the same as the field index in
676
+ # the recarray, if the column is a phantom column
677
+ column = self.columns[key]
678
+ name = column.name
679
+ format = column.format
680
+
681
+ if format.dtype.itemsize == 0:
682
+ warnings.warn(
683
+ 'Field {!r} has a repeat count of 0 in its format code, '
684
+ 'indicating an empty field.'.format(key))
685
+ return np.array([], dtype=format.dtype)
686
+
687
+ # If field's base is a FITS_rec, we can run into trouble because it
688
+ # contains a reference to the ._coldefs object of the original data;
689
+ # this can lead to a circular reference; see ticket #49
690
+ base = self
691
+ while (isinstance(base, FITS_rec) and
692
+ isinstance(base.base, np.recarray)):
693
+ base = base.base
694
+ # base could still be a FITS_rec in some cases, so take care to
695
+ # use rec.recarray.field to avoid a potential infinite
696
+ # recursion
697
+ field = _get_recarray_field(base, name)
698
+
699
+ if name not in self._converted:
700
+ recformat = format.recformat
701
+ # TODO: If we're now passing the column to these subroutines, do we
702
+ # really need to pass them the recformat?
703
+ if isinstance(recformat, _FormatP):
704
+ # for P format
705
+ converted = self._convert_p(column, field, recformat)
706
+ else:
707
+ # Handle all other column data types which are fixed-width
708
+ # fields
709
+ converted = self._convert_other(column, field, recformat)
710
+
711
+ # Note: Never assign values directly into the self._converted dict;
712
+ # always go through self._cache_field; this way self._converted is
713
+ # only used to store arrays that are not already direct views of
714
+ # our own data.
715
+ self._cache_field(name, converted)
716
+ return converted
717
+
718
+ return self._converted[name]
719
+
720
+ def _cache_field(self, name, field):
721
+ """
722
+ Do not store fields in _converted if one of its bases is self,
723
+ or if it has a common base with self.
724
+
725
+ This results in a reference cycle that cannot be broken since
726
+ ndarrays do not participate in cyclic garbage collection.
727
+ """
728
+
729
+ base = field
730
+ while True:
731
+ self_base = self
732
+ while True:
733
+ if self_base is base:
734
+ return
735
+
736
+ if getattr(self_base, 'base', None) is not None:
737
+ self_base = self_base.base
738
+ else:
739
+ break
740
+
741
+ if getattr(base, 'base', None) is not None:
742
+ base = base.base
743
+ else:
744
+ break
745
+
746
+ self._converted[name] = field
747
+
748
+ def _update_column_attribute_changed(self, column, idx, attr, old_value,
749
+ new_value):
750
+ """
751
+ Update how the data is formatted depending on changes to column
752
+ attributes initiated by the user through the `Column` interface.
753
+
754
+ Dispatches column attribute change notifications to individual methods
755
+ for each attribute ``_update_column_<attr>``
756
+ """
757
+
758
+ method_name = '_update_column_{0}'.format(attr)
759
+ if hasattr(self, method_name):
760
+ # Right now this is so we can be lazy and not implement updaters
761
+ # for every attribute yet--some we may not need at all, TBD
762
+ getattr(self, method_name)(column, idx, old_value, new_value)
763
+
764
+ def _update_column_name(self, column, idx, old_name, name):
765
+ """Update the dtype field names when a column name is changed."""
766
+
767
+ dtype = self.dtype
768
+ # Updating the names on the dtype should suffice
769
+ dtype.names = dtype.names[:idx] + (name,) + dtype.names[idx + 1:]
770
+
771
+ def _convert_x(self, field, recformat):
772
+ """Convert a raw table column to a bit array as specified by the
773
+ FITS X format.
774
+ """
775
+
776
+ dummy = np.zeros(self.shape + (recformat.repeat,), dtype=np.bool_)
777
+ _unwrapx(field, dummy, recformat.repeat)
778
+ return dummy
779
+
780
+ def _convert_p(self, column, field, recformat):
781
+ """Convert a raw table column of FITS P or Q format descriptors
782
+ to a VLA column with the array data returned from the heap.
783
+ """
784
+
785
+ dummy = _VLF([None] * len(self), dtype=recformat.dtype)
786
+ raw_data = self._get_raw_data()
787
+
788
+ if raw_data is None:
789
+ raise OSError(
790
+ "Could not find heap data for the {!r} variable-length "
791
+ "array column.".format(column.name))
792
+
793
+ for idx in range(len(self)):
794
+ offset = field[idx, 1] + self._heapoffset
795
+ count = field[idx, 0]
796
+
797
+ if recformat.dtype == 'a':
798
+ dt = np.dtype(recformat.dtype + str(1))
799
+ arr_len = count * dt.itemsize
800
+ da = raw_data[offset:offset + arr_len].view(dt)
801
+ da = np.char.array(da.view(dtype=dt), itemsize=count)
802
+ dummy[idx] = decode_ascii(da)
803
+ else:
804
+ dt = np.dtype(recformat.dtype)
805
+ arr_len = count * dt.itemsize
806
+ dummy[idx] = raw_data[offset:offset + arr_len].view(dt)
807
+ dummy[idx].dtype = dummy[idx].dtype.newbyteorder('>')
808
+ # Each array in the field may now require additional
809
+ # scaling depending on the other scaling parameters
810
+ # TODO: The same scaling parameters apply to every
811
+ # array in the column so this is currently very slow; we
812
+ # really only need to check once whether any scaling will
813
+ # be necessary and skip this step if not
814
+ # TODO: Test that this works for X format; I don't think
815
+ # that it does--the recformat variable only applies to the P
816
+ # format not the X format
817
+ dummy[idx] = self._convert_other(column, dummy[idx],
818
+ recformat)
819
+
820
+ return dummy
821
+
822
+ def _convert_ascii(self, column, field):
823
+ """
824
+ Special handling for ASCII table columns to convert columns containing
825
+ numeric types to actual numeric arrays from the string representation.
826
+ """
827
+
828
+ format = column.format
829
+ recformat = ASCII2NUMPY[format[0]]
830
+ # if the string = TNULL, return ASCIITNULL
831
+ nullval = str(column.null).strip().encode('ascii')
832
+ if len(nullval) > format.width:
833
+ nullval = nullval[:format.width]
834
+
835
+ # Before using .replace make sure that any trailing bytes in each
836
+ # column are filled with spaces, and *not*, say, nulls; this causes
837
+ # functions like replace to potentially leave gibberish bytes in the
838
+ # array buffer.
839
+ dummy = np.char.ljust(field, format.width)
840
+ dummy = np.char.replace(dummy, encode_ascii('D'), encode_ascii('E'))
841
+ null_fill = encode_ascii(str(ASCIITNULL).rjust(format.width))
842
+
843
+ # Convert all fields equal to the TNULL value (nullval) to empty fields.
844
+ # TODO: These fields really should be conerted to NaN or something else undefined.
845
+ # Currently they are converted to empty fields, which are then set to zero.
846
+ dummy = np.where(np.char.strip(dummy) == nullval, null_fill, dummy)
847
+
848
+ # always replace empty fields, see https://github.com/astropy/astropy/pull/5394
849
+ if nullval != b'':
850
+ dummy = np.where(np.char.strip(dummy) == b'', null_fill, dummy)
851
+
852
+ try:
853
+ dummy = np.array(dummy, dtype=recformat)
854
+ except ValueError as exc:
855
+ indx = self.names.index(column.name)
856
+ raise ValueError(
857
+ '{}; the header may be missing the necessary TNULL{} '
858
+ 'keyword or the table contains invalid data'.format(
859
+ exc, indx + 1))
860
+
861
+ return dummy
862
+
863
+ def _convert_other(self, column, field, recformat):
864
+ """Perform conversions on any other fixed-width column data types.
865
+
866
+ This may not perform any conversion at all if it's not necessary, in
867
+ which case the original column array is returned.
868
+ """
869
+
870
+ if isinstance(recformat, _FormatX):
871
+ # special handling for the X format
872
+ return self._convert_x(field, recformat)
873
+
874
+ (_str, _bool, _number, _scale, _zero, bscale, bzero, dim) = \
875
+ self._get_scale_factors(column)
876
+
877
+ indx = self.names.index(column.name)
878
+
879
+ # ASCII table, convert strings to numbers
880
+ # TODO:
881
+ # For now, check that these are ASCII columns by checking the coldefs
882
+ # type; in the future all columns (for binary tables, ASCII tables, or
883
+ # otherwise) should "know" what type they are already and how to handle
884
+ # converting their data from FITS format to native format and vice
885
+ # versa...
886
+ if not _str and isinstance(self._coldefs, _AsciiColDefs):
887
+ field = self._convert_ascii(column, field)
888
+
889
+ # Test that the dimensions given in dim are sensible; otherwise
890
+ # display a warning and ignore them
891
+ if dim:
892
+ # See if the dimensions already match, if not, make sure the
893
+ # number items will fit in the specified dimensions
894
+ if field.ndim > 1:
895
+ actual_shape = field.shape[1:]
896
+ if _str:
897
+ actual_shape = actual_shape + (field.itemsize,)
898
+ else:
899
+ actual_shape = field.shape[0]
900
+
901
+ if dim == actual_shape:
902
+ # The array already has the correct dimensions, so we
903
+ # ignore dim and don't convert
904
+ dim = None
905
+ else:
906
+ nitems = reduce(operator.mul, dim)
907
+ if _str:
908
+ actual_nitems = field.itemsize
909
+ elif len(field.shape) == 1: # No repeat count in TFORMn, equivalent to 1
910
+ actual_nitems = 1
911
+ else:
912
+ actual_nitems = field.shape[1]
913
+ if nitems > actual_nitems:
914
+ warnings.warn(
915
+ 'TDIM{} value {:d} does not fit with the size of '
916
+ 'the array items ({:d}). TDIM{:d} will be ignored.'
917
+ .format(indx + 1, self._coldefs[indx].dims,
918
+ actual_nitems, indx + 1))
919
+ dim = None
920
+
921
+ # further conversion for both ASCII and binary tables
922
+ # For now we've made columns responsible for *knowing* whether their
923
+ # data has been scaled, but we make the FITS_rec class responsible for
924
+ # actually doing the scaling
925
+ # TODO: This also needs to be fixed in the effort to make Columns
926
+ # responsible for scaling their arrays to/from FITS native values
927
+ if not column.ascii and column.format.p_format:
928
+ format_code = column.format.p_format
929
+ else:
930
+ # TODO: Rather than having this if/else it might be nice if the
931
+ # ColumnFormat class had an attribute guaranteed to give the format
932
+ # of actual values in a column regardless of whether the true
933
+ # format is something like P or Q
934
+ format_code = column.format.format
935
+
936
+ if (_number and (_scale or _zero) and not column._physical_values):
937
+ # This is to handle pseudo unsigned ints in table columns
938
+ # TODO: For now this only really works correctly for binary tables
939
+ # Should it work for ASCII tables as well?
940
+ if self._uint:
941
+ if bzero == 2**15 and format_code == 'I':
942
+ field = np.array(field, dtype=np.uint16)
943
+ elif bzero == 2**31 and format_code == 'J':
944
+ field = np.array(field, dtype=np.uint32)
945
+ elif bzero == 2**63 and format_code == 'K':
946
+ field = np.array(field, dtype=np.uint64)
947
+ bzero64 = np.uint64(2 ** 63)
948
+ else:
949
+ field = np.array(field, dtype=np.float64)
950
+ else:
951
+ field = np.array(field, dtype=np.float64)
952
+
953
+ if _scale:
954
+ np.multiply(field, bscale, field)
955
+ if _zero:
956
+ if self._uint and format_code == 'K':
957
+ # There is a chance of overflow, so be careful
958
+ test_overflow = field.copy()
959
+ try:
960
+ test_overflow += bzero64
961
+ except OverflowError:
962
+ warnings.warn(
963
+ "Overflow detected while applying TZERO{0:d}. "
964
+ "Returning unscaled data.".format(indx + 1))
965
+ else:
966
+ field = test_overflow
967
+ else:
968
+ field += bzero
969
+
970
+ # mark the column as scaled
971
+ column._physical_values = True
972
+
973
+ elif _bool and field.dtype != bool:
974
+ field = np.equal(field, ord('T'))
975
+ elif _str:
976
+ if not self._character_as_bytes:
977
+ with suppress(UnicodeDecodeError):
978
+ field = decode_ascii(field)
979
+
980
+ if dim:
981
+ # Apply the new field item dimensions
982
+ nitems = reduce(operator.mul, dim)
983
+ if field.ndim > 1:
984
+ field = field[:, :nitems]
985
+ if _str:
986
+ fmt = field.dtype.char
987
+ dtype = ('|{}{}'.format(fmt, dim[-1]), dim[:-1])
988
+ field.dtype = dtype
989
+ else:
990
+ field.shape = (field.shape[0],) + dim
991
+
992
+ return field
993
+
994
+ def _get_heap_data(self):
995
+ """
996
+ Returns a pointer into the table's raw data to its heap (if present).
997
+
998
+ This is returned as a numpy byte array.
999
+ """
1000
+
1001
+ if self._heapsize:
1002
+ raw_data = self._get_raw_data().view(np.ubyte)
1003
+ heap_end = self._heapoffset + self._heapsize
1004
+ return raw_data[self._heapoffset:heap_end]
1005
+ else:
1006
+ return np.array([], dtype=np.ubyte)
1007
+
1008
+ def _get_raw_data(self):
1009
+ """
1010
+ Returns the base array of self that "raw data array" that is the
1011
+ array in the format that it was first read from a file before it was
1012
+ sliced or viewed as a different type in any way.
1013
+
1014
+ This is determined by walking through the bases until finding one that
1015
+ has at least the same number of bytes as self, plus the heapsize. This
1016
+ may be the immediate .base but is not always. This is used primarily
1017
+ for variable-length array support which needs to be able to find the
1018
+ heap (the raw data *may* be larger than nbytes + heapsize if it
1019
+ contains a gap or padding).
1020
+
1021
+ May return ``None`` if no array resembling the "raw data" according to
1022
+ the stated criteria can be found.
1023
+ """
1024
+
1025
+ raw_data_bytes = self.nbytes + self._heapsize
1026
+ base = self
1027
+ while hasattr(base, 'base') and base.base is not None:
1028
+ base = base.base
1029
+ if hasattr(base, 'nbytes') and base.nbytes >= raw_data_bytes:
1030
+ return base
1031
+
1032
+ def _get_scale_factors(self, column):
1033
+ """Get all the scaling flags and factors for one column."""
1034
+
1035
+ # TODO: Maybe this should be a method/property on Column? Or maybe
1036
+ # it's not really needed at all...
1037
+ _str = column.format.format == 'A'
1038
+ _bool = column.format.format == 'L'
1039
+
1040
+ _number = not (_bool or _str)
1041
+ bscale = column.bscale
1042
+ bzero = column.bzero
1043
+
1044
+ _scale = bscale not in ('', None, 1)
1045
+ _zero = bzero not in ('', None, 0)
1046
+
1047
+ # ensure bscale/bzero are numbers
1048
+ if not _scale:
1049
+ bscale = 1
1050
+ if not _zero:
1051
+ bzero = 0
1052
+
1053
+ # column._dims gives a tuple, rather than column.dim which returns the
1054
+ # original string format code from the FITS header...
1055
+ dim = column._dims
1056
+
1057
+ return (_str, _bool, _number, _scale, _zero, bscale, bzero, dim)
1058
+
1059
+ def _scale_back(self, update_heap_pointers=True):
1060
+ """
1061
+ Update the parent array, using the (latest) scaled array.
1062
+
1063
+ If ``update_heap_pointers`` is `False`, this will leave all the heap
1064
+ pointers in P/Q columns as they are verbatim--it only makes sense to do
1065
+ this if there is already data on the heap and it can be guaranteed that
1066
+ that data has not been modified, and there is not new data to add to
1067
+ the heap. Currently this is only used as an optimization for
1068
+ CompImageHDU that does its own handling of the heap.
1069
+ """
1070
+
1071
+ # Running total for the new heap size
1072
+ heapsize = 0
1073
+
1074
+ for indx, name in enumerate(self.dtype.names):
1075
+ column = self._coldefs[indx]
1076
+ recformat = column.format.recformat
1077
+ raw_field = _get_recarray_field(self, indx)
1078
+
1079
+ # add the location offset of the heap area for each
1080
+ # variable length column
1081
+ if isinstance(recformat, _FormatP):
1082
+ # Irritatingly, this can return a different dtype than just
1083
+ # doing np.dtype(recformat.dtype); but this returns the results
1084
+ # that we want. For example if recformat.dtype is 'a' we want
1085
+ # an array of characters.
1086
+ dtype = np.array([], dtype=recformat.dtype).dtype
1087
+
1088
+ if update_heap_pointers and name in self._converted:
1089
+ # The VLA has potentially been updated, so we need to
1090
+ # update the array descriptors
1091
+ raw_field[:] = 0 # reset
1092
+ npts = [len(arr) for arr in self._converted[name]]
1093
+
1094
+ raw_field[:len(npts), 0] = npts
1095
+ raw_field[1:, 1] = (np.add.accumulate(raw_field[:-1, 0]) *
1096
+ dtype.itemsize)
1097
+ raw_field[:, 1][:] += heapsize
1098
+
1099
+ heapsize += raw_field[:, 0].sum() * dtype.itemsize
1100
+ # Even if this VLA has not been read or updated, we need to
1101
+ # include the size of its constituent arrays in the heap size
1102
+ # total
1103
+
1104
+ if isinstance(recformat, _FormatX) and name in self._converted:
1105
+ _wrapx(self._converted[name], raw_field, recformat.repeat)
1106
+ continue
1107
+
1108
+ _str, _bool, _number, _scale, _zero, bscale, bzero, _ = \
1109
+ self._get_scale_factors(column)
1110
+
1111
+ field = self._converted.get(name, raw_field)
1112
+
1113
+ # conversion for both ASCII and binary tables
1114
+ if _number or _str:
1115
+ if _number and (_scale or _zero) and column._physical_values:
1116
+ dummy = field.copy()
1117
+ if _zero:
1118
+ dummy -= bzero
1119
+ if _scale:
1120
+ dummy /= bscale
1121
+ # This will set the raw values in the recarray back to
1122
+ # their non-physical storage values, so the column should
1123
+ # be mark is not scaled
1124
+ column._physical_values = False
1125
+ elif _str or isinstance(self._coldefs, _AsciiColDefs):
1126
+ dummy = field
1127
+ else:
1128
+ continue
1129
+
1130
+ # ASCII table, convert numbers to strings
1131
+ if isinstance(self._coldefs, _AsciiColDefs):
1132
+ self._scale_back_ascii(indx, dummy, raw_field)
1133
+ # binary table string column
1134
+ elif isinstance(raw_field, chararray.chararray):
1135
+ self._scale_back_strings(indx, dummy, raw_field)
1136
+ # all other binary table columns
1137
+ else:
1138
+ if len(raw_field) and isinstance(raw_field[0],
1139
+ np.integer):
1140
+ dummy = np.around(dummy)
1141
+
1142
+ if raw_field.shape == dummy.shape:
1143
+ raw_field[:] = dummy
1144
+ else:
1145
+ # Reshaping the data is necessary in cases where the
1146
+ # TDIMn keyword was used to shape a column's entries
1147
+ # into arrays
1148
+ raw_field[:] = dummy.ravel().view(raw_field.dtype)
1149
+
1150
+ del dummy
1151
+
1152
+ # ASCII table does not have Boolean type
1153
+ elif _bool and name in self._converted:
1154
+ choices = (np.array([ord('F')], dtype=np.int8)[0],
1155
+ np.array([ord('T')], dtype=np.int8)[0])
1156
+ raw_field[:] = np.choose(field, choices)
1157
+
1158
+ # Store the updated heapsize
1159
+ self._heapsize = heapsize
1160
+
1161
+ def _scale_back_strings(self, col_idx, input_field, output_field):
1162
+ # There are a few possibilities this has to be able to handle properly
1163
+ # The input_field, which comes from the _converted column is of dtype
1164
+ # 'Un' so that elements read out of the array are normal str
1165
+ # objects (i.e. unicode strings)
1166
+ #
1167
+ # At the other end the *output_field* may also be of type 'S' or of
1168
+ # type 'U'. It will *usually* be of type 'S' because when reading
1169
+ # an existing FITS table the raw data is just ASCII strings, and
1170
+ # represented in Numpy as an S array. However, when a user creates
1171
+ # a new table from scratch, they *might* pass in a column containing
1172
+ # unicode strings (dtype 'U'). Therefore the output_field of the
1173
+ # raw array is actually a unicode array. But we still want to make
1174
+ # sure the data is encodable as ASCII. Later when we write out the
1175
+ # array we use, in the dtype 'U' case, a different write routine
1176
+ # that writes row by row and encodes any 'U' columns to ASCII.
1177
+
1178
+ # If the output_field is non-ASCII we will worry about ASCII encoding
1179
+ # later when writing; otherwise we can do it right here
1180
+ if input_field.dtype.kind == 'U' and output_field.dtype.kind == 'S':
1181
+ try:
1182
+ _ascii_encode(input_field, out=output_field)
1183
+ except _UnicodeArrayEncodeError as exc:
1184
+ raise ValueError(
1185
+ "Could not save column '{0}': Contains characters that "
1186
+ "cannot be encoded as ASCII as required by FITS, starting "
1187
+ "at the index {1!r} of the column, and the index {2} of "
1188
+ "the string at that location.".format(
1189
+ self._coldefs[col_idx].name,
1190
+ exc.index[0] if len(exc.index) == 1 else exc.index,
1191
+ exc.start))
1192
+ else:
1193
+ # Otherwise go ahead and do a direct copy into--if both are type
1194
+ # 'U' we'll handle encoding later
1195
+ input_field = input_field.flatten().view(output_field.dtype)
1196
+ output_field.flat[:] = input_field
1197
+
1198
+ # Ensure that blanks at the end of each string are
1199
+ # converted to nulls instead of spaces, see Trac #15
1200
+ # and #111
1201
+ _rstrip_inplace(output_field)
1202
+
1203
+ def _scale_back_ascii(self, col_idx, input_field, output_field):
1204
+ """
1205
+ Convert internal array values back to ASCII table representation.
1206
+
1207
+ The ``input_field`` is the internal representation of the values, and
1208
+ the ``output_field`` is the character array representing the ASCII
1209
+ output that will be written.
1210
+ """
1211
+
1212
+ starts = self._coldefs.starts[:]
1213
+ spans = self._coldefs.spans
1214
+ format = self._coldefs[col_idx].format
1215
+
1216
+ # The the index of the "end" column of the record, beyond
1217
+ # which we can't write
1218
+ end = super().field(-1).itemsize
1219
+ starts.append(end + starts[-1])
1220
+
1221
+ if col_idx > 0:
1222
+ lead = starts[col_idx] - starts[col_idx - 1] - spans[col_idx - 1]
1223
+ else:
1224
+ lead = 0
1225
+
1226
+ if lead < 0:
1227
+ warnings.warn('Column {!r} starting point overlaps the previous '
1228
+ 'column.'.format(col_idx + 1))
1229
+
1230
+ trail = starts[col_idx + 1] - starts[col_idx] - spans[col_idx]
1231
+
1232
+ if trail < 0:
1233
+ warnings.warn('Column {!r} ending point overlaps the next '
1234
+ 'column.'.format(col_idx + 1))
1235
+
1236
+ # TODO: It would be nice if these string column formatting
1237
+ # details were left to a specialized class, as is the case
1238
+ # with FormatX and FormatP
1239
+ if 'A' in format:
1240
+ _pc = '{:'
1241
+ else:
1242
+ _pc = '{:>'
1243
+
1244
+ fmt = ''.join([_pc, format[1:], ASCII2STR[format[0]], '}',
1245
+ (' ' * trail)])
1246
+
1247
+ # Even if the format precision is 0, we should output a decimal point
1248
+ # as long as there is space to do so--not including a decimal point in
1249
+ # a float value is discouraged by the FITS Standard
1250
+ trailing_decimal = (format.precision == 0 and
1251
+ format.format in ('F', 'E', 'D'))
1252
+
1253
+ # not using numarray.strings's num2char because the
1254
+ # result is not allowed to expand (as C/Python does).
1255
+ for jdx, value in enumerate(input_field):
1256
+ value = fmt.format(value)
1257
+ if len(value) > starts[col_idx + 1] - starts[col_idx]:
1258
+ raise ValueError(
1259
+ "Value {!r} does not fit into the output's itemsize of "
1260
+ "{}.".format(value, spans[col_idx]))
1261
+
1262
+ if trailing_decimal and value[0] == ' ':
1263
+ # We have some extra space in the field for the trailing
1264
+ # decimal point
1265
+ value = value[1:] + '.'
1266
+
1267
+ output_field[jdx] = value
1268
+
1269
+ # Replace exponent separator in floating point numbers
1270
+ if 'D' in format:
1271
+ output_field[:] = output_field.replace(b'E', b'D')
1272
+
1273
+
1274
+ def _get_recarray_field(array, key):
1275
+ """
1276
+ Compatibility function for using the recarray base class's field method.
1277
+ This incorporates the legacy functionality of returning string arrays as
1278
+ Numeric-style chararray objects.
1279
+ """
1280
+
1281
+ # Numpy >= 1.10.dev recarray no longer returns chararrays for strings
1282
+ # This is currently needed for backwards-compatibility and for
1283
+ # automatic truncation of trailing whitespace
1284
+ field = np.recarray.field(array, key)
1285
+ if (field.dtype.char in ('S', 'U') and
1286
+ not isinstance(field, chararray.chararray)):
1287
+ field = field.view(chararray.chararray)
1288
+ return field
1289
+
1290
+
1291
+ class _UnicodeArrayEncodeError(UnicodeEncodeError):
1292
+ def __init__(self, encoding, object_, start, end, reason, index):
1293
+ super().__init__(encoding, object_, start, end, reason)
1294
+ self.index = index
1295
+
1296
+
1297
+ def _ascii_encode(inarray, out=None):
1298
+ """
1299
+ Takes a unicode array and fills the output string array with the ASCII
1300
+ encodings (if possible) of the elements of the input array. The two arrays
1301
+ must be the same size (though not necessarily the same shape).
1302
+
1303
+ This is like an inplace version of `np.char.encode` though simpler since
1304
+ it's only limited to ASCII, and hence the size of each character is
1305
+ guaranteed to be 1 byte.
1306
+
1307
+ If any strings are non-ASCII an UnicodeArrayEncodeError is raised--this is
1308
+ just a `UnicodeEncodeError` with an additional attribute for the index of
1309
+ the item that couldn't be encoded.
1310
+ """
1311
+
1312
+ out_dtype = np.dtype(('S{0}'.format(inarray.dtype.itemsize // 4),
1313
+ inarray.dtype.shape))
1314
+ if out is not None:
1315
+ out = out.view(out_dtype)
1316
+
1317
+ op_dtypes = [inarray.dtype, out_dtype]
1318
+ op_flags = [['readonly'], ['writeonly', 'allocate']]
1319
+ it = np.nditer([inarray, out], op_dtypes=op_dtypes,
1320
+ op_flags=op_flags, flags=['zerosize_ok'])
1321
+
1322
+ try:
1323
+ for initem, outitem in it:
1324
+ outitem[...] = initem.item().encode('ascii')
1325
+ except UnicodeEncodeError as exc:
1326
+ index = np.unravel_index(it.iterindex, inarray.shape)
1327
+ raise _UnicodeArrayEncodeError(*(exc.args + (index,)))
1328
+
1329
+ return it.operands[1]
1330
+
1331
+
1332
+ def _has_unicode_fields(array):
1333
+ """
1334
+ Returns True if any fields in a structured array have Unicode dtype.
1335
+ """
1336
+
1337
+ dtypes = (d[0] for d in array.dtype.fields.values())
1338
+ return any(d.kind == 'U' for d in dtypes)
testbed/astropy__astropy/astropy/io/fits/fitstime.py ADDED
@@ -0,0 +1,576 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ import re
4
+ import warnings
5
+ from collections import defaultdict, OrderedDict
6
+
7
+ import numpy as np
8
+
9
+ from . import Header, Card
10
+
11
+ from astropy import units as u
12
+ from astropy.coordinates import EarthLocation
13
+ from astropy.table import Column
14
+ from astropy.time import Time, TimeDelta
15
+ from astropy.time.core import BARYCENTRIC_SCALES
16
+ from astropy.time.formats import FITS_DEPRECATED_SCALES
17
+ from astropy.utils.exceptions import AstropyUserWarning
18
+
19
+ # The following is based on the FITS WCS Paper IV, "Representations of time
20
+ # coordinates in FITS".
21
+ # http://adsabs.harvard.edu/abs/2015A%26A...574A..36R
22
+
23
+
24
+ # FITS WCS standard specified "4-3" form for non-linear coordinate types
25
+ TCTYP_RE_TYPE = re.compile(r'(?P<type>[A-Z]+)[-]+')
26
+ TCTYP_RE_ALGO = re.compile(r'(?P<algo>[A-Z]+)\s*')
27
+
28
+
29
+ # FITS Time standard specified time units
30
+ FITS_TIME_UNIT = ['s', 'd', 'a', 'cy', 'min', 'h', 'yr', 'ta', 'Ba']
31
+
32
+
33
+ # Global time reference coordinate keywords
34
+ TIME_KEYWORDS = ('TIMESYS', 'MJDREF', 'JDREF', 'DATEREF',
35
+ 'TREFPOS', 'TREFDIR', 'TIMEUNIT', 'TIMEOFFS',
36
+ 'OBSGEO-X', 'OBSGEO-Y', 'OBSGEO-Z',
37
+ 'OBSGEO-L', 'OBSGEO-B', 'OBSGEO-H', 'DATE',
38
+ 'DATE-OBS', 'DATE-AVG', 'DATE-BEG', 'DATE-END',
39
+ 'MJD-OBS', 'MJD-AVG', 'MJD-BEG', 'MJD-END')
40
+
41
+
42
+ # Column-specific time override keywords
43
+ COLUMN_TIME_KEYWORDS = ('TCTYP', 'TCUNI', 'TRPOS')
44
+
45
+
46
+ # Column-specific keywords regex
47
+ COLUMN_TIME_KEYWORD_REGEXP = '({0})[0-9]+'.format(
48
+ '|'.join(COLUMN_TIME_KEYWORDS))
49
+
50
+
51
+ def is_time_column_keyword(keyword):
52
+ """
53
+ Check if the FITS header keyword is a time column-specific keyword.
54
+
55
+ Parameters
56
+ ----------
57
+ keyword : str
58
+ FITS keyword.
59
+ """
60
+ return re.match(COLUMN_TIME_KEYWORD_REGEXP, keyword) is not None
61
+
62
+
63
+ # Set astropy time global information
64
+ GLOBAL_TIME_INFO = {'TIMESYS': ('UTC', 'Default time scale'),
65
+ 'JDREF': (0.0, 'Time columns are jd = jd1 + jd2'),
66
+ 'TREFPOS': ('TOPOCENTER', 'Time reference position')}
67
+
68
+
69
+ def _verify_global_info(global_info):
70
+ """
71
+ Given the global time reference frame information, verify that
72
+ each global time coordinate attribute will be given a valid value.
73
+
74
+ Parameters
75
+ ----------
76
+ global_info : dict
77
+ Global time reference frame information.
78
+ """
79
+
80
+ # Translate FITS deprecated scale into astropy scale, or else just convert
81
+ # to lower case for further checks.
82
+ global_info['scale'] = FITS_DEPRECATED_SCALES.get(global_info['TIMESYS'],
83
+ global_info['TIMESYS'].lower())
84
+
85
+ # Verify global time scale
86
+ if global_info['scale'] not in Time.SCALES:
87
+
88
+ # 'GPS' and 'LOCAL' are FITS recognized time scale values
89
+ # but are not supported by astropy.
90
+
91
+ if global_info['scale'] == 'gps':
92
+ warnings.warn(
93
+ 'Global time scale (TIMESYS) has a FITS recognized time scale '
94
+ 'value "GPS". In Astropy, "GPS" is a time from epoch format '
95
+ 'which runs synchronously with TAI; GPS is approximately 19 s '
96
+ 'ahead of TAI. Hence, this format will be used.', AstropyUserWarning)
97
+ # Assume that the values are in GPS format
98
+ global_info['scale'] = 'tai'
99
+ global_info['format'] = 'gps'
100
+
101
+ if global_info['scale'] == 'local':
102
+ warnings.warn(
103
+ 'Global time scale (TIMESYS) has a FITS recognized time scale '
104
+ 'value "LOCAL". However, the standard states that "LOCAL" should be '
105
+ 'tied to one of the existing scales because it is intrinsically '
106
+ 'unreliable and/or ill-defined. Astropy will thus use the default '
107
+ 'global time scale "UTC" instead of "LOCAL".', AstropyUserWarning)
108
+ # Default scale 'UTC'
109
+ global_info['scale'] = 'utc'
110
+ global_info['format'] = None
111
+
112
+ else:
113
+ raise AssertionError(
114
+ 'Global time scale (TIMESYS) should have a FITS recognized '
115
+ 'time scale value (got {!r}). The FITS standard states that '
116
+ 'the use of local time scales should be restricted to alternate '
117
+ 'coordinates.'.format(global_info['TIMESYS']))
118
+ else:
119
+ # Scale is already set
120
+ global_info['format'] = None
121
+
122
+ # Check if geocentric global location is specified
123
+ obs_geo = [global_info[attr] for attr in ('OBSGEO-X', 'OBSGEO-Y', 'OBSGEO-Z')
124
+ if attr in global_info]
125
+
126
+ # Location full specification is (X, Y, Z)
127
+ if len(obs_geo) == 3:
128
+ global_info['location'] = EarthLocation.from_geocentric(*obs_geo, unit=u.m)
129
+ else:
130
+ # Check if geodetic global location is specified (since geocentric failed)
131
+
132
+ # First warn the user if geocentric location is partially specified
133
+ if obs_geo:
134
+ warnings.warn(
135
+ 'The geocentric observatory location {} is not completely '
136
+ 'specified (X, Y, Z) and will be ignored.'.format(obs_geo),
137
+ AstropyUserWarning)
138
+
139
+ # Check geodetic location
140
+ obs_geo = [global_info[attr] for attr in ('OBSGEO-L', 'OBSGEO-B', 'OBSGEO-H')
141
+ if attr in global_info]
142
+
143
+ if len(obs_geo) == 3:
144
+ global_info['location'] = EarthLocation.from_geodetic(*obs_geo)
145
+ else:
146
+ # Since both geocentric and geodetic locations are not specified,
147
+ # location will be None.
148
+
149
+ # Warn the user if geodetic location is partially specified
150
+ if obs_geo:
151
+ warnings.warn(
152
+ 'The geodetic observatory location {} is not completely '
153
+ 'specified (lon, lat, alt) and will be ignored.'.format(obs_geo),
154
+ AstropyUserWarning)
155
+ global_info['location'] = None
156
+
157
+ # Get global time reference
158
+ # Keywords are listed in order of precedence, as stated by the standard
159
+ for key, format_ in (('MJDREF', 'mjd'), ('JDREF', 'jd'), ('DATEREF', 'fits')):
160
+ if key in global_info:
161
+ global_info['ref_time'] = {'val': global_info[key], 'format': format_}
162
+ break
163
+ else:
164
+ # If none of the three keywords is present, MJDREF = 0.0 must be assumed
165
+ global_info['ref_time'] = {'val': 0, 'format': 'mjd'}
166
+
167
+
168
+ def _verify_column_info(column_info, global_info):
169
+ """
170
+ Given the column-specific time reference frame information, verify that
171
+ each column-specific time coordinate attribute has a valid value.
172
+ Return True if the coordinate column is time, or else return False.
173
+
174
+ Parameters
175
+ ----------
176
+ global_info : dict
177
+ Global time reference frame information.
178
+ column_info : dict
179
+ Column-specific time reference frame override information.
180
+ """
181
+
182
+ scale = column_info.get('TCTYP', None)
183
+ unit = column_info.get('TCUNI', None)
184
+ location = column_info.get('TRPOS', None)
185
+
186
+ if scale is not None:
187
+
188
+ # Non-linear coordinate types have "4-3" form and are not time coordinates
189
+ if TCTYP_RE_TYPE.match(scale[:5]) and TCTYP_RE_ALGO.match(scale[5:]):
190
+ return False
191
+
192
+ elif scale.lower() in Time.SCALES:
193
+ column_info['scale'] = scale.lower()
194
+ column_info['format'] = None
195
+
196
+ elif scale in FITS_DEPRECATED_SCALES.keys():
197
+ column_info['scale'] = FITS_DEPRECATED_SCALES[scale]
198
+ column_info['format'] = None
199
+
200
+ # TCTYPn (scale) = 'TIME' indicates that the column scale is
201
+ # controlled by the global scale.
202
+ elif scale == 'TIME':
203
+ column_info['scale'] = global_info['scale']
204
+ column_info['format'] = global_info['format']
205
+
206
+ elif scale == 'GPS':
207
+ warnings.warn(
208
+ 'Table column "{}" has a FITS recognized time scale value "GPS". '
209
+ 'In Astropy, "GPS" is a time from epoch format which runs '
210
+ 'synchronously with TAI; GPS runs ahead of TAI approximately '
211
+ 'by 19 s. Hence, this format will be used.'.format(column_info),
212
+ AstropyUserWarning)
213
+ column_info['scale'] = 'tai'
214
+ column_info['format'] = 'gps'
215
+
216
+ elif scale == 'LOCAL':
217
+ warnings.warn(
218
+ 'Table column "{}" has a FITS recognized time scale value "LOCAL". '
219
+ 'However, the standard states that "LOCAL" should be tied to one '
220
+ 'of the existing scales because it is intrinsically unreliable '
221
+ 'and/or ill-defined. Astropy will thus use the global time scale '
222
+ '(TIMESYS) as the default.'. format(column_info),
223
+ AstropyUserWarning)
224
+ column_info['scale'] = global_info['scale']
225
+ column_info['format'] = global_info['format']
226
+
227
+ else:
228
+ # Coordinate type is either an unrecognized local time scale
229
+ # or a linear coordinate type
230
+ return False
231
+
232
+ # If TCUNIn is a time unit or TRPOSn is specified, the column is a time
233
+ # coordinate. This has to be tested since TCTYP (scale) is not specified.
234
+ elif (unit is not None and unit in FITS_TIME_UNIT) or location is not None:
235
+ column_info['scale'] = global_info['scale']
236
+ column_info['format'] = global_info['format']
237
+
238
+ # None of the conditions for time coordinate columns is satisfied
239
+ else:
240
+ return False
241
+
242
+ # Check if column-specific reference position TRPOSn is specified
243
+ if location is not None:
244
+
245
+ # Observatory position (location) needs to be specified only
246
+ # for 'TOPOCENTER'.
247
+ if location == 'TOPOCENTER':
248
+ column_info['location'] = global_info['location']
249
+ if column_info['location'] is None:
250
+ warnings.warn(
251
+ 'Time column reference position "TRPOSn" value is "TOPOCENTER". '
252
+ 'However, the observatory position is not properly specified. '
253
+ 'The FITS standard does not support this and hence reference '
254
+ 'position will be ignored.', AstropyUserWarning)
255
+ else:
256
+ column_info['location'] = None
257
+
258
+ # Since TRPOSn is not specified, global reference position is
259
+ # considered.
260
+ elif global_info['TREFPOS'] == 'TOPOCENTER':
261
+
262
+ column_info['location'] = global_info['location']
263
+ if column_info['location'] is None:
264
+ warnings.warn(
265
+ 'Time column reference position "TRPOSn" is not specified. The '
266
+ 'default value for it is "TOPOCENTER", but due to unspecified '
267
+ 'observatory position, reference position will be ignored.',
268
+ AstropyUserWarning)
269
+ else:
270
+ column_info['location'] = None
271
+
272
+ # Get reference time
273
+ column_info['ref_time'] = global_info['ref_time']
274
+
275
+ return True
276
+
277
+
278
+ def _get_info_if_time_column(col, global_info):
279
+ """
280
+ Check if a column without corresponding time column keywords in the
281
+ FITS header represents time or not. If yes, return the time column
282
+ information needed for its conversion to Time.
283
+ This is only applicable to the special-case where a column has the
284
+ name 'TIME' and a time unit.
285
+ """
286
+
287
+ # Column with TTYPEn = 'TIME' and lacking any TC*n or time
288
+ # specific keywords will be controlled by the global keywords.
289
+ if col.info.name.upper() == 'TIME' and col.info.unit in FITS_TIME_UNIT:
290
+ column_info = {'scale': global_info['scale'],
291
+ 'format': global_info['format'],
292
+ 'ref_time': global_info['ref_time'],
293
+ 'location': None}
294
+
295
+ if global_info['TREFPOS'] == 'TOPOCENTER':
296
+ column_info['location'] = global_info['location']
297
+ if column_info['location'] is None:
298
+ warnings.warn(
299
+ 'Time column "{}" reference position will be ignored '
300
+ 'due to unspecified observatory position.'.format(col.info.name),
301
+ AstropyUserWarning)
302
+
303
+ return column_info
304
+
305
+ return None
306
+
307
+
308
+ def _convert_global_time(table, global_info):
309
+ """
310
+ Convert the table metadata for time informational keywords
311
+ to astropy Time.
312
+
313
+ Parameters
314
+ ----------
315
+ table : `~astropy.table.Table`
316
+ The table whose time metadata is to be converted.
317
+ global_info : dict
318
+ Global time reference frame information.
319
+ """
320
+
321
+ # Read in Global Informational keywords as Time
322
+ for key, value in global_info.items():
323
+ # FITS uses a subset of ISO-8601 for DATE-xxx
324
+ if key.startswith('DATE'):
325
+ if key not in table.meta:
326
+ scale = 'utc' if key == 'DATE' else global_info['scale']
327
+ try:
328
+ precision = len(value.split('.')[-1]) if '.' in value else 0
329
+ value = Time(value, format='fits', scale=scale,
330
+ precision=precision)
331
+ except ValueError:
332
+ pass
333
+ table.meta[key] = value
334
+
335
+ # MJD-xxx in MJD according to TIMESYS
336
+ elif key.startswith('MJD-'):
337
+ if key not in table.meta:
338
+ try:
339
+ value = Time(value, format='mjd',
340
+ scale=global_info['scale'])
341
+ except ValueError:
342
+ pass
343
+ table.meta[key] = value
344
+
345
+
346
+ def _convert_time_column(col, column_info):
347
+ """
348
+ Convert time columns to astropy Time columns.
349
+
350
+ Parameters
351
+ ----------
352
+ col : `~astropy.table.Column`
353
+ The time coordinate column to be converted to Time.
354
+ column_info : dict
355
+ Column-specific time reference frame override information.
356
+ """
357
+
358
+ # The code might fail while attempting to read FITS files not written by astropy.
359
+ try:
360
+ # ISO-8601 is the only string representation of time in FITS
361
+ if col.info.dtype.kind in ['S', 'U']:
362
+ # [+/-C]CCYY-MM-DD[Thh:mm:ss[.s...]] where the number of characters
363
+ # from index 20 to the end of string represents the precision
364
+ precision = max(int(col.info.dtype.str[2:]) - 20, 0)
365
+ return Time(col, format='fits', scale=column_info['scale'],
366
+ precision=precision,
367
+ location=column_info['location'])
368
+
369
+ if column_info['format'] == 'gps':
370
+ return Time(col, format='gps', location=column_info['location'])
371
+
372
+ # If reference value is 0 for JD or MJD, the column values can be
373
+ # directly converted to Time, as they are absolute (relative
374
+ # to a globally accepted zero point).
375
+ if (column_info['ref_time']['val'] == 0 and
376
+ column_info['ref_time']['format'] in ['jd', 'mjd']):
377
+ # (jd1, jd2) where jd = jd1 + jd2
378
+ if col.shape[-1] == 2 and col.ndim > 1:
379
+ return Time(col[..., 0], col[..., 1], scale=column_info['scale'],
380
+ format=column_info['ref_time']['format'],
381
+ location=column_info['location'])
382
+ else:
383
+ return Time(col, scale=column_info['scale'],
384
+ format=column_info['ref_time']['format'],
385
+ location=column_info['location'])
386
+
387
+ # Reference time
388
+ ref_time = Time(column_info['ref_time']['val'], scale=column_info['scale'],
389
+ format=column_info['ref_time']['format'],
390
+ location=column_info['location'])
391
+
392
+ # Elapsed time since reference time
393
+ if col.shape[-1] == 2 and col.ndim > 1:
394
+ delta_time = TimeDelta(col[..., 0], col[..., 1])
395
+ else:
396
+ delta_time = TimeDelta(col)
397
+
398
+ return ref_time + delta_time
399
+ except Exception as err:
400
+ warnings.warn(
401
+ 'The exception "{}" was encountered while trying to convert the time '
402
+ 'column "{}" to Astropy Time.'.format(err, col.info.name),
403
+ AstropyUserWarning)
404
+ return col
405
+
406
+
407
+ def fits_to_time(hdr, table):
408
+ """
409
+ Read FITS binary table time columns as `~astropy.time.Time`.
410
+
411
+ This method reads the metadata associated with time coordinates, as
412
+ stored in a FITS binary table header, converts time columns into
413
+ `~astropy.time.Time` columns and reads global reference times as
414
+ `~astropy.time.Time` instances.
415
+
416
+ Parameters
417
+ ----------
418
+ hdr : `~astropy.io.fits.header.Header`
419
+ FITS Header
420
+ table : `~astropy.table.Table`
421
+ The table whose time columns are to be read as Time
422
+
423
+ Returns
424
+ -------
425
+ hdr : `~astropy.io.fits.header.Header`
426
+ Modified FITS Header (time metadata removed)
427
+ """
428
+
429
+ # Set defaults for global time scale, reference, etc.
430
+ global_info = {'TIMESYS': 'UTC',
431
+ 'TREFPOS': 'TOPOCENTER'}
432
+
433
+ # Set default dictionary for time columns
434
+ time_columns = defaultdict(OrderedDict)
435
+
436
+ # Make a "copy" (not just a view) of the input header, since it
437
+ # may get modified. the data is still a "view" (for now)
438
+ hcopy = hdr.copy(strip=True)
439
+
440
+ # Scan the header for global and column-specific time keywords
441
+ for key, value, comment in hdr.cards:
442
+ if key in TIME_KEYWORDS:
443
+
444
+ global_info[key] = value
445
+ hcopy.remove(key)
446
+
447
+ elif is_time_column_keyword(key):
448
+
449
+ base, idx = re.match(r'([A-Z]+)([0-9]+)', key).groups()
450
+ time_columns[int(idx)][base] = value
451
+ hcopy.remove(key)
452
+
453
+ elif (value in ('OBSGEO-X', 'OBSGEO-Y', 'OBSGEO-Z') and
454
+ re.match('TTYPE[0-9]+', key)):
455
+
456
+ global_info[value] = table[value]
457
+
458
+ # Verify and get the global time reference frame information
459
+ _verify_global_info(global_info)
460
+ _convert_global_time(table, global_info)
461
+
462
+ # Columns with column-specific time (coordinate) keywords
463
+ if time_columns:
464
+ for idx, column_info in time_columns.items():
465
+ # Check if the column is time coordinate (not spatial)
466
+ if _verify_column_info(column_info, global_info):
467
+ colname = table.colnames[idx - 1]
468
+ # Convert to Time
469
+ table[colname] = _convert_time_column(table[colname],
470
+ column_info)
471
+
472
+ # Check for special-cases of time coordinate columns
473
+ for idx, colname in enumerate(table.colnames):
474
+ if (idx + 1) not in time_columns:
475
+ column_info = _get_info_if_time_column(table[colname], global_info)
476
+ if column_info:
477
+ table[colname] = _convert_time_column(table[colname], column_info)
478
+
479
+ return hcopy
480
+
481
+
482
+ def time_to_fits(table):
483
+ """
484
+ Replace Time columns in a Table with non-mixin columns containing
485
+ each element as a vector of two doubles (jd1, jd2) and return a FITS
486
+ header with appropriate time coordinate keywords.
487
+ jd = jd1 + jd2 represents time in the Julian Date format with
488
+ high-precision.
489
+
490
+ Parameters
491
+ ----------
492
+ table : `~astropy.table.Table`
493
+ The table whose Time columns are to be replaced.
494
+
495
+ Returns
496
+ -------
497
+ table : `~astropy.table.Table`
498
+ The table with replaced Time columns
499
+ hdr : `~astropy.io.fits.header.Header`
500
+ Header containing global time reference frame FITS keywords
501
+ """
502
+
503
+ # Shallow copy of the input table
504
+ newtable = table.copy(copy_data=False)
505
+
506
+ # Global time coordinate frame keywords
507
+ hdr = Header([Card(keyword=key, value=val[0], comment=val[1])
508
+ for key, val in GLOBAL_TIME_INFO.items()])
509
+
510
+ # Store coordinate column-specific metadata
511
+ newtable.meta['__coordinate_columns__'] = defaultdict(OrderedDict)
512
+ coord_meta = newtable.meta['__coordinate_columns__']
513
+
514
+ time_cols = table.columns.isinstance(Time)
515
+
516
+ # Geocentric location
517
+ location = None
518
+
519
+ for col in time_cols:
520
+ # By default, Time objects are written in full precision, i.e. we store both
521
+ # jd1 and jd2 (serialize_method['fits'] = 'jd1_jd2'). Formatted values for
522
+ # Time can be stored if the user explicitly chooses to do so.
523
+ if col.info.serialize_method['fits'] == 'formatted_value':
524
+ newtable.replace_column(col.info.name, Column(col.value))
525
+ continue
526
+
527
+ # The following is necessary to deal with multi-dimensional ``Time`` objects
528
+ # (i.e. where Time.shape is non-trivial).
529
+ jd12 = np.array([col.jd1, col.jd2])
530
+ # Roll the 0th (innermost) axis backwards, until it lies in the last position
531
+ # (jd12.ndim)
532
+ jd12 = np.rollaxis(jd12, 0, jd12.ndim)
533
+ newtable.replace_column(col.info.name, Column(jd12, unit='d'))
534
+
535
+ # Get column position(index)
536
+ n = table.colnames.index(col.info.name) + 1
537
+
538
+ # Time column-specific override keywords
539
+ coord_meta[col.info.name]['coord_type'] = col.scale.upper()
540
+ coord_meta[col.info.name]['coord_unit'] = 'd'
541
+
542
+ # Time column reference position
543
+ if getattr(col, 'location') is None:
544
+ if location is not None:
545
+ warnings.warn(
546
+ 'Time Column "{}" has no specified location, but global Time '
547
+ 'Position is present, which will be the default for this column '
548
+ 'in FITS specification.'.format(col.info.name),
549
+ AstropyUserWarning)
550
+ else:
551
+ coord_meta[col.info.name]['time_ref_pos'] = 'TOPOCENTER'
552
+ # Compatibility of Time Scales and Reference Positions
553
+ if col.scale in BARYCENTRIC_SCALES:
554
+ warnings.warn(
555
+ 'Earth Location "TOPOCENTER" for Time Column "{}" is incompatabile '
556
+ 'with scale "{}".'.format(col.info.name, col.scale.upper()),
557
+ AstropyUserWarning)
558
+
559
+ if location is None:
560
+ # Set global geocentric location
561
+ location = col.location
562
+ if location.size > 1:
563
+ for dim in ('x', 'y', 'z'):
564
+ newtable.add_column(Column(getattr(location, dim).to_value(u.m)),
565
+ name='OBSGEO-{}'.format(dim.upper()))
566
+ else:
567
+ hdr.extend([Card(keyword='OBSGEO-{}'.format(dim.upper()),
568
+ value=getattr(location, dim).to_value(u.m))
569
+ for dim in ('x', 'y', 'z')])
570
+ elif location != col.location:
571
+ raise ValueError('Multiple Time Columns with different geocentric '
572
+ 'observatory locations ({}, {}) encountered.'
573
+ 'This is not supported by the FITS standard.'
574
+ .format(location, col.location))
575
+
576
+ return newtable, hdr
testbed/astropy__astropy/astropy/io/fits/header.py ADDED
@@ -0,0 +1,2306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import collections
4
+ import copy
5
+ import itertools
6
+ import re
7
+ import warnings
8
+
9
+ from .card import Card, _pad, KEYWORD_LENGTH, UNDEFINED
10
+ from .file import _File
11
+ from .util import (encode_ascii, decode_ascii, fileobj_closed,
12
+ fileobj_is_binary, path_like)
13
+ from ._utils import parse_header
14
+
15
+ from astropy.utils import isiterable
16
+ from astropy.utils.exceptions import AstropyUserWarning
17
+ from astropy.utils.decorators import deprecated_renamed_argument
18
+
19
+
20
+ BLOCK_SIZE = 2880 # the FITS block size
21
+
22
+ # This regular expression can match a *valid* END card which just consists of
23
+ # the string 'END' followed by all spaces, or an *invalid* end card which
24
+ # consists of END, followed by any character that is *not* a valid character
25
+ # for a valid FITS keyword (that is, this is not a keyword like 'ENDER' which
26
+ # starts with 'END' but is not 'END'), followed by any arbitrary bytes. An
27
+ # invalid end card may also consist of just 'END' with no trailing bytes.
28
+ HEADER_END_RE = re.compile(encode_ascii(
29
+ r'(?:(?P<valid>END {77}) *)|(?P<invalid>END$|END {0,76}[^A-Z0-9_-])'))
30
+
31
+
32
+ # According to the FITS standard the only characters that may appear in a
33
+ # header record are the restricted ASCII chars from 0x20 through 0x7E.
34
+ VALID_HEADER_CHARS = set(map(chr, range(0x20, 0x7F)))
35
+ END_CARD = 'END' + ' ' * 77
36
+
37
+
38
+ __doctest_skip__ = ['Header', 'Header.comments', 'Header.fromtextfile',
39
+ 'Header.totextfile', 'Header.set', 'Header.update']
40
+
41
+
42
+ class Header:
43
+ """
44
+ FITS header class. This class exposes both a dict-like interface and a
45
+ list-like interface to FITS headers.
46
+
47
+ The header may be indexed by keyword and, like a dict, the associated value
48
+ will be returned. When the header contains cards with duplicate keywords,
49
+ only the value of the first card with the given keyword will be returned.
50
+ It is also possible to use a 2-tuple as the index in the form (keyword,
51
+ n)--this returns the n-th value with that keyword, in the case where there
52
+ are duplicate keywords.
53
+
54
+ For example::
55
+
56
+ >>> header['NAXIS']
57
+ 0
58
+ >>> header[('FOO', 1)] # Return the value of the second FOO keyword
59
+ 'foo'
60
+
61
+ The header may also be indexed by card number::
62
+
63
+ >>> header[0] # Return the value of the first card in the header
64
+ 'T'
65
+
66
+ Commentary keywords such as HISTORY and COMMENT are special cases: When
67
+ indexing the Header object with either 'HISTORY' or 'COMMENT' a list of all
68
+ the HISTORY/COMMENT values is returned::
69
+
70
+ >>> header['HISTORY']
71
+ This is the first history entry in this header.
72
+ This is the second history entry in this header.
73
+ ...
74
+
75
+ See the Astropy documentation for more details on working with headers.
76
+ """
77
+
78
+ def __init__(self, cards=[], copy=False):
79
+ """
80
+ Construct a `Header` from an iterable and/or text file.
81
+
82
+ Parameters
83
+ ----------
84
+ cards : A list of `Card` objects, optional
85
+ The cards to initialize the header with. Also allowed are other
86
+ `Header` (or `dict`-like) objects.
87
+
88
+ .. versionchanged:: 1.2
89
+ Allowed ``cards`` to be a `dict`-like object.
90
+
91
+ copy : bool, optional
92
+
93
+ If ``True`` copies the ``cards`` if they were another `Header`
94
+ instance.
95
+ Default is ``False``.
96
+
97
+ .. versionadded:: 1.3
98
+ """
99
+ self.clear()
100
+
101
+ if isinstance(cards, Header):
102
+ if copy:
103
+ cards = cards.copy()
104
+ cards = cards.cards
105
+ elif isinstance(cards, dict):
106
+ cards = cards.items()
107
+
108
+ for card in cards:
109
+ self.append(card, end=True)
110
+
111
+ self._modified = False
112
+
113
+ def __len__(self):
114
+ return len(self._cards)
115
+
116
+ def __iter__(self):
117
+ for card in self._cards:
118
+ yield card.keyword
119
+
120
+ def __contains__(self, keyword):
121
+ if keyword in self._keyword_indices or keyword in self._rvkc_indices:
122
+ # For the most common case (single, standard form keyword lookup)
123
+ # this will work and is an O(1) check. If it fails that doesn't
124
+ # guarantee absence, just that we have to perform the full set of
125
+ # checks in self._cardindex
126
+ return True
127
+ try:
128
+ self._cardindex(keyword)
129
+ except (KeyError, IndexError):
130
+ return False
131
+ return True
132
+
133
+ def __getitem__(self, key):
134
+ if isinstance(key, slice):
135
+ return Header([copy.copy(c) for c in self._cards[key]])
136
+ elif self._haswildcard(key):
137
+ return Header([copy.copy(self._cards[idx])
138
+ for idx in self._wildcardmatch(key)])
139
+ elif (isinstance(key, str) and
140
+ key.upper() in Card._commentary_keywords):
141
+ key = key.upper()
142
+ # Special case for commentary cards
143
+ return _HeaderCommentaryCards(self, key)
144
+ if isinstance(key, tuple):
145
+ keyword = key[0]
146
+ else:
147
+ keyword = key
148
+ card = self._cards[self._cardindex(key)]
149
+ if card.field_specifier is not None and keyword == card.rawkeyword:
150
+ # This is RVKC; if only the top-level keyword was specified return
151
+ # the raw value, not the parsed out float value
152
+ return card.rawvalue
153
+
154
+ value = card.value
155
+ if value == UNDEFINED:
156
+ return None
157
+ return value
158
+
159
+ def __setitem__(self, key, value):
160
+ if self._set_slice(key, value, self):
161
+ return
162
+
163
+ if isinstance(value, tuple):
164
+ if not (0 < len(value) <= 2):
165
+ raise ValueError(
166
+ 'A Header item may be set with either a scalar value, '
167
+ 'a 1-tuple containing a scalar value, or a 2-tuple '
168
+ 'containing a scalar value and comment string.')
169
+ if len(value) == 1:
170
+ value, comment = value[0], None
171
+ if value is None:
172
+ value = UNDEFINED
173
+ elif len(value) == 2:
174
+ value, comment = value
175
+ if value is None:
176
+ value = UNDEFINED
177
+ if comment is None:
178
+ comment = ''
179
+ else:
180
+ comment = None
181
+
182
+ card = None
183
+ if isinstance(key, int):
184
+ card = self._cards[key]
185
+ elif isinstance(key, tuple):
186
+ card = self._cards[self._cardindex(key)]
187
+ if value is None:
188
+ value = UNDEFINED
189
+ if card:
190
+ card.value = value
191
+ if comment is not None:
192
+ card.comment = comment
193
+ if card._modified:
194
+ self._modified = True
195
+ else:
196
+ # If we get an IndexError that should be raised; we don't allow
197
+ # assignment to non-existing indices
198
+ self._update((key, value, comment))
199
+
200
+ def __delitem__(self, key):
201
+ if isinstance(key, slice) or self._haswildcard(key):
202
+ # This is very inefficient but it's not a commonly used feature.
203
+ # If someone out there complains that they make heavy use of slice
204
+ # deletions and it's too slow, well, we can worry about it then
205
+ # [the solution is not too complicated--it would be wait 'til all
206
+ # the cards are deleted before updating _keyword_indices rather
207
+ # than updating it once for each card that gets deleted]
208
+ if isinstance(key, slice):
209
+ indices = range(*key.indices(len(self)))
210
+ # If the slice step is backwards we want to reverse it, because
211
+ # it will be reversed in a few lines...
212
+ if key.step and key.step < 0:
213
+ indices = reversed(indices)
214
+ else:
215
+ indices = self._wildcardmatch(key)
216
+ for idx in reversed(indices):
217
+ del self[idx]
218
+ return
219
+ elif isinstance(key, str):
220
+ # delete ALL cards with the same keyword name
221
+ key = Card.normalize_keyword(key)
222
+ indices = self._keyword_indices
223
+ if key not in self._keyword_indices:
224
+ indices = self._rvkc_indices
225
+
226
+ if key not in indices:
227
+ # if keyword is not present raise KeyError.
228
+ # To delete keyword without caring if they were present,
229
+ # Header.remove(Keyword) can be used with optional argument ignore_missing as True
230
+ raise KeyError("Keyword '{}' not found.".format(key))
231
+
232
+ for idx in reversed(indices[key]):
233
+ # Have to copy the indices list since it will be modified below
234
+ del self[idx]
235
+ return
236
+
237
+ idx = self._cardindex(key)
238
+ card = self._cards[idx]
239
+ keyword = card.keyword
240
+ del self._cards[idx]
241
+ keyword = Card.normalize_keyword(keyword)
242
+ indices = self._keyword_indices[keyword]
243
+ indices.remove(idx)
244
+ if not indices:
245
+ del self._keyword_indices[keyword]
246
+
247
+ # Also update RVKC indices if necessary :/
248
+ if card.field_specifier is not None:
249
+ indices = self._rvkc_indices[card.rawkeyword]
250
+ indices.remove(idx)
251
+ if not indices:
252
+ del self._rvkc_indices[card.rawkeyword]
253
+
254
+ # We also need to update all other indices
255
+ self._updateindices(idx, increment=False)
256
+ self._modified = True
257
+
258
+ def __repr__(self):
259
+ return self.tostring(sep='\n', endcard=False, padding=False)
260
+
261
+ def __str__(self):
262
+ return self.tostring()
263
+
264
+ def __eq__(self, other):
265
+ """
266
+ Two Headers are equal only if they have the exact same string
267
+ representation.
268
+ """
269
+
270
+ return str(self) == str(other)
271
+
272
+ def __add__(self, other):
273
+ temp = self.copy(strip=False)
274
+ temp.extend(other)
275
+ return temp
276
+
277
+ def __iadd__(self, other):
278
+ self.extend(other)
279
+ return self
280
+
281
+ def _ipython_key_completions_(self):
282
+ return self.__iter__()
283
+
284
+ @property
285
+ def cards(self):
286
+ """
287
+ The underlying physical cards that make up this Header; it can be
288
+ looked at, but it should not be modified directly.
289
+ """
290
+
291
+ return _CardAccessor(self)
292
+
293
+ @property
294
+ def comments(self):
295
+ """
296
+ View the comments associated with each keyword, if any.
297
+
298
+ For example, to see the comment on the NAXIS keyword:
299
+
300
+ >>> header.comments['NAXIS']
301
+ number of data axes
302
+
303
+ Comments can also be updated through this interface:
304
+
305
+ >>> header.comments['NAXIS'] = 'Number of data axes'
306
+
307
+ """
308
+
309
+ return _HeaderComments(self)
310
+
311
+ @property
312
+ def _modified(self):
313
+ """
314
+ Whether or not the header has been modified; this is a property so that
315
+ it can also check each card for modifications--cards may have been
316
+ modified directly without the header containing it otherwise knowing.
317
+ """
318
+
319
+ modified_cards = any(c._modified for c in self._cards)
320
+ if modified_cards:
321
+ # If any cards were modified then by definition the header was
322
+ # modified
323
+ self.__dict__['_modified'] = True
324
+
325
+ return self.__dict__['_modified']
326
+
327
+ @_modified.setter
328
+ def _modified(self, val):
329
+ self.__dict__['_modified'] = val
330
+
331
+ @classmethod
332
+ def fromstring(cls, data, sep=''):
333
+ """
334
+ Creates an HDU header from a byte string containing the entire header
335
+ data.
336
+
337
+ Parameters
338
+ ----------
339
+ data : str or bytes
340
+ String or bytes containing the entire header. In the case of bytes
341
+ they will be decoded using latin-1 (only plain ASCII characters are
342
+ allowed in FITS headers but latin-1 allows us to retain any invalid
343
+ bytes that might appear in malformatted FITS files).
344
+
345
+ sep : str, optional
346
+ The string separating cards from each other, such as a newline. By
347
+ default there is no card separator (as is the case in a raw FITS
348
+ file). In general this is only used in cases where a header was
349
+ printed as text (e.g. with newlines after each card) and you want
350
+ to create a new `Header` from it by copy/pasting.
351
+
352
+ Examples
353
+ --------
354
+
355
+ >>> from astropy.io.fits import Header
356
+ >>> hdr = Header({'SIMPLE': True})
357
+ >>> Header.fromstring(hdr.tostring()) == hdr
358
+ True
359
+
360
+ If you want to create a `Header` from printed text it's not necessary
361
+ to have the exact binary structure as it would appear in a FITS file,
362
+ with the full 80 byte card length. Rather, each "card" can end in a
363
+ newline and does not have to be padded out to a full card length as
364
+ long as it "looks like" a FITS header:
365
+
366
+ >>> hdr = Header.fromstring(\"\"\"\\
367
+ ... SIMPLE = T / conforms to FITS standard
368
+ ... BITPIX = 8 / array data type
369
+ ... NAXIS = 0 / number of array dimensions
370
+ ... EXTEND = T
371
+ ... \"\"\", sep='\\n')
372
+ >>> hdr['SIMPLE']
373
+ True
374
+ >>> hdr['BITPIX']
375
+ 8
376
+ >>> len(hdr)
377
+ 4
378
+
379
+ Returns
380
+ -------
381
+ header
382
+ A new `Header` instance.
383
+ """
384
+
385
+ cards = []
386
+
387
+ # If the card separator contains characters that may validly appear in
388
+ # a card, the only way to unambiguously distinguish between cards is to
389
+ # require that they be Card.length long. However, if the separator
390
+ # contains non-valid characters (namely \n) the cards may be split
391
+ # immediately at the separator
392
+ require_full_cardlength = set(sep).issubset(VALID_HEADER_CHARS)
393
+
394
+ if isinstance(data, bytes):
395
+ # FITS supports only ASCII, but decode as latin1 and just take all
396
+ # bytes for now; if it results in mojibake due to e.g. UTF-8
397
+ # encoded data in a FITS header that's OK because it shouldn't be
398
+ # there in the first place--accepting it here still gives us the
399
+ # opportunity to display warnings later during validation
400
+ CONTINUE = b'CONTINUE'
401
+ END = b'END'
402
+ end_card = END_CARD.encode('ascii')
403
+ sep = sep.encode('latin1')
404
+ empty = b''
405
+ else:
406
+ CONTINUE = 'CONTINUE'
407
+ END = 'END'
408
+ end_card = END_CARD
409
+ empty = ''
410
+
411
+ # Split the header into individual cards
412
+ idx = 0
413
+ image = []
414
+
415
+ while idx < len(data):
416
+ if require_full_cardlength:
417
+ end_idx = idx + Card.length
418
+ else:
419
+ try:
420
+ end_idx = data.index(sep, idx)
421
+ except ValueError:
422
+ end_idx = len(data)
423
+
424
+ next_image = data[idx:end_idx]
425
+ idx = end_idx + len(sep)
426
+
427
+ if image:
428
+ if next_image[:8] == CONTINUE:
429
+ image.append(next_image)
430
+ continue
431
+ cards.append(Card.fromstring(empty.join(image)))
432
+
433
+ if require_full_cardlength:
434
+ if next_image == end_card:
435
+ image = []
436
+ break
437
+ else:
438
+ if next_image.split(sep)[0].rstrip() == END:
439
+ image = []
440
+ break
441
+
442
+ image = [next_image]
443
+
444
+ # Add the last image that was found before the end, if any
445
+ if image:
446
+ cards.append(Card.fromstring(empty.join(image)))
447
+
448
+ return cls._fromcards(cards)
449
+
450
+ @classmethod
451
+ def fromfile(cls, fileobj, sep='', endcard=True, padding=True):
452
+ """
453
+ Similar to :meth:`Header.fromstring`, but reads the header string from
454
+ a given file-like object or filename.
455
+
456
+ Parameters
457
+ ----------
458
+ fileobj : str, file-like
459
+ A filename or an open file-like object from which a FITS header is
460
+ to be read. For open file handles the file pointer must be at the
461
+ beginning of the header.
462
+
463
+ sep : str, optional
464
+ The string separating cards from each other, such as a newline. By
465
+ default there is no card separator (as is the case in a raw FITS
466
+ file).
467
+
468
+ endcard : bool, optional
469
+ If True (the default) the header must end with an END card in order
470
+ to be considered valid. If an END card is not found an
471
+ `OSError` is raised.
472
+
473
+ padding : bool, optional
474
+ If True (the default) the header will be required to be padded out
475
+ to a multiple of 2880, the FITS header block size. Otherwise any
476
+ padding, or lack thereof, is ignored.
477
+
478
+ Returns
479
+ -------
480
+ header
481
+ A new `Header` instance.
482
+ """
483
+
484
+ close_file = False
485
+
486
+ if isinstance(fileobj, path_like):
487
+ # If sep is non-empty we are trying to read a header printed to a
488
+ # text file, so open in text mode by default to support newline
489
+ # handling; if a binary-mode file object is passed in, the user is
490
+ # then on their own w.r.t. newline handling.
491
+ #
492
+ # Otherwise assume we are reading from an actual FITS file and open
493
+ # in binary mode.
494
+ if sep:
495
+ fileobj = open(fileobj, 'r', encoding='latin1')
496
+ else:
497
+ fileobj = open(fileobj, 'rb')
498
+
499
+ close_file = True
500
+
501
+ try:
502
+ is_binary = fileobj_is_binary(fileobj)
503
+
504
+ def block_iter(nbytes):
505
+ while True:
506
+ data = fileobj.read(nbytes)
507
+
508
+ if data:
509
+ yield data
510
+ else:
511
+ break
512
+
513
+ return cls._from_blocks(block_iter, is_binary, sep, endcard,
514
+ padding)[1]
515
+ finally:
516
+ if close_file:
517
+ fileobj.close()
518
+
519
+ @classmethod
520
+ def _fromcards(cls, cards):
521
+ header = cls()
522
+ for idx, card in enumerate(cards):
523
+ header._cards.append(card)
524
+ keyword = Card.normalize_keyword(card.keyword)
525
+ header._keyword_indices[keyword].append(idx)
526
+ if card.field_specifier is not None:
527
+ header._rvkc_indices[card.rawkeyword].append(idx)
528
+
529
+ header._modified = False
530
+ return header
531
+
532
+ @classmethod
533
+ def _from_blocks(cls, block_iter, is_binary, sep, endcard, padding):
534
+ """
535
+ The meat of `Header.fromfile`; in a separate method so that
536
+ `Header.fromfile` itself is just responsible for wrapping file
537
+ handling. Also used by `_BaseHDU.fromstring`.
538
+
539
+ ``block_iter`` should be a callable which, given a block size n
540
+ (typically 2880 bytes as used by the FITS standard) returns an iterator
541
+ of byte strings of that block size.
542
+
543
+ ``is_binary`` specifies whether the returned blocks are bytes or text
544
+
545
+ Returns both the entire header *string*, and the `Header` object
546
+ returned by Header.fromstring on that string.
547
+ """
548
+
549
+ actual_block_size = _block_size(sep)
550
+ clen = Card.length + len(sep)
551
+
552
+ blocks = block_iter(actual_block_size)
553
+
554
+ # Read the first header block.
555
+ try:
556
+ block = next(blocks)
557
+ except StopIteration:
558
+ raise EOFError()
559
+
560
+ if not is_binary:
561
+ # TODO: There needs to be error handling at *this* level for
562
+ # non-ASCII characters; maybe at this stage decoding latin-1 might
563
+ # be safer
564
+ block = encode_ascii(block)
565
+
566
+ read_blocks = []
567
+ is_eof = False
568
+ end_found = False
569
+
570
+ # continue reading header blocks until END card or EOF is reached
571
+ while True:
572
+ # find the END card
573
+ end_found, block = cls._find_end_card(block, clen)
574
+
575
+ read_blocks.append(decode_ascii(block))
576
+
577
+ if end_found:
578
+ break
579
+
580
+ try:
581
+ block = next(blocks)
582
+ except StopIteration:
583
+ is_eof = True
584
+ break
585
+
586
+ if not block:
587
+ is_eof = True
588
+ break
589
+
590
+ if not is_binary:
591
+ block = encode_ascii(block)
592
+
593
+ if not end_found and is_eof and endcard:
594
+ # TODO: Pass this error to validation framework as an ERROR,
595
+ # rather than raising an exception
596
+ raise OSError('Header missing END card.')
597
+
598
+ header_str = ''.join(read_blocks)
599
+ _check_padding(header_str, actual_block_size, is_eof,
600
+ check_block_size=padding)
601
+
602
+ return header_str, cls.fromstring(header_str, sep=sep)
603
+
604
+ @classmethod
605
+ def _find_end_card(cls, block, card_len):
606
+ """
607
+ Utility method to search a header block for the END card and handle
608
+ invalid END cards.
609
+
610
+ This method can also returned a modified copy of the input header block
611
+ in case an invalid end card needs to be sanitized.
612
+ """
613
+
614
+ for mo in HEADER_END_RE.finditer(block):
615
+ # Ensure the END card was found, and it started on the
616
+ # boundary of a new card (see ticket #142)
617
+ if mo.start() % card_len != 0:
618
+ continue
619
+
620
+ # This must be the last header block, otherwise the
621
+ # file is malformatted
622
+ if mo.group('invalid'):
623
+ offset = mo.start()
624
+ trailing = block[offset + 3:offset + card_len - 3].rstrip()
625
+ if trailing:
626
+ trailing = repr(trailing).lstrip('ub')
627
+ # TODO: Pass this warning up to the validation framework
628
+ warnings.warn(
629
+ 'Unexpected bytes trailing END keyword: {0}; these '
630
+ 'bytes will be replaced with spaces on write.'.format(
631
+ trailing), AstropyUserWarning)
632
+ else:
633
+ # TODO: Pass this warning up to the validation framework
634
+ warnings.warn(
635
+ 'Missing padding to end of the FITS block after the '
636
+ 'END keyword; additional spaces will be appended to '
637
+ 'the file upon writing to pad out to {0} '
638
+ 'bytes.'.format(BLOCK_SIZE), AstropyUserWarning)
639
+
640
+ # Sanitize out invalid END card now that the appropriate
641
+ # warnings have been issued
642
+ block = (block[:offset] + encode_ascii(END_CARD) +
643
+ block[offset + len(END_CARD):])
644
+
645
+ return True, block
646
+
647
+ return False, block
648
+
649
+ def tostring(self, sep='', endcard=True, padding=True):
650
+ r"""
651
+ Returns a string representation of the header.
652
+
653
+ By default this uses no separator between cards, adds the END card, and
654
+ pads the string with spaces to the next multiple of 2880 bytes. That
655
+ is, it returns the header exactly as it would appear in a FITS file.
656
+
657
+ Parameters
658
+ ----------
659
+ sep : str, optional
660
+ The character or string with which to separate cards. By default
661
+ there is no separator, but one could use ``'\\n'``, for example, to
662
+ separate each card with a new line
663
+
664
+ endcard : bool, optional
665
+ If True (default) adds the END card to the end of the header
666
+ string
667
+
668
+ padding : bool, optional
669
+ If True (default) pads the string with spaces out to the next
670
+ multiple of 2880 characters
671
+
672
+ Returns
673
+ -------
674
+ s : str
675
+ A string representing a FITS header.
676
+ """
677
+
678
+ lines = []
679
+ for card in self._cards:
680
+ s = str(card)
681
+ # Cards with CONTINUE cards may be longer than 80 chars; so break
682
+ # them into multiple lines
683
+ while s:
684
+ lines.append(s[:Card.length])
685
+ s = s[Card.length:]
686
+
687
+ s = sep.join(lines)
688
+ if endcard:
689
+ s += sep + _pad('END')
690
+ if padding:
691
+ s += ' ' * _pad_length(len(s))
692
+ return s
693
+
694
+ @deprecated_renamed_argument('clobber', 'overwrite', '2.0')
695
+ def tofile(self, fileobj, sep='', endcard=True, padding=True,
696
+ overwrite=False):
697
+ r"""
698
+ Writes the header to file or file-like object.
699
+
700
+ By default this writes the header exactly as it would be written to a
701
+ FITS file, with the END card included and padding to the next multiple
702
+ of 2880 bytes. However, aspects of this may be controlled.
703
+
704
+ Parameters
705
+ ----------
706
+ fileobj : str, file, optional
707
+ Either the pathname of a file, or an open file handle or file-like
708
+ object
709
+
710
+ sep : str, optional
711
+ The character or string with which to separate cards. By default
712
+ there is no separator, but one could use ``'\\n'``, for example, to
713
+ separate each card with a new line
714
+
715
+ endcard : bool, optional
716
+ If `True` (default) adds the END card to the end of the header
717
+ string
718
+
719
+ padding : bool, optional
720
+ If `True` (default) pads the string with spaces out to the next
721
+ multiple of 2880 characters
722
+
723
+ overwrite : bool, optional
724
+ If ``True``, overwrite the output file if it exists. Raises an
725
+ ``OSError`` if ``False`` and the output file exists. Default is
726
+ ``False``.
727
+
728
+ .. versionchanged:: 1.3
729
+ ``overwrite`` replaces the deprecated ``clobber`` argument.
730
+ """
731
+
732
+ close_file = fileobj_closed(fileobj)
733
+
734
+ if not isinstance(fileobj, _File):
735
+ fileobj = _File(fileobj, mode='ostream', overwrite=overwrite)
736
+
737
+ try:
738
+ blocks = self.tostring(sep=sep, endcard=endcard, padding=padding)
739
+ actual_block_size = _block_size(sep)
740
+ if padding and len(blocks) % actual_block_size != 0:
741
+ raise OSError(
742
+ 'Header size ({}) is not a multiple of block '
743
+ 'size ({}).'.format(
744
+ len(blocks) - actual_block_size + BLOCK_SIZE,
745
+ BLOCK_SIZE))
746
+
747
+ if not fileobj.simulateonly:
748
+ fileobj.flush()
749
+ try:
750
+ offset = fileobj.tell()
751
+ except (AttributeError, OSError):
752
+ offset = 0
753
+ fileobj.write(blocks.encode('ascii'))
754
+ fileobj.flush()
755
+ finally:
756
+ if close_file:
757
+ fileobj.close()
758
+
759
+ @classmethod
760
+ def fromtextfile(cls, fileobj, endcard=False):
761
+ """
762
+ Read a header from a simple text file or file-like object.
763
+
764
+ Equivalent to::
765
+
766
+ >>> Header.fromfile(fileobj, sep='\\n', endcard=False,
767
+ ... padding=False)
768
+
769
+ See Also
770
+ --------
771
+ fromfile
772
+ """
773
+
774
+ return cls.fromfile(fileobj, sep='\n', endcard=endcard, padding=False)
775
+
776
+ @deprecated_renamed_argument('clobber', 'overwrite', '2.0')
777
+ def totextfile(self, fileobj, endcard=False, overwrite=False):
778
+ """
779
+ Write the header as text to a file or a file-like object.
780
+
781
+ Equivalent to::
782
+
783
+ >>> Header.tofile(fileobj, sep='\\n', endcard=False,
784
+ ... padding=False, overwrite=overwrite)
785
+
786
+ .. versionchanged:: 1.3
787
+ ``overwrite`` replaces the deprecated ``clobber`` argument.
788
+
789
+ See Also
790
+ --------
791
+ tofile
792
+ """
793
+
794
+ self.tofile(fileobj, sep='\n', endcard=endcard, padding=False,
795
+ overwrite=overwrite)
796
+
797
+ def clear(self):
798
+ """
799
+ Remove all cards from the header.
800
+ """
801
+
802
+ self._cards = []
803
+ self._keyword_indices = collections.defaultdict(list)
804
+ self._rvkc_indices = collections.defaultdict(list)
805
+
806
+ def copy(self, strip=False):
807
+ """
808
+ Make a copy of the :class:`Header`.
809
+
810
+ .. versionchanged:: 1.3
811
+ `copy.copy` and `copy.deepcopy` on a `Header` will call this
812
+ method.
813
+
814
+ Parameters
815
+ ----------
816
+ strip : bool, optional
817
+ If `True`, strip any headers that are specific to one of the
818
+ standard HDU types, so that this header can be used in a different
819
+ HDU.
820
+
821
+ Returns
822
+ -------
823
+ header
824
+ A new :class:`Header` instance.
825
+ """
826
+
827
+ tmp = Header((copy.copy(card) for card in self._cards))
828
+ if strip:
829
+ tmp._strip()
830
+ return tmp
831
+
832
+ def __copy__(self):
833
+ return self.copy()
834
+
835
+ def __deepcopy__(self, *args, **kwargs):
836
+ return self.copy()
837
+
838
+ @classmethod
839
+ def fromkeys(cls, iterable, value=None):
840
+ """
841
+ Similar to :meth:`dict.fromkeys`--creates a new `Header` from an
842
+ iterable of keywords and an optional default value.
843
+
844
+ This method is not likely to be particularly useful for creating real
845
+ world FITS headers, but it is useful for testing.
846
+
847
+ Parameters
848
+ ----------
849
+ iterable
850
+ Any iterable that returns strings representing FITS keywords.
851
+
852
+ value : optional
853
+ A default value to assign to each keyword; must be a valid type for
854
+ FITS keywords.
855
+
856
+ Returns
857
+ -------
858
+ header
859
+ A new `Header` instance.
860
+ """
861
+
862
+ d = cls()
863
+ if not isinstance(value, tuple):
864
+ value = (value,)
865
+ for key in iterable:
866
+ d.append((key,) + value)
867
+ return d
868
+
869
+ def get(self, key, default=None):
870
+ """
871
+ Similar to :meth:`dict.get`--returns the value associated with keyword
872
+ in the header, or a default value if the keyword is not found.
873
+
874
+ Parameters
875
+ ----------
876
+ key : str
877
+ A keyword that may or may not be in the header.
878
+
879
+ default : optional
880
+ A default value to return if the keyword is not found in the
881
+ header.
882
+
883
+ Returns
884
+ -------
885
+ value
886
+ The value associated with the given keyword, or the default value
887
+ if the keyword is not in the header.
888
+ """
889
+
890
+ try:
891
+ return self[key]
892
+ except (KeyError, IndexError):
893
+ return default
894
+
895
+ def set(self, keyword, value=None, comment=None, before=None, after=None):
896
+ """
897
+ Set the value and/or comment and/or position of a specified keyword.
898
+
899
+ If the keyword does not already exist in the header, a new keyword is
900
+ created in the specified position, or appended to the end of the header
901
+ if no position is specified.
902
+
903
+ This method is similar to :meth:`Header.update` prior to Astropy v0.1.
904
+
905
+ .. note::
906
+ It should be noted that ``header.set(keyword, value)`` and
907
+ ``header.set(keyword, value, comment)`` are equivalent to
908
+ ``header[keyword] = value`` and
909
+ ``header[keyword] = (value, comment)`` respectively.
910
+
911
+ New keywords can also be inserted relative to existing keywords
912
+ using, for example::
913
+
914
+ >>> header.insert('NAXIS1', ('NAXIS', 2, 'Number of axes'))
915
+
916
+ to insert before an existing keyword, or::
917
+
918
+ >>> header.insert('NAXIS', ('NAXIS1', 4096), after=True)
919
+
920
+ to insert after an existing keyword.
921
+
922
+ The only advantage of using :meth:`Header.set` is that it
923
+ easily replaces the old usage of :meth:`Header.update` both
924
+ conceptually and in terms of function signature.
925
+
926
+ Parameters
927
+ ----------
928
+ keyword : str
929
+ A header keyword
930
+
931
+ value : str, optional
932
+ The value to set for the given keyword; if None the existing value
933
+ is kept, but '' may be used to set a blank value
934
+
935
+ comment : str, optional
936
+ The comment to set for the given keyword; if None the existing
937
+ comment is kept, but ``''`` may be used to set a blank comment
938
+
939
+ before : str, int, optional
940
+ Name of the keyword, or index of the `Card` before which this card
941
+ should be located in the header. The argument ``before`` takes
942
+ precedence over ``after`` if both specified.
943
+
944
+ after : str, int, optional
945
+ Name of the keyword, or index of the `Card` after which this card
946
+ should be located in the header.
947
+
948
+ """
949
+
950
+ # Create a temporary card that looks like the one being set; if the
951
+ # temporary card turns out to be a RVKC this will make it easier to
952
+ # deal with the idiosyncrasies thereof
953
+ # Don't try to make a temporary card though if they keyword looks like
954
+ # it might be a HIERARCH card or is otherwise invalid--this step is
955
+ # only for validating RVKCs.
956
+ if (len(keyword) <= KEYWORD_LENGTH and
957
+ Card._keywd_FSC_RE.match(keyword) and
958
+ keyword not in self._keyword_indices):
959
+ new_card = Card(keyword, value, comment)
960
+ new_keyword = new_card.keyword
961
+ else:
962
+ new_keyword = keyword
963
+
964
+ if (new_keyword not in Card._commentary_keywords and
965
+ new_keyword in self):
966
+ if comment is None:
967
+ comment = self.comments[keyword]
968
+ if value is None:
969
+ value = self[keyword]
970
+
971
+ self[keyword] = (value, comment)
972
+
973
+ if before is not None or after is not None:
974
+ card = self._cards[self._cardindex(keyword)]
975
+ self._relativeinsert(card, before=before, after=after,
976
+ replace=True)
977
+ elif before is not None or after is not None:
978
+ self._relativeinsert((keyword, value, comment), before=before,
979
+ after=after)
980
+ else:
981
+ self[keyword] = (value, comment)
982
+
983
+ def items(self):
984
+ """Like :meth:`dict.items`."""
985
+
986
+ for card in self._cards:
987
+ yield (card.keyword, card.value)
988
+
989
+ def keys(self):
990
+ """
991
+ Like :meth:`dict.keys`--iterating directly over the `Header`
992
+ instance has the same behavior.
993
+ """
994
+
995
+ for card in self._cards:
996
+ yield card.keyword
997
+
998
+ def values(self):
999
+ """Like :meth:`dict.values`."""
1000
+
1001
+ for card in self._cards:
1002
+ yield card.value
1003
+
1004
+ def pop(self, *args):
1005
+ """
1006
+ Works like :meth:`list.pop` if no arguments or an index argument are
1007
+ supplied; otherwise works like :meth:`dict.pop`.
1008
+ """
1009
+
1010
+ if len(args) > 2:
1011
+ raise TypeError('Header.pop expected at most 2 arguments, got '
1012
+ '{}'.format(len(args)))
1013
+
1014
+ if len(args) == 0:
1015
+ key = -1
1016
+ else:
1017
+ key = args[0]
1018
+
1019
+ try:
1020
+ value = self[key]
1021
+ except (KeyError, IndexError):
1022
+ if len(args) == 2:
1023
+ return args[1]
1024
+ raise
1025
+
1026
+ del self[key]
1027
+ return value
1028
+
1029
+ def popitem(self):
1030
+ """Similar to :meth:`dict.popitem`."""
1031
+
1032
+ try:
1033
+ k, v = next(self.items())
1034
+ except StopIteration:
1035
+ raise KeyError('Header is empty')
1036
+ del self[k]
1037
+ return k, v
1038
+
1039
+ def setdefault(self, key, default=None):
1040
+ """Similar to :meth:`dict.setdefault`."""
1041
+
1042
+ try:
1043
+ return self[key]
1044
+ except (KeyError, IndexError):
1045
+ self[key] = default
1046
+ return default
1047
+
1048
+ def update(self, *args, **kwargs):
1049
+ """
1050
+ Update the Header with new keyword values, updating the values of
1051
+ existing keywords and appending new keywords otherwise; similar to
1052
+ `dict.update`.
1053
+
1054
+ `update` accepts either a dict-like object or an iterable. In the
1055
+ former case the keys must be header keywords and the values may be
1056
+ either scalar values or (value, comment) tuples. In the case of an
1057
+ iterable the items must be (keyword, value) tuples or (keyword, value,
1058
+ comment) tuples.
1059
+
1060
+ Arbitrary arguments are also accepted, in which case the update() is
1061
+ called again with the kwargs dict as its only argument. That is,
1062
+
1063
+ ::
1064
+
1065
+ >>> header.update(NAXIS1=100, NAXIS2=100)
1066
+
1067
+ is equivalent to::
1068
+
1069
+ header.update({'NAXIS1': 100, 'NAXIS2': 100})
1070
+
1071
+ .. warning::
1072
+ As this method works similarly to `dict.update` it is very
1073
+ different from the ``Header.update()`` method in Astropy v0.1.
1074
+ Use of the old API was
1075
+ **deprecated** for a long time and is now removed. Most uses of the
1076
+ old API can be replaced as follows:
1077
+
1078
+ * Replace ::
1079
+
1080
+ header.update(keyword, value)
1081
+
1082
+ with ::
1083
+
1084
+ header[keyword] = value
1085
+
1086
+ * Replace ::
1087
+
1088
+ header.update(keyword, value, comment=comment)
1089
+
1090
+ with ::
1091
+
1092
+ header[keyword] = (value, comment)
1093
+
1094
+ * Replace ::
1095
+
1096
+ header.update(keyword, value, before=before_keyword)
1097
+
1098
+ with ::
1099
+
1100
+ header.insert(before_keyword, (keyword, value))
1101
+
1102
+ * Replace ::
1103
+
1104
+ header.update(keyword, value, after=after_keyword)
1105
+
1106
+ with ::
1107
+
1108
+ header.insert(after_keyword, (keyword, value),
1109
+ after=True)
1110
+
1111
+ See also :meth:`Header.set` which is a new method that provides an
1112
+ interface similar to the old ``Header.update()`` and may help make
1113
+ transition a little easier.
1114
+
1115
+ """
1116
+
1117
+ if args:
1118
+ other = args[0]
1119
+ else:
1120
+ other = None
1121
+
1122
+ def update_from_dict(k, v):
1123
+ if not isinstance(v, tuple):
1124
+ card = Card(k, v)
1125
+ elif 0 < len(v) <= 2:
1126
+ card = Card(*((k,) + v))
1127
+ else:
1128
+ raise ValueError(
1129
+ 'Header update value for key %r is invalid; the '
1130
+ 'value must be either a scalar, a 1-tuple '
1131
+ 'containing the scalar value, or a 2-tuple '
1132
+ 'containing the value and a comment string.' % k)
1133
+ self._update(card)
1134
+
1135
+ if other is None:
1136
+ pass
1137
+ elif isinstance(other, Header):
1138
+ for card in other.cards:
1139
+ self._update(card)
1140
+ elif hasattr(other, 'items'):
1141
+ for k, v in other.items():
1142
+ update_from_dict(k, v)
1143
+ elif hasattr(other, 'keys'):
1144
+ for k in other.keys():
1145
+ update_from_dict(k, other[k])
1146
+ else:
1147
+ for idx, card in enumerate(other):
1148
+ if isinstance(card, Card):
1149
+ self._update(card)
1150
+ elif isinstance(card, tuple) and (1 < len(card) <= 3):
1151
+ self._update(Card(*card))
1152
+ else:
1153
+ raise ValueError(
1154
+ 'Header update sequence item #{} is invalid; '
1155
+ 'the item must either be a 2-tuple containing '
1156
+ 'a keyword and value, or a 3-tuple containing '
1157
+ 'a keyword, value, and comment string.'.format(idx))
1158
+ if kwargs:
1159
+ self.update(kwargs)
1160
+
1161
+ def append(self, card=None, useblanks=True, bottom=False, end=False):
1162
+ """
1163
+ Appends a new keyword+value card to the end of the Header, similar
1164
+ to `list.append`.
1165
+
1166
+ By default if the last cards in the Header have commentary keywords,
1167
+ this will append the new keyword before the commentary (unless the new
1168
+ keyword is also commentary).
1169
+
1170
+ Also differs from `list.append` in that it can be called with no
1171
+ arguments: In this case a blank card is appended to the end of the
1172
+ Header. In the case all the keyword arguments are ignored.
1173
+
1174
+ Parameters
1175
+ ----------
1176
+ card : str, tuple
1177
+ A keyword or a (keyword, value, [comment]) tuple representing a
1178
+ single header card; the comment is optional in which case a
1179
+ 2-tuple may be used
1180
+
1181
+ useblanks : bool, optional
1182
+ If there are blank cards at the end of the Header, replace the
1183
+ first blank card so that the total number of cards in the Header
1184
+ does not increase. Otherwise preserve the number of blank cards.
1185
+
1186
+ bottom : bool, optional
1187
+ If True, instead of appending after the last non-commentary card,
1188
+ append after the last non-blank card.
1189
+
1190
+ end : bool, optional
1191
+ If True, ignore the useblanks and bottom options, and append at the
1192
+ very end of the Header.
1193
+
1194
+ """
1195
+
1196
+ if isinstance(card, str):
1197
+ card = Card(card)
1198
+ elif isinstance(card, tuple):
1199
+ card = Card(*card)
1200
+ elif card is None:
1201
+ card = Card()
1202
+ elif not isinstance(card, Card):
1203
+ raise ValueError(
1204
+ 'The value appended to a Header must be either a keyword or '
1205
+ '(keyword, value, [comment]) tuple; got: {!r}'.format(card))
1206
+
1207
+ if not end and card.is_blank:
1208
+ # Blank cards should always just be appended to the end
1209
+ end = True
1210
+
1211
+ if end:
1212
+ self._cards.append(card)
1213
+ idx = len(self._cards) - 1
1214
+ else:
1215
+ idx = len(self._cards) - 1
1216
+ while idx >= 0 and self._cards[idx].is_blank:
1217
+ idx -= 1
1218
+
1219
+ if not bottom and card.keyword not in Card._commentary_keywords:
1220
+ while (idx >= 0 and
1221
+ self._cards[idx].keyword in Card._commentary_keywords):
1222
+ idx -= 1
1223
+
1224
+ idx += 1
1225
+ self._cards.insert(idx, card)
1226
+ self._updateindices(idx)
1227
+
1228
+ keyword = Card.normalize_keyword(card.keyword)
1229
+ self._keyword_indices[keyword].append(idx)
1230
+ if card.field_specifier is not None:
1231
+ self._rvkc_indices[card.rawkeyword].append(idx)
1232
+
1233
+ if not end:
1234
+ # If the appended card was a commentary card, and it was appended
1235
+ # before existing cards with the same keyword, the indices for
1236
+ # cards with that keyword may have changed
1237
+ if not bottom and card.keyword in Card._commentary_keywords:
1238
+ self._keyword_indices[keyword].sort()
1239
+
1240
+ # Finally, if useblanks, delete a blank cards from the end
1241
+ if useblanks and self._countblanks():
1242
+ # Don't do this unless there is at least one blanks at the end
1243
+ # of the header; we need to convert the card to its string
1244
+ # image to see how long it is. In the vast majority of cases
1245
+ # this will just be 80 (Card.length) but it may be longer for
1246
+ # CONTINUE cards
1247
+ self._useblanks(len(str(card)) // Card.length)
1248
+
1249
+ self._modified = True
1250
+
1251
+ def extend(self, cards, strip=True, unique=False, update=False,
1252
+ update_first=False, useblanks=True, bottom=False, end=False):
1253
+ """
1254
+ Appends multiple keyword+value cards to the end of the header, similar
1255
+ to `list.extend`.
1256
+
1257
+ Parameters
1258
+ ----------
1259
+ cards : iterable
1260
+ An iterable of (keyword, value, [comment]) tuples; see
1261
+ `Header.append`.
1262
+
1263
+ strip : bool, optional
1264
+ Remove any keywords that have meaning only to specific types of
1265
+ HDUs, so that only more general keywords are added from extension
1266
+ Header or Card list (default: `True`).
1267
+
1268
+ unique : bool, optional
1269
+ If `True`, ensures that no duplicate keywords are appended;
1270
+ keywords already in this header are simply discarded. The
1271
+ exception is commentary keywords (COMMENT, HISTORY, etc.): they are
1272
+ only treated as duplicates if their values match.
1273
+
1274
+ update : bool, optional
1275
+ If `True`, update the current header with the values and comments
1276
+ from duplicate keywords in the input header. This supersedes the
1277
+ ``unique`` argument. Commentary keywords are treated the same as
1278
+ if ``unique=True``.
1279
+
1280
+ update_first : bool, optional
1281
+ If the first keyword in the header is 'SIMPLE', and the first
1282
+ keyword in the input header is 'XTENSION', the 'SIMPLE' keyword is
1283
+ replaced by the 'XTENSION' keyword. Likewise if the first keyword
1284
+ in the header is 'XTENSION' and the first keyword in the input
1285
+ header is 'SIMPLE', the 'XTENSION' keyword is replaced by the
1286
+ 'SIMPLE' keyword. This behavior is otherwise dumb as to whether or
1287
+ not the resulting header is a valid primary or extension header.
1288
+ This is mostly provided to support backwards compatibility with the
1289
+ old ``Header.fromTxtFile`` method, and only applies if
1290
+ ``update=True``.
1291
+
1292
+ useblanks, bottom, end : bool, optional
1293
+ These arguments are passed to :meth:`Header.append` while appending
1294
+ new cards to the header.
1295
+ """
1296
+
1297
+ temp = Header(cards)
1298
+ if strip:
1299
+ temp._strip()
1300
+
1301
+ if len(self):
1302
+ first = self._cards[0].keyword
1303
+ else:
1304
+ first = None
1305
+
1306
+ # We don't immediately modify the header, because first we need to sift
1307
+ # out any duplicates in the new header prior to adding them to the
1308
+ # existing header, but while *allowing* duplicates from the header
1309
+ # being extended from (see ticket #156)
1310
+ extend_cards = []
1311
+
1312
+ for idx, card in enumerate(temp.cards):
1313
+ keyword = card.keyword
1314
+ if keyword not in Card._commentary_keywords:
1315
+ if unique and not update and keyword in self:
1316
+ continue
1317
+ elif update:
1318
+ if idx == 0 and update_first:
1319
+ # Dumbly update the first keyword to either SIMPLE or
1320
+ # XTENSION as the case may be, as was in the case in
1321
+ # Header.fromTxtFile
1322
+ if ((keyword == 'SIMPLE' and first == 'XTENSION') or
1323
+ (keyword == 'XTENSION' and first == 'SIMPLE')):
1324
+ del self[0]
1325
+ self.insert(0, card)
1326
+ else:
1327
+ self[keyword] = (card.value, card.comment)
1328
+ elif keyword in self:
1329
+ self[keyword] = (card.value, card.comment)
1330
+ else:
1331
+ extend_cards.append(card)
1332
+ else:
1333
+ extend_cards.append(card)
1334
+ else:
1335
+ if (unique or update) and keyword in self:
1336
+ if card.is_blank:
1337
+ extend_cards.append(card)
1338
+ continue
1339
+
1340
+ for value in self[keyword]:
1341
+ if value == card.value:
1342
+ break
1343
+ else:
1344
+ extend_cards.append(card)
1345
+ else:
1346
+ extend_cards.append(card)
1347
+
1348
+ for card in extend_cards:
1349
+ self.append(card, useblanks=useblanks, bottom=bottom, end=end)
1350
+
1351
+ def count(self, keyword):
1352
+ """
1353
+ Returns the count of the given keyword in the header, similar to
1354
+ `list.count` if the Header object is treated as a list of keywords.
1355
+
1356
+ Parameters
1357
+ ----------
1358
+ keyword : str
1359
+ The keyword to count instances of in the header
1360
+
1361
+ """
1362
+
1363
+ keyword = Card.normalize_keyword(keyword)
1364
+
1365
+ # We have to look before we leap, since otherwise _keyword_indices,
1366
+ # being a defaultdict, will create an entry for the nonexistent keyword
1367
+ if keyword not in self._keyword_indices:
1368
+ raise KeyError("Keyword {!r} not found.".format(keyword))
1369
+
1370
+ return len(self._keyword_indices[keyword])
1371
+
1372
+ def index(self, keyword, start=None, stop=None):
1373
+ """
1374
+ Returns the index if the first instance of the given keyword in the
1375
+ header, similar to `list.index` if the Header object is treated as a
1376
+ list of keywords.
1377
+
1378
+ Parameters
1379
+ ----------
1380
+ keyword : str
1381
+ The keyword to look up in the list of all keywords in the header
1382
+
1383
+ start : int, optional
1384
+ The lower bound for the index
1385
+
1386
+ stop : int, optional
1387
+ The upper bound for the index
1388
+
1389
+ """
1390
+
1391
+ if start is None:
1392
+ start = 0
1393
+
1394
+ if stop is None:
1395
+ stop = len(self._cards)
1396
+
1397
+ if stop < start:
1398
+ step = -1
1399
+ else:
1400
+ step = 1
1401
+
1402
+ norm_keyword = Card.normalize_keyword(keyword)
1403
+
1404
+ for idx in range(start, stop, step):
1405
+ if self._cards[idx].keyword.upper() == norm_keyword:
1406
+ return idx
1407
+ else:
1408
+ raise ValueError('The keyword {!r} is not in the '
1409
+ ' header.'.format(keyword))
1410
+
1411
+ def insert(self, key, card, useblanks=True, after=False):
1412
+ """
1413
+ Inserts a new keyword+value card into the Header at a given location,
1414
+ similar to `list.insert`.
1415
+
1416
+ Parameters
1417
+ ----------
1418
+ key : int, str, or tuple
1419
+ The index into the list of header keywords before which the
1420
+ new keyword should be inserted, or the name of a keyword before
1421
+ which the new keyword should be inserted. Can also accept a
1422
+ (keyword, index) tuple for inserting around duplicate keywords.
1423
+
1424
+ card : str, tuple
1425
+ A keyword or a (keyword, value, [comment]) tuple; see
1426
+ `Header.append`
1427
+
1428
+ useblanks : bool, optional
1429
+ If there are blank cards at the end of the Header, replace the
1430
+ first blank card so that the total number of cards in the Header
1431
+ does not increase. Otherwise preserve the number of blank cards.
1432
+
1433
+ after : bool, optional
1434
+ If set to `True`, insert *after* the specified index or keyword,
1435
+ rather than before it. Defaults to `False`.
1436
+ """
1437
+
1438
+ if not isinstance(key, int):
1439
+ # Don't pass through ints to _cardindex because it will not take
1440
+ # kindly to indices outside the existing number of cards in the
1441
+ # header, which insert needs to be able to support (for example
1442
+ # when inserting into empty headers)
1443
+ idx = self._cardindex(key)
1444
+ else:
1445
+ idx = key
1446
+
1447
+ if after:
1448
+ if idx == -1:
1449
+ idx = len(self._cards)
1450
+ else:
1451
+ idx += 1
1452
+
1453
+ if idx >= len(self._cards):
1454
+ # This is just an append (Though it must be an append absolutely to
1455
+ # the bottom, ignoring blanks, etc.--the point of the insert method
1456
+ # is that you get exactly what you asked for with no surprises)
1457
+ self.append(card, end=True)
1458
+ return
1459
+
1460
+ if isinstance(card, str):
1461
+ card = Card(card)
1462
+ elif isinstance(card, tuple):
1463
+ card = Card(*card)
1464
+ elif not isinstance(card, Card):
1465
+ raise ValueError(
1466
+ 'The value inserted into a Header must be either a keyword or '
1467
+ '(keyword, value, [comment]) tuple; got: {!r}'.format(card))
1468
+
1469
+ self._cards.insert(idx, card)
1470
+
1471
+ keyword = card.keyword
1472
+
1473
+ # If idx was < 0, determine the actual index according to the rules
1474
+ # used by list.insert()
1475
+ if idx < 0:
1476
+ idx += len(self._cards) - 1
1477
+ if idx < 0:
1478
+ idx = 0
1479
+
1480
+ # All the keyword indices above the insertion point must be updated
1481
+ self._updateindices(idx)
1482
+
1483
+ keyword = Card.normalize_keyword(keyword)
1484
+ self._keyword_indices[keyword].append(idx)
1485
+ count = len(self._keyword_indices[keyword])
1486
+ if count > 1:
1487
+ # There were already keywords with this same name
1488
+ if keyword not in Card._commentary_keywords:
1489
+ warnings.warn(
1490
+ 'A {!r} keyword already exists in this header. Inserting '
1491
+ 'duplicate keyword.'.format(keyword), AstropyUserWarning)
1492
+ self._keyword_indices[keyword].sort()
1493
+
1494
+ if card.field_specifier is not None:
1495
+ # Update the index of RVKC as well
1496
+ rvkc_indices = self._rvkc_indices[card.rawkeyword]
1497
+ rvkc_indices.append(idx)
1498
+ rvkc_indices.sort()
1499
+
1500
+ if useblanks:
1501
+ self._useblanks(len(str(card)) // Card.length)
1502
+
1503
+ self._modified = True
1504
+
1505
+ def remove(self, keyword, ignore_missing=False, remove_all=False):
1506
+ """
1507
+ Removes the first instance of the given keyword from the header similar
1508
+ to `list.remove` if the Header object is treated as a list of keywords.
1509
+
1510
+ Parameters
1511
+ ----------
1512
+ keyword : str
1513
+ The keyword of which to remove the first instance in the header.
1514
+
1515
+ ignore_missing : bool, optional
1516
+ When True, ignores missing keywords. Otherwise, if the keyword
1517
+ is not present in the header a KeyError is raised.
1518
+
1519
+ remove_all : bool, optional
1520
+ When True, all instances of keyword will be removed.
1521
+ Otherwise only the first instance of the given keyword is removed.
1522
+
1523
+ """
1524
+ keyword = Card.normalize_keyword(keyword)
1525
+ if keyword in self._keyword_indices:
1526
+ del self[self._keyword_indices[keyword][0]]
1527
+ if remove_all:
1528
+ while keyword in self._keyword_indices:
1529
+ del self[self._keyword_indices[keyword][0]]
1530
+ elif not ignore_missing:
1531
+ raise KeyError("Keyword '{}' not found.".format(keyword))
1532
+
1533
+ def rename_keyword(self, oldkeyword, newkeyword, force=False):
1534
+ """
1535
+ Rename a card's keyword in the header.
1536
+
1537
+ Parameters
1538
+ ----------
1539
+ oldkeyword : str or int
1540
+ Old keyword or card index
1541
+
1542
+ newkeyword : str
1543
+ New keyword
1544
+
1545
+ force : bool, optional
1546
+ When `True`, if the new keyword already exists in the header, force
1547
+ the creation of a duplicate keyword. Otherwise a
1548
+ `ValueError` is raised.
1549
+ """
1550
+
1551
+ oldkeyword = Card.normalize_keyword(oldkeyword)
1552
+ newkeyword = Card.normalize_keyword(newkeyword)
1553
+
1554
+ if newkeyword == 'CONTINUE':
1555
+ raise ValueError('Can not rename to CONTINUE')
1556
+
1557
+ if (newkeyword in Card._commentary_keywords or
1558
+ oldkeyword in Card._commentary_keywords):
1559
+ if not (newkeyword in Card._commentary_keywords and
1560
+ oldkeyword in Card._commentary_keywords):
1561
+ raise ValueError('Regular and commentary keys can not be '
1562
+ 'renamed to each other.')
1563
+ elif not force and newkeyword in self:
1564
+ raise ValueError('Intended keyword {} already exists in header.'
1565
+ .format(newkeyword))
1566
+
1567
+ idx = self.index(oldkeyword)
1568
+ card = self._cards[idx]
1569
+ del self[idx]
1570
+ self.insert(idx, (newkeyword, card.value, card.comment))
1571
+
1572
+ def add_history(self, value, before=None, after=None):
1573
+ """
1574
+ Add a ``HISTORY`` card.
1575
+
1576
+ Parameters
1577
+ ----------
1578
+ value : str
1579
+ History text to be added.
1580
+
1581
+ before : str or int, optional
1582
+ Same as in `Header.update`
1583
+
1584
+ after : str or int, optional
1585
+ Same as in `Header.update`
1586
+ """
1587
+
1588
+ self._add_commentary('HISTORY', value, before=before, after=after)
1589
+
1590
+ def add_comment(self, value, before=None, after=None):
1591
+ """
1592
+ Add a ``COMMENT`` card.
1593
+
1594
+ Parameters
1595
+ ----------
1596
+ value : str
1597
+ Text to be added.
1598
+
1599
+ before : str or int, optional
1600
+ Same as in `Header.update`
1601
+
1602
+ after : str or int, optional
1603
+ Same as in `Header.update`
1604
+ """
1605
+
1606
+ self._add_commentary('COMMENT', value, before=before, after=after)
1607
+
1608
+ def add_blank(self, value='', before=None, after=None):
1609
+ """
1610
+ Add a blank card.
1611
+
1612
+ Parameters
1613
+ ----------
1614
+ value : str, optional
1615
+ Text to be added.
1616
+
1617
+ before : str or int, optional
1618
+ Same as in `Header.update`
1619
+
1620
+ after : str or int, optional
1621
+ Same as in `Header.update`
1622
+ """
1623
+
1624
+ self._add_commentary('', value, before=before, after=after)
1625
+
1626
+ def _update(self, card):
1627
+ """
1628
+ The real update code. If keyword already exists, its value and/or
1629
+ comment will be updated. Otherwise a new card will be appended.
1630
+
1631
+ This will not create a duplicate keyword except in the case of
1632
+ commentary cards. The only other way to force creation of a duplicate
1633
+ is to use the insert(), append(), or extend() methods.
1634
+ """
1635
+
1636
+ keyword, value, comment = card
1637
+
1638
+ # Lookups for existing/known keywords are case-insensitive
1639
+ keyword = keyword.upper()
1640
+ if keyword.startswith('HIERARCH '):
1641
+ keyword = keyword[9:]
1642
+
1643
+ if (keyword not in Card._commentary_keywords and
1644
+ keyword in self._keyword_indices):
1645
+ # Easy; just update the value/comment
1646
+ idx = self._keyword_indices[keyword][0]
1647
+ existing_card = self._cards[idx]
1648
+ existing_card.value = value
1649
+ if comment is not None:
1650
+ # '' should be used to explicitly blank a comment
1651
+ existing_card.comment = comment
1652
+ if existing_card._modified:
1653
+ self._modified = True
1654
+ elif keyword in Card._commentary_keywords:
1655
+ cards = self._splitcommentary(keyword, value)
1656
+ if keyword in self._keyword_indices:
1657
+ # Append after the last keyword of the same type
1658
+ idx = self.index(keyword, start=len(self) - 1, stop=-1)
1659
+ isblank = not (keyword or value or comment)
1660
+ for c in reversed(cards):
1661
+ self.insert(idx + 1, c, useblanks=(not isblank))
1662
+ else:
1663
+ for c in cards:
1664
+ self.append(c, bottom=True)
1665
+ else:
1666
+ # A new keyword! self.append() will handle updating _modified
1667
+ self.append(card)
1668
+
1669
+ def _cardindex(self, key):
1670
+ """Returns an index into the ._cards list given a valid lookup key."""
1671
+
1672
+ # This used to just set key = (key, 0) and then go on to act as if the
1673
+ # user passed in a tuple, but it's much more common to just be given a
1674
+ # string as the key, so optimize more for that case
1675
+ if isinstance(key, str):
1676
+ keyword = key
1677
+ n = 0
1678
+ elif isinstance(key, int):
1679
+ # If < 0, determine the actual index
1680
+ if key < 0:
1681
+ key += len(self._cards)
1682
+ if key < 0 or key >= len(self._cards):
1683
+ raise IndexError('Header index out of range.')
1684
+ return key
1685
+ elif isinstance(key, slice):
1686
+ return key
1687
+ elif isinstance(key, tuple):
1688
+ if (len(key) != 2 or not isinstance(key[0], str) or
1689
+ not isinstance(key[1], int)):
1690
+ raise ValueError(
1691
+ 'Tuple indices must be 2-tuples consisting of a '
1692
+ 'keyword string and an integer index.')
1693
+ keyword, n = key
1694
+ else:
1695
+ raise ValueError(
1696
+ 'Header indices must be either a string, a 2-tuple, or '
1697
+ 'an integer.')
1698
+
1699
+ keyword = Card.normalize_keyword(keyword)
1700
+ # Returns the index into _cards for the n-th card with the given
1701
+ # keyword (where n is 0-based)
1702
+ indices = self._keyword_indices.get(keyword, None)
1703
+
1704
+ if keyword and not indices:
1705
+ if len(keyword) > KEYWORD_LENGTH or '.' in keyword:
1706
+ raise KeyError("Keyword {!r} not found.".format(keyword))
1707
+ else:
1708
+ # Maybe it's a RVKC?
1709
+ indices = self._rvkc_indices.get(keyword, None)
1710
+
1711
+ if not indices:
1712
+ raise KeyError("Keyword {!r} not found.".format(keyword))
1713
+
1714
+ try:
1715
+ return indices[n]
1716
+ except IndexError:
1717
+ raise IndexError('There are only {} {!r} cards in the '
1718
+ 'header.'.format(len(indices), keyword))
1719
+
1720
+ def _keyword_from_index(self, idx):
1721
+ """
1722
+ Given an integer index, return the (keyword, repeat) tuple that index
1723
+ refers to. For most keywords the repeat will always be zero, but it
1724
+ may be greater than zero for keywords that are duplicated (especially
1725
+ commentary keywords).
1726
+
1727
+ In a sense this is the inverse of self.index, except that it also
1728
+ supports duplicates.
1729
+ """
1730
+
1731
+ if idx < 0:
1732
+ idx += len(self._cards)
1733
+
1734
+ keyword = self._cards[idx].keyword
1735
+ keyword = Card.normalize_keyword(keyword)
1736
+ repeat = self._keyword_indices[keyword].index(idx)
1737
+ return keyword, repeat
1738
+
1739
+ def _relativeinsert(self, card, before=None, after=None, replace=False):
1740
+ """
1741
+ Inserts a new card before or after an existing card; used to
1742
+ implement support for the legacy before/after keyword arguments to
1743
+ Header.update().
1744
+
1745
+ If replace=True, move an existing card with the same keyword.
1746
+ """
1747
+
1748
+ if before is None:
1749
+ insertionkey = after
1750
+ else:
1751
+ insertionkey = before
1752
+
1753
+ def get_insertion_idx():
1754
+ if not (isinstance(insertionkey, int) and
1755
+ insertionkey >= len(self._cards)):
1756
+ idx = self._cardindex(insertionkey)
1757
+ else:
1758
+ idx = insertionkey
1759
+
1760
+ if before is None:
1761
+ idx += 1
1762
+
1763
+ return idx
1764
+
1765
+ if replace:
1766
+ # The card presumably already exists somewhere in the header.
1767
+ # Check whether or not we actually have to move it; if it does need
1768
+ # to be moved we just delete it and then it will be reinserted
1769
+ # below
1770
+ old_idx = self._cardindex(card.keyword)
1771
+ insertion_idx = get_insertion_idx()
1772
+
1773
+ if (insertion_idx >= len(self._cards) and
1774
+ old_idx == len(self._cards) - 1):
1775
+ # The card would be appended to the end, but it's already at
1776
+ # the end
1777
+ return
1778
+
1779
+ if before is not None:
1780
+ if old_idx == insertion_idx - 1:
1781
+ return
1782
+ elif after is not None and old_idx == insertion_idx:
1783
+ return
1784
+
1785
+ del self[old_idx]
1786
+
1787
+ # Even if replace=True, the insertion idx may have changed since the
1788
+ # old card was deleted
1789
+ idx = get_insertion_idx()
1790
+
1791
+ if card[0] in Card._commentary_keywords:
1792
+ cards = reversed(self._splitcommentary(card[0], card[1]))
1793
+ else:
1794
+ cards = [card]
1795
+ for c in cards:
1796
+ self.insert(idx, c)
1797
+
1798
+ def _updateindices(self, idx, increment=True):
1799
+ """
1800
+ For all cards with index above idx, increment or decrement its index
1801
+ value in the keyword_indices dict.
1802
+ """
1803
+ if idx > len(self._cards):
1804
+ # Save us some effort
1805
+ return
1806
+
1807
+ increment = 1 if increment else -1
1808
+
1809
+ for index_sets in (self._keyword_indices, self._rvkc_indices):
1810
+ for indices in index_sets.values():
1811
+ for jdx, keyword_index in enumerate(indices):
1812
+ if keyword_index >= idx:
1813
+ indices[jdx] += increment
1814
+
1815
+ def _countblanks(self):
1816
+ """Returns the number of blank cards at the end of the Header."""
1817
+
1818
+ for idx in range(1, len(self._cards)):
1819
+ if not self._cards[-idx].is_blank:
1820
+ return idx - 1
1821
+ return 0
1822
+
1823
+ def _useblanks(self, count):
1824
+ for _ in range(count):
1825
+ if self._cards[-1].is_blank:
1826
+ del self[-1]
1827
+ else:
1828
+ break
1829
+
1830
+ def _haswildcard(self, keyword):
1831
+ """Return `True` if the input keyword contains a wildcard pattern."""
1832
+
1833
+ return (isinstance(keyword, str) and
1834
+ (keyword.endswith('...') or '*' in keyword or '?' in keyword))
1835
+
1836
+ def _wildcardmatch(self, pattern):
1837
+ """
1838
+ Returns a list of indices of the cards matching the given wildcard
1839
+ pattern.
1840
+
1841
+ * '*' matches 0 or more characters
1842
+ * '?' matches a single character
1843
+ * '...' matches 0 or more of any non-whitespace character
1844
+ """
1845
+
1846
+ pattern = pattern.replace('*', r'.*').replace('?', r'.')
1847
+ pattern = pattern.replace('...', r'\S*') + '$'
1848
+ pattern_re = re.compile(pattern, re.I)
1849
+
1850
+ return [idx for idx, card in enumerate(self._cards)
1851
+ if pattern_re.match(card.keyword)]
1852
+
1853
+ def _set_slice(self, key, value, target):
1854
+ """
1855
+ Used to implement Header.__setitem__ and CardAccessor.__setitem__.
1856
+ """
1857
+
1858
+ if isinstance(key, slice) or self._haswildcard(key):
1859
+ if isinstance(key, slice):
1860
+ indices = range(*key.indices(len(target)))
1861
+ else:
1862
+ indices = self._wildcardmatch(key)
1863
+
1864
+ if isinstance(value, str) or not isiterable(value):
1865
+ value = itertools.repeat(value, len(indices))
1866
+
1867
+ for idx, val in zip(indices, value):
1868
+ target[idx] = val
1869
+
1870
+ return True
1871
+
1872
+ return False
1873
+
1874
+ def _splitcommentary(self, keyword, value):
1875
+ """
1876
+ Given a commentary keyword and value, returns a list of the one or more
1877
+ cards needed to represent the full value. This is primarily used to
1878
+ create the multiple commentary cards needed to represent a long value
1879
+ that won't fit into a single commentary card.
1880
+ """
1881
+
1882
+ # The maximum value in each card can be the maximum card length minus
1883
+ # the maximum key length (which can include spaces if they key length
1884
+ # less than 8
1885
+ maxlen = Card.length - KEYWORD_LENGTH
1886
+ valuestr = str(value)
1887
+
1888
+ if len(valuestr) <= maxlen:
1889
+ # The value can fit in a single card
1890
+ cards = [Card(keyword, value)]
1891
+ else:
1892
+ # The value must be split across multiple consecutive commentary
1893
+ # cards
1894
+ idx = 0
1895
+ cards = []
1896
+ while idx < len(valuestr):
1897
+ cards.append(Card(keyword, valuestr[idx:idx + maxlen]))
1898
+ idx += maxlen
1899
+ return cards
1900
+
1901
+ def _strip(self):
1902
+ """
1903
+ Strip cards specific to a certain kind of header.
1904
+
1905
+ Strip cards like ``SIMPLE``, ``BITPIX``, etc. so the rest of
1906
+ the header can be used to reconstruct another kind of header.
1907
+ """
1908
+
1909
+ # TODO: Previously this only deleted some cards specific to an HDU if
1910
+ # _hdutype matched that type. But it seemed simple enough to just
1911
+ # delete all desired cards anyways, and just ignore the KeyErrors if
1912
+ # they don't exist.
1913
+ # However, it might be desirable to make this extendable somehow--have
1914
+ # a way for HDU classes to specify some headers that are specific only
1915
+ # to that type, and should be removed otherwise.
1916
+
1917
+ if 'NAXIS' in self:
1918
+ naxis = self['NAXIS']
1919
+ else:
1920
+ naxis = 0
1921
+
1922
+ if 'TFIELDS' in self:
1923
+ tfields = self['TFIELDS']
1924
+ else:
1925
+ tfields = 0
1926
+
1927
+ for idx in range(naxis):
1928
+ try:
1929
+ del self['NAXIS' + str(idx + 1)]
1930
+ except KeyError:
1931
+ pass
1932
+
1933
+ for name in ('TFORM', 'TSCAL', 'TZERO', 'TNULL', 'TTYPE',
1934
+ 'TUNIT', 'TDISP', 'TDIM', 'THEAP', 'TBCOL'):
1935
+ for idx in range(tfields):
1936
+ try:
1937
+ del self[name + str(idx + 1)]
1938
+ except KeyError:
1939
+ pass
1940
+
1941
+ for name in ('SIMPLE', 'XTENSION', 'BITPIX', 'NAXIS', 'EXTEND',
1942
+ 'PCOUNT', 'GCOUNT', 'GROUPS', 'BSCALE', 'BZERO',
1943
+ 'TFIELDS'):
1944
+ try:
1945
+ del self[name]
1946
+ except KeyError:
1947
+ pass
1948
+
1949
+ def _add_commentary(self, key, value, before=None, after=None):
1950
+ """
1951
+ Add a commentary card.
1952
+
1953
+ If ``before`` and ``after`` are `None`, add to the last occurrence
1954
+ of cards of the same name (except blank card). If there is no
1955
+ card (or blank card), append at the end.
1956
+ """
1957
+
1958
+ if before is not None or after is not None:
1959
+ self._relativeinsert((key, value), before=before,
1960
+ after=after)
1961
+ else:
1962
+ self[key] = value
1963
+
1964
+
1965
+ collections.abc.MutableSequence.register(Header)
1966
+ collections.abc.MutableMapping.register(Header)
1967
+
1968
+
1969
+ class _DelayedHeader:
1970
+ """
1971
+ Descriptor used to create the Header object from the header string that
1972
+ was stored in HDU._header_str when parsing the file.
1973
+ """
1974
+
1975
+ def __get__(self, obj, owner=None):
1976
+ try:
1977
+ return obj.__dict__['_header']
1978
+ except KeyError:
1979
+ if obj._header_str is not None:
1980
+ hdr = Header.fromstring(obj._header_str)
1981
+ obj._header_str = None
1982
+ else:
1983
+ raise AttributeError("'{}' object has no attribute '_header'"
1984
+ .format(obj.__class__.__name__))
1985
+
1986
+ obj.__dict__['_header'] = hdr
1987
+ return hdr
1988
+
1989
+ def __set__(self, obj, val):
1990
+ obj.__dict__['_header'] = val
1991
+
1992
+ def __delete__(self, obj):
1993
+ del obj.__dict__['_header']
1994
+
1995
+
1996
+ class _BasicHeaderCards:
1997
+ """
1998
+ This class allows to access cards with the _BasicHeader.cards attribute.
1999
+
2000
+ This is needed because during the HDU class detection, some HDUs uses
2001
+ the .cards interface. Cards cannot be modified here as the _BasicHeader
2002
+ object will be deleted once the HDU object is created.
2003
+
2004
+ """
2005
+
2006
+ def __init__(self, header):
2007
+ self.header = header
2008
+
2009
+ def __getitem__(self, key):
2010
+ # .cards is a list of cards, so key here is an integer.
2011
+ # get the keyword name from its index.
2012
+ key = self.header._keys[key]
2013
+ # then we get the card from the _BasicHeader._cards list, or parse it
2014
+ # if needed.
2015
+ try:
2016
+ return self.header._cards[key]
2017
+ except KeyError:
2018
+ cardstr = self.header._raw_cards[key]
2019
+ card = Card.fromstring(cardstr)
2020
+ self.header._cards[key] = card
2021
+ return card
2022
+
2023
+
2024
+ class _BasicHeader(collections.abc.Mapping):
2025
+ """This class provides a fast header parsing, without all the additional
2026
+ features of the Header class. Here only standard keywords are parsed, no
2027
+ support for CONTINUE, HIERARCH, COMMENT, HISTORY, or rvkc.
2028
+
2029
+ The raw card images are stored and parsed only if needed. The idea is that
2030
+ to create the HDU objects, only a small subset of standard cards is needed.
2031
+ Once a card is parsed, which is deferred to the Card class, the Card object
2032
+ is kept in a cache. This is useful because a small subset of cards is used
2033
+ a lot in the HDU creation process (NAXIS, XTENSION, ...).
2034
+
2035
+ """
2036
+
2037
+ def __init__(self, cards):
2038
+ # dict of (keywords, card images)
2039
+ self._raw_cards = cards
2040
+ self._keys = list(cards.keys())
2041
+ # dict of (keyword, Card object) storing the parsed cards
2042
+ self._cards = {}
2043
+ # the _BasicHeaderCards object allows to access Card objects from
2044
+ # keyword indices
2045
+ self.cards = _BasicHeaderCards(self)
2046
+
2047
+ self._modified = False
2048
+
2049
+ def __getitem__(self, key):
2050
+ if isinstance(key, int):
2051
+ key = self._keys[key]
2052
+
2053
+ try:
2054
+ return self._cards[key].value
2055
+ except KeyError:
2056
+ # parse the Card and store it
2057
+ cardstr = self._raw_cards[key]
2058
+ self._cards[key] = card = Card.fromstring(cardstr)
2059
+ return card.value
2060
+
2061
+ def __len__(self):
2062
+ return len(self._raw_cards)
2063
+
2064
+ def __iter__(self):
2065
+ return iter(self._raw_cards)
2066
+
2067
+ def index(self, keyword):
2068
+ return self._keys.index(keyword)
2069
+
2070
+ @classmethod
2071
+ def fromfile(cls, fileobj):
2072
+ """The main method to parse a FITS header from a file. The parsing is
2073
+ done with the parse_header function implemented in Cython."""
2074
+
2075
+ close_file = False
2076
+ if isinstance(fileobj, str):
2077
+ fileobj = open(fileobj, 'rb')
2078
+ close_file = True
2079
+
2080
+ try:
2081
+ header_str, cards = parse_header(fileobj)
2082
+ _check_padding(header_str, BLOCK_SIZE, False)
2083
+ return header_str, cls(cards)
2084
+ finally:
2085
+ if close_file:
2086
+ fileobj.close()
2087
+
2088
+
2089
+ class _CardAccessor:
2090
+ """
2091
+ This is a generic class for wrapping a Header in such a way that you can
2092
+ use the header's slice/filtering capabilities to return a subset of cards
2093
+ and do something with them.
2094
+
2095
+ This is sort of the opposite notion of the old CardList class--whereas
2096
+ Header used to use CardList to get lists of cards, this uses Header to get
2097
+ lists of cards.
2098
+ """
2099
+
2100
+ # TODO: Consider giving this dict/list methods like Header itself
2101
+ def __init__(self, header):
2102
+ self._header = header
2103
+
2104
+ def __repr__(self):
2105
+ return '\n'.join(repr(c) for c in self._header._cards)
2106
+
2107
+ def __len__(self):
2108
+ return len(self._header._cards)
2109
+
2110
+ def __iter__(self):
2111
+ return iter(self._header._cards)
2112
+
2113
+ def __eq__(self, other):
2114
+ # If the `other` item is a scalar we will still treat it as equal if
2115
+ # this _CardAccessor only contains one item
2116
+ if not isiterable(other) or isinstance(other, str):
2117
+ if len(self) == 1:
2118
+ other = [other]
2119
+ else:
2120
+ return False
2121
+
2122
+ for a, b in itertools.zip_longest(self, other):
2123
+ if a != b:
2124
+ return False
2125
+ else:
2126
+ return True
2127
+
2128
+ def __ne__(self, other):
2129
+ return not (self == other)
2130
+
2131
+ def __getitem__(self, item):
2132
+ if isinstance(item, slice) or self._header._haswildcard(item):
2133
+ return self.__class__(self._header[item])
2134
+
2135
+ idx = self._header._cardindex(item)
2136
+ return self._header._cards[idx]
2137
+
2138
+ def _setslice(self, item, value):
2139
+ """
2140
+ Helper for implementing __setitem__ on _CardAccessor subclasses; slices
2141
+ should always be handled in this same way.
2142
+ """
2143
+
2144
+ if isinstance(item, slice) or self._header._haswildcard(item):
2145
+ if isinstance(item, slice):
2146
+ indices = range(*item.indices(len(self)))
2147
+ else:
2148
+ indices = self._header._wildcardmatch(item)
2149
+ if isinstance(value, str) or not isiterable(value):
2150
+ value = itertools.repeat(value, len(indices))
2151
+ for idx, val in zip(indices, value):
2152
+ self[idx] = val
2153
+ return True
2154
+ return False
2155
+
2156
+
2157
+ collections.abc.Mapping.register(_CardAccessor)
2158
+ collections.abc.Sequence.register(_CardAccessor)
2159
+
2160
+
2161
+ class _HeaderComments(_CardAccessor):
2162
+ """
2163
+ A class used internally by the Header class for the Header.comments
2164
+ attribute access.
2165
+
2166
+ This object can be used to display all the keyword comments in the Header,
2167
+ or look up the comments on specific keywords. It allows all the same forms
2168
+ of keyword lookup as the Header class itself, but returns comments instead
2169
+ of values.
2170
+ """
2171
+
2172
+ def __iter__(self):
2173
+ for card in self._header._cards:
2174
+ yield card.comment
2175
+
2176
+ def __repr__(self):
2177
+ """Returns a simple list of all keywords and their comments."""
2178
+
2179
+ keyword_length = KEYWORD_LENGTH
2180
+ for card in self._header._cards:
2181
+ keyword_length = max(keyword_length, len(card.keyword))
2182
+ return '\n'.join('{:>{len}} {}'.format(c.keyword, c.comment,
2183
+ len=keyword_length)
2184
+ for c in self._header._cards)
2185
+
2186
+ def __getitem__(self, item):
2187
+ """
2188
+ Slices and filter strings return a new _HeaderComments containing the
2189
+ returned cards. Otherwise the comment of a single card is returned.
2190
+ """
2191
+
2192
+ item = super().__getitem__(item)
2193
+ if isinstance(item, _HeaderComments):
2194
+ # The item key was a slice
2195
+ return item
2196
+ return item.comment
2197
+
2198
+ def __setitem__(self, item, comment):
2199
+ """
2200
+ Set/update the comment on specified card or cards.
2201
+
2202
+ Slice/filter updates work similarly to how Header.__setitem__ works.
2203
+ """
2204
+
2205
+ if self._header._set_slice(item, comment, self):
2206
+ return
2207
+
2208
+ # In this case, key/index errors should be raised; don't update
2209
+ # comments of nonexistent cards
2210
+ idx = self._header._cardindex(item)
2211
+ value = self._header[idx]
2212
+ self._header[idx] = (value, comment)
2213
+
2214
+
2215
+ class _HeaderCommentaryCards(_CardAccessor):
2216
+ """
2217
+ This is used to return a list-like sequence over all the values in the
2218
+ header for a given commentary keyword, such as HISTORY.
2219
+ """
2220
+
2221
+ def __init__(self, header, keyword=''):
2222
+ super().__init__(header)
2223
+ self._keyword = keyword
2224
+ self._count = self._header.count(self._keyword)
2225
+ self._indices = slice(self._count).indices(self._count)
2226
+
2227
+ # __len__ and __iter__ need to be overridden from the base class due to the
2228
+ # different approach this class has to take for slicing
2229
+ def __len__(self):
2230
+ return len(range(*self._indices))
2231
+
2232
+ def __iter__(self):
2233
+ for idx in range(*self._indices):
2234
+ yield self._header[(self._keyword, idx)]
2235
+
2236
+ def __repr__(self):
2237
+ return '\n'.join(self)
2238
+
2239
+ def __getitem__(self, idx):
2240
+ if isinstance(idx, slice):
2241
+ n = self.__class__(self._header, self._keyword)
2242
+ n._indices = idx.indices(self._count)
2243
+ return n
2244
+ elif not isinstance(idx, int):
2245
+ raise ValueError('{} index must be an integer'.format(self._keyword))
2246
+
2247
+ idx = list(range(*self._indices))[idx]
2248
+ return self._header[(self._keyword, idx)]
2249
+
2250
+ def __setitem__(self, item, value):
2251
+ """
2252
+ Set the value of a specified commentary card or cards.
2253
+
2254
+ Slice/filter updates work similarly to how Header.__setitem__ works.
2255
+ """
2256
+
2257
+ if self._header._set_slice(item, value, self):
2258
+ return
2259
+
2260
+ # In this case, key/index errors should be raised; don't update
2261
+ # comments of nonexistent cards
2262
+ self._header[(self._keyword, item)] = value
2263
+
2264
+
2265
+ def _block_size(sep):
2266
+ """
2267
+ Determine the size of a FITS header block if a non-blank separator is used
2268
+ between cards.
2269
+ """
2270
+
2271
+ return BLOCK_SIZE + (len(sep) * (BLOCK_SIZE // Card.length - 1))
2272
+
2273
+
2274
+ def _pad_length(stringlen):
2275
+ """Bytes needed to pad the input stringlen to the next FITS block."""
2276
+
2277
+ return (BLOCK_SIZE - (stringlen % BLOCK_SIZE)) % BLOCK_SIZE
2278
+
2279
+
2280
+ def _check_padding(header_str, block_size, is_eof, check_block_size=True):
2281
+ # Strip any zero-padding (see ticket #106)
2282
+ if header_str and header_str[-1] == '\0':
2283
+ if is_eof and header_str.strip('\0') == '':
2284
+ # TODO: Pass this warning to validation framework
2285
+ warnings.warn(
2286
+ 'Unexpected extra padding at the end of the file. This '
2287
+ 'padding may not be preserved when saving changes.',
2288
+ AstropyUserWarning)
2289
+ raise EOFError()
2290
+ else:
2291
+ # Replace the illegal null bytes with spaces as required by
2292
+ # the FITS standard, and issue a nasty warning
2293
+ # TODO: Pass this warning to validation framework
2294
+ warnings.warn(
2295
+ 'Header block contains null bytes instead of spaces for '
2296
+ 'padding, and is not FITS-compliant. Nulls may be '
2297
+ 'replaced with spaces upon writing.', AstropyUserWarning)
2298
+ header_str.replace('\0', ' ')
2299
+
2300
+ if check_block_size and (len(header_str) % block_size) != 0:
2301
+ # This error message ignores the length of the separator for
2302
+ # now, but maybe it shouldn't?
2303
+ actual_len = len(header_str) - block_size + BLOCK_SIZE
2304
+ # TODO: Pass this error to validation framework
2305
+ raise ValueError('Header size is not multiple of {0}: {1}'
2306
+ .format(BLOCK_SIZE, actual_len))
testbed/astropy__astropy/astropy/io/fits/scripts/fitscheck.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+ """
3
+ ``fitscheck`` is a command line script based on astropy.io.fits for verifying
4
+ and updating the CHECKSUM and DATASUM keywords of .fits files. ``fitscheck``
5
+ can also detect and often fix other FITS standards violations. ``fitscheck``
6
+ facilitates re-writing the non-standard checksums originally generated by
7
+ astropy.io.fits with standard checksums which will interoperate with CFITSIO.
8
+
9
+ ``fitscheck`` will refuse to write new checksums if the checksum keywords are
10
+ missing or their values are bad. Use ``--force`` to write new checksums
11
+ regardless of whether or not they currently exist or pass. Use
12
+ ``--ignore-missing`` to tolerate missing checksum keywords without comment.
13
+
14
+ Example uses of fitscheck:
15
+
16
+ 1. Add checksums::
17
+
18
+ $ fitscheck --write *.fits
19
+
20
+ 2. Write new checksums, even if existing checksums are bad or missing::
21
+
22
+ $ fitscheck --write --force *.fits
23
+
24
+ 3. Verify standard checksums and FITS compliance without changing the files::
25
+
26
+ $ fitscheck --compliance *.fits
27
+
28
+ 4. Only check and fix compliance problems, ignoring checksums::
29
+
30
+ $ fitscheck --checksum none --compliance --write *.fits
31
+
32
+ 5. Verify standard interoperable checksums::
33
+
34
+ $ fitscheck *.fits
35
+
36
+ 6. Delete checksum keywords::
37
+
38
+ $ fitscheck --checksum remove --write *.fits
39
+
40
+ """
41
+
42
+
43
+ import logging
44
+ import optparse
45
+ import sys
46
+ import textwrap
47
+
48
+ from astropy.tests.helper import catch_warnings
49
+ from astropy.io import fits
50
+
51
+
52
+ log = logging.getLogger('fitscheck')
53
+
54
+
55
+ def handle_options(args):
56
+ if not len(args):
57
+ args = ['-h']
58
+
59
+ parser = optparse.OptionParser(usage=textwrap.dedent("""
60
+ fitscheck [options] <.fits files...>
61
+
62
+ .e.g. fitscheck example.fits
63
+
64
+ Verifies and optionally re-writes the CHECKSUM and DATASUM keywords
65
+ for a .fits file.
66
+ Optionally detects and fixes FITS standard compliance problems.
67
+ """.strip()))
68
+
69
+ parser.add_option(
70
+ '-k', '--checksum', dest='checksum_kind',
71
+ type='choice', choices=['standard', 'remove', 'none'],
72
+ help='Choose FITS checksum mode or none. Defaults standard.',
73
+ default='standard', metavar='[standard | remove | none]')
74
+
75
+ parser.add_option(
76
+ '-w', '--write', dest='write_file',
77
+ help='Write out file checksums and/or FITS compliance fixes.',
78
+ default=False, action='store_true')
79
+
80
+ parser.add_option(
81
+ '-f', '--force', dest='force',
82
+ help='Do file update even if original checksum was bad.',
83
+ default=False, action='store_true')
84
+
85
+ parser.add_option(
86
+ '-c', '--compliance', dest='compliance',
87
+ help='Do FITS compliance checking; fix if possible.',
88
+ default=False, action='store_true')
89
+
90
+ parser.add_option(
91
+ '-i', '--ignore-missing', dest='ignore_missing',
92
+ help='Ignore missing checksums.',
93
+ default=False, action='store_true')
94
+
95
+ parser.add_option(
96
+ '-v', '--verbose', dest='verbose', help='Generate extra output.',
97
+ default=False, action='store_true')
98
+
99
+ global OPTIONS
100
+ OPTIONS, fits_files = parser.parse_args(args)
101
+
102
+ if OPTIONS.checksum_kind == 'none':
103
+ OPTIONS.checksum_kind = False
104
+ elif OPTIONS.checksum_kind == 'remove':
105
+ OPTIONS.write_file = True
106
+ OPTIONS.force = True
107
+
108
+ return fits_files
109
+
110
+
111
+ def setup_logging():
112
+ if OPTIONS.verbose:
113
+ log.setLevel(logging.INFO)
114
+ else:
115
+ log.setLevel(logging.WARNING)
116
+
117
+ handler = logging.StreamHandler()
118
+ handler.setFormatter(logging.Formatter('%(message)s'))
119
+ log.addHandler(handler)
120
+
121
+
122
+ def verify_checksums(filename):
123
+ """
124
+ Prints a message if any HDU in `filename` has a bad checksum or datasum.
125
+ """
126
+
127
+ with catch_warnings() as wlist:
128
+ with fits.open(filename, checksum=OPTIONS.checksum_kind) as hdulist:
129
+ for i, hdu in enumerate(hdulist):
130
+ # looping on HDUs is needed to read them and verify the
131
+ # checksums
132
+ if not OPTIONS.ignore_missing:
133
+ if not hdu._checksum:
134
+ log.warning('MISSING {!r} .. Checksum not found '
135
+ 'in HDU #{}'.format(filename, i))
136
+ return 1
137
+ if not hdu._datasum:
138
+ log.warning('MISSING {!r} .. Datasum not found '
139
+ 'in HDU #{}'.format(filename, i))
140
+ return 1
141
+
142
+ for w in wlist:
143
+ if str(w.message).startswith(('Checksum verification failed',
144
+ 'Datasum verification failed')):
145
+ log.warning('BAD %r %s', filename, str(w.message))
146
+ return 1
147
+
148
+ log.info('OK {!r}'.format(filename))
149
+ return 0
150
+
151
+
152
+ def verify_compliance(filename):
153
+ """Check for FITS standard compliance."""
154
+
155
+ with fits.open(filename) as hdulist:
156
+ try:
157
+ hdulist.verify('exception')
158
+ except fits.VerifyError as exc:
159
+ log.warning('NONCOMPLIANT %r .. %s',
160
+ filename, str(exc).replace('\n', ' '))
161
+ return 1
162
+ return 0
163
+
164
+
165
+ def update(filename):
166
+ """
167
+ Sets the ``CHECKSUM`` and ``DATASUM`` keywords for each HDU of `filename`.
168
+
169
+ Also updates fixes standards violations if possible and requested.
170
+ """
171
+
172
+ output_verify = 'silentfix' if OPTIONS.compliance else 'ignore'
173
+ with fits.open(filename, do_not_scale_image_data=True,
174
+ checksum=OPTIONS.checksum_kind, mode='update') as hdulist:
175
+ hdulist.flush(output_verify=output_verify)
176
+
177
+
178
+ def process_file(filename):
179
+ """
180
+ Handle a single .fits file, returning the count of checksum and compliance
181
+ errors.
182
+ """
183
+
184
+ try:
185
+ checksum_errors = verify_checksums(filename)
186
+ if OPTIONS.compliance:
187
+ compliance_errors = verify_compliance(filename)
188
+ else:
189
+ compliance_errors = 0
190
+ if OPTIONS.write_file and checksum_errors == 0 or OPTIONS.force:
191
+ update(filename)
192
+ return checksum_errors + compliance_errors
193
+ except Exception as e:
194
+ log.error('EXCEPTION {!r} .. {}'.format(filename, e))
195
+ return 1
196
+
197
+
198
+ def main(args=None):
199
+ """
200
+ Processes command line parameters into options and files, then checks
201
+ or update FITS DATASUM and CHECKSUM keywords for the specified files.
202
+ """
203
+
204
+ errors = 0
205
+ fits_files = handle_options(args or sys.argv[1:])
206
+ setup_logging()
207
+ for filename in fits_files:
208
+ errors += process_file(filename)
209
+ if errors:
210
+ log.warning('{} errors'.format(errors))
211
+ return int(bool(errors))
testbed/astropy__astropy/astropy/io/fits/scripts/fitsheader.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+ """
3
+ ``fitsheader`` is a command line script based on astropy.io.fits for printing
4
+ the header(s) of one or more FITS file(s) to the standard output in a human-
5
+ readable format.
6
+
7
+ Example uses of fitsheader:
8
+
9
+ 1. Print the header of all the HDUs of a .fits file::
10
+
11
+ $ fitsheader filename.fits
12
+
13
+ 2. Print the header of the third and fifth HDU extension::
14
+
15
+ $ fitsheader --extension 3 --extension 5 filename.fits
16
+
17
+ 3. Print the header of a named extension, e.g. select the HDU containing
18
+ keywords EXTNAME='SCI' and EXTVER='2'::
19
+
20
+ $ fitsheader --extension "SCI,2" filename.fits
21
+
22
+ 4. Print only specific keywords::
23
+
24
+ $ fitsheader --keyword BITPIX --keyword NAXIS filename.fits
25
+
26
+ 5. Print keywords NAXIS, NAXIS1, NAXIS2, etc using a wildcard::
27
+
28
+ $ fitsheader --keyword NAXIS* filename.fits
29
+
30
+ 6. Dump the header keywords of all the files in the current directory into a
31
+ machine-readable csv file::
32
+
33
+ $ fitsheader --table ascii.csv *.fits > keywords.csv
34
+
35
+ 7. Specify hierarchical keywords with the dotted or spaced notation::
36
+
37
+ $ fitsheader --keyword ESO.INS.ID filename.fits
38
+ $ fitsheader --keyword "ESO INS ID" filename.fits
39
+
40
+ 8. Compare the headers of different fites files, following ESO's ``fitsort``
41
+ format::
42
+
43
+ $ fitsheader --fitsort --extension 0 --keyword ESO.INS.ID *.fits
44
+
45
+ 9. Same as above, sorting the output along a specified keyword::
46
+
47
+ $ fitsheader -f DATE-OBS -e 0 -k DATE-OBS -k ESO.INS.ID *.fits
48
+
49
+ Note that compressed images (HDUs of type
50
+ :class:`~astropy.io.fits.CompImageHDU`) really have two headers: a real
51
+ BINTABLE header to describe the compressed data, and a fake IMAGE header
52
+ representing the image that was compressed. Astropy returns the latter by
53
+ default. You must supply the ``--compressed`` option if you require the real
54
+ header that describes the compression.
55
+
56
+ With Astropy installed, please run ``fitsheader --help`` to see the full usage
57
+ documentation.
58
+ """
59
+
60
+ import sys
61
+ import argparse
62
+
63
+ import numpy as np
64
+
65
+ from astropy.io import fits
66
+ from astropy import log
67
+
68
+
69
+ class ExtensionNotFoundException(Exception):
70
+ """Raised if an HDU extension requested by the user does not exist."""
71
+ pass
72
+
73
+
74
+ class HeaderFormatter:
75
+ """Class to format the header(s) of a FITS file for display by the
76
+ `fitsheader` tool; essentially a wrapper around a `HDUList` object.
77
+
78
+ Example usage:
79
+ fmt = HeaderFormatter('/path/to/file.fits')
80
+ print(fmt.parse(extensions=[0, 3], keywords=['NAXIS', 'BITPIX']))
81
+
82
+ Parameters
83
+ ----------
84
+ filename : str
85
+ Path to a single FITS file.
86
+ verbose : bool
87
+ Verbose flag, to show more information about missing extensions,
88
+ keywords, etc.
89
+
90
+ Raises
91
+ ------
92
+ OSError
93
+ If `filename` does not exist or cannot be read.
94
+ """
95
+
96
+ def __init__(self, filename, verbose=True):
97
+ self.filename = filename
98
+ self.verbose = verbose
99
+ self._hdulist = fits.open(filename)
100
+
101
+ def parse(self, extensions=None, keywords=None, compressed=False):
102
+ """Returns the FITS file header(s) in a readable format.
103
+
104
+ Parameters
105
+ ----------
106
+ extensions : list of int or str, optional
107
+ Format only specific HDU(s), identified by number or name.
108
+ The name can be composed of the "EXTNAME" or "EXTNAME,EXTVER"
109
+ keywords.
110
+
111
+ keywords : list of str, optional
112
+ Keywords for which the value(s) should be returned.
113
+ If not specified, then the entire header is returned.
114
+
115
+ compressed : boolean, optional
116
+ If True, shows the header describing the compression, rather than
117
+ the header obtained after decompression. (Affects FITS files
118
+ containing `CompImageHDU` extensions only.)
119
+
120
+ Returns
121
+ -------
122
+ formatted_header : str or astropy.table.Table
123
+ Traditional 80-char wide format in the case of `HeaderFormatter`;
124
+ an Astropy Table object in the case of `TableHeaderFormatter`.
125
+ """
126
+ # `hdukeys` will hold the keys of the HDUList items to display
127
+ if extensions is None:
128
+ hdukeys = range(len(self._hdulist)) # Display all by default
129
+ else:
130
+ hdukeys = []
131
+ for ext in extensions:
132
+ try:
133
+ # HDU may be specified by number
134
+ hdukeys.append(int(ext))
135
+ except ValueError:
136
+ # The user can specify "EXTNAME" or "EXTNAME,EXTVER"
137
+ parts = ext.split(',')
138
+ if len(parts) > 1:
139
+ extname = ','.join(parts[0:-1])
140
+ extver = int(parts[-1])
141
+ hdukeys.append((extname, extver))
142
+ else:
143
+ hdukeys.append(ext)
144
+
145
+ # Having established which HDUs the user wants, we now format these:
146
+ return self._parse_internal(hdukeys, keywords, compressed)
147
+
148
+ def _parse_internal(self, hdukeys, keywords, compressed):
149
+ """The meat of the formatting; in a separate method to allow overriding.
150
+ """
151
+ result = []
152
+ for idx, hdu in enumerate(hdukeys):
153
+ try:
154
+ cards = self._get_cards(hdu, keywords, compressed)
155
+ except ExtensionNotFoundException:
156
+ continue
157
+
158
+ if idx > 0: # Separate HDUs by a blank line
159
+ result.append('\n')
160
+ result.append('# HDU {} in {}:\n'.format(hdu, self.filename))
161
+ for c in cards:
162
+ result.append('{}\n'.format(c))
163
+ return ''.join(result)
164
+
165
+ def _get_cards(self, hdukey, keywords, compressed):
166
+ """Returns a list of `astropy.io.fits.card.Card` objects.
167
+
168
+ This function will return the desired header cards, taking into
169
+ account the user's preference to see the compressed or uncompressed
170
+ version.
171
+
172
+ Parameters
173
+ ----------
174
+ hdukey : int or str
175
+ Key of a single HDU in the HDUList.
176
+
177
+ keywords : list of str, optional
178
+ Keywords for which the cards should be returned.
179
+
180
+ compressed : boolean, optional
181
+ If True, shows the header describing the compression.
182
+
183
+ Raises
184
+ ------
185
+ ExtensionNotFoundException
186
+ If the hdukey does not correspond to an extension.
187
+ """
188
+ # First we obtain the desired header
189
+ try:
190
+ if compressed:
191
+ # In the case of a compressed image, return the header before
192
+ # decompression (not the default behavior)
193
+ header = self._hdulist[hdukey]._header
194
+ else:
195
+ header = self._hdulist[hdukey].header
196
+ except (IndexError, KeyError):
197
+ message = '{0}: Extension {1} not found.'.format(self.filename,
198
+ hdukey)
199
+ if self.verbose:
200
+ log.warning(message)
201
+ raise ExtensionNotFoundException(message)
202
+
203
+ if not keywords: # return all cards
204
+ cards = header.cards
205
+ else: # specific keywords are requested
206
+ cards = []
207
+ for kw in keywords:
208
+ try:
209
+ crd = header.cards[kw]
210
+ if isinstance(crd, fits.card.Card): # Single card
211
+ cards.append(crd)
212
+ else: # Allow for wildcard access
213
+ cards.extend(crd)
214
+ except KeyError as e: # Keyword does not exist
215
+ if self.verbose:
216
+ log.warning('{filename} (HDU {hdukey}): '
217
+ 'Keyword {kw} not found.'.format(
218
+ filename=self.filename,
219
+ hdukey=hdukey,
220
+ kw=kw))
221
+ return cards
222
+
223
+ def close(self):
224
+ self._hdulist.close()
225
+
226
+
227
+ class TableHeaderFormatter(HeaderFormatter):
228
+ """Class to convert the header(s) of a FITS file into a Table object.
229
+ The table returned by the `parse` method will contain four columns:
230
+ filename, hdu, keyword, and value.
231
+
232
+ Subclassed from HeaderFormatter, which contains the meat of the formatting.
233
+ """
234
+
235
+ def _parse_internal(self, hdukeys, keywords, compressed):
236
+ """Method called by the parse method in the parent class."""
237
+ tablerows = []
238
+ for hdu in hdukeys:
239
+ try:
240
+ for card in self._get_cards(hdu, keywords, compressed):
241
+ tablerows.append({'filename': self.filename,
242
+ 'hdu': hdu,
243
+ 'keyword': card.keyword,
244
+ 'value': str(card.value)})
245
+ except ExtensionNotFoundException:
246
+ pass
247
+
248
+ if tablerows:
249
+ from astropy import table
250
+ return table.Table(tablerows)
251
+ return None
252
+
253
+
254
+ def print_headers_traditional(args):
255
+ """Prints FITS header(s) using the traditional 80-char format.
256
+
257
+ Parameters
258
+ ----------
259
+ args : argparse.Namespace
260
+ Arguments passed from the command-line as defined below.
261
+ """
262
+ for idx, filename in enumerate(args.filename): # support wildcards
263
+ if idx > 0 and not args.keywords:
264
+ print() # print a newline between different files
265
+
266
+ formatter = None
267
+ try:
268
+ formatter = HeaderFormatter(filename)
269
+ print(formatter.parse(args.extensions,
270
+ args.keywords,
271
+ args.compressed), end='')
272
+ except OSError as e:
273
+ log.error(str(e))
274
+ finally:
275
+ if formatter:
276
+ formatter.close()
277
+
278
+
279
+ def print_headers_as_table(args):
280
+ """Prints FITS header(s) in a machine-readable table format.
281
+
282
+ Parameters
283
+ ----------
284
+ args : argparse.Namespace
285
+ Arguments passed from the command-line as defined below.
286
+ """
287
+ tables = []
288
+ # Create a Table object for each file
289
+ for filename in args.filename: # Support wildcards
290
+ formatter = None
291
+ try:
292
+ formatter = TableHeaderFormatter(filename)
293
+ tbl = formatter.parse(args.extensions,
294
+ args.keywords,
295
+ args.compressed)
296
+ if tbl:
297
+ tables.append(tbl)
298
+ except OSError as e:
299
+ log.error(str(e)) # file not found or unreadable
300
+ finally:
301
+ if formatter:
302
+ formatter.close()
303
+
304
+ # Concatenate the tables
305
+ if len(tables) == 0:
306
+ return False
307
+ elif len(tables) == 1:
308
+ resulting_table = tables[0]
309
+ else:
310
+ from astropy import table
311
+ resulting_table = table.vstack(tables)
312
+ # Print the string representation of the concatenated table
313
+ resulting_table.write(sys.stdout, format=args.table)
314
+
315
+
316
+ def print_headers_as_comparison(args):
317
+ """Prints FITS header(s) with keywords as columns.
318
+
319
+ This follows the dfits+fitsort format.
320
+
321
+ Parameters
322
+ ----------
323
+ args : argparse.Namespace
324
+ Arguments passed from the command-line as defined below.
325
+ """
326
+ from astropy import table
327
+ tables = []
328
+ # Create a Table object for each file
329
+ for filename in args.filename: # Support wildcards
330
+ formatter = None
331
+ try:
332
+ formatter = TableHeaderFormatter(filename, verbose=False)
333
+ tbl = formatter.parse(args.extensions,
334
+ args.keywords,
335
+ args.compressed)
336
+ if tbl:
337
+ # Remove empty keywords
338
+ tbl = tbl[np.where(tbl['keyword'] != '')]
339
+ else:
340
+ tbl = table.Table([[filename]], names=('filename',))
341
+ tables.append(tbl)
342
+ except OSError as e:
343
+ log.error(str(e)) # file not found or unreadable
344
+ finally:
345
+ if formatter:
346
+ formatter.close()
347
+
348
+ # Concatenate the tables
349
+ if len(tables) == 0:
350
+ return False
351
+ elif len(tables) == 1:
352
+ resulting_table = tables[0]
353
+ else:
354
+ resulting_table = table.vstack(tables)
355
+
356
+ # If we obtained more than one hdu, merge hdu and keywords columns
357
+ hdus = resulting_table['hdu']
358
+ if np.ma.isMaskedArray(hdus):
359
+ hdus = hdus.compressed()
360
+ if len(np.unique(hdus)) > 1:
361
+ for tab in tables:
362
+ new_column = table.Column(
363
+ ['{}:{}'.format(row['hdu'], row['keyword']) for row in tab])
364
+ tab.add_column(new_column, name='hdu+keyword')
365
+ keyword_column_name = 'hdu+keyword'
366
+ else:
367
+ keyword_column_name = 'keyword'
368
+
369
+ # Check how many hdus we are processing
370
+ final_tables = []
371
+ for tab in tables:
372
+ final_table = [table.Column([tab['filename'][0]], name='filename')]
373
+ if 'value' in tab.colnames:
374
+ for row in tab:
375
+ if row['keyword'] in ('COMMENT', 'HISTORY'):
376
+ continue
377
+ final_table.append(table.Column([row['value']],
378
+ name=row[keyword_column_name]))
379
+ final_tables.append(table.Table(final_table))
380
+ final_table = table.vstack(final_tables)
381
+ # Sort if requested
382
+ if args.fitsort is not True: # then it must be a keyword, therefore sort
383
+ final_table.sort(args.fitsort)
384
+ # Reorganise to keyword by columns
385
+ final_table.pprint(max_lines=-1, max_width=-1)
386
+
387
+
388
+ class KeywordAppendAction(argparse.Action):
389
+ def __call__(self, parser, namespace, values, option_string=None):
390
+ keyword = values.replace('.', ' ')
391
+ if namespace.keywords is None:
392
+ namespace.keywords = []
393
+ if keyword not in namespace.keywords:
394
+ namespace.keywords.append(keyword)
395
+
396
+
397
+ def main(args=None):
398
+ """This is the main function called by the `fitsheader` script."""
399
+
400
+ parser = argparse.ArgumentParser(
401
+ description=('Print the header(s) of a FITS file. '
402
+ 'Optional arguments allow the desired extension(s), '
403
+ 'keyword(s), and output format to be specified. '
404
+ 'Note that in the case of a compressed image, '
405
+ 'the decompressed header is shown by default.'))
406
+ parser.add_argument('-e', '--extension', metavar='HDU',
407
+ action='append', dest='extensions',
408
+ help='specify the extension by name or number; '
409
+ 'this argument can be repeated '
410
+ 'to select multiple extensions')
411
+ parser.add_argument('-k', '--keyword', metavar='KEYWORD',
412
+ action=KeywordAppendAction, dest='keywords',
413
+ help='specify a keyword; this argument can be '
414
+ 'repeated to select multiple keywords; '
415
+ 'also supports wildcards')
416
+ parser.add_argument('-t', '--table',
417
+ nargs='?', default=False, metavar='FORMAT',
418
+ help='print the header(s) in machine-readable table '
419
+ 'format; the default format is '
420
+ '"ascii.fixed_width" (can be "ascii.csv", '
421
+ '"ascii.html", "ascii.latex", "fits", etc)')
422
+ parser.add_argument('-f', '--fitsort', action='store_true',
423
+ help='print the headers as a table with each unique '
424
+ 'keyword in a given column (fitsort format); '
425
+ 'if a SORT_KEYWORD is specified, the result will be '
426
+ 'sorted along that keyword')
427
+ parser.add_argument('-c', '--compressed', action='store_true',
428
+ help='for compressed image data, '
429
+ 'show the true header which describes '
430
+ 'the compression rather than the data')
431
+ parser.add_argument('filename', nargs='+',
432
+ help='path to one or more files; '
433
+ 'wildcards are supported')
434
+ args = parser.parse_args(args)
435
+
436
+ # If `--table` was used but no format specified,
437
+ # then use ascii.fixed_width by default
438
+ if args.table is None:
439
+ args.table = 'ascii.fixed_width'
440
+
441
+ # Now print the desired headers
442
+ try:
443
+ if args.table:
444
+ print_headers_as_table(args)
445
+ elif args.fitsort:
446
+ print_headers_as_comparison(args)
447
+ else:
448
+ print_headers_traditional(args)
449
+ except OSError as e:
450
+ # A 'Broken pipe' OSError may occur when stdout is closed prematurely,
451
+ # eg. when calling `fitsheader file.fits | head`. We let this pass.
452
+ pass
testbed/astropy__astropy/astropy/io/fits/setup_package.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import os
4
+
5
+ from distutils.core import Extension
6
+ from glob import glob
7
+
8
+ from astropy_helpers import setup_helpers
9
+ from astropy_helpers.distutils_helpers import get_distutils_build_option
10
+
11
+
12
+ def _get_compression_extension():
13
+ # 'numpy' will be replaced with the proper path to the numpy includes
14
+ cfg = setup_helpers.DistutilsExtensionArgs()
15
+ cfg['include_dirs'].append('numpy')
16
+ cfg['sources'].append(os.path.join(os.path.dirname(__file__), 'src',
17
+ 'compressionmodule.c'))
18
+
19
+ if not setup_helpers.use_system_library('cfitsio'):
20
+ if setup_helpers.get_compiler_option() == 'msvc':
21
+ # These come from the CFITSIO vcc makefile, except the last
22
+ # which ensures on windows we do not include unistd.h (in regular
23
+ # compilation of cfitsio, an empty file would be generated)
24
+ cfg['extra_compile_args'].extend(
25
+ ['/D', '"WIN32"',
26
+ '/D', '"_WINDOWS"',
27
+ '/D', '"_MBCS"',
28
+ '/D', '"_USRDLL"',
29
+ '/D', '"_CRT_SECURE_NO_DEPRECATE"',
30
+ '/D', '"FF_NO_UNISTD_H"'])
31
+ else:
32
+ cfg['extra_compile_args'].extend([
33
+ '-Wno-declaration-after-statement'
34
+ ])
35
+
36
+ if not get_distutils_build_option('debug'):
37
+ # these switches are to silence warnings from compiling CFITSIO
38
+ # For full silencing, some are added that only are used in
39
+ # later versions of gcc (versions approximate; see #6474)
40
+ cfg['extra_compile_args'].extend([
41
+ '-Wno-strict-prototypes',
42
+ '-Wno-unused',
43
+ '-Wno-uninitialized',
44
+ '-Wno-unused-result', # gcc >~4.8
45
+ '-Wno-misleading-indentation', # gcc >~7.2
46
+ '-Wno-format-overflow', # gcc >~7.2
47
+ ])
48
+
49
+ cfitsio_lib_path = os.path.join('cextern', 'cfitsio', 'lib')
50
+ cfitsio_zlib_path = os.path.join('cextern', 'cfitsio', 'zlib')
51
+ cfitsio_files = glob(os.path.join(cfitsio_lib_path, '*.c'))
52
+ cfitsio_zlib_files = glob(os.path.join(cfitsio_zlib_path, '*.c'))
53
+ cfg['include_dirs'].append(cfitsio_lib_path)
54
+ cfg['include_dirs'].append(cfitsio_zlib_path)
55
+ cfg['sources'].extend(cfitsio_files)
56
+ cfg['sources'].extend(cfitsio_zlib_files)
57
+ else:
58
+ cfg.update(setup_helpers.pkg_config(['cfitsio'], ['cfitsio']))
59
+
60
+ return Extension('astropy.io.fits.compression', **cfg)
61
+
62
+
63
+ def get_extensions():
64
+ return [_get_compression_extension()]
65
+
66
+
67
+ def get_external_libraries():
68
+ return ['cfitsio']
testbed/astropy__astropy/astropy/io/fits/src/compressionmodule.c ADDED
@@ -0,0 +1,1323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* "compression module */
2
+
3
+ /*****************************************************************************/
4
+ /* */
5
+ /* The compression software is a python module implemented in C that, when */
6
+ /* accessed through the astropy module, supports the storage of compressed */
7
+ /* images in FITS binary tables. An n-dimensional image is divided into a */
8
+ /* rectangular grid of subimages or 'tiles'. Each tile is then compressed */
9
+ /* as a continuous block of data, and the resulting compressed byte stream */
10
+ /* is stored in a row of a variable length column in a FITS binary table. */
11
+ /* The default tiling pattern treates each row of a 2-dimensional image */
12
+ /* (or higher dimensional cube) as a tile, such that each tile contains */
13
+ /* NAXIS1 pixels. */
14
+ /* */
15
+ /* This module contains three functions that are callable from python. The */
16
+ /* first is compress_hdu. This function takes an */
17
+ /* astropy.io.fits.CompImageHDU object containing the uncompressed image */
18
+ /* data and returns the compressed data for all tiles into the */
19
+ /* .compressed_data attribute of that HDU. */
20
+ /* */
21
+ /* The second function is decompress_hdu. It takes an */
22
+ /* astropy.io.fits.CompImageHDU object that already has compressed data in */
23
+ /* its .compressed_data attribute. It returns the decompressed image data */
24
+ /* into the HDU's .data attribute. */
25
+ /* */
26
+ /* Copyright (C) 2013 Association of Universities for Research in Astronomy */
27
+ /* (AURA) */
28
+ /* */
29
+ /* Redistribution and use in source and binary forms, with or without */
30
+ /* modification, are permitted provided that the following conditions are */
31
+ /* met: */
32
+ /* */
33
+ /* 1. Redistributions of source code must retain the above copyright */
34
+ /* notice, this list of conditions and the following disclaimer. */
35
+ /* */
36
+ /* 2. Redistributions in binary form must reproduce the above */
37
+ /* copyright notice, this list of conditions and the following */
38
+ /* disclaimer in the documentation and/or other materials provided */
39
+ /* with the distribution. */
40
+ /* */
41
+ /* 3. The name of AURA and its representatives may not be used to */
42
+ /* endorse or promote products derived from this software without */
43
+ /* specific prior written permission. */
44
+ /* */
45
+ /* THIS SOFTWARE IS PROVIDED BY AURA ``AS IS'' AND ANY EXPRESS OR IMPLIED */
46
+ /* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
47
+ /* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
48
+ /* DISCLAIMED. IN NO EVENT SHALL AURA BE LIABLE FOR ANY DIRECT, INDIRECT, */
49
+ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */
50
+ /* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS */
51
+ /* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND */
52
+ /* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR */
53
+ /* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE */
54
+ /* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH */
55
+ /* DAMAGE. */
56
+ /* */
57
+ /* Some of the source code used by this module was copied and modified from */
58
+ /* the FITSIO software that was written by William Pence at the High Energy */
59
+ /* Astrophysic Science Archive Research Center (HEASARC) at the NASA Goddard */
60
+ /* Space Flight Center. That software contained the following copyright and */
61
+ /* warranty notices: */
62
+ /* */
63
+ /* Copyright (Unpublished--all rights reserved under the copyright laws of */
64
+ /* the United States), U.S. Government as represented by the Administrator */
65
+ /* of the National Aeronautics and Space Administration. No copyright is */
66
+ /* claimed in the United States under Title 17, U.S. Code. */
67
+ /* */
68
+ /* Permission to freely use, copy, modify, and distribute this software */
69
+ /* and its documentation without fee is hereby granted, provided that this */
70
+ /* copyright notice and disclaimer of warranty appears in all copies. */
71
+ /* */
72
+ /* DISCLAIMER: */
73
+ /* */
74
+ /* THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND, */
75
+ /* EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, */
76
+ /* ANY WARRANTY THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY */
77
+ /* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR */
78
+ /* PURPOSE, AND FREEDOM FROM INFRINGEMENT, AND ANY WARRANTY THAT THE */
79
+ /* DOCUMENTATION WILL CONFORM TO THE SOFTWARE, OR ANY WARRANTY THAT THE */
80
+ /* SOFTWARE WILL BE ERROR FREE. IN NO EVENT SHALL NASA BE LIABLE FOR ANY */
81
+ /* DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT, INDIRECT, SPECIAL OR */
82
+ /* CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, OR IN ANY WAY */
83
+ /* CONNECTED WITH THIS SOFTWARE, WHETHER OR NOT BASED UPON WARRANTY, */
84
+ /* CONTRACT, TORT , OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED BY */
85
+ /* PERSONS OR PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED */
86
+ /* FROM, OR AROSE OUT OF THE RESULTS OF, OR USE OF, THE SOFTWARE OR */
87
+ /* SERVICES PROVIDED HEREUNDER." */
88
+ /* */
89
+ /*****************************************************************************/
90
+
91
+ /* Include the Python C API */
92
+
93
+ #include <float.h>
94
+ #include <limits.h>
95
+ #include <math.h>
96
+ #include <string.h>
97
+
98
+ #include <Python.h>
99
+ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
100
+ #include <numpy/arrayobject.h>
101
+ #include <fitsio2.h>
102
+ #include "compressionmodule.h"
103
+
104
+
105
+ /* These defaults mirror the defaults in astropy.io.fits.hdu.compressed */
106
+ #define DEFAULT_COMPRESSION_TYPE "RICE_1"
107
+ #define DEFAULT_QUANTIZE_LEVEL 16.0
108
+ #define DEFAULT_HCOMP_SCALE 0
109
+ #define DEFAULT_HCOMP_SMOOTH 0
110
+ #define DEFAULT_BLOCK_SIZE 32
111
+ #define DEFAULT_BYTE_PIX 4
112
+
113
+ /* Flags to pass to get_header_* functions to control error messages. */
114
+ typedef enum {
115
+ HDR_NOFLAG = 0,
116
+ HDR_FAIL_KEY_MISSING = 1 << 0,
117
+ HDR_FAIL_VAL_NEGATIVE = 1 << 1,
118
+ } HeaderGetFlags;
119
+
120
+
121
+ /* Report any error based on the status returned from cfitsio. */
122
+ void process_status_err(int status)
123
+ {
124
+ PyObject* except_type;
125
+ char err_msg[81];
126
+ char def_err_msg[81];
127
+
128
+ err_msg[0] = '\0';
129
+ def_err_msg[0] = '\0';
130
+
131
+ switch (status) {
132
+ case MEMORY_ALLOCATION:
133
+ except_type = PyExc_MemoryError;
134
+ break;
135
+ case OVERFLOW_ERR:
136
+ except_type = PyExc_OverflowError;
137
+ break;
138
+ case BAD_COL_NUM:
139
+ strcpy(def_err_msg, "bad column number");
140
+ except_type = PyExc_ValueError;
141
+ break;
142
+ case BAD_PIX_NUM:
143
+ strcpy(def_err_msg, "bad pixel number");
144
+ except_type = PyExc_ValueError;
145
+ break;
146
+ case NEG_AXIS:
147
+ strcpy(def_err_msg, "negative axis number");
148
+ except_type = PyExc_ValueError;
149
+ break;
150
+ case BAD_DATATYPE:
151
+ strcpy(def_err_msg, "bad data type");
152
+ except_type = PyExc_TypeError;
153
+ break;
154
+ case NO_COMPRESSED_TILE:
155
+ strcpy(def_err_msg, "no compressed or uncompressed data for tile.");
156
+ except_type = PyExc_ValueError;
157
+ break;
158
+ default:
159
+ except_type = PyExc_RuntimeError;
160
+ break;
161
+ }
162
+
163
+ if (fits_read_errmsg(err_msg)) {
164
+ PyErr_SetString(except_type, err_msg);
165
+ } else if (*def_err_msg) {
166
+ PyErr_SetString(except_type, def_err_msg);
167
+ } else {
168
+ PyErr_Format(except_type, "unknown error %i.", status);
169
+ }
170
+ }
171
+
172
+
173
+ void bitpix_to_datatypes(int bitpix, int* datatype, int* npdatatype) {
174
+ /* Given a FITS BITPIX value, returns the appropriate CFITSIO type code and
175
+ Numpy type code for that BITPIX into datatype and npdatatype
176
+ respectively.
177
+ */
178
+ switch (bitpix) {
179
+ case BYTE_IMG:
180
+ *datatype = TBYTE;
181
+ *npdatatype = NPY_INT8;
182
+ break;
183
+ case SHORT_IMG:
184
+ *datatype = TSHORT;
185
+ *npdatatype = NPY_INT16;
186
+ break;
187
+ case LONG_IMG:
188
+ *datatype = TINT;
189
+ *npdatatype = NPY_INT32;
190
+ break;
191
+ case LONGLONG_IMG:
192
+ *datatype = TLONGLONG;
193
+ *npdatatype = NPY_LONGLONG;
194
+ break;
195
+ case FLOAT_IMG:
196
+ *datatype = TFLOAT;
197
+ *npdatatype = NPY_FLOAT;
198
+ break;
199
+ case DOUBLE_IMG:
200
+ *datatype = TDOUBLE;
201
+ *npdatatype = NPY_DOUBLE;
202
+ break;
203
+ default:
204
+ PyErr_Format(PyExc_ValueError, "Invalid value for BITPIX: %d",
205
+ bitpix);
206
+ break;
207
+ }
208
+
209
+ return;
210
+ }
211
+
212
+
213
+
214
+ int compress_type_from_string(char* zcmptype) {
215
+ if (0 == strcmp(zcmptype, "RICE_1")) {
216
+ return RICE_1;
217
+ } else if (0 == strcmp(zcmptype, "GZIP_1")) {
218
+ return GZIP_1;
219
+ } else if (0 == strcmp(zcmptype, "GZIP_2")) {
220
+ return GZIP_2;
221
+ } else if (0 == strcmp(zcmptype, "PLIO_1")) {
222
+ return PLIO_1;
223
+ } else if (0 == strcmp(zcmptype, "HCOMPRESS_1")) {
224
+ return HCOMPRESS_1;
225
+ }
226
+ #ifdef CFITSIO_SUPPORTS_SUBTRACTIVE_DITHER_2
227
+ /* CFITSIO adds a compression type alias for RICE_1 compression
228
+ as a flag for using subtractive_dither_2 */
229
+ else if (0 == strcmp(zcmptype, "RICE_ONE")) {
230
+ return RICE_1;
231
+ }
232
+ #endif
233
+ else {
234
+ PyErr_Format(PyExc_ValueError, "Unrecognized compression type: %s",
235
+ zcmptype);
236
+ return -1;
237
+ }
238
+ }
239
+
240
+
241
+ PyObject *
242
+ get_header_value(PyObject* header, const char* key, HeaderGetFlags flags) {
243
+ PyObject* hdrkey;
244
+ PyObject* hdrval;
245
+ hdrkey = PyUnicode_FromString(key);
246
+ if (hdrkey == NULL) {
247
+ return NULL;
248
+ }
249
+ hdrval = PyObject_GetItem(header, hdrkey);
250
+ Py_DECREF(hdrkey);
251
+ if ((flags & HDR_FAIL_KEY_MISSING) == 0) {
252
+ /* Normally we have a default so we want to ignore the exception in
253
+ any case. But if the flag was given this step must be skipped. */
254
+ PyErr_Clear();
255
+ }
256
+ return hdrval;
257
+ }
258
+
259
+
260
+ // TODO: It might be possible to simplify these further by making the
261
+ // conversion function (eg. PyString_AsString) an argument to a macro or
262
+ // something, but I'm not sure yet how easy it is to generalize the error
263
+ // handling
264
+ /* The get_header_* functions resemble "Header.get" where "def" is the default
265
+ value, "keyword" is a string representing the header-key and the result is
266
+ stored in "val".
267
+ The function returns 0 on success, 1 if the header didn't have the keyword
268
+ and the default was applied and -1 (with an exception set) if an Exception
269
+ happened (like a MemoryError or Overflow).
270
+ */
271
+ #define GET_HEADER_SUCCESS 0
272
+ #define GET_HEADER_DEFAULT_USED 1
273
+ #define GET_HEADER_FAILED -1
274
+ int get_header_string(PyObject* header, const char* keyword, char* val,
275
+ const char* def, HeaderGetFlags flags) {
276
+ /* nonnegative doesn't make sense for strings*/
277
+ assert(!(flags & HDR_FAIL_VAL_NEGATIVE));
278
+ PyObject* keyval = get_header_value(header, keyword, flags);
279
+
280
+ if (keyval == NULL) {
281
+ strncpy(val, def, 72);
282
+ return PyErr_Occurred() ? GET_HEADER_FAILED : GET_HEADER_DEFAULT_USED;
283
+ }
284
+ PyObject* tmp = PyUnicode_AsLatin1String(keyval);
285
+ // FITS header values should always be ASCII, but Latin1 is on the
286
+ // safe side
287
+ Py_DECREF(keyval);
288
+ if (tmp == NULL) {
289
+ /* could always fail to allocate the memory or such like. */
290
+ return GET_HEADER_FAILED;
291
+ }
292
+ strncpy(val, PyBytes_AsString(tmp), 72);
293
+ Py_DECREF(tmp);
294
+ return GET_HEADER_SUCCESS;
295
+ }
296
+
297
+
298
+ int get_header_long(PyObject* header, const char* keyword, long* val, long def,
299
+ HeaderGetFlags flags) {
300
+ PyObject* keyval = get_header_value(header, keyword, flags);
301
+
302
+ if (keyval == NULL) {
303
+ *val = def;
304
+ return PyErr_Occurred() ? GET_HEADER_FAILED : GET_HEADER_DEFAULT_USED;
305
+ }
306
+ long tmp = PyLong_AsLong(keyval);
307
+ Py_DECREF(keyval);
308
+ if (PyErr_Occurred()) {
309
+ return GET_HEADER_FAILED;
310
+ }
311
+ if ((flags & HDR_FAIL_VAL_NEGATIVE) && (tmp < 0)) {
312
+ PyErr_Format(PyExc_ValueError, "%s should not be negative.", keyword);
313
+ return GET_HEADER_FAILED;
314
+ }
315
+ *val = tmp;
316
+ return GET_HEADER_SUCCESS;
317
+ }
318
+
319
+
320
+ int get_header_int(PyObject* header, const char* keyword, int* val, int def,
321
+ HeaderGetFlags flags) {
322
+ long tmp;
323
+ int ret = get_header_long(header, keyword, &tmp, def, flags);
324
+ if (ret == GET_HEADER_SUCCESS) {
325
+ if (tmp >= INT_MIN && tmp <= INT_MAX) {
326
+ *val = (int) tmp;
327
+ } else {
328
+ PyErr_Format(PyExc_OverflowError, "Cannot convert %ld to C 'int'", tmp);
329
+ ret = GET_HEADER_FAILED;
330
+ }
331
+ }
332
+ return ret;
333
+ }
334
+
335
+
336
+ int get_header_double(PyObject* header, const char* keyword, double* val,
337
+ double def, HeaderGetFlags flags) {
338
+ /* nonnegative isn't currently used for doubles/floats. But if needed one
339
+ could simply remove the assert again and implement the negative check. */
340
+ assert(!(flags & HDR_FAIL_VAL_NEGATIVE));
341
+ PyObject* keyval = get_header_value(header, keyword, flags);
342
+
343
+ if (keyval == NULL) {
344
+ *val = def;
345
+ return PyErr_Occurred() ? GET_HEADER_FAILED : GET_HEADER_DEFAULT_USED;
346
+ }
347
+ double tmp = PyFloat_AsDouble(keyval);
348
+ Py_DECREF(keyval);
349
+ if (PyErr_Occurred()) {
350
+ return GET_HEADER_FAILED;
351
+ }
352
+ *val = tmp;
353
+ return GET_HEADER_SUCCESS;
354
+ }
355
+
356
+
357
+ int get_header_float(PyObject* header, const char* keyword, float* val,
358
+ float def, HeaderGetFlags flags) {
359
+ double tmp;
360
+ int ret = get_header_double(header, keyword, &tmp, def, flags);
361
+ if (ret == GET_HEADER_SUCCESS) {
362
+ if (tmp == 0.0 || (fabs(tmp) >= FLT_MIN && fabs(tmp) <= FLT_MAX)) {
363
+ *val = (float) tmp;
364
+ } else {
365
+ PyErr_SetString(PyExc_OverflowError,
366
+ "Cannot convert 'double' to 'float'");
367
+ ret = GET_HEADER_FAILED;
368
+ }
369
+ }
370
+ return ret;
371
+ }
372
+
373
+
374
+ int get_header_longlong(PyObject* header, const char* keyword, long long* val,
375
+ long long def, HeaderGetFlags flags) {
376
+ PyObject* keyval = get_header_value(header, keyword, flags);
377
+
378
+ if (keyval == NULL) {
379
+ *val = def;
380
+ return PyErr_Occurred() ? GET_HEADER_FAILED : GET_HEADER_DEFAULT_USED;
381
+ }
382
+ long long tmp = PyLong_AsLongLong(keyval);
383
+ Py_DECREF(keyval);
384
+ if (PyErr_Occurred()) {
385
+ return GET_HEADER_FAILED;
386
+ }
387
+ if ((flags & HDR_FAIL_VAL_NEGATIVE) && (tmp < 0)) {
388
+ PyErr_Format(PyExc_ValueError, "%s should not be negative.", keyword);
389
+ return GET_HEADER_FAILED;
390
+ }
391
+ *val = tmp;
392
+ return GET_HEADER_SUCCESS;
393
+ }
394
+
395
+
396
+ void tcolumns_from_header(fitsfile* fileptr, PyObject* header,
397
+ tcolumn** columns) {
398
+ // Creates the array of tcolumn structures from the table column keywords
399
+ // read from the astropy.io.fits.Header object; caller is responsible for
400
+ // freeing the memory allocated for this array
401
+
402
+ tcolumn* column;
403
+ char tkw[9];
404
+
405
+ int tfields;
406
+ char ttype[72];
407
+ char tform[72];
408
+ int dtcode;
409
+ long trepeat;
410
+ long twidth;
411
+ long long totalwidth;
412
+ int status = 0;
413
+ int idx;
414
+
415
+ if (get_header_int(header, "TFIELDS", &tfields, 0, HDR_FAIL_VAL_NEGATIVE) == GET_HEADER_FAILED) {
416
+ return;
417
+ }
418
+ /* To avoid issues in the loop we need to limit the number of TFIELDs to
419
+ 999. Otherwise we would exceed the maximum length of the keyword name of
420
+ 8. This could lead to multiple accesses of the same header keyword with
421
+ snprintf because we limit it to 8 characters + null-termination. */
422
+ if (tfields > 999) {
423
+ PyErr_SetString(PyExc_ValueError, "The TFIELDS value exceeds 999.");
424
+ return;
425
+ }
426
+
427
+ // This used to use PyMem_New, but don't do that; CFITSIO will later
428
+ // free() this object when the file is closed, so just use malloc here
429
+ // *columns = column = PyMem_New(tcolumn, (size_t) tfields);
430
+ *columns = column = calloc((size_t) tfields, sizeof(tcolumn));
431
+ if (column == NULL) {
432
+ PyErr_SetString(PyExc_MemoryError,
433
+ "Couldn't allocate memory for columns.");
434
+ return;
435
+ }
436
+
437
+
438
+ for (idx = 1; idx <= tfields; idx++, column++) {
439
+ /* set some invalid defaults */
440
+ column->ttype[0] = '\0';
441
+ column->tbcol = 0;
442
+ column->tdatatype = -9999; /* this default used by cfitsio */
443
+ column->trepeat = 1;
444
+ column->strnull[0] = '\0';
445
+ column->tform[0] = '\0';
446
+ column->twidth = 0;
447
+
448
+ snprintf(tkw, 9, "TTYPE%u", idx);
449
+ if (get_header_string(header, tkw, ttype, "", HDR_NOFLAG) == GET_HEADER_FAILED) {
450
+ return;
451
+ }
452
+ strncpy(column->ttype, ttype, 69);
453
+ column->ttype[69] = '\0';
454
+
455
+ snprintf(tkw, 9, "TFORM%u", idx);
456
+ if (get_header_string(header, tkw, tform, "", HDR_NOFLAG) == GET_HEADER_FAILED) {
457
+ return;
458
+ }
459
+ strncpy(column->tform, tform, 9);
460
+ column->tform[9] = '\0';
461
+ fits_binary_tform(tform, &dtcode, &trepeat, &twidth, &status);
462
+ if (status != 0) {
463
+ process_status_err(status);
464
+ return;
465
+ }
466
+
467
+ column->tdatatype = dtcode;
468
+ column->trepeat = trepeat;
469
+ column->twidth = twidth;
470
+
471
+ snprintf(tkw, 9, "TSCAL%u", idx);
472
+ if (get_header_double(header, tkw, &(column->tscale), 1.0, HDR_NOFLAG) == GET_HEADER_FAILED) {
473
+ return;
474
+ }
475
+
476
+ snprintf(tkw, 9, "TZERO%u", idx);
477
+ if (get_header_double(header, tkw, &(column->tzero), 0.0, HDR_NOFLAG) == GET_HEADER_FAILED) {
478
+ return;
479
+ }
480
+
481
+ snprintf(tkw, 9, "TNULL%u", idx);
482
+ if (get_header_longlong(header, tkw, &(column->tnull), NULL_UNDEFINED, HDR_NOFLAG) == GET_HEADER_FAILED) {
483
+ return;
484
+ }
485
+ }
486
+
487
+ fileptr->Fptr->tableptr = *columns;
488
+ fileptr->Fptr->tfield = tfields;
489
+
490
+ // This routine from CFITSIO calculates the byte offset of each column
491
+ // and stores it in the column->tbcol field
492
+ ffgtbc(fileptr, &totalwidth, &status);
493
+ if (status != 0) {
494
+ process_status_err(status);
495
+ }
496
+
497
+ return;
498
+ }
499
+
500
+
501
+
502
+ void configure_compression(fitsfile* fileptr, PyObject* header) {
503
+ /* Configure the compression-related elements in the fitsfile struct
504
+ using values in the FITS header. */
505
+
506
+ FITSfile* Fptr;
507
+
508
+ int tfields;
509
+ tcolumn* columns;
510
+
511
+ char keyword[9];
512
+ char zname[72];
513
+ int znaxis;
514
+ char tmp[72];
515
+ float version;
516
+
517
+ int idx;
518
+
519
+ Fptr = fileptr->Fptr;
520
+ tfields = Fptr->tfield;
521
+ columns = Fptr->tableptr;
522
+
523
+ int tmp_retval;
524
+
525
+ // Get the ZBITPIX header value; if this is missing we're in trouble
526
+ if (get_header_int(header, "ZBITPIX", &(Fptr->zbitpix), 0, HDR_FAIL_KEY_MISSING) != GET_HEADER_SUCCESS) {
527
+ return;
528
+ }
529
+
530
+ // By default assume there is no ZBLANK column and check for ZBLANK or
531
+ // BLANK in the header
532
+ Fptr->cn_zblank = Fptr->cn_zzero = Fptr->cn_zscale = -1;
533
+ Fptr->cn_uncompressed = 0;
534
+ #ifdef CFITSIO_SUPPORTS_GZIPDATA
535
+ Fptr->cn_gzip_data = 0;
536
+ #endif
537
+
538
+ // Check for a ZBLANK, ZZERO, ZSCALE, and
539
+ // UNCOMPRESSED_DATA/GZIP_COMPRESSED_DATA columns in the compressed data
540
+ // table
541
+ for (idx = 0; idx < tfields; idx++) {
542
+ if (0 == strncmp(columns[idx].ttype, "UNCOMPRESSED_DATA", 18)) {
543
+ Fptr->cn_uncompressed = idx + 1;
544
+ #ifdef CFITSIO_SUPPORTS_GZIPDATA
545
+ } else if (0 == strncmp(columns[idx].ttype,
546
+ "GZIP_COMPRESSED_DATA", 21)) {
547
+ Fptr->cn_gzip_data = idx + 1;
548
+ #endif
549
+ } else if (0 == strncmp(columns[idx].ttype, "ZSCALE", 7)) {
550
+ Fptr->cn_zscale = idx + 1;
551
+ } else if (0 == strncmp(columns[idx].ttype, "ZZERO", 6)) {
552
+ Fptr->cn_zzero = idx + 1;
553
+ } else if (0 == strncmp(columns[idx].ttype, "ZBLANK", 7)) {
554
+ Fptr->cn_zblank = idx + 1;
555
+ }
556
+ }
557
+
558
+ Fptr->zblank = 0;
559
+ if (Fptr->cn_zblank < 1) {
560
+ // No ZBLANK column--check the ZBLANK and BLANK heard keywords
561
+ switch (get_header_int(header, "ZBLANK", &(Fptr->zblank), 0, HDR_NOFLAG)) {
562
+ case GET_HEADER_FAILED:
563
+ return;
564
+ case GET_HEADER_DEFAULT_USED:
565
+ // ZBLANK keyword not found
566
+ if (get_header_int(header, "BLANK", &(Fptr->zblank), 0, HDR_NOFLAG) == GET_HEADER_FAILED) {
567
+ return;
568
+ }
569
+ break;
570
+ default:
571
+ break;
572
+ }
573
+ }
574
+
575
+ Fptr->zscale = 1.0;
576
+ if (Fptr->cn_zscale < 1) {
577
+ switch (get_header_double(header, "ZSCALE", &(Fptr->zscale), 1.0, HDR_NOFLAG)) {
578
+ case GET_HEADER_FAILED:
579
+ return;
580
+ case GET_HEADER_DEFAULT_USED:
581
+ Fptr->cn_zscale = 0;
582
+ break;
583
+ default:
584
+ break;
585
+ }
586
+ }
587
+ Fptr->cn_bscale = Fptr->zscale;
588
+
589
+ Fptr->zzero = 0.0;
590
+ if (Fptr->cn_zzero < 1) {
591
+ switch (get_header_double(header, "ZZERO", &(Fptr->zzero), 0.0, HDR_NOFLAG)) {
592
+ case GET_HEADER_FAILED:
593
+ return;
594
+ case GET_HEADER_DEFAULT_USED:
595
+ Fptr->cn_zzero = 0;
596
+ break;
597
+ default:
598
+ break;
599
+ }
600
+ }
601
+ Fptr->cn_bzero = Fptr->zzero;
602
+
603
+ if (get_header_string(header, "ZCMPTYPE", tmp, DEFAULT_COMPRESSION_TYPE, HDR_NOFLAG) == GET_HEADER_FAILED) {
604
+ return;
605
+ }
606
+ strncpy(Fptr->zcmptype, tmp, 11);
607
+ Fptr->zcmptype[strlen(tmp)] = '\0';
608
+
609
+ Fptr->compress_type = compress_type_from_string(Fptr->zcmptype);
610
+ if (PyErr_Occurred()) {
611
+ return;
612
+ }
613
+
614
+ if (get_header_int(header, "ZNAXIS", &znaxis, 0, HDR_NOFLAG) == GET_HEADER_FAILED) {
615
+ return;
616
+ }
617
+ Fptr->zndim = znaxis;
618
+
619
+ if (znaxis > MAX_COMPRESS_DIM) {
620
+ // The CFITSIO compression code currently only supports up to 6
621
+ // dimensions by default.
622
+ znaxis = MAX_COMPRESS_DIM;
623
+ }
624
+
625
+ Fptr->tilerow = NULL;
626
+ Fptr->maxtilelen = 1;
627
+ for (idx = 1; idx <= znaxis; idx++) {
628
+ snprintf(keyword, 9, "ZNAXIS%u", idx);
629
+ if (get_header_long(header, keyword, Fptr->znaxis + idx - 1, 0, HDR_NOFLAG) == GET_HEADER_FAILED) {
630
+ return;
631
+ }
632
+ snprintf(keyword, 9, "ZTILE%u", idx);
633
+ if (get_header_long(header, keyword, Fptr->tilesize + idx - 1, 0, HDR_NOFLAG) == GET_HEADER_FAILED) {
634
+ return;
635
+ }
636
+ Fptr->maxtilelen *= Fptr->tilesize[idx - 1];
637
+ }
638
+
639
+ // Set some more default compression options
640
+ Fptr->rice_blocksize = DEFAULT_BLOCK_SIZE;
641
+ Fptr->rice_bytepix = DEFAULT_BYTE_PIX;
642
+ Fptr->quantize_level = DEFAULT_QUANTIZE_LEVEL;
643
+ Fptr->hcomp_smooth = DEFAULT_HCOMP_SMOOTH;
644
+ Fptr->hcomp_scale = DEFAULT_HCOMP_SCALE;
645
+
646
+ // Now process the ZVALn keywords
647
+ idx = 1;
648
+ while (1) {
649
+ snprintf(keyword, 9, "ZNAME%u", idx);
650
+ // Assumes there are no gaps in the ZNAMEn keywords; this same
651
+ // assumption was made in the Python code. This could be done slightly
652
+ // more flexibly by using a wildcard slice of the header
653
+ tmp_retval = get_header_string(header, keyword, zname, "", HDR_NOFLAG);
654
+ if (tmp_retval == GET_HEADER_FAILED) {
655
+ return;
656
+ } else if (tmp_retval == 1) {
657
+ break;
658
+ }
659
+
660
+ snprintf(keyword, 9, "ZVAL%u", idx);
661
+ if (Fptr->compress_type == RICE_1) {
662
+ if (0 == strcmp(zname, "BLOCKSIZE")) {
663
+ if (get_header_int(header, keyword, &(Fptr->rice_blocksize),
664
+ DEFAULT_BLOCK_SIZE, HDR_NOFLAG) == GET_HEADER_FAILED) {
665
+ return;
666
+ }
667
+ } else if (0 == strcmp(zname, "BYTEPIX")) {
668
+ if (get_header_int(header, keyword, &(Fptr->rice_bytepix),
669
+ DEFAULT_BYTE_PIX, HDR_NOFLAG) == GET_HEADER_FAILED) {
670
+ return;
671
+ }
672
+ }
673
+ } else if (Fptr->compress_type == HCOMPRESS_1) {
674
+ if (0 == strcmp(zname, "SMOOTH")) {
675
+ if (get_header_int(header, keyword, &(Fptr->hcomp_smooth),
676
+ DEFAULT_HCOMP_SMOOTH, HDR_NOFLAG) == GET_HEADER_FAILED) {
677
+ return;
678
+ }
679
+ } else if (0 == strcmp(zname, "SCALE")) {
680
+ if (get_header_float(header, keyword, &(Fptr->hcomp_scale),
681
+ DEFAULT_HCOMP_SCALE, HDR_NOFLAG) == GET_HEADER_FAILED) {
682
+ return;
683
+ }
684
+ }
685
+ }
686
+ if (Fptr->zbitpix < 0 && 0 == strcmp(zname, "NOISEBIT")) {
687
+ if (get_header_float(header, keyword, &(Fptr->quantize_level),
688
+ DEFAULT_QUANTIZE_LEVEL, HDR_NOFLAG) == GET_HEADER_FAILED) {
689
+ return;
690
+ }
691
+ if (Fptr->quantize_level == 0.0) {
692
+ /* NOISEBIT == 0 is equivalent to no quantize */
693
+ Fptr->quantize_level = NO_QUANTIZE;
694
+ }
695
+ }
696
+
697
+ idx++;
698
+ }
699
+
700
+ /* The ZQUANTIZ keyword determines the quantization algorithm; NO_QUANTIZE
701
+ implies lossless compression */
702
+ tmp_retval = get_header_string(header, "ZQUANTIZ", tmp, "", HDR_NOFLAG);
703
+ if (tmp_retval == GET_HEADER_FAILED) {
704
+ return;
705
+ } else if (tmp_retval == GET_HEADER_SUCCESS) {
706
+ /* Ugh; the fact that cfitsio defines its version as a float makes
707
+ preprocessor comparison impossible */
708
+ fits_get_version(&version);
709
+ if ((version >= CFITSIO_LOSSLESS_COMP_SUPPORTED_VERS) &&
710
+ (0 == strcmp(tmp, "NONE"))) {
711
+ Fptr->quantize_level = NO_QUANTIZE;
712
+ } else if (0 == strcmp(tmp, "SUBTRACTIVE_DITHER_1")) {
713
+ #ifdef CFITSIO_SUPPORTS_SUBTRACTIVE_DITHER_2
714
+ // Added in CFITSIO 3.35, this also changed the name of the
715
+ // quantize_dither struct member to quantize_method
716
+ Fptr->quantize_method = SUBTRACTIVE_DITHER_1;
717
+ } else if (0 == strcmp(tmp, "SUBTRACTIVE_DITHER_2")) {
718
+ Fptr->quantize_method = SUBTRACTIVE_DITHER_2;
719
+ } else {
720
+ Fptr->quantize_method = NO_DITHER;
721
+ }
722
+ } else {
723
+ Fptr->quantize_method = NO_DITHER;
724
+ }
725
+
726
+ if (Fptr->quantize_method != NO_DITHER) {
727
+ switch (get_header_int(header, "ZDITHER0", &(Fptr->dither_seed), 0, HDR_NOFLAG)) {
728
+ case GET_HEADER_FAILED:
729
+ return;
730
+ case GET_HEADER_DEFAULT_USED: // ZDITHER0 keyword not found
731
+ Fptr->dither_seed = 0;
732
+ Fptr->request_dither_seed = 0;
733
+ break;
734
+ default:
735
+ break;
736
+ }
737
+ }
738
+ #else
739
+ Fptr->quantize_dither = SUBTRACTIVE_DITHER_1;
740
+ } else {
741
+ Fptr->quantize_dither = NO_DITHER;
742
+ }
743
+ } else {
744
+ Fptr->quantize_dither = NO_DITHER;
745
+ }
746
+
747
+ if (Fptr->quantize_dither != NO_DITHER) {
748
+ switch (get_header_int(header, "ZDITHER0", &(Fptr->dither_offset), 0, HDR_NOFLAG)) {
749
+ case GET_HEADER_FAILED:
750
+ return;
751
+ case GET_HEADER_DEFAULT_USED: // ZDITHER0 keyword no found
752
+ /* TODO: Find out if that's actually working and not invalid... */
753
+ Fptr->dither_offset = 0;
754
+ Fptr->request_dither_offset = 0;
755
+ break;
756
+ default:
757
+ break;
758
+ }
759
+ }
760
+ #endif
761
+
762
+ Fptr->compressimg = 1;
763
+ Fptr->maxelem = imcomp_calc_max_elem(Fptr->compress_type,
764
+ Fptr->maxtilelen,
765
+ Fptr->zbitpix,
766
+ Fptr->rice_blocksize);
767
+ Fptr->cn_compressed = 1;
768
+ return;
769
+ }
770
+
771
+
772
+ void init_output_buffer(PyObject* hdu, void** buf, size_t* bufsize) {
773
+ // Determines a good size for the output data buffer and allocates
774
+ // memory for it, returning the address and size of the allocated
775
+ // memory into **buf and *bufsize respectively.
776
+
777
+ PyObject* header = NULL;
778
+ char keyword[9];
779
+ char tmp[72];
780
+ int znaxis;
781
+ int compress_type;
782
+ int zbitpix;
783
+ int rice_blocksize = 0;
784
+ long long rowlen;
785
+ long long nrows;
786
+ long maxelem;
787
+ long tilelen;
788
+ unsigned long maxtilelen = 1;
789
+ int idx;
790
+
791
+ header = PyObject_GetAttrString(hdu, "_header");
792
+ if (header == NULL) {
793
+ return;
794
+ }
795
+
796
+ if (get_header_int(header, "ZNAXIS", &znaxis, 0,
797
+ HDR_FAIL_KEY_MISSING | HDR_FAIL_VAL_NEGATIVE) != GET_HEADER_SUCCESS) {
798
+ goto fail;
799
+ }
800
+
801
+ if (znaxis > 999) {
802
+ PyErr_SetString(PyExc_ValueError, "ZNAXIS is greater than 999.");
803
+ goto fail;
804
+ }
805
+
806
+ for (idx = 1; idx <= znaxis; idx++) {
807
+ snprintf(keyword, 9, "ZTILE%u", idx);
808
+ if (get_header_long(header, keyword, &tilelen, 1, HDR_NOFLAG) == GET_HEADER_FAILED) {
809
+ goto fail;
810
+ }
811
+ maxtilelen *= tilelen;
812
+ }
813
+
814
+ if (get_header_string(header, "ZCMPTYPE", tmp, DEFAULT_COMPRESSION_TYPE, HDR_NOFLAG) == GET_HEADER_FAILED) {
815
+ goto fail;
816
+ }
817
+ compress_type = compress_type_from_string(tmp);
818
+ if (PyErr_Occurred()) {
819
+ goto fail;
820
+ }
821
+ if (compress_type == RICE_1) {
822
+ if (get_header_int(header, "ZVAL1", &rice_blocksize, 0, HDR_NOFLAG) == GET_HEADER_FAILED) {
823
+ goto fail;
824
+ }
825
+ }
826
+
827
+ /* Because we calculate the size of the buffer based on these values they
828
+ must not be negative. Otherwise it would wrap around during the casting
829
+ to size_t and give huge values. */
830
+ if (get_header_longlong(header, "NAXIS1", &rowlen, 0, HDR_FAIL_VAL_NEGATIVE) == GET_HEADER_FAILED) {
831
+ goto fail;
832
+ }
833
+ if (get_header_longlong(header, "NAXIS2", &nrows, 0, HDR_FAIL_VAL_NEGATIVE) == GET_HEADER_FAILED) {
834
+ goto fail;
835
+ }
836
+
837
+ // Get the ZBITPIX header value; if this is missing we're in trouble
838
+ if (get_header_int(header, "ZBITPIX", &zbitpix, 0, HDR_FAIL_KEY_MISSING) != GET_HEADER_SUCCESS) {
839
+ goto fail;
840
+ }
841
+
842
+ maxelem = imcomp_calc_max_elem(compress_type, maxtilelen, zbitpix,
843
+ rice_blocksize);
844
+
845
+ *bufsize = ((size_t) (rowlen * nrows) + (nrows * maxelem));
846
+
847
+ if (*bufsize < IOBUFLEN) {
848
+ // We must have a full FITS block at a minimum
849
+ *bufsize = IOBUFLEN;
850
+ } else if (*bufsize % IOBUFLEN != 0) {
851
+ // Still make sure to pad out to a multiple of 2880 byte blocks
852
+ // otherwise CFITSIO can get read errors when it tries to read
853
+ // a partial block that goes past the end of the file
854
+ *bufsize += ((size_t) (IOBUFLEN - (*bufsize % IOBUFLEN)));
855
+ }
856
+
857
+ *buf = calloc(*bufsize, sizeof(char));
858
+ if (*buf == NULL) {
859
+ // Checking if calloc failed.
860
+ PyErr_SetString(PyExc_MemoryError,
861
+ "Failed to allocate memory for output data buffer.");
862
+ goto fail;
863
+ }
864
+
865
+ fail:
866
+ Py_DECREF(header);
867
+ return;
868
+ }
869
+
870
+
871
+ void get_hdu_data_base(PyObject* hdu, void** buf, size_t* bufsize) {
872
+ // Given a pointer to an HDU object, returns a pointer to the deepest base
873
+ // array of that HDU's data array into **buf, and the size of that array
874
+ // into *bufsize.
875
+
876
+ PyArrayObject* data = NULL;
877
+ PyArrayObject* base;
878
+ PyArrayObject* tmp;
879
+
880
+ data = (PyArrayObject*) PyObject_GetAttrString(hdu, "compressed_data");
881
+ if (data == NULL) {
882
+ goto fail;
883
+ }
884
+
885
+ // Walk the array data bases until we find the lowest ndarray base; for
886
+ // CompImageHDUs there should always be at least one contiguous byte array
887
+ // allocated for the table and its heap
888
+ if (!PyObject_TypeCheck(data, &PyArray_Type)) {
889
+ PyErr_SetString(PyExc_TypeError,
890
+ "CompImageHDU.compressed_data must be a numpy.ndarray");
891
+ goto fail;
892
+ }
893
+
894
+ tmp = base = data;
895
+ while (PyObject_TypeCheck((PyObject*) tmp, &PyArray_Type)) {
896
+ base = tmp;
897
+ *bufsize = (size_t) PyArray_NBYTES(base);
898
+ tmp = (PyArrayObject*) PyArray_BASE(base);
899
+ if (tmp == NULL) {
900
+ break;
901
+ }
902
+ }
903
+
904
+ *buf = PyArray_DATA(base);
905
+ fail:
906
+ Py_XDECREF(data);
907
+ return;
908
+ }
909
+
910
+
911
+ void open_from_hdu(fitsfile** fileptr, void** buf, size_t* bufsize,
912
+ PyObject* hdu, tcolumn** columns, int mode) {
913
+
914
+ PyObject* header = NULL;
915
+ FITSfile* Fptr;
916
+
917
+ int status = 0;
918
+ long long rowlen;
919
+ long long nrows;
920
+ long long heapsize;
921
+ long long theap;
922
+
923
+ header = PyObject_GetAttrString(hdu, "_header");
924
+ if (header == NULL) {
925
+ goto fail;
926
+ }
927
+
928
+ if (get_header_longlong(header, "NAXIS1", &rowlen, 0, HDR_NOFLAG) == GET_HEADER_FAILED) {
929
+ goto fail;
930
+ }
931
+ if (get_header_longlong(header, "NAXIS2", &nrows, 0, HDR_NOFLAG) == GET_HEADER_FAILED) {
932
+ goto fail;
933
+ }
934
+
935
+ // The PCOUNT keyword contains the number of bytes in the table heap
936
+ if (get_header_longlong(header, "PCOUNT", &heapsize, 0, HDR_FAIL_VAL_NEGATIVE) == GET_HEADER_FAILED) {
937
+ goto fail;
938
+ }
939
+
940
+ // The THEAP keyword gives the offset of the heap from the beginning of
941
+ // the HDU data portion; normally this offset is 0 but it can be set
942
+ // to something else with THEAP
943
+ if (get_header_longlong(header, "THEAP", &theap, 0, HDR_NOFLAG) == GET_HEADER_FAILED) {
944
+ goto fail;
945
+ }
946
+
947
+ fits_create_memfile(fileptr, buf, bufsize, 0, realloc, &status);
948
+ if (status != 0) {
949
+ process_status_err(status);
950
+ goto fail;
951
+ }
952
+
953
+ Fptr = (*fileptr)->Fptr;
954
+
955
+ // Now we have some fun munging some of the elements in the fitsfile struct
956
+ Fptr->writemode = mode;
957
+ Fptr->open_count = 1;
958
+ Fptr->hdutype = BINARY_TBL; /* This is a binary table HDU */
959
+ Fptr->lasthdu = 1;
960
+ Fptr->headstart[0] = 0;
961
+ Fptr->headend = 0;
962
+ Fptr->datastart = 0; /* There is no header, data starts at 0 */
963
+ Fptr->origrows = Fptr->numrows = nrows;
964
+ Fptr->rowlength = rowlen;
965
+ if (theap != 0) {
966
+ Fptr->heapstart = theap;
967
+ } else {
968
+ Fptr->heapstart = rowlen * nrows;
969
+ }
970
+
971
+ Fptr->heapsize = heapsize;
972
+
973
+ // Configure the array of table column structs from the Astropy header
974
+ // instead of allowing CFITSIO to try to read from the header
975
+ tcolumns_from_header(*fileptr, header, columns);
976
+ if (PyErr_Occurred()) {
977
+ goto fail;
978
+ }
979
+
980
+ // If any errors occur in this function they'll bubble up from here to
981
+ // compression_decompress_hdu
982
+ configure_compression(*fileptr, header);
983
+
984
+ fail:
985
+ Py_XDECREF(header);
986
+ return;
987
+ }
988
+
989
+
990
+ PyObject* compression_compress_hdu(PyObject* self, PyObject* args)
991
+ {
992
+ PyObject* hdu;
993
+ PyObject* retval = NULL;
994
+ tcolumn* columns = NULL;
995
+
996
+ void* outbuf = NULL;
997
+ size_t outbufsize;
998
+
999
+ PyObject* tmp_indata;
1000
+ PyArrayObject* indata = NULL;
1001
+ PyArrayObject* tmp;
1002
+ npy_intp znaxis;
1003
+ int datatype;
1004
+ int npdatatype;
1005
+ unsigned long long heapsize;
1006
+
1007
+ fitsfile* fileptr = NULL;
1008
+ FITSfile* Fptr = NULL;
1009
+ int status = 0;
1010
+
1011
+ if (!PyArg_ParseTuple(args, "O:compression.compress_hdu", &hdu)) {
1012
+ return NULL;
1013
+ }
1014
+
1015
+ // For HDU compression never use CFITSIO to write directly to the file;
1016
+ // although there's nothing wrong with CFITSIO, right now that would cause
1017
+ // too much confusion to Astropy's internal book keeping.
1018
+ // We just need to get the compressed bytes and Astropy will handle the
1019
+ // writing of them.
1020
+ init_output_buffer(hdu, &outbuf, &outbufsize);
1021
+ if (outbuf == NULL) {
1022
+ return NULL;
1023
+ }
1024
+
1025
+ open_from_hdu(&fileptr, &outbuf, &outbufsize, hdu, &columns, READWRITE);
1026
+ if (PyErr_Occurred()) {
1027
+ goto fail;
1028
+ }
1029
+
1030
+ Fptr = fileptr->Fptr;
1031
+
1032
+ bitpix_to_datatypes(Fptr->zbitpix, &datatype, &npdatatype);
1033
+ if (PyErr_Occurred()) {
1034
+ goto fail;
1035
+ }
1036
+
1037
+ /* The data attribute could be something different from an array, i.e. None */
1038
+ tmp_indata = PyObject_GetAttrString(hdu, "data");
1039
+ if (tmp_indata == NULL) {
1040
+ goto fail;
1041
+ }
1042
+
1043
+ if (!PyObject_TypeCheck(tmp_indata, &PyArray_Type)) {
1044
+ PyErr_SetString(PyExc_TypeError,
1045
+ "CompImageHDU.data must be a numpy.ndarray");
1046
+ Py_DECREF(tmp_indata);
1047
+ goto fail;
1048
+ }
1049
+
1050
+ indata = (PyArrayObject*) tmp_indata;
1051
+
1052
+ fits_write_img(fileptr, datatype, 1, PyArray_SIZE(indata),
1053
+ PyArray_DATA(indata), &status);
1054
+ if (status != 0) {
1055
+ process_status_err(status);
1056
+ goto fail;
1057
+ }
1058
+
1059
+ fits_flush_buffer(fileptr, 1, &status);
1060
+ if (status != 0) {
1061
+ process_status_err(status);
1062
+ goto fail;
1063
+ }
1064
+
1065
+ // Previously this used outbufsize as the size to use for the new Numpy
1066
+ // byte array. However outbufsize is usually larger than necessary to
1067
+ // store all the compressed data exactly; instead use the exact size
1068
+ // of the compressed data from the heapsize plus the size of the table
1069
+ // itself
1070
+ heapsize = (unsigned long long) Fptr->heapsize;
1071
+ znaxis = (npy_intp) (Fptr->heapstart + heapsize);
1072
+
1073
+ if (znaxis < outbufsize) {
1074
+ void* tmp_outbuf = NULL;
1075
+ // Go ahead and truncate to the size in znaxis to free the
1076
+ // redundant allocation
1077
+ if (znaxis == 0) {
1078
+ /* This really shouldn't happen, but if it did, we would have a
1079
+ problem because realloc would deallocate outbuf AND return NULL.
1080
+ */
1081
+ PyErr_SetString(PyExc_ValueError,
1082
+ "Calculated array size is zero. This shouldn't happen!");
1083
+ goto fail;
1084
+ }
1085
+ tmp_outbuf = realloc(outbuf, (size_t) znaxis);
1086
+ if (tmp_outbuf == NULL) {
1087
+ PyErr_SetString(PyExc_MemoryError,
1088
+ "Couldn't resize the output-buffer.");
1089
+ goto fail;
1090
+ }
1091
+ outbuf = tmp_outbuf;
1092
+ }
1093
+
1094
+ tmp = (PyArrayObject*) PyArray_SimpleNewFromData(1, &znaxis, NPY_UBYTE,
1095
+ outbuf);
1096
+ if (tmp == NULL) {
1097
+ /* Really not sure if it's always safe to free outbuf when
1098
+ PyArray_SimpleNewFromData failed (which is unlikely but could happen)
1099
+ but it seems like if it fails then the outbuf NEEDS to be freed... */
1100
+ goto fail;
1101
+ }
1102
+ PyArray_ENABLEFLAGS(tmp, NPY_ARRAY_OWNDATA);
1103
+ /* From this point on outbuf MUST NOT BE FREED! */
1104
+
1105
+ // Leaves refcount of tmp untouched, so its refcount should remain as 1
1106
+ retval = Py_BuildValue("KN", heapsize, tmp);
1107
+ if (retval == NULL) {
1108
+ Py_DECREF(tmp);
1109
+ goto cleanup;
1110
+ }
1111
+
1112
+ goto cleanup;
1113
+
1114
+ fail:
1115
+ if (outbuf != NULL) {
1116
+ // At this point outbuf should never not be NULL, but in principle
1117
+ // buggy code somewhere in CFITSIO or Numpy could set it to NULL
1118
+ free(outbuf);
1119
+ }
1120
+ cleanup:
1121
+ if (columns != NULL) {
1122
+ free(columns);
1123
+ /* See https://github.com/astropy/astropy/pull/4489
1124
+ We can only set the tableptr to NULL if Fptr is actually not NULL.
1125
+ */
1126
+ if (fileptr != NULL && fileptr->Fptr != NULL) {
1127
+ fileptr->Fptr->tableptr = NULL;
1128
+ }
1129
+ }
1130
+
1131
+ if (fileptr != NULL) {
1132
+ status = 1; // Disable header-related errors
1133
+ fits_close_file(fileptr, &status);
1134
+ if (status != 1) {
1135
+ process_status_err(status);
1136
+ retval = NULL;
1137
+ }
1138
+ }
1139
+
1140
+ Py_XDECREF(indata);
1141
+
1142
+ // Clear any messages remaining in CFITSIO's error stack
1143
+ fits_clear_errmsg();
1144
+
1145
+ return retval;
1146
+ }
1147
+
1148
+
1149
+ PyObject* compression_decompress_hdu(PyObject* self, PyObject* args)
1150
+ {
1151
+
1152
+ PyObject* hdu;
1153
+ tcolumn* columns = NULL;
1154
+
1155
+ void* inbuf;
1156
+ size_t inbufsize;
1157
+
1158
+ PyArrayObject* outdata = NULL;
1159
+ int datatype;
1160
+ int npdatatype;
1161
+ npy_intp zndim;
1162
+ npy_intp* znaxis = NULL;
1163
+ long arrsize;
1164
+
1165
+ fitsfile* fileptr = NULL;
1166
+ int anynul = 0;
1167
+ int status = 0;
1168
+ int idx;
1169
+
1170
+ int free_columns_manually = 1;
1171
+
1172
+ if (!PyArg_ParseTuple(args, "O:compression.decompress_hdu", &hdu)) {
1173
+ return NULL;
1174
+ }
1175
+
1176
+ // Grab a pointer to the input data from the HDU's compressed_data
1177
+ // attribute
1178
+ get_hdu_data_base(hdu, &inbuf, &inbufsize);
1179
+ if (PyErr_Occurred()) {
1180
+ return NULL;
1181
+ } else if (inbufsize == 0) {
1182
+ // The compressed data buffer is empty (probably zero rows, for an
1183
+ // empty "compressed" image. Just return None in this case.
1184
+ Py_RETURN_NONE;
1185
+ }
1186
+
1187
+ open_from_hdu(&fileptr, &inbuf, &inbufsize, hdu, &columns, READONLY);
1188
+ if (PyErr_Occurred()) {
1189
+ goto fail;
1190
+ }
1191
+
1192
+ bitpix_to_datatypes(fileptr->Fptr->zbitpix, &datatype, &npdatatype);
1193
+ if (PyErr_Occurred()) {
1194
+ goto fail;
1195
+ }
1196
+
1197
+ zndim = (npy_intp)fileptr->Fptr->zndim;
1198
+ znaxis = PyMem_Malloc(sizeof(npy_intp) * zndim);
1199
+ if (znaxis == NULL) {
1200
+ goto fail;
1201
+ }
1202
+
1203
+ arrsize = 1;
1204
+ for (idx = 0; idx < zndim; idx++) {
1205
+ znaxis[zndim - idx - 1] = fileptr->Fptr->znaxis[idx];
1206
+ arrsize *= fileptr->Fptr->znaxis[idx];
1207
+ }
1208
+
1209
+ /* Create and allocate a new array for the decompressed data */
1210
+ outdata = (PyArrayObject*) PyArray_SimpleNew(zndim, znaxis, npdatatype);
1211
+ if (outdata == NULL) {
1212
+ goto fail;
1213
+ }
1214
+
1215
+ fits_read_img(fileptr, datatype, 1, arrsize, NULL, PyArray_DATA(outdata),
1216
+ &anynul, &status);
1217
+ /* At this point we need to let CFITSIO clean up the tableptr and the
1218
+ compressed tile cache. */
1219
+ free_columns_manually = 0;
1220
+ if (status != 0) {
1221
+ process_status_err(status);
1222
+ Py_DECREF(outdata);
1223
+ outdata = NULL;
1224
+ }
1225
+
1226
+ fail:
1227
+ // CFITSIO will free this object in the ffchdu function by way of
1228
+ // fits_close_file; we need to let CFITSIO handle this so that it also
1229
+ // cleans up the compressed tile cache - but that's only necessary in case
1230
+ // we called "fits_read_img"...
1231
+ if (free_columns_manually && columns != NULL) {
1232
+ free(columns);
1233
+ if (fileptr != NULL && fileptr->Fptr != NULL) {
1234
+ fileptr->Fptr->tableptr = NULL;
1235
+ }
1236
+ }
1237
+
1238
+ if (fileptr != NULL) {
1239
+ status = 1;// Disable header-related errors
1240
+ fits_close_file(fileptr, &status);
1241
+ if (status != 1) {
1242
+ process_status_err(status);
1243
+ outdata = NULL;
1244
+ }
1245
+ }
1246
+
1247
+ if (znaxis != NULL) {
1248
+ PyMem_Free(znaxis);
1249
+ }
1250
+
1251
+ // Clear any messages remaining in CFITSIO's error stack
1252
+ fits_clear_errmsg();
1253
+
1254
+ return (PyObject*) outdata;
1255
+ }
1256
+
1257
+
1258
+ /* CFITSIO version float as returned by fits_get_version() */
1259
+ static double cfitsio_version;
1260
+
1261
+
1262
+ int compression_module_init(PyObject* module) {
1263
+ /* Python version-independent initialization routine for the
1264
+ compression module. Returns 0 on success and -1 (with exception set)
1265
+ on failure. */
1266
+ PyObject* tmp;
1267
+ float version_tmp;
1268
+ int ret;
1269
+
1270
+ fits_get_version(&version_tmp);
1271
+ cfitsio_version = (double) version_tmp;
1272
+ /* The conversion to double can lead to some rounding errors; round to the
1273
+ nearest 3 decimal places, which should be accurate for any past or
1274
+ current CFITSIO version. This is why relying on floats for version
1275
+ comparison isn't generally a bright idea... */
1276
+ cfitsio_version = floor((1000 * version_tmp + 0.5)) / 1000;
1277
+
1278
+ tmp = PyFloat_FromDouble(cfitsio_version);
1279
+ if (tmp == NULL) {
1280
+ return -1;
1281
+ }
1282
+ ret = PyObject_SetAttrString(module, "CFITSIO_VERSION", tmp);
1283
+ Py_DECREF(tmp);
1284
+ return ret;
1285
+ }
1286
+
1287
+
1288
+ /* Method table mapping names to wrappers */
1289
+ static PyMethodDef compression_methods[] =
1290
+ {
1291
+ {"compress_hdu", compression_compress_hdu, METH_VARARGS},
1292
+ {"decompress_hdu", compression_decompress_hdu, METH_VARARGS},
1293
+ {NULL, NULL}
1294
+ };
1295
+
1296
+ static struct PyModuleDef compressionmodule = {
1297
+ PyModuleDef_HEAD_INIT,
1298
+ "compression",
1299
+ "astropy.compression module",
1300
+ -1, /* No global state */
1301
+ compression_methods
1302
+ };
1303
+
1304
+ PyObject *
1305
+ PyInit_compression(void)
1306
+ {
1307
+ PyObject* module = PyModule_Create(&compressionmodule);
1308
+ if (module == NULL) {
1309
+ return NULL;
1310
+ }
1311
+ if (compression_module_init(module)) {
1312
+ Py_DECREF(module);
1313
+ return NULL;
1314
+ }
1315
+
1316
+ /* Needed to use Numpy routines */
1317
+ /* Note -- import_array() is a macro that behaves differently in Python2.x
1318
+ * vs. Python 3. See the discussion at:
1319
+ * https://groups.google.com/d/topic/astropy-dev/6_AesAsCauM/discussion
1320
+ */
1321
+ import_array();
1322
+ return module;
1323
+ }
testbed/astropy__astropy/astropy/io/fits/src/compressionmodule.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef _COMPRESSIONMODULE_H
2
+ #define _COMPRESSIONMODULE_H
3
+
4
+
5
+ /* CFITSIO version-specific feature support */
6
+ #ifndef CFITSIO_MAJOR
7
+ // Define a minimized version
8
+ #define CFITSIO_MAJOR 0
9
+ #ifdef _MSC_VER
10
+ #pragma warning ( "CFITSIO_MAJOR not defined; your CFITSIO version may be too old; compile at your own risk" )
11
+ #else
12
+ #warning "CFITSIO_MAJOR not defined; your CFITSIO version may be too old; compile at your own risk"
13
+ #endif
14
+ #endif
15
+
16
+ #ifndef CFITSIO_MINOR
17
+ #define CFITSIO_MINOR 0
18
+ #endif
19
+
20
+
21
+ #if CFITSIO_MAJOR >= 3
22
+ #if CFITSIO_MINOR >= 35
23
+ #define CFITSIO_SUPPORTS_Q_FORMAT_COMPRESSION
24
+ #define CFITSIO_SUPPORTS_SUBTRACTIVE_DITHER_2
25
+ #else
26
+ /* This constant isn't defined in older versions and has a different */
27
+ /* value anyways. */
28
+ #define NO_DITHER 0
29
+ #endif
30
+ #if CFITSIO_MINOR >= 28
31
+ #define CFITSIO_SUPPORTS_GZIPDATA
32
+ #else
33
+ #ifdef _MSC_VER
34
+ #pragma warning ( "GZIP_COMPRESSED_DATA columns not supported" )
35
+ #else
36
+ #warning "GZIP_COMPRESSED_DATA columns not supported"
37
+ #endif
38
+ #endif
39
+ #endif
40
+
41
+
42
+ #define CFITSIO_LOSSLESS_COMP_SUPPORTED_VERS 3.22
43
+
44
+
45
+ /* These defaults mirror the defaults in io.fits.hdu.compressed */
46
+ #define DEFAULT_COMPRESSION_TYPE "RICE_1"
47
+ #define DEFAULT_QUANTIZE_LEVEL 16.0
48
+ #define DEFAULT_HCOMP_SCALE 0
49
+ #define DEFAULT_HCOMP_SMOOTH 0
50
+ #define DEFAULT_BLOCK_SIZE 32
51
+ #define DEFAULT_BYTE_PIX 4
52
+
53
+ /* This constant is defined by cfitsio in imcompress.c */
54
+ #define NO_QUANTIZE 9999
55
+
56
+ #endif
testbed/astropy__astropy/astropy/io/fits/tests/__init__.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import os
4
+ import shutil
5
+ import stat
6
+ import tempfile
7
+ import time
8
+
9
+ from astropy.io import fits
10
+
11
+
12
+ class FitsTestCase:
13
+ def setup(self):
14
+ self.data_dir = os.path.join(os.path.dirname(__file__), 'data')
15
+ self.temp_dir = tempfile.mkdtemp(prefix='fits-test-')
16
+
17
+ # Restore global settings to defaults
18
+ # TODO: Replace this when there's a better way to in the config API to
19
+ # force config values to their defaults
20
+ fits.conf.enable_record_valued_keyword_cards = True
21
+ fits.conf.extension_name_case_sensitive = False
22
+ fits.conf.strip_header_whitespace = True
23
+ fits.conf.use_memmap = True
24
+
25
+ def teardown(self):
26
+ if hasattr(self, 'temp_dir') and os.path.exists(self.temp_dir):
27
+ tries = 3
28
+ while tries:
29
+ try:
30
+ shutil.rmtree(self.temp_dir)
31
+ break
32
+ except OSError:
33
+ # Probably couldn't delete the file because for whatever
34
+ # reason a handle to it is still open/hasn't been
35
+ # garbage-collected
36
+ time.sleep(0.5)
37
+ tries -= 1
38
+
39
+ fits.conf.reset('enable_record_valued_keyword_cards')
40
+ fits.conf.reset('extension_name_case_sensitive')
41
+ fits.conf.reset('strip_header_whitespace')
42
+ fits.conf.reset('use_memmap')
43
+
44
+ def copy_file(self, filename):
45
+ """Copies a backup of a test data file to the temp dir and sets its
46
+ mode to writeable.
47
+ """
48
+
49
+ shutil.copy(self.data(filename), self.temp(filename))
50
+ os.chmod(self.temp(filename), stat.S_IREAD | stat.S_IWRITE)
51
+
52
+ def data(self, filename):
53
+ """Returns the path to a test data file."""
54
+
55
+ return os.path.join(self.data_dir, filename)
56
+
57
+ def temp(self, filename):
58
+ """ Returns the full path to a file in the test temp dir."""
59
+
60
+ return os.path.join(self.temp_dir, filename)
testbed/astropy__astropy/astropy/io/fits/tests/cfitsio_verify.c ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* This script verifies .fits checksums using CFITSIO to demonstrate
2
+ compatibility with Astropy. Since running it requires compiling and
3
+ linking against cfitsio, the script is included as a maintenance
4
+ asset but not automatically compiled and run.
5
+
6
+ After installing cfitsio to ~/include and ~/lib, I built cfitsio_verify
7
+ like this:
8
+
9
+ % gcc cfitsio_verify.c -I~/include -L~/lib -lcfitsio -lm -o cfitsio_verify
10
+
11
+ Run cfitsio_verify like this:
12
+
13
+ % cfitsio_verify tmp.fits
14
+
15
+ TODO: Compile this as an optional extension module and write unit tests that
16
+ use it; if compilation fails any such tests should be skipped.
17
+
18
+ */
19
+
20
+ #include <fitsio.h>
21
+
22
+ char * verify_status(int status)
23
+ {
24
+ if (status == 1) {
25
+ return "ok";
26
+ } else if (status == 0) {
27
+ return "missing";
28
+ } else if (status == -1) {
29
+ return "error";
30
+ }
31
+ }
32
+
33
+ int main(int argc, char *argv[])
34
+ {
35
+ fitsfile *fptr;
36
+ int i, j, status, dataok, hduok, hdunum, hdutype;
37
+ char *hdustr, *datastr;
38
+
39
+ for (i=1; i<argc; i++) {
40
+
41
+ fits_open_file(&fptr, argv[i], READONLY, &status);
42
+ if (status) {
43
+ fits_report_error(stderr, status);
44
+ exit(-1);
45
+ }
46
+
47
+ fits_get_num_hdus(fptr, &hdunum, &status);
48
+ if (status) {
49
+ fprintf(stderr, "Bad get_num_hdus status for '%s' = %d",
50
+ argv[i], status);
51
+ exit(-1);
52
+ }
53
+
54
+ for (j=0; j<hdunum; j++) {
55
+ fits_movabs_hdu(fptr, hdunum, &hdutype, &status);
56
+ if (status) {
57
+ fprintf(stderr, "Bad movabs status for '%s[%d]' = %d.",
58
+ argv[i], j, status);
59
+ exit(-1);
60
+ }
61
+ fits_verify_chksum(fptr, &dataok, &hduok, &status);
62
+ if (status) {
63
+ fprintf(stderr, "Bad verify status for '%s[%d]' = %d.",
64
+ argv[i], j, status);
65
+ exit(-1);
66
+ }
67
+ datastr = verify_status(dataok);
68
+ hdustr = verify_status(hduok);
69
+ printf("Verifying '%s[%d]' data='%s' hdu='%s'.\n",
70
+ argv[i], j, datastr, hdustr);
71
+ }
72
+ }
73
+ }
74
+
testbed/astropy__astropy/astropy/io/fits/tests/data/blank.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/compressed_float_bzero.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/history_header.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/memtest.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/o4sp040b0_raw.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/random_groups.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/stddata.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/table.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/tb.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/tdim.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/test0.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/variable_length_table.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/data/zerowidth.fits ADDED
testbed/astropy__astropy/astropy/io/fits/tests/test_checksum.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import sys
4
+ import warnings
5
+
6
+ import pytest
7
+ import numpy as np
8
+
9
+ from .test_table import comparerecords
10
+ from astropy.io.fits.hdu.base import _ValidHDU
11
+ from astropy.io import fits
12
+
13
+ from . import FitsTestCase
14
+
15
+
16
+ class TestChecksumFunctions(FitsTestCase):
17
+
18
+ # All checksums have been verified against CFITSIO
19
+ def setup(self):
20
+ super().setup()
21
+ self._oldfilters = warnings.filters[:]
22
+ warnings.filterwarnings(
23
+ 'error',
24
+ message='Checksum verification failed')
25
+ warnings.filterwarnings(
26
+ 'error',
27
+ message='Datasum verification failed')
28
+
29
+ # Monkey-patch the _get_timestamp method so that the checksum
30
+ # timestamps (and hence the checksum themselves) are always the same
31
+ self._old_get_timestamp = _ValidHDU._get_timestamp
32
+ _ValidHDU._get_timestamp = lambda self: '2013-12-20T13:36:10'
33
+
34
+ def teardown(self):
35
+ super().teardown()
36
+ warnings.filters = self._oldfilters
37
+ _ValidHDU._get_timestamp = self._old_get_timestamp
38
+
39
+ def test_sample_file(self):
40
+ hdul = fits.open(self.data('checksum.fits'), checksum=True)
41
+ hdul.close()
42
+
43
+ def test_image_create(self):
44
+ n = np.arange(100, dtype=np.int64)
45
+ hdu = fits.PrimaryHDU(n)
46
+ hdu.writeto(self.temp('tmp.fits'), overwrite=True, checksum=True)
47
+ with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
48
+ assert (hdu.data == hdul[0].data).all()
49
+ assert 'CHECKSUM' in hdul[0].header
50
+ assert 'DATASUM' in hdul[0].header
51
+
52
+ if not sys.platform.startswith('win32'):
53
+ # The checksum ends up being different on Windows, possibly due
54
+ # to slight floating point differences
55
+ assert hdul[0].header['CHECKSUM'] == 'ZHMkeGKjZGKjbGKj'
56
+ assert hdul[0].header['DATASUM'] == '4950'
57
+
58
+ def test_scaled_data(self):
59
+ with fits.open(self.data('scale.fits')) as hdul:
60
+ orig_data = hdul[0].data.copy()
61
+ hdul[0].scale('int16', 'old')
62
+ hdul.writeto(self.temp('tmp.fits'), overwrite=True, checksum=True)
63
+ with fits.open(self.temp('tmp.fits'), checksum=True) as hdul1:
64
+ assert (hdul1[0].data == orig_data).all()
65
+ assert 'CHECKSUM' in hdul1[0].header
66
+ assert hdul1[0].header['CHECKSUM'] == 'cUmaeUjZcUjacUjW'
67
+ assert 'DATASUM' in hdul1[0].header
68
+ assert hdul1[0].header['DATASUM'] == '1891563534'
69
+
70
+ def test_scaled_data_auto_rescale(self):
71
+ """
72
+ Regression test for
73
+ https://github.com/astropy/astropy/issues/3883#issuecomment-115122647
74
+
75
+ Ensure that when scaled data is automatically rescaled on
76
+ opening/writing a file that the checksum and datasum are computed for
77
+ the rescaled array.
78
+ """
79
+
80
+ with fits.open(self.data('scale.fits')) as hdul:
81
+ # Write out a copy of the data with the rescaling applied
82
+ hdul.writeto(self.temp('rescaled.fits'))
83
+
84
+ # Reopen the new file and save it back again with a checksum
85
+ with fits.open(self.temp('rescaled.fits')) as hdul:
86
+ hdul.writeto(self.temp('rescaled2.fits'), overwrite=True,
87
+ checksum=True)
88
+
89
+ # Now do like in the first writeto but use checksum immediately
90
+ with fits.open(self.data('scale.fits')) as hdul:
91
+ hdul.writeto(self.temp('rescaled3.fits'), checksum=True)
92
+
93
+ # Also don't rescale the data but add a checksum
94
+ with fits.open(self.data('scale.fits'),
95
+ do_not_scale_image_data=True) as hdul:
96
+ hdul.writeto(self.temp('scaled.fits'), checksum=True)
97
+
98
+ # Must used nested with statements to support older Python versions
99
+ # (but contextlib.nested is not available in newer Pythons :(
100
+ with fits.open(self.temp('rescaled2.fits')) as hdul1:
101
+ with fits.open(self.temp('rescaled3.fits')) as hdul2:
102
+ with fits.open(self.temp('scaled.fits')) as hdul3:
103
+ hdr1 = hdul1[0].header
104
+ hdr2 = hdul2[0].header
105
+ hdr3 = hdul3[0].header
106
+ assert hdr1['DATASUM'] == hdr2['DATASUM']
107
+ assert hdr1['CHECKSUM'] == hdr2['CHECKSUM']
108
+ assert hdr1['DATASUM'] != hdr3['DATASUM']
109
+ assert hdr1['CHECKSUM'] != hdr3['CHECKSUM']
110
+
111
+ def test_uint16_data(self):
112
+ checksums = [
113
+ ('aDcXaCcXaCcXaCcX', '0'), ('oYiGqXi9oXiEoXi9', '1746888714'),
114
+ ('VhqQWZoQVfoQVZoQ', '0'), ('4cPp5aOn4aOn4aOn', '0'),
115
+ ('8aCN8X9N8aAN8W9N', '1756785133'), ('UhqdUZnbUfnbUZnb', '0'),
116
+ ('4cQJ5aN94aNG4aN9', '0')]
117
+ with fits.open(self.data('o4sp040b0_raw.fits'), uint=True) as hdul:
118
+ hdul.writeto(self.temp('tmp.fits'), overwrite=True, checksum=True)
119
+ with fits.open(self.temp('tmp.fits'), uint=True,
120
+ checksum=True) as hdul1:
121
+ for idx, (hdu_a, hdu_b) in enumerate(zip(hdul, hdul1)):
122
+ if hdu_a.data is None or hdu_b.data is None:
123
+ assert hdu_a.data is hdu_b.data
124
+ else:
125
+ assert (hdu_a.data == hdu_b.data).all()
126
+
127
+ assert 'CHECKSUM' in hdul[idx].header
128
+ assert hdul[idx].header['CHECKSUM'] == checksums[idx][0]
129
+ assert 'DATASUM' in hdul[idx].header
130
+ assert hdul[idx].header['DATASUM'] == checksums[idx][1]
131
+
132
+ def test_groups_hdu_data(self):
133
+ imdata = np.arange(100.0)
134
+ imdata.shape = (10, 1, 1, 2, 5)
135
+ pdata1 = np.arange(10) + 0.1
136
+ pdata2 = 42
137
+ x = fits.hdu.groups.GroupData(imdata, parnames=[str('abc'), str('xyz')],
138
+ pardata=[pdata1, pdata2], bitpix=-32)
139
+ hdu = fits.GroupsHDU(x)
140
+ hdu.writeto(self.temp('tmp.fits'), overwrite=True, checksum=True)
141
+ with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
142
+ assert comparerecords(hdul[0].data, hdu.data)
143
+ assert 'CHECKSUM' in hdul[0].header
144
+ assert hdul[0].header['CHECKSUM'] == '3eDQAZDO4dDOAZDO'
145
+ assert 'DATASUM' in hdul[0].header
146
+ assert hdul[0].header['DATASUM'] == '2797758084'
147
+
148
+ def test_binary_table_data(self):
149
+ a1 = np.array(['NGC1001', 'NGC1002', 'NGC1003'])
150
+ a2 = np.array([11.1, 12.3, 15.2])
151
+ col1 = fits.Column(name='target', format='20A', array=a1)
152
+ col2 = fits.Column(name='V_mag', format='E', array=a2)
153
+ cols = fits.ColDefs([col1, col2])
154
+ tbhdu = fits.BinTableHDU.from_columns(cols)
155
+ tbhdu.writeto(self.temp('tmp.fits'), overwrite=True, checksum=True)
156
+ with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
157
+ assert comparerecords(tbhdu.data, hdul[1].data)
158
+ assert 'CHECKSUM' in hdul[0].header
159
+ assert hdul[0].header['CHECKSUM'] == 'D8iBD6ZAD6fAD6ZA'
160
+ assert 'DATASUM' in hdul[0].header
161
+ assert hdul[0].header['DATASUM'] == '0'
162
+ assert 'CHECKSUM' in hdul[1].header
163
+ assert hdul[1].header['CHECKSUM'] == 'aD1Oa90MaC0Ma90M'
164
+ assert 'DATASUM' in hdul[1].header
165
+ assert hdul[1].header['DATASUM'] == '1062205743'
166
+
167
+ def test_variable_length_table_data(self):
168
+ c1 = fits.Column(name='var', format='PJ()',
169
+ array=np.array([[45.0, 56], np.array([11, 12, 13])],
170
+ 'O'))
171
+ c2 = fits.Column(name='xyz', format='2I', array=[[11, 3], [12, 4]])
172
+ tbhdu = fits.BinTableHDU.from_columns([c1, c2])
173
+ tbhdu.writeto(self.temp('tmp.fits'), overwrite=True, checksum=True)
174
+ with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
175
+ assert comparerecords(tbhdu.data, hdul[1].data)
176
+ assert 'CHECKSUM' in hdul[0].header
177
+ assert hdul[0].header['CHECKSUM'] == 'D8iBD6ZAD6fAD6ZA'
178
+ assert 'DATASUM' in hdul[0].header
179
+ assert hdul[0].header['DATASUM'] == '0'
180
+ assert 'CHECKSUM' in hdul[1].header
181
+ assert hdul[1].header['CHECKSUM'] == 'YIGoaIEmZIEmaIEm'
182
+ assert 'DATASUM' in hdul[1].header
183
+ assert hdul[1].header['DATASUM'] == '1507485'
184
+
185
+ def test_ascii_table_data(self):
186
+ a1 = np.array(['abc', 'def'])
187
+ r1 = np.array([11.0, 12.0])
188
+ c1 = fits.Column(name='abc', format='A3', array=a1)
189
+ # This column used to be E format, but the single-precision float lost
190
+ # too much precision when scaling so it was changed to a D
191
+ c2 = fits.Column(name='def', format='D', array=r1, bscale=2.3,
192
+ bzero=0.6)
193
+ c3 = fits.Column(name='t1', format='I', array=[91, 92, 93])
194
+ x = fits.ColDefs([c1, c2, c3])
195
+ hdu = fits.TableHDU.from_columns(x)
196
+ hdu.writeto(self.temp('tmp.fits'), overwrite=True, checksum=True)
197
+ with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
198
+ assert comparerecords(hdu.data, hdul[1].data)
199
+ assert 'CHECKSUM' in hdul[0].header
200
+ assert hdul[0].header['CHECKSUM'] == 'D8iBD6ZAD6fAD6ZA'
201
+ assert 'DATASUM' in hdul[0].header
202
+ assert hdul[0].header['DATASUM'] == '0'
203
+
204
+ if not sys.platform.startswith('win32'):
205
+ # The checksum ends up being different on Windows, possibly due
206
+ # to slight floating point differences
207
+ assert 'CHECKSUM' in hdul[1].header
208
+ assert hdul[1].header['CHECKSUM'] == '3rKFAoI94oICAoI9'
209
+ assert 'DATASUM' in hdul[1].header
210
+ assert hdul[1].header['DATASUM'] == '1914653725'
211
+
212
+ def test_compressed_image_data(self):
213
+ with fits.open(self.data('comp.fits')) as h1:
214
+ h1.writeto(self.temp('tmp.fits'), overwrite=True, checksum=True)
215
+ with fits.open(self.temp('tmp.fits'), checksum=True) as h2:
216
+ assert np.all(h1[1].data == h2[1].data)
217
+ assert 'CHECKSUM' in h2[0].header
218
+ assert h2[0].header['CHECKSUM'] == 'D8iBD6ZAD6fAD6ZA'
219
+ assert 'DATASUM' in h2[0].header
220
+ assert h2[0].header['DATASUM'] == '0'
221
+ assert 'CHECKSUM' in h2[1].header
222
+ assert h2[1].header['CHECKSUM'] == 'ZeAbdb8aZbAabb7a'
223
+ assert 'DATASUM' in h2[1].header
224
+ assert h2[1].header['DATASUM'] == '113055149'
225
+
226
+ def test_compressed_image_data_int16(self):
227
+ n = np.arange(100, dtype='int16')
228
+ hdu = fits.ImageHDU(n)
229
+ comp_hdu = fits.CompImageHDU(hdu.data, hdu.header)
230
+ comp_hdu.writeto(self.temp('tmp.fits'), checksum=True)
231
+ hdu.writeto(self.temp('uncomp.fits'), checksum=True)
232
+ with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
233
+ assert np.all(hdul[1].data == comp_hdu.data)
234
+ assert np.all(hdul[1].data == hdu.data)
235
+ assert 'CHECKSUM' in hdul[0].header
236
+ assert hdul[0].header['CHECKSUM'] == 'D8iBD6ZAD6fAD6ZA'
237
+ assert 'DATASUM' in hdul[0].header
238
+ assert hdul[0].header['DATASUM'] == '0'
239
+
240
+ assert 'CHECKSUM' in hdul[1].header
241
+ assert hdul[1]._header['CHECKSUM'] == 'J5cCJ5c9J5cAJ5c9'
242
+ assert 'DATASUM' in hdul[1].header
243
+ assert hdul[1]._header['DATASUM'] == '2453673070'
244
+ assert 'CHECKSUM' in hdul[1].header
245
+
246
+ with fits.open(self.temp('uncomp.fits'), checksum=True) as hdul2:
247
+ header_comp = hdul[1]._header
248
+ header_uncomp = hdul2[1].header
249
+ assert 'ZHECKSUM' in header_comp
250
+ assert 'CHECKSUM' in header_uncomp
251
+ assert header_uncomp['CHECKSUM'] == 'ZE94eE91ZE91bE91'
252
+ assert header_comp['ZHECKSUM'] == header_uncomp['CHECKSUM']
253
+ assert 'ZDATASUM' in header_comp
254
+ assert 'DATASUM' in header_uncomp
255
+ assert header_uncomp['DATASUM'] == '160565700'
256
+ assert header_comp['ZDATASUM'] == header_uncomp['DATASUM']
257
+
258
+ def test_compressed_image_data_float32(self):
259
+ n = np.arange(100, dtype='float32')
260
+ hdu = fits.ImageHDU(n)
261
+ comp_hdu = fits.CompImageHDU(hdu.data, hdu.header)
262
+ comp_hdu.writeto(self.temp('tmp.fits'), checksum=True)
263
+ hdu.writeto(self.temp('uncomp.fits'), checksum=True)
264
+ with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
265
+ assert np.all(hdul[1].data == comp_hdu.data)
266
+ assert np.all(hdul[1].data == hdu.data)
267
+ assert 'CHECKSUM' in hdul[0].header
268
+ assert hdul[0].header['CHECKSUM'] == 'D8iBD6ZAD6fAD6ZA'
269
+ assert 'DATASUM' in hdul[0].header
270
+ assert hdul[0].header['DATASUM'] == '0'
271
+
272
+ assert 'CHECKSUM' in hdul[1].header
273
+ assert 'DATASUM' in hdul[1].header
274
+
275
+ if not sys.platform.startswith('win32'):
276
+ # The checksum ends up being different on Windows, possibly due
277
+ # to slight floating point differences
278
+ assert hdul[1]._header['CHECKSUM'] == 'eATIf3SHe9SHe9SH'
279
+ assert hdul[1]._header['DATASUM'] == '1277667818'
280
+
281
+ with fits.open(self.temp('uncomp.fits'), checksum=True) as hdul2:
282
+ header_comp = hdul[1]._header
283
+ header_uncomp = hdul2[1].header
284
+ assert 'ZHECKSUM' in header_comp
285
+ assert 'CHECKSUM' in header_uncomp
286
+ assert header_uncomp['CHECKSUM'] == 'Cgr5FZo2Cdo2CZo2'
287
+ assert header_comp['ZHECKSUM'] == header_uncomp['CHECKSUM']
288
+ assert 'ZDATASUM' in header_comp
289
+ assert 'DATASUM' in header_uncomp
290
+ assert header_uncomp['DATASUM'] == '2393636889'
291
+ assert header_comp['ZDATASUM'] == header_uncomp['DATASUM']
292
+
293
+ def test_open_with_no_keywords(self):
294
+ hdul = fits.open(self.data('arange.fits'), checksum=True)
295
+ hdul.close()
296
+
297
+ def test_append(self):
298
+ hdul = fits.open(self.data('tb.fits'))
299
+ hdul.writeto(self.temp('tmp.fits'), overwrite=True)
300
+ n = np.arange(100)
301
+ fits.append(self.temp('tmp.fits'), n, checksum=True)
302
+ hdul.close()
303
+ hdul = fits.open(self.temp('tmp.fits'), checksum=True)
304
+ assert hdul[0]._checksum is None
305
+ hdul.close()
306
+
307
+ def test_writeto_convenience(self):
308
+ n = np.arange(100)
309
+ fits.writeto(self.temp('tmp.fits'), n, overwrite=True, checksum=True)
310
+ hdul = fits.open(self.temp('tmp.fits'), checksum=True)
311
+ self._check_checksums(hdul[0])
312
+ hdul.close()
313
+
314
+ def test_hdu_writeto(self):
315
+ n = np.arange(100, dtype='int16')
316
+ hdu = fits.ImageHDU(n)
317
+ hdu.writeto(self.temp('tmp.fits'), checksum=True)
318
+ hdul = fits.open(self.temp('tmp.fits'), checksum=True)
319
+ self._check_checksums(hdul[0])
320
+ hdul.close()
321
+
322
+ def test_hdu_writeto_existing(self):
323
+ """
324
+ Tests that when using writeto with checksum=True, a checksum and
325
+ datasum are added to HDUs that did not previously have one.
326
+
327
+ Regression test for https://github.com/spacetelescope/PyFITS/issues/8
328
+ """
329
+
330
+ with fits.open(self.data('tb.fits')) as hdul:
331
+ hdul.writeto(self.temp('test.fits'), checksum=True)
332
+
333
+ with fits.open(self.temp('test.fits')) as hdul:
334
+ assert 'CHECKSUM' in hdul[0].header
335
+ # These checksums were verified against CFITSIO
336
+ assert hdul[0].header['CHECKSUM'] == '7UgqATfo7TfoATfo'
337
+ assert 'DATASUM' in hdul[0].header
338
+ assert hdul[0].header['DATASUM'] == '0'
339
+ assert 'CHECKSUM' in hdul[1].header
340
+ assert hdul[1].header['CHECKSUM'] == '99daD8bX98baA8bU'
341
+ assert 'DATASUM' in hdul[1].header
342
+ assert hdul[1].header['DATASUM'] == '1829680925'
343
+
344
+ def test_datasum_only(self):
345
+ n = np.arange(100, dtype='int16')
346
+ hdu = fits.ImageHDU(n)
347
+ hdu.writeto(self.temp('tmp.fits'), overwrite=True, checksum='datasum')
348
+ with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
349
+ if not (hasattr(hdul[0], '_datasum') and hdul[0]._datasum):
350
+ pytest.fail(msg='Missing DATASUM keyword')
351
+
352
+ if not (hasattr(hdul[0], '_checksum') and not hdul[0]._checksum):
353
+ pytest.fail(msg='Non-empty CHECKSUM keyword')
354
+
355
+ def test_open_update_mode_preserve_checksum(self):
356
+ """
357
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/148 where
358
+ checksums are being removed from headers when a file is opened in
359
+ update mode, even though no changes were made to the file.
360
+ """
361
+
362
+ self.copy_file('checksum.fits')
363
+
364
+ with fits.open(self.temp('checksum.fits')) as hdul:
365
+ data = hdul[1].data.copy()
366
+
367
+ hdul = fits.open(self.temp('checksum.fits'), mode='update')
368
+ hdul.close()
369
+
370
+ with fits.open(self.temp('checksum.fits')) as hdul:
371
+ assert 'CHECKSUM' in hdul[1].header
372
+ assert 'DATASUM' in hdul[1].header
373
+ assert comparerecords(data, hdul[1].data)
374
+
375
+ def test_open_update_mode_update_checksum(self):
376
+ """
377
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/148, part
378
+ 2. This ensures that if a file contains a checksum, the checksum is
379
+ updated when changes are saved to the file, even if the file was opened
380
+ with the default of checksum=False.
381
+
382
+ An existing checksum and/or datasum are only stripped if the file is
383
+ opened with checksum='remove'.
384
+ """
385
+
386
+ self.copy_file('checksum.fits')
387
+ with fits.open(self.temp('checksum.fits')) as hdul:
388
+ header = hdul[1].header.copy()
389
+ data = hdul[1].data.copy()
390
+
391
+ with fits.open(self.temp('checksum.fits'), mode='update') as hdul:
392
+ hdul[1].header['FOO'] = 'BAR'
393
+ hdul[1].data[0]['TIME'] = 42
394
+
395
+ with fits.open(self.temp('checksum.fits')) as hdul:
396
+ header2 = hdul[1].header
397
+ data2 = hdul[1].data
398
+ assert header2[:-3] == header[:-2]
399
+ assert 'CHECKSUM' in header2
400
+ assert 'DATASUM' in header2
401
+ assert header2['FOO'] == 'BAR'
402
+ assert (data2['TIME'][1:] == data['TIME'][1:]).all()
403
+ assert data2['TIME'][0] == 42
404
+
405
+ with fits.open(self.temp('checksum.fits'), mode='update',
406
+ checksum='remove') as hdul:
407
+ pass
408
+
409
+ with fits.open(self.temp('checksum.fits')) as hdul:
410
+ header2 = hdul[1].header
411
+ data2 = hdul[1].data
412
+ assert header2[:-1] == header[:-2]
413
+ assert 'CHECKSUM' not in header2
414
+ assert 'DATASUM' not in header2
415
+ assert header2['FOO'] == 'BAR'
416
+ assert (data2['TIME'][1:] == data['TIME'][1:]).all()
417
+ assert data2['TIME'][0] == 42
418
+
419
+ def test_overwrite_invalid(self):
420
+ """
421
+ Tests that invalid checksum or datasum are overwriten when the file is
422
+ saved.
423
+ """
424
+
425
+ reffile = self.temp('ref.fits')
426
+ with fits.open(self.data('tb.fits')) as hdul:
427
+ hdul.writeto(reffile, checksum=True)
428
+
429
+ testfile = self.temp('test.fits')
430
+ with fits.open(self.data('tb.fits')) as hdul:
431
+ hdul[0].header['DATASUM'] = '1 '
432
+ hdul[0].header['CHECKSUM'] = '8UgqATfo7TfoATfo'
433
+ hdul[1].header['DATASUM'] = '2349680925'
434
+ hdul[1].header['CHECKSUM'] = '11daD8bX98baA8bU'
435
+ hdul.writeto(testfile)
436
+
437
+ with fits.open(testfile) as hdul:
438
+ hdul.writeto(self.temp('test2.fits'), checksum=True)
439
+
440
+ with fits.open(self.temp('test2.fits')) as hdul:
441
+ with fits.open(reffile) as ref:
442
+ assert 'CHECKSUM' in hdul[0].header
443
+ # These checksums were verified against CFITSIO
444
+ assert hdul[0].header['CHECKSUM'] == ref[0].header['CHECKSUM']
445
+ assert 'DATASUM' in hdul[0].header
446
+ assert hdul[0].header['DATASUM'] == '0'
447
+ assert 'CHECKSUM' in hdul[1].header
448
+ assert hdul[1].header['CHECKSUM'] == ref[1].header['CHECKSUM']
449
+ assert 'DATASUM' in hdul[1].header
450
+ assert hdul[1].header['DATASUM'] == ref[1].header['DATASUM']
451
+
452
+ def _check_checksums(self, hdu):
453
+ if not (hasattr(hdu, '_datasum') and hdu._datasum):
454
+ pytest.fail(msg='Missing DATASUM keyword')
455
+
456
+ if not (hasattr(hdu, '_checksum') and hdu._checksum):
457
+ pytest.fail(msg='Missing CHECKSUM keyword')
testbed/astropy__astropy/astropy/io/fits/tests/test_compression_failures.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import pytest
4
+ import numpy as np
5
+
6
+ from astropy.io import fits
7
+ from astropy.io.fits.compression import compress_hdu
8
+
9
+ from . import FitsTestCase
10
+
11
+
12
+ MAX_INT = np.iinfo(np.intc).max
13
+ MAX_LONG = np.iinfo(np.long).max
14
+ MAX_LONGLONG = np.iinfo(np.longlong).max
15
+
16
+
17
+ class TestCompressionFunction(FitsTestCase):
18
+ def test_wrong_argument_number(self):
19
+ with pytest.raises(TypeError):
20
+ compress_hdu(1, 2)
21
+
22
+ def test_unknown_compression_type(self):
23
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
24
+ hdu._header['ZCMPTYPE'] = 'fun'
25
+ with pytest.raises(ValueError) as exc:
26
+ compress_hdu(hdu)
27
+ assert 'Unrecognized compression type: fun' in str(exc)
28
+
29
+ def test_zbitpix_unknown(self):
30
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
31
+ hdu._header['ZBITPIX'] = 13
32
+ with pytest.raises(ValueError) as exc:
33
+ compress_hdu(hdu)
34
+ assert 'Invalid value for BITPIX: 13' in str(exc)
35
+
36
+ def test_data_none(self):
37
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
38
+ hdu.data = None
39
+ with pytest.raises(TypeError) as exc:
40
+ compress_hdu(hdu)
41
+ assert 'CompImageHDU.data must be a numpy.ndarray' in str(exc)
42
+
43
+ def test_missing_internal_header(self):
44
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
45
+ del hdu._header
46
+ with pytest.raises(AttributeError) as exc:
47
+ compress_hdu(hdu)
48
+ assert '_header' in str(exc)
49
+
50
+ def test_invalid_tform(self):
51
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
52
+ hdu._header['TFORM1'] = 'TX'
53
+ with pytest.raises(RuntimeError) as exc:
54
+ compress_hdu(hdu)
55
+ assert 'TX' in str(exc) and 'TFORM' in str(exc)
56
+
57
+ def test_invalid_zdither(self):
58
+ hdu = fits.CompImageHDU(np.ones((10, 10)), quantize_method=1)
59
+ hdu._header['ZDITHER0'] = 'a'
60
+ with pytest.raises(TypeError):
61
+ compress_hdu(hdu)
62
+
63
+ @pytest.mark.parametrize('kw', ['ZNAXIS', 'ZBITPIX'])
64
+ def test_header_missing_keyword(self, kw):
65
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
66
+ del hdu._header[kw]
67
+ with pytest.raises(KeyError) as exc:
68
+ compress_hdu(hdu)
69
+ assert kw in str(exc)
70
+
71
+ @pytest.mark.parametrize('kw', ['ZNAXIS', 'ZVAL1', 'ZVAL2', 'ZBLANK', 'BLANK'])
72
+ def test_header_value_int_overflow(self, kw):
73
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
74
+ hdu._header[kw] = MAX_INT + 1
75
+ with pytest.raises(OverflowError):
76
+ compress_hdu(hdu)
77
+
78
+ @pytest.mark.parametrize('kw', ['ZTILE1', 'ZNAXIS1'])
79
+ def test_header_value_long_overflow(self, kw):
80
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
81
+ hdu._header[kw] = MAX_LONG + 1
82
+ with pytest.raises(OverflowError):
83
+ compress_hdu(hdu)
84
+
85
+ @pytest.mark.parametrize('kw', ['NAXIS1', 'NAXIS2', 'TNULL1', 'PCOUNT', 'THEAP'])
86
+ def test_header_value_longlong_overflow(self, kw):
87
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
88
+ hdu._header[kw] = MAX_LONGLONG + 1
89
+ with pytest.raises(OverflowError):
90
+ compress_hdu(hdu)
91
+
92
+ @pytest.mark.parametrize('kw', ['ZVAL3'])
93
+ def test_header_value_float_overflow(self, kw):
94
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
95
+ hdu._header[kw] = 1e300
96
+ with pytest.raises(OverflowError):
97
+ compress_hdu(hdu)
98
+
99
+ @pytest.mark.parametrize('kw', ['NAXIS1', 'NAXIS2', 'TFIELDS', 'PCOUNT'])
100
+ def test_header_value_negative(self, kw):
101
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
102
+ hdu._header[kw] = -1
103
+ with pytest.raises(ValueError) as exc:
104
+ compress_hdu(hdu)
105
+ assert '{} should not be negative.'.format(kw) in str(exc)
106
+
107
+ @pytest.mark.parametrize(
108
+ ('kw', 'limit'),
109
+ [('ZNAXIS', 999),
110
+ ('TFIELDS', 999)])
111
+ def test_header_value_exceeds_custom_limit(self, kw, limit):
112
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
113
+ hdu._header[kw] = limit + 1
114
+ with pytest.raises(ValueError) as exc:
115
+ compress_hdu(hdu)
116
+ assert kw in str(exc)
117
+
118
+ @pytest.mark.parametrize('kw', ['TTYPE1', 'TFORM1', 'ZCMPTYPE', 'ZNAME1',
119
+ 'ZQUANTIZ'])
120
+ def test_header_value_no_string(self, kw):
121
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
122
+ hdu._header[kw] = 1
123
+ with pytest.raises(TypeError):
124
+ compress_hdu(hdu)
125
+
126
+ @pytest.mark.parametrize('kw', ['TZERO1', 'TSCAL1'])
127
+ def test_header_value_no_double(self, kw):
128
+ hdu = fits.CompImageHDU(np.ones((10, 10)))
129
+ hdu._header[kw] = '1'
130
+ with pytest.raises(TypeError):
131
+ compress_hdu(hdu)
132
+
133
+ @pytest.mark.parametrize('kw', ['ZSCALE', 'ZZERO'])
134
+ def test_header_value_no_double_int_image(self, kw):
135
+ hdu = fits.CompImageHDU(np.ones((10, 10), dtype=np.int32))
136
+ hdu._header[kw] = '1'
137
+ with pytest.raises(TypeError):
138
+ compress_hdu(hdu)
testbed/astropy__astropy/astropy/io/fits/tests/test_connect.py ADDED
@@ -0,0 +1,696 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gc
3
+ import pathlib
4
+ import warnings
5
+
6
+ import pytest
7
+ import numpy as np
8
+ from numpy.testing import assert_allclose
9
+
10
+ from astropy.io.fits.column import (_parse_tdisp_format, _fortran_to_python_format,
11
+ python_to_tdisp)
12
+
13
+ from astropy.io.fits import HDUList, PrimaryHDU, BinTableHDU
14
+
15
+ from astropy.io import fits
16
+
17
+ from astropy import units as u
18
+ from astropy.table import Table, QTable, NdarrayMixin, Column
19
+ from astropy.table.table_helpers import simple_table
20
+ from astropy.tests.helper import catch_warnings
21
+ from astropy.units.format.fits import UnitScaleError
22
+ from astropy.utils.exceptions import AstropyUserWarning
23
+
24
+ from astropy.coordinates import SkyCoord, Latitude, Longitude, Angle, EarthLocation
25
+ from astropy.time import Time, TimeDelta
26
+ from astropy.units.quantity import QuantityInfo
27
+
28
+ try:
29
+ import yaml # pylint: disable=W0611 # noqa
30
+ HAS_YAML = True
31
+ except ImportError:
32
+ HAS_YAML = False
33
+
34
+ DATA = os.path.join(os.path.dirname(__file__), 'data')
35
+
36
+
37
+ def equal_data(a, b):
38
+ for name in a.dtype.names:
39
+ if not np.all(a[name] == b[name]):
40
+ return False
41
+ return True
42
+
43
+
44
+ class TestSingleTable:
45
+
46
+ def setup_class(self):
47
+ self.data = np.array(list(zip([1, 2, 3, 4],
48
+ ['a', 'b', 'c', 'd'],
49
+ [2.3, 4.5, 6.7, 8.9])),
50
+ dtype=[(str('a'), int), (str('b'), str('U1')), (str('c'), float)])
51
+
52
+ def test_simple(self, tmpdir):
53
+ filename = str(tmpdir.join('test_simple.fts'))
54
+ t1 = Table(self.data)
55
+ t1.write(filename, overwrite=True)
56
+ t2 = Table.read(filename)
57
+ assert equal_data(t1, t2)
58
+
59
+ def test_simple_pathlib(self, tmpdir):
60
+ filename = pathlib.Path(str(tmpdir.join('test_simple.fit')))
61
+ t1 = Table(self.data)
62
+ t1.write(filename, overwrite=True)
63
+ t2 = Table.read(filename)
64
+ assert equal_data(t1, t2)
65
+
66
+ def test_simple_meta(self, tmpdir):
67
+ filename = str(tmpdir.join('test_simple.fits'))
68
+ t1 = Table(self.data)
69
+ t1.meta['A'] = 1
70
+ t1.meta['B'] = 2.3
71
+ t1.meta['C'] = 'spam'
72
+ t1.meta['comments'] = ['this', 'is', 'a', 'long', 'comment']
73
+ t1.meta['HISTORY'] = ['first', 'second', 'third']
74
+ t1.write(filename, overwrite=True)
75
+ t2 = Table.read(filename)
76
+ assert equal_data(t1, t2)
77
+ for key in t1.meta:
78
+ if isinstance(t1.meta, list):
79
+ for i in range(len(t1.meta[key])):
80
+ assert t1.meta[key][i] == t2.meta[key][i]
81
+ else:
82
+ assert t1.meta[key] == t2.meta[key]
83
+
84
+ def test_simple_meta_conflicting(self, tmpdir):
85
+ filename = str(tmpdir.join('test_simple.fits'))
86
+ t1 = Table(self.data)
87
+ t1.meta['ttype1'] = 'spam'
88
+ with catch_warnings() as l:
89
+ t1.write(filename, overwrite=True)
90
+ assert len(l) == 1
91
+ assert str(l[0].message).startswith(
92
+ 'Meta-data keyword ttype1 will be ignored since it conflicts with a FITS reserved keyword')
93
+
94
+ def test_simple_noextension(self, tmpdir):
95
+ """
96
+ Test that file type is recognized without extension
97
+ """
98
+ filename = str(tmpdir.join('test_simple'))
99
+ t1 = Table(self.data)
100
+ t1.write(filename, overwrite=True, format='fits')
101
+ t2 = Table.read(filename)
102
+ assert equal_data(t1, t2)
103
+
104
+ @pytest.mark.parametrize('table_type', (Table, QTable))
105
+ def test_with_units(self, table_type, tmpdir):
106
+ filename = str(tmpdir.join('test_with_units.fits'))
107
+ t1 = table_type(self.data)
108
+ t1['a'].unit = u.m
109
+ t1['c'].unit = u.km / u.s
110
+ t1.write(filename, overwrite=True)
111
+ t2 = table_type.read(filename)
112
+ assert equal_data(t1, t2)
113
+ assert t2['a'].unit == u.m
114
+ assert t2['c'].unit == u.km / u.s
115
+
116
+ @pytest.mark.parametrize('table_type', (Table, QTable))
117
+ def test_with_format(self, table_type, tmpdir):
118
+ filename = str(tmpdir.join('test_with_format.fits'))
119
+ t1 = table_type(self.data)
120
+ t1['a'].format = '{:5d}'
121
+ t1['b'].format = '{:>20}'
122
+ t1['c'].format = '{:6.2f}'
123
+ t1.write(filename, overwrite=True)
124
+ t2 = table_type.read(filename)
125
+ assert equal_data(t1, t2)
126
+ assert t2['a'].format == '{:5d}'
127
+ assert t2['b'].format == '{:>20}'
128
+ assert t2['c'].format == '{:6.2f}'
129
+
130
+ def test_masked(self, tmpdir):
131
+ filename = str(tmpdir.join('test_masked.fits'))
132
+ t1 = Table(self.data, masked=True)
133
+ t1.mask['a'] = [1, 0, 1, 0]
134
+ t1.mask['b'] = [1, 0, 0, 1]
135
+ t1.mask['c'] = [0, 1, 1, 0]
136
+ t1.write(filename, overwrite=True)
137
+ t2 = Table.read(filename)
138
+ assert t2.masked
139
+ assert equal_data(t1, t2)
140
+ assert np.all(t1['a'].mask == t2['a'].mask)
141
+ # Disabled for now, as there is no obvious way to handle masking of
142
+ # non-integer columns in FITS
143
+ # TODO: Re-enable these tests if some workaround for this can be found
144
+ # assert np.all(t1['b'].mask == t2['b'].mask)
145
+ # assert np.all(t1['c'].mask == t2['c'].mask)
146
+
147
+ def test_masked_nan(self, tmpdir):
148
+ filename = str(tmpdir.join('test_masked_nan.fits'))
149
+ data = np.array(list(zip([5.2, 8.4, 3.9, 6.3],
150
+ [2.3, 4.5, 6.7, 8.9])),
151
+ dtype=[(str('a'), np.float64), (str('b'), np.float32)])
152
+ t1 = Table(data, masked=True)
153
+ t1.mask['a'] = [1, 0, 1, 0]
154
+ t1.mask['b'] = [1, 0, 0, 1]
155
+ t1.write(filename, overwrite=True)
156
+ t2 = Table.read(filename)
157
+ np.testing.assert_array_almost_equal(t2['a'], [np.nan, 8.4, np.nan, 6.3])
158
+ np.testing.assert_array_almost_equal(t2['b'], [np.nan, 4.5, 6.7, np.nan])
159
+ # assert t2.masked
160
+ # t2.masked = false currently, as the only way to determine whether a table is masked
161
+ # while reading is to check whether col.null is present. For float columns, col.null
162
+ # is not initialized
163
+
164
+ def test_read_from_fileobj(self, tmpdir):
165
+ filename = str(tmpdir.join('test_read_from_fileobj.fits'))
166
+ hdu = BinTableHDU(self.data)
167
+ hdu.writeto(filename, overwrite=True)
168
+ with open(filename, 'rb') as f:
169
+ t = Table.read(f)
170
+ assert equal_data(t, self.data)
171
+
172
+ def test_read_with_nonstandard_units(self):
173
+ hdu = BinTableHDU(self.data)
174
+ hdu.columns[0].unit = 'RADIANS'
175
+ hdu.columns[1].unit = 'spam'
176
+ hdu.columns[2].unit = 'millieggs'
177
+ t = Table.read(hdu)
178
+ assert equal_data(t, self.data)
179
+
180
+ def test_memmap(self, tmpdir):
181
+ filename = str(tmpdir.join('test_simple.fts'))
182
+ t1 = Table(self.data)
183
+ t1.write(filename, overwrite=True)
184
+ t2 = Table.read(filename, memmap=False)
185
+ t3 = Table.read(filename, memmap=True)
186
+ assert equal_data(t2, t3)
187
+ # To avoid issues with --open-files, we need to remove references to
188
+ # data that uses memory mapping and force the garbage collection
189
+ del t1, t2, t3
190
+ gc.collect()
191
+
192
+ @pytest.mark.parametrize('memmap', (False, True))
193
+ def test_character_as_bytes(self, tmpdir, memmap):
194
+ filename = str(tmpdir.join('test_simple.fts'))
195
+ t1 = Table(self.data)
196
+ t1.write(filename, overwrite=True)
197
+ t2 = Table.read(filename, character_as_bytes=False, memmap=memmap)
198
+ t3 = Table.read(filename, character_as_bytes=True, memmap=memmap)
199
+ assert t2['b'].dtype.kind == 'U'
200
+ assert t3['b'].dtype.kind == 'S'
201
+ assert equal_data(t2, t3)
202
+ # To avoid issues with --open-files, we need to remove references to
203
+ # data that uses memory mapping and force the garbage collection
204
+ del t1, t2, t3
205
+ gc.collect()
206
+
207
+
208
+ class TestMultipleHDU:
209
+
210
+ def setup_class(self):
211
+ self.data1 = np.array(list(zip([1, 2, 3, 4],
212
+ ['a', 'b', 'c', 'd'],
213
+ [2.3, 4.5, 6.7, 8.9])),
214
+ dtype=[(str('a'), int), (str('b'), str('U1')), (str('c'), float)])
215
+ self.data2 = np.array(list(zip([1.4, 2.3, 3.2, 4.7],
216
+ [2.3, 4.5, 6.7, 8.9])),
217
+ dtype=[(str('p'), float), (str('q'), float)])
218
+ hdu1 = PrimaryHDU()
219
+ hdu2 = BinTableHDU(self.data1, name='first')
220
+ hdu3 = BinTableHDU(self.data2, name='second')
221
+
222
+ self.hdus = HDUList([hdu1, hdu2, hdu3])
223
+
224
+ def teardown_class(self):
225
+ del self.hdus
226
+
227
+ def setup_method(self, method):
228
+ warnings.filterwarnings('always')
229
+
230
+ def test_read(self, tmpdir):
231
+ filename = str(tmpdir.join('test_read.fits'))
232
+ self.hdus.writeto(filename)
233
+ with catch_warnings() as l:
234
+ t = Table.read(filename)
235
+ assert len(l) == 1
236
+ assert str(l[0].message).startswith(
237
+ 'hdu= was not specified but multiple tables are present, reading in first available table (hdu=1)')
238
+ assert equal_data(t, self.data1)
239
+
240
+ def test_read_with_hdu_0(self, tmpdir):
241
+ filename = str(tmpdir.join('test_read_with_hdu_0.fits'))
242
+ self.hdus.writeto(filename)
243
+ with pytest.raises(ValueError) as exc:
244
+ Table.read(filename, hdu=0)
245
+ assert exc.value.args[0] == 'No table found in hdu=0'
246
+
247
+ @pytest.mark.parametrize('hdu', [1, 'first'])
248
+ def test_read_with_hdu_1(self, tmpdir, hdu):
249
+ filename = str(tmpdir.join('test_read_with_hdu_1.fits'))
250
+ self.hdus.writeto(filename)
251
+ with catch_warnings() as l:
252
+ t = Table.read(filename, hdu=hdu)
253
+ assert len(l) == 0
254
+ assert equal_data(t, self.data1)
255
+
256
+ @pytest.mark.parametrize('hdu', [2, 'second'])
257
+ def test_read_with_hdu_2(self, tmpdir, hdu):
258
+ filename = str(tmpdir.join('test_read_with_hdu_2.fits'))
259
+ self.hdus.writeto(filename)
260
+ with catch_warnings() as l:
261
+ t = Table.read(filename, hdu=hdu)
262
+ assert len(l) == 0
263
+ assert equal_data(t, self.data2)
264
+
265
+ def test_read_from_hdulist(self):
266
+ with catch_warnings() as l:
267
+ t = Table.read(self.hdus)
268
+ assert len(l) == 1
269
+ assert str(l[0].message).startswith(
270
+ 'hdu= was not specified but multiple tables are present, reading in first available table (hdu=1)')
271
+ assert equal_data(t, self.data1)
272
+
273
+ def test_read_from_hdulist_with_hdu_0(self, tmpdir):
274
+ with pytest.raises(ValueError) as exc:
275
+ Table.read(self.hdus, hdu=0)
276
+ assert exc.value.args[0] == 'No table found in hdu=0'
277
+
278
+ @pytest.mark.parametrize('hdu', [1, 'first'])
279
+ def test_read_from_hdulist_with_hdu_1(self, tmpdir, hdu):
280
+ with catch_warnings() as l:
281
+ t = Table.read(self.hdus, hdu=hdu)
282
+ assert len(l) == 0
283
+ assert equal_data(t, self.data1)
284
+
285
+ @pytest.mark.parametrize('hdu', [2, 'second'])
286
+ def test_read_from_hdulist_with_hdu_2(self, tmpdir, hdu):
287
+ with catch_warnings() as l:
288
+ t = Table.read(self.hdus, hdu=hdu)
289
+ assert len(l) == 0
290
+ assert equal_data(t, self.data2)
291
+
292
+ def test_read_from_single_hdu(self):
293
+ with catch_warnings() as l:
294
+ t = Table.read(self.hdus[1])
295
+ assert len(l) == 0
296
+ assert equal_data(t, self.data1)
297
+
298
+
299
+ def test_masking_regression_1795():
300
+ """
301
+ Regression test for #1795 - this bug originally caused columns where TNULL
302
+ was not defined to have their first element masked.
303
+ """
304
+ t = Table.read(os.path.join(DATA, 'tb.fits'))
305
+ assert np.all(t['c1'].mask == np.array([False, False]))
306
+ assert np.all(t['c2'].mask == np.array([False, False]))
307
+ assert np.all(t['c3'].mask == np.array([False, False]))
308
+ assert np.all(t['c4'].mask == np.array([False, False]))
309
+ assert np.all(t['c1'].data == np.array([1, 2]))
310
+ assert np.all(t['c2'].data == np.array([b'abc', b'xy ']))
311
+ assert_allclose(t['c3'].data, np.array([3.70000007153, 6.6999997139]))
312
+ assert np.all(t['c4'].data == np.array([False, True]))
313
+
314
+
315
+ def test_scale_error():
316
+ a = [1, 4, 5]
317
+ b = [2.0, 5.0, 8.2]
318
+ c = ['x', 'y', 'z']
319
+ t = Table([a, b, c], names=('a', 'b', 'c'), meta={'name': 'first table'})
320
+ t['a'].unit = '1.2'
321
+ with pytest.raises(UnitScaleError) as exc:
322
+ t.write('t.fits', format='fits', overwrite=True)
323
+ assert exc.value.args[0] == "The column 'a' could not be stored in FITS format because it has a scale '(1.2)' that is not recognized by the FITS standard. Either scale the data or change the units."
324
+
325
+
326
+ @pytest.mark.parametrize('tdisp_str, format_return',
327
+ [('EN10.5', ('EN', '10', '5', None)),
328
+ ('F6.2', ('F', '6', '2', None)),
329
+ ('B5.10', ('B', '5', '10', None)),
330
+ ('E10.5E3', ('E', '10', '5', '3')),
331
+ ('A21', ('A', '21', None, None))])
332
+ def test_parse_tdisp_format(tdisp_str, format_return):
333
+ assert _parse_tdisp_format(tdisp_str) == format_return
334
+
335
+
336
+ @pytest.mark.parametrize('tdisp_str, format_str_return',
337
+ [('G15.4E2', '{:15.4g}'),
338
+ ('Z5.10', '{:5x}'),
339
+ ('I6.5', '{:6d}'),
340
+ ('L8', '{:>8}'),
341
+ ('E20.7', '{:20.7e}')])
342
+ def test_fortran_to_python_format(tdisp_str, format_str_return):
343
+ assert _fortran_to_python_format(tdisp_str) == format_str_return
344
+
345
+
346
+ @pytest.mark.parametrize('fmt_str, tdisp_str',
347
+ [('{:3d}', 'I3'),
348
+ ('3d', 'I3'),
349
+ ('7.3f', 'F7.3'),
350
+ ('{:>4}', 'A4'),
351
+ ('{:7.4f}', 'F7.4'),
352
+ ('%5.3g', 'G5.3'),
353
+ ('%10s', 'A10'),
354
+ ('%.4f', 'F13.4')])
355
+ def test_python_to_tdisp(fmt_str, tdisp_str):
356
+ assert python_to_tdisp(fmt_str) == tdisp_str
357
+
358
+
359
+ def test_logical_python_to_tdisp():
360
+ assert python_to_tdisp('{:>7}', logical_dtype=True) == 'L7'
361
+
362
+
363
+ def test_bool_column(tmpdir):
364
+ """
365
+ Regression test for https://github.com/astropy/astropy/issues/1953
366
+
367
+ Ensures that Table columns of bools are properly written to a FITS table.
368
+ """
369
+
370
+ arr = np.ones(5, dtype=bool)
371
+ arr[::2] == np.False_
372
+
373
+ t = Table([arr])
374
+ t.write(str(tmpdir.join('test.fits')), overwrite=True)
375
+
376
+ with fits.open(str(tmpdir.join('test.fits'))) as hdul:
377
+ assert hdul[1].data['col0'].dtype == np.dtype('bool')
378
+ assert np.all(hdul[1].data['col0'] == arr)
379
+
380
+
381
+ def test_unicode_column(tmpdir):
382
+ """
383
+ Test that a column of unicode strings is still written as one
384
+ byte-per-character in the FITS table (so long as the column can be ASCII
385
+ encoded).
386
+
387
+ Regression test for one of the issues fixed in
388
+ https://github.com/astropy/astropy/pull/4228
389
+ """
390
+
391
+ t = Table([np.array([u'a', u'b', u'cd'])])
392
+ t.write(str(tmpdir.join('test.fits')), overwrite=True)
393
+
394
+ with fits.open(str(tmpdir.join('test.fits'))) as hdul:
395
+ assert np.all(hdul[1].data['col0'] == ['a', 'b', 'cd'])
396
+ assert hdul[1].header['TFORM1'] == '2A'
397
+
398
+ t2 = Table([np.array([u'\N{SNOWMAN}'])])
399
+
400
+ with pytest.raises(UnicodeEncodeError):
401
+ t2.write(str(tmpdir.join('test.fits')), overwrite=True)
402
+
403
+
404
+ def test_unit_warnings_read_write(tmpdir):
405
+ filename = str(tmpdir.join('test_unit.fits'))
406
+ t1 = Table([[1, 2], [3, 4]], names=['a', 'b'])
407
+ t1['a'].unit = 'm/s'
408
+ t1['b'].unit = 'not-a-unit'
409
+
410
+ with catch_warnings() as l:
411
+ t1.write(filename, overwrite=True)
412
+ assert len(l) == 1
413
+ assert str(l[0].message).startswith("'not-a-unit' did not parse as fits unit")
414
+
415
+ with catch_warnings() as l:
416
+ Table.read(filename, hdu=1)
417
+ assert len(l) == 0
418
+
419
+
420
+ def test_convert_comment_convention(tmpdir):
421
+ """
422
+ Regression test for https://github.com/astropy/astropy/issues/6079
423
+ """
424
+ filename = os.path.join(DATA, 'stddata.fits')
425
+ with pytest.warns(AstropyUserWarning, match='hdu= was not specified but '
426
+ 'multiple tables are present'):
427
+ t = Table.read(filename)
428
+
429
+ assert t.meta['comments'] == [
430
+ '',
431
+ ' *** End of mandatory fields ***',
432
+ '',
433
+ '',
434
+ ' *** Column names ***',
435
+ '',
436
+ '',
437
+ ' *** Column formats ***',
438
+ ''
439
+ ]
440
+
441
+
442
+ def assert_objects_equal(obj1, obj2, attrs, compare_class=True):
443
+ if compare_class:
444
+ assert obj1.__class__ is obj2.__class__
445
+
446
+ info_attrs = ['info.name', 'info.format', 'info.unit', 'info.description', 'info.meta']
447
+ for attr in attrs + info_attrs:
448
+ a1 = obj1
449
+ a2 = obj2
450
+ for subattr in attr.split('.'):
451
+ try:
452
+ a1 = getattr(a1, subattr)
453
+ a2 = getattr(a2, subattr)
454
+ except AttributeError:
455
+ a1 = a1[subattr]
456
+ a2 = a2[subattr]
457
+
458
+ # Mixin info.meta can None instead of empty OrderedDict(), #6720 would
459
+ # fix this.
460
+ if attr == 'info.meta':
461
+ if a1 is None:
462
+ a1 = {}
463
+ if a2 is None:
464
+ a2 = {}
465
+
466
+ assert np.all(a1 == a2)
467
+
468
+ # Testing FITS table read/write with mixins. This is mostly
469
+ # copied from ECSV mixin testing.
470
+
471
+ el = EarthLocation(x=1 * u.km, y=3 * u.km, z=5 * u.km)
472
+ el2 = EarthLocation(x=[1, 2] * u.km, y=[3, 4] * u.km, z=[5, 6] * u.km)
473
+ sc = SkyCoord([1, 2], [3, 4], unit='deg,deg', frame='fk4',
474
+ obstime='J1990.5')
475
+ scc = sc.copy()
476
+ scc.representation_type = 'cartesian'
477
+ tm = Time([2450814.5, 2450815.5], format='jd', scale='tai', location=el)
478
+
479
+
480
+ mixin_cols = {
481
+ 'tm': tm,
482
+ 'dt': TimeDelta([1, 2] * u.day),
483
+ 'sc': sc,
484
+ 'scc': scc,
485
+ 'scd': SkyCoord([1, 2], [3, 4], [5, 6], unit='deg,deg,m', frame='fk4',
486
+ obstime=['J1990.5', 'J1991.5']),
487
+ 'q': [1, 2] * u.m,
488
+ 'lat': Latitude([1, 2] * u.deg),
489
+ 'lon': Longitude([1, 2] * u.deg, wrap_angle=180. * u.deg),
490
+ 'ang': Angle([1, 2] * u.deg),
491
+ 'el2': el2,
492
+ }
493
+
494
+ time_attrs = ['value', 'shape', 'format', 'scale', 'location']
495
+ compare_attrs = {
496
+ 'c1': ['data'],
497
+ 'c2': ['data'],
498
+ 'tm': time_attrs,
499
+ 'dt': ['shape', 'value', 'format', 'scale'],
500
+ 'sc': ['ra', 'dec', 'representation_type', 'frame.name'],
501
+ 'scc': ['x', 'y', 'z', 'representation_type', 'frame.name'],
502
+ 'scd': ['ra', 'dec', 'distance', 'representation_type', 'frame.name'],
503
+ 'q': ['value', 'unit'],
504
+ 'lon': ['value', 'unit', 'wrap_angle'],
505
+ 'lat': ['value', 'unit'],
506
+ 'ang': ['value', 'unit'],
507
+ 'el2': ['x', 'y', 'z', 'ellipsoid'],
508
+ 'nd': ['x', 'y', 'z'],
509
+ }
510
+
511
+
512
+ @pytest.mark.skipif('not HAS_YAML')
513
+ def test_fits_mixins_qtable_to_table(tmpdir):
514
+ """Test writing as QTable and reading as Table. Ensure correct classes
515
+ come out.
516
+ """
517
+ filename = str(tmpdir.join('test_simple.fits'))
518
+
519
+ names = sorted(mixin_cols)
520
+
521
+ t = QTable([mixin_cols[name] for name in names], names=names)
522
+ t.write(filename, format='fits')
523
+ t2 = Table.read(filename, format='fits', astropy_native=True)
524
+
525
+ assert t.colnames == t2.colnames
526
+
527
+ for name, col in t.columns.items():
528
+ col2 = t2[name]
529
+
530
+ # Special-case Time, which does not yet support round-tripping
531
+ # the format.
532
+ if isinstance(col2, Time):
533
+ col2.format = col.format
534
+
535
+ attrs = compare_attrs[name]
536
+ compare_class = True
537
+
538
+ if isinstance(col.info, QuantityInfo):
539
+ # Downgrade Quantity to Column + unit
540
+ assert type(col2) is Column
541
+ # Class-specific attributes like `value` or `wrap_angle` are lost.
542
+ attrs = ['unit']
543
+ compare_class = False
544
+ # Compare data values here (assert_objects_equal doesn't know how in this case)
545
+ assert np.all(col.value == col2)
546
+
547
+ assert_objects_equal(col, col2, attrs, compare_class)
548
+
549
+
550
+ @pytest.mark.skipif('not HAS_YAML')
551
+ @pytest.mark.parametrize('table_cls', (Table, QTable))
552
+ def test_fits_mixins_as_one(table_cls, tmpdir):
553
+ """Test write/read all cols at once and validate intermediate column names"""
554
+ filename = str(tmpdir.join('test_simple.fits'))
555
+ names = sorted(mixin_cols)
556
+
557
+ serialized_names = ['ang',
558
+ 'dt.jd1', 'dt.jd2',
559
+ 'el2.x', 'el2.y', 'el2.z',
560
+ 'lat',
561
+ 'lon',
562
+ 'q',
563
+ 'sc.ra', 'sc.dec',
564
+ 'scc.x', 'scc.y', 'scc.z',
565
+ 'scd.ra', 'scd.dec', 'scd.distance',
566
+ 'scd.obstime.jd1', 'scd.obstime.jd2',
567
+ 'tm', # serialize_method is formatted_value
568
+ ]
569
+
570
+ t = table_cls([mixin_cols[name] for name in names], names=names)
571
+ t.meta['C'] = 'spam'
572
+ t.meta['comments'] = ['this', 'is', 'a', 'comment']
573
+ t.meta['history'] = ['first', 'second', 'third']
574
+
575
+ t.write(filename, format="fits")
576
+
577
+ t2 = table_cls.read(filename, format='fits', astropy_native=True)
578
+ assert t2.meta['C'] == 'spam'
579
+ assert t2.meta['comments'] == ['this', 'is', 'a', 'comment']
580
+ assert t2.meta['HISTORY'] == ['first', 'second', 'third']
581
+
582
+ assert t.colnames == t2.colnames
583
+
584
+ # Read directly via fits and confirm column names
585
+ with fits.open(filename) as hdus:
586
+ assert hdus[1].columns.names == serialized_names
587
+
588
+
589
+ @pytest.mark.skipif('not HAS_YAML')
590
+ @pytest.mark.parametrize('name_col', list(mixin_cols.items()))
591
+ @pytest.mark.parametrize('table_cls', (Table, QTable))
592
+ def test_fits_mixins_per_column(table_cls, name_col, tmpdir):
593
+ """Test write/read one col at a time and do detailed validation"""
594
+ filename = str(tmpdir.join('test_simple.fits'))
595
+ name, col = name_col
596
+
597
+ c = [1.0, 2.0]
598
+ t = table_cls([c, col, c], names=['c1', name, 'c2'])
599
+ t[name].info.description = 'my \n\n\n description'
600
+ t[name].info.meta = {'list': list(range(50)), 'dict': {'a': 'b' * 200}}
601
+
602
+ if not t.has_mixin_columns:
603
+ pytest.skip('column is not a mixin (e.g. Quantity subclass in Table)')
604
+
605
+ if isinstance(t[name], NdarrayMixin):
606
+ pytest.xfail('NdarrayMixin not supported')
607
+
608
+ t.write(filename, format="fits")
609
+ t2 = table_cls.read(filename, format='fits', astropy_native=True)
610
+
611
+ assert t.colnames == t2.colnames
612
+
613
+ for colname in t.colnames:
614
+ assert_objects_equal(t[colname], t2[colname], compare_attrs[colname])
615
+
616
+ # Special case to make sure Column type doesn't leak into Time class data
617
+ if name.startswith('tm'):
618
+ assert t2[name]._time.jd1.__class__ is np.ndarray
619
+ assert t2[name]._time.jd2.__class__ is np.ndarray
620
+
621
+
622
+ @pytest.mark.skipif('HAS_YAML')
623
+ def test_warn_for_dropped_info_attributes(tmpdir):
624
+ filename = str(tmpdir.join('test.fits'))
625
+ t = Table([[1, 2]])
626
+ t['col0'].info.description = 'hello'
627
+ with catch_warnings() as warns:
628
+ t.write(filename, overwrite=True)
629
+ assert len(warns) == 1
630
+ assert str(warns[0].message).startswith(
631
+ "table contains column(s) with defined 'format'")
632
+
633
+
634
+ @pytest.mark.skipif('HAS_YAML')
635
+ def test_error_for_mixins_but_no_yaml(tmpdir):
636
+ filename = str(tmpdir.join('test.fits'))
637
+ t = Table([mixin_cols['sc']])
638
+ with pytest.raises(TypeError) as err:
639
+ t.write(filename)
640
+ assert "cannot write type SkyCoord column 'col0' to FITS without PyYAML" in str(err)
641
+
642
+
643
+ @pytest.mark.skipif('not HAS_YAML')
644
+ def test_info_attributes_with_no_mixins(tmpdir):
645
+ """Even if there are no mixin columns, if there is metadata that would be lost it still
646
+ gets serialized
647
+ """
648
+ filename = str(tmpdir.join('test.fits'))
649
+ t = Table([[1.0, 2.0]])
650
+ t['col0'].description = 'hello' * 40
651
+ t['col0'].format = '{:8.4f}'
652
+ t['col0'].meta['a'] = {'b': 'c'}
653
+ t.write(filename, overwrite=True)
654
+
655
+ t2 = Table.read(filename)
656
+ assert t2['col0'].description == 'hello' * 40
657
+ assert t2['col0'].format == '{:8.4f}'
658
+ assert t2['col0'].meta['a'] == {'b': 'c'}
659
+
660
+
661
+ @pytest.mark.skipif('not HAS_YAML')
662
+ @pytest.mark.parametrize('method', ['set_cols', 'names', 'class'])
663
+ def test_round_trip_masked_table_serialize_mask(tmpdir, method):
664
+ """
665
+ Same as previous test but set the serialize_method to 'data_mask' so mask is
666
+ written out and the behavior is all correct.
667
+ """
668
+ filename = str(tmpdir.join('test.fits'))
669
+
670
+ t = simple_table(masked=True) # int, float, and str cols with one masked element
671
+
672
+ # MaskedColumn but no masked elements. See table the MaskedColumnInfo class
673
+ # _represent_as_dict() method for info about we test a column with no masked elements.
674
+ t['d'] = [1, 2, 3]
675
+
676
+ if method == 'set_cols':
677
+ for col in t.itercols():
678
+ col.info.serialize_method['fits'] = 'data_mask'
679
+ t.write(filename)
680
+ elif method == 'names':
681
+ t.write(filename, serialize_method={'a': 'data_mask', 'b': 'data_mask',
682
+ 'c': 'data_mask', 'd': 'data_mask'})
683
+ elif method == 'class':
684
+ t.write(filename, serialize_method='data_mask')
685
+
686
+ t2 = Table.read(filename)
687
+ assert t2.masked is True
688
+ assert t2.colnames == t.colnames
689
+ for name in t2.colnames:
690
+ assert np.all(t2[name].mask == t[name].mask)
691
+ assert np.all(t2[name] == t[name])
692
+
693
+ # Data under the mask round-trips also (unmask data to show this).
694
+ t[name].mask = False
695
+ t2[name].mask = False
696
+ assert np.all(t2[name] == t[name])
testbed/astropy__astropy/astropy/io/fits/tests/test_convenience.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+
4
+ import os
5
+ import warnings
6
+
7
+ import pytest
8
+ import numpy as np
9
+
10
+ from astropy.io import fits
11
+ from astropy.table import Table
12
+ from astropy.io.fits import printdiff
13
+ from astropy.tests.helper import catch_warnings
14
+
15
+ from . import FitsTestCase
16
+
17
+
18
+ class TestConvenience(FitsTestCase):
19
+
20
+ def test_resource_warning(self):
21
+ warnings.simplefilter('always', ResourceWarning)
22
+ with catch_warnings() as w:
23
+ data = fits.getdata(self.data('test0.fits'))
24
+ assert len(w) == 0
25
+
26
+ with catch_warnings() as w:
27
+ header = fits.getheader(self.data('test0.fits'))
28
+ assert len(w) == 0
29
+
30
+ def test_fileobj_not_closed(self):
31
+ """
32
+ Tests that file-like objects are not closed after being passed
33
+ to convenience functions.
34
+
35
+ Regression test for https://github.com/astropy/astropy/issues/5063
36
+ """
37
+
38
+ f = open(self.data('test0.fits'), 'rb')
39
+ data = fits.getdata(f)
40
+ assert not f.closed
41
+
42
+ f.seek(0)
43
+ header = fits.getheader(f)
44
+ assert not f.closed
45
+
46
+ f.close() # Close it now
47
+
48
+ def test_table_to_hdu(self):
49
+ table = Table([[1, 2, 3], ['a', 'b', 'c'], [2.3, 4.5, 6.7]],
50
+ names=['a', 'b', 'c'], dtype=['i', 'U1', 'f'])
51
+ table['a'].unit = 'm/s'
52
+ table['b'].unit = 'not-a-unit'
53
+
54
+ with catch_warnings() as w:
55
+ hdu = fits.table_to_hdu(table)
56
+ assert len(w) == 1
57
+ assert str(w[0].message).startswith("'not-a-unit' did not parse as"
58
+ " fits unit")
59
+
60
+ # Check that TUNITn cards appear in the correct order
61
+ # (https://github.com/astropy/astropy/pull/5720)
62
+ assert hdu.header.index('TUNIT1') < hdu.header.index('TTYPE2')
63
+
64
+ assert isinstance(hdu, fits.BinTableHDU)
65
+ filename = self.temp('test_table_to_hdu.fits')
66
+ hdu.writeto(filename, overwrite=True)
67
+
68
+ def test_table_to_hdu_convert_comment_convention(self):
69
+ """
70
+ Regression test for https://github.com/astropy/astropy/issues/6079
71
+ """
72
+ table = Table([[1, 2, 3], ['a', 'b', 'c'], [2.3, 4.5, 6.7]],
73
+ names=['a', 'b', 'c'], dtype=['i', 'U1', 'f'])
74
+ table.meta['comments'] = ['This', 'is', 'a', 'comment']
75
+ hdu = fits.table_to_hdu(table)
76
+
77
+ assert hdu.header.get('comment') == ['This', 'is', 'a', 'comment']
78
+ with pytest.raises(ValueError):
79
+ hdu.header.index('comments')
80
+
81
+ def test_table_writeto_header(self):
82
+ """
83
+ Regression test for https://github.com/astropy/astropy/issues/5988
84
+ """
85
+ data = np.zeros((5, ), dtype=[('x', float), ('y', int)])
86
+ h_in = fits.Header()
87
+ h_in['ANSWER'] = (42.0, 'LTU&E')
88
+ filename = self.temp('tabhdr42.fits')
89
+ fits.writeto(filename, data=data, header=h_in, overwrite=True)
90
+ h_out = fits.getheader(filename, ext=1)
91
+ assert h_out['ANSWER'] == 42
92
+
93
+ def test_image_extension_update_header(self):
94
+ """
95
+ Test that _makehdu correctly includes the header. For example in the
96
+ fits.update convenience function.
97
+ """
98
+ filename = self.temp('twoextension.fits')
99
+
100
+ hdus = [fits.PrimaryHDU(np.zeros((10, 10))),
101
+ fits.ImageHDU(np.zeros((10, 10)))]
102
+
103
+ fits.HDUList(hdus).writeto(filename)
104
+
105
+ fits.update(filename,
106
+ np.zeros((10, 10)),
107
+ header=fits.Header([('WHAT', 100)]),
108
+ ext=1)
109
+ h_out = fits.getheader(filename, ext=1)
110
+ assert h_out['WHAT'] == 100
111
+
112
+ def test_printdiff(self):
113
+ """
114
+ Test that FITSDiff can run the different inputs without crashing.
115
+ """
116
+
117
+ # Testing different string input options
118
+ assert printdiff(self.data('arange.fits'),
119
+ self.data('blank.fits')) is None
120
+ assert printdiff(self.data('arange.fits'),
121
+ self.data('blank.fits'), ext=0) is None
122
+ assert printdiff(self.data('o4sp040b0_raw.fits'),
123
+ self.data('o4sp040b0_raw.fits'),
124
+ extname='sci') is None
125
+
126
+ # This may seem weird, but check printdiff to see, need to test
127
+ # incorrect second file
128
+ with pytest.raises(OSError):
129
+ printdiff('o4sp040b0_raw.fits', 'fakefile.fits', extname='sci')
130
+
131
+ # Test HDU object inputs
132
+ with fits.open(self.data('stddata.fits'), mode='readonly') as in1:
133
+ with fits.open(self.data('checksum.fits'), mode='readonly') as in2:
134
+
135
+ assert printdiff(in1[0], in2[0]) is None
136
+
137
+ with pytest.raises(ValueError):
138
+ printdiff(in1[0], in2[0], ext=0)
139
+
140
+ assert printdiff(in1, in2) is None
141
+
142
+ with pytest.raises(NotImplementedError):
143
+ printdiff(in1, in2, 0)
144
+
145
+ def test_tabledump(self):
146
+ """
147
+ Regression test for https://github.com/astropy/astropy/issues/6937
148
+ """
149
+ # copy fits file to the temp directory
150
+ self.copy_file('tb.fits')
151
+
152
+ # test without datafile
153
+ fits.tabledump(self.temp('tb.fits'))
154
+ assert os.path.isfile(self.temp('tb_1.txt'))
155
+
156
+ # test with datafile
157
+ fits.tabledump(self.temp('tb.fits'), datafile=self.temp('test_tb.txt'))
158
+ assert os.path.isfile(self.temp('test_tb.txt'))
159
+
160
+ def test_append_filename(self):
161
+ """
162
+ Test fits.append with a filename argument.
163
+ """
164
+ data = np.arange(6)
165
+ testfile = self.temp('test_append_1.fits')
166
+
167
+ # Test case 1: creation of file
168
+ fits.append(testfile, data=data, checksum=True)
169
+
170
+ # Test case 2: append to existing file, with verify=True
171
+ # Also test that additional keyword can be passed to fitsopen
172
+ fits.append(testfile, data=data * 2, checksum=True, ignore_blank=True)
173
+
174
+ # Test case 3: append to existing file, with verify=False
175
+ fits.append(testfile, data=data * 3, checksum=True, verify=False)
176
+
177
+ with fits.open(testfile, checksum=True) as hdu1:
178
+ np.testing.assert_array_equal(hdu1[0].data, data)
179
+ np.testing.assert_array_equal(hdu1[1].data, data * 2)
180
+ np.testing.assert_array_equal(hdu1[2].data, data * 3)
181
+
182
+ @pytest.mark.parametrize('mode', ['wb', 'wb+', 'ab', 'ab+'])
183
+ def test_append_filehandle(self, tmpdir, mode):
184
+ """
185
+ Test fits.append with a file handle argument.
186
+ """
187
+ append_file = tmpdir.join('append.fits')
188
+ with append_file.open(mode) as handle:
189
+ fits.append(filename=handle, data=np.ones((4, 4)))
190
+
191
+ def test_append_with_header(self):
192
+ """
193
+ Test fits.append with a fits Header, which triggers detection of the
194
+ HDU class. Regression test for
195
+ https://github.com/astropy/astropy/issues/8660
196
+ """
197
+ testfile = self.temp('test_append_1.fits')
198
+ with fits.open(self.data('test0.fits')) as hdus:
199
+ for hdu in hdus:
200
+ fits.append(testfile, hdu.data, hdu.header, checksum=True)
201
+
202
+ with fits.open(testfile, checksum=True) as hdus:
203
+ assert len(hdus) == 5
testbed/astropy__astropy/astropy/io/fits/tests/test_core.py ADDED
@@ -0,0 +1,1389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import gzip
4
+ import bz2
5
+ import io
6
+ import mmap
7
+ import errno
8
+ import os
9
+ import pathlib
10
+ import warnings
11
+ import zipfile
12
+ from unittest.mock import patch
13
+
14
+ import pytest
15
+ import numpy as np
16
+
17
+ from . import FitsTestCase
18
+
19
+ from astropy.io.fits.convenience import _getext
20
+ from astropy.io.fits.diff import FITSDiff
21
+ from astropy.io.fits.file import _File, GZIP_MAGIC
22
+
23
+ from astropy.io import fits
24
+ from astropy.tests.helper import raises, catch_warnings, ignore_warnings
25
+ from astropy.utils.data import conf, get_pkg_data_filename
26
+ from astropy.utils.exceptions import AstropyUserWarning
27
+ from astropy.utils import data
28
+
29
+
30
+ class TestCore(FitsTestCase):
31
+
32
+ @raises(OSError)
33
+ def test_missing_file(self):
34
+ fits.open(self.temp('does-not-exist.fits'))
35
+
36
+ def test_filename_is_bytes_object(self):
37
+ with pytest.raises(TypeError):
38
+ fits.open(self.data('ascii.fits').encode())
39
+
40
+ def test_naxisj_check(self):
41
+ with fits.open(self.data('o4sp040b0_raw.fits')) as hdulist:
42
+ hdulist[1].header['NAXIS3'] = 500
43
+
44
+ assert 'NAXIS3' in hdulist[1].header
45
+ hdulist.verify('silentfix')
46
+ assert 'NAXIS3' not in hdulist[1].header
47
+
48
+ def test_byteswap(self):
49
+ p = fits.PrimaryHDU()
50
+ l = fits.HDUList()
51
+
52
+ n = np.zeros(3, dtype='i2')
53
+ n[0] = 1
54
+ n[1] = 60000
55
+ n[2] = 2
56
+
57
+ c = fits.Column(name='foo', format='i2', bscale=1, bzero=32768,
58
+ array=n)
59
+ t = fits.BinTableHDU.from_columns([c])
60
+
61
+ l.append(p)
62
+ l.append(t)
63
+
64
+ l.writeto(self.temp('test.fits'), overwrite=True)
65
+
66
+ with fits.open(self.temp('test.fits')) as p:
67
+ assert p[1].data[1]['foo'] == 60000.0
68
+
69
+ def test_fits_file_path_object(self):
70
+ """
71
+ Testing when fits file is passed as pathlib.Path object #4412.
72
+ """
73
+ fpath = pathlib.Path(get_pkg_data_filename('data/tdim.fits'))
74
+ with fits.open(fpath) as hdulist:
75
+ assert hdulist[0].filebytes() == 2880
76
+ assert hdulist[1].filebytes() == 5760
77
+
78
+ with fits.open(self.data('tdim.fits')) as hdulist2:
79
+ assert FITSDiff(hdulist2, hdulist).identical is True
80
+
81
+ def test_add_del_columns(self):
82
+ p = fits.ColDefs([])
83
+ p.add_col(fits.Column(name='FOO', format='3J'))
84
+ p.add_col(fits.Column(name='BAR', format='1I'))
85
+ assert p.names == ['FOO', 'BAR']
86
+ p.del_col('FOO')
87
+ assert p.names == ['BAR']
88
+
89
+ def test_add_del_columns2(self):
90
+ hdulist = fits.open(self.data('tb.fits'))
91
+ table = hdulist[1]
92
+ assert table.data.dtype.names == ('c1', 'c2', 'c3', 'c4')
93
+ assert table.columns.names == ['c1', 'c2', 'c3', 'c4']
94
+ table.columns.del_col(str('c1'))
95
+ assert table.data.dtype.names == ('c2', 'c3', 'c4')
96
+ assert table.columns.names == ['c2', 'c3', 'c4']
97
+
98
+ table.columns.del_col(str('c3'))
99
+ assert table.data.dtype.names == ('c2', 'c4')
100
+ assert table.columns.names == ['c2', 'c4']
101
+
102
+ table.columns.add_col(fits.Column(str('foo'), str('3J')))
103
+ assert table.data.dtype.names == ('c2', 'c4', 'foo')
104
+ assert table.columns.names == ['c2', 'c4', 'foo']
105
+
106
+ hdulist.writeto(self.temp('test.fits'), overwrite=True)
107
+ with ignore_warnings():
108
+ # TODO: The warning raised by this test is actually indication of a
109
+ # bug and should *not* be ignored. But as it is a known issue we
110
+ # hide it for now. See
111
+ # https://github.com/spacetelescope/PyFITS/issues/44
112
+ with fits.open(self.temp('test.fits')) as hdulist:
113
+ table = hdulist[1]
114
+ assert table.data.dtype.names == ('c2', 'c4', 'foo')
115
+ assert table.columns.names == ['c2', 'c4', 'foo']
116
+
117
+ def test_update_header_card(self):
118
+ """A very basic test for the Header.update method--I'd like to add a
119
+ few more cases to this at some point.
120
+ """
121
+
122
+ header = fits.Header()
123
+ comment = 'number of bits per data pixel'
124
+ header['BITPIX'] = (16, comment)
125
+ assert 'BITPIX' in header
126
+ assert header['BITPIX'] == 16
127
+ assert header.comments['BITPIX'] == comment
128
+
129
+ header.update(BITPIX=32)
130
+ assert header['BITPIX'] == 32
131
+ assert header.comments['BITPIX'] == ''
132
+
133
+ def test_set_card_value(self):
134
+ """Similar to test_update_header_card(), but tests the the
135
+ `header['FOO'] = 'bar'` method of updating card values.
136
+ """
137
+
138
+ header = fits.Header()
139
+ comment = 'number of bits per data pixel'
140
+ card = fits.Card.fromstring('BITPIX = 32 / {}'.format(comment))
141
+ header.append(card)
142
+
143
+ header['BITPIX'] = 32
144
+
145
+ assert 'BITPIX' in header
146
+ assert header['BITPIX'] == 32
147
+ assert header.cards[0].keyword == 'BITPIX'
148
+ assert header.cards[0].value == 32
149
+ assert header.cards[0].comment == comment
150
+
151
+ def test_uint(self):
152
+ filename = self.data('o4sp040b0_raw.fits')
153
+ with fits.open(filename, uint=False) as hdulist_f:
154
+ with fits.open(filename, uint=True) as hdulist_i:
155
+ assert hdulist_f[1].data.dtype == np.float32
156
+ assert hdulist_i[1].data.dtype == np.uint16
157
+ assert np.all(hdulist_f[1].data == hdulist_i[1].data)
158
+
159
+ def test_fix_missing_card_append(self):
160
+ hdu = fits.ImageHDU()
161
+ errs = hdu.req_cards('TESTKW', None, None, 'foo', 'silentfix', [])
162
+ assert len(errs) == 1
163
+ assert 'TESTKW' in hdu.header
164
+ assert hdu.header['TESTKW'] == 'foo'
165
+ assert hdu.header.cards[-1].keyword == 'TESTKW'
166
+
167
+ def test_fix_invalid_keyword_value(self):
168
+ hdu = fits.ImageHDU()
169
+ hdu.header['TESTKW'] = 'foo'
170
+ errs = hdu.req_cards('TESTKW', None,
171
+ lambda v: v == 'foo', 'foo', 'ignore', [])
172
+ assert len(errs) == 0
173
+
174
+ # Now try a test that will fail, and ensure that an error will be
175
+ # raised in 'exception' mode
176
+ errs = hdu.req_cards('TESTKW', None, lambda v: v == 'bar', 'bar',
177
+ 'exception', [])
178
+ assert len(errs) == 1
179
+ assert errs[0][1] == "'TESTKW' card has invalid value 'foo'."
180
+
181
+ # See if fixing will work
182
+ hdu.req_cards('TESTKW', None, lambda v: v == 'bar', 'bar', 'silentfix',
183
+ [])
184
+ assert hdu.header['TESTKW'] == 'bar'
185
+
186
+ @raises(fits.VerifyError)
187
+ def test_unfixable_missing_card(self):
188
+ class TestHDU(fits.hdu.base.NonstandardExtHDU):
189
+ def _verify(self, option='warn'):
190
+ errs = super()._verify(option)
191
+ hdu.req_cards('TESTKW', None, None, None, 'fix', errs)
192
+ return errs
193
+
194
+ @classmethod
195
+ def match_header(cls, header):
196
+ # Since creating this HDU class adds it to the registry we
197
+ # don't want the file reader to possibly think any actual
198
+ # HDU from a file should be handled by this class
199
+ return False
200
+
201
+ hdu = TestHDU(header=fits.Header())
202
+ hdu.verify('fix')
203
+
204
+ @raises(fits.VerifyError)
205
+ def test_exception_on_verification_error(self):
206
+ hdu = fits.ImageHDU()
207
+ del hdu.header['XTENSION']
208
+ hdu.verify('exception')
209
+
210
+ def test_ignore_verification_error(self):
211
+ hdu = fits.ImageHDU()
212
+ # The default here would be to issue a warning; ensure that no warnings
213
+ # or exceptions are raised
214
+ with catch_warnings():
215
+ warnings.simplefilter('error')
216
+ del hdu.header['NAXIS']
217
+ try:
218
+ hdu.verify('ignore')
219
+ except Exception as exc:
220
+ self.fail('An exception occurred when the verification error '
221
+ 'should have been ignored: {}'.format(exc))
222
+ # Make sure the error wasn't fixed either, silently or otherwise
223
+ assert 'NAXIS' not in hdu.header
224
+
225
+ @raises(ValueError)
226
+ def test_unrecognized_verify_option(self):
227
+ hdu = fits.ImageHDU()
228
+ hdu.verify('foobarbaz')
229
+
230
+ def test_errlist_basic(self):
231
+ # Just some tests to make sure that _ErrList is setup correctly.
232
+ # No arguments
233
+ error_list = fits.verify._ErrList()
234
+ assert error_list == []
235
+ # Some contents - this is not actually working, it just makes sure they
236
+ # are kept.
237
+ error_list = fits.verify._ErrList([1, 2, 3])
238
+ assert error_list == [1, 2, 3]
239
+
240
+ def test_combined_verify_options(self):
241
+ """
242
+ Test verify options like fix+ignore.
243
+ """
244
+
245
+ def make_invalid_hdu():
246
+ hdu = fits.ImageHDU()
247
+ # Add one keyword to the header that contains a fixable defect, and one
248
+ # with an unfixable defect
249
+ c1 = fits.Card.fromstring("test = ' test'")
250
+ c2 = fits.Card.fromstring("P.I. = ' Hubble'")
251
+ hdu.header.append(c1)
252
+ hdu.header.append(c2)
253
+ return hdu
254
+
255
+ # silentfix+ignore should be completely silent
256
+ hdu = make_invalid_hdu()
257
+ with catch_warnings():
258
+ warnings.simplefilter('error')
259
+ try:
260
+ hdu.verify('silentfix+ignore')
261
+ except Exception as exc:
262
+ self.fail('An exception occurred when the verification error '
263
+ 'should have been ignored: {}'.format(exc))
264
+
265
+ # silentfix+warn should be quiet about the fixed HDU and only warn
266
+ # about the unfixable one
267
+ hdu = make_invalid_hdu()
268
+ with catch_warnings() as w:
269
+ hdu.verify('silentfix+warn')
270
+ assert len(w) == 4
271
+ assert 'Illegal keyword name' in str(w[2].message)
272
+
273
+ # silentfix+exception should only mention the unfixable error in the
274
+ # exception
275
+ hdu = make_invalid_hdu()
276
+ try:
277
+ hdu.verify('silentfix+exception')
278
+ except fits.VerifyError as exc:
279
+ assert 'Illegal keyword name' in str(exc)
280
+ assert 'not upper case' not in str(exc)
281
+ else:
282
+ self.fail('An exception should have been raised.')
283
+
284
+ # fix+ignore is not too useful, but it should warn about the fixed
285
+ # problems while saying nothing about the unfixable problems
286
+ hdu = make_invalid_hdu()
287
+ with catch_warnings() as w:
288
+ hdu.verify('fix+ignore')
289
+ assert len(w) == 4
290
+ assert 'not upper case' in str(w[2].message)
291
+
292
+ # fix+warn
293
+ hdu = make_invalid_hdu()
294
+ with catch_warnings() as w:
295
+ hdu.verify('fix+warn')
296
+ assert len(w) == 6
297
+ assert 'not upper case' in str(w[2].message)
298
+ assert 'Illegal keyword name' in str(w[4].message)
299
+
300
+ # fix+exception
301
+ hdu = make_invalid_hdu()
302
+ try:
303
+ hdu.verify('fix+exception')
304
+ except fits.VerifyError as exc:
305
+ assert 'Illegal keyword name' in str(exc)
306
+ assert 'not upper case' in str(exc)
307
+ else:
308
+ self.fail('An exception should have been raised.')
309
+
310
+ def test_getext(self):
311
+ """
312
+ Test the various different ways of specifying an extension header in
313
+ the convenience functions.
314
+ """
315
+ filename = self.data('test0.fits')
316
+
317
+ hl, ext = _getext(filename, 'readonly', 1)
318
+ assert ext == 1
319
+ hl.close()
320
+
321
+ pytest.raises(ValueError, _getext, filename, 'readonly',
322
+ 1, 2)
323
+ pytest.raises(ValueError, _getext, filename, 'readonly',
324
+ (1, 2))
325
+ pytest.raises(ValueError, _getext, filename, 'readonly',
326
+ 'sci', 'sci')
327
+ pytest.raises(TypeError, _getext, filename, 'readonly',
328
+ 1, 2, 3)
329
+
330
+ hl, ext = _getext(filename, 'readonly', ext=1)
331
+ assert ext == 1
332
+ hl.close()
333
+
334
+ hl, ext = _getext(filename, 'readonly', ext=('sci', 2))
335
+ assert ext == ('sci', 2)
336
+ hl.close()
337
+
338
+ pytest.raises(TypeError, _getext, filename, 'readonly',
339
+ 1, ext=('sci', 2), extver=3)
340
+ pytest.raises(TypeError, _getext, filename, 'readonly',
341
+ ext=('sci', 2), extver=3)
342
+
343
+ hl, ext = _getext(filename, 'readonly', 'sci')
344
+ assert ext == ('sci', 1)
345
+ hl.close()
346
+
347
+ hl, ext = _getext(filename, 'readonly', 'sci', 1)
348
+ assert ext == ('sci', 1)
349
+ hl.close()
350
+
351
+ hl, ext = _getext(filename, 'readonly', ('sci', 1))
352
+ assert ext == ('sci', 1)
353
+ hl.close()
354
+
355
+ hl, ext = _getext(filename, 'readonly', 'sci',
356
+ extver=1, do_not_scale_image_data=True)
357
+ assert ext == ('sci', 1)
358
+ hl.close()
359
+
360
+ pytest.raises(TypeError, _getext, filename, 'readonly',
361
+ 'sci', ext=1)
362
+ pytest.raises(TypeError, _getext, filename, 'readonly',
363
+ 'sci', 1, extver=2)
364
+
365
+ hl, ext = _getext(filename, 'readonly', extname='sci')
366
+ assert ext == ('sci', 1)
367
+ hl.close()
368
+
369
+ hl, ext = _getext(filename, 'readonly', extname='sci',
370
+ extver=1)
371
+ assert ext == ('sci', 1)
372
+ hl.close()
373
+
374
+ pytest.raises(TypeError, _getext, filename, 'readonly',
375
+ extver=1)
376
+
377
+ def test_extension_name_case_sensitive(self):
378
+ """
379
+ Tests that setting fits.conf.extension_name_case_sensitive at
380
+ runtime works.
381
+ """
382
+
383
+ hdu = fits.ImageHDU()
384
+ hdu.name = 'sCi'
385
+ assert hdu.name == 'SCI'
386
+ assert hdu.header['EXTNAME'] == 'SCI'
387
+
388
+ with fits.conf.set_temp('extension_name_case_sensitive', True):
389
+ hdu = fits.ImageHDU()
390
+ hdu.name = 'sCi'
391
+ assert hdu.name == 'sCi'
392
+ assert hdu.header['EXTNAME'] == 'sCi'
393
+
394
+ hdu.name = 'sCi'
395
+ assert hdu.name == 'SCI'
396
+ assert hdu.header['EXTNAME'] == 'SCI'
397
+
398
+ def test_hdu_fromstring(self):
399
+ """
400
+ Tests creating a fully-formed HDU object from a string containing the
401
+ bytes of the HDU.
402
+ """
403
+ infile = self.data('test0.fits')
404
+ outfile = self.temp('test.fits')
405
+
406
+ with open(infile, 'rb') as fin:
407
+ dat = fin.read()
408
+
409
+ offset = 0
410
+ with fits.open(infile) as hdul:
411
+ hdulen = hdul[0]._data_offset + hdul[0]._data_size
412
+ hdu = fits.PrimaryHDU.fromstring(dat[:hdulen])
413
+ assert isinstance(hdu, fits.PrimaryHDU)
414
+ assert hdul[0].header == hdu.header
415
+ assert hdu.data is None
416
+
417
+ hdu.header['TEST'] = 'TEST'
418
+ hdu.writeto(outfile)
419
+ with fits.open(outfile) as hdul:
420
+ assert isinstance(hdu, fits.PrimaryHDU)
421
+ assert hdul[0].header[:-1] == hdu.header[:-1]
422
+ assert hdul[0].header['TEST'] == 'TEST'
423
+ assert hdu.data is None
424
+
425
+ with fits.open(infile)as hdul:
426
+ for ext_hdu in hdul[1:]:
427
+ offset += hdulen
428
+ hdulen = len(str(ext_hdu.header)) + ext_hdu._data_size
429
+ hdu = fits.ImageHDU.fromstring(dat[offset:offset + hdulen])
430
+ assert isinstance(hdu, fits.ImageHDU)
431
+ assert ext_hdu.header == hdu.header
432
+ assert (ext_hdu.data == hdu.data).all()
433
+
434
+ def test_nonstandard_hdu(self):
435
+ """
436
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/157
437
+
438
+ Tests that "Nonstandard" HDUs with SIMPLE = F are read and written
439
+ without prepending a superfluous and unwanted standard primary HDU.
440
+ """
441
+
442
+ data = np.arange(100, dtype=np.uint8)
443
+ hdu = fits.PrimaryHDU(data=data)
444
+ hdu.header['SIMPLE'] = False
445
+ hdu.writeto(self.temp('test.fits'))
446
+
447
+ info = [(0, '', 1, 'NonstandardHDU', 5, (), '', '')]
448
+ with fits.open(self.temp('test.fits')) as hdul:
449
+ assert hdul.info(output=False) == info
450
+ # NonstandardHDUs just treat the data as an unspecified array of
451
+ # bytes. The first 100 bytes should match the original data we
452
+ # passed in...the rest should be zeros padding out the rest of the
453
+ # FITS block
454
+ assert (hdul[0].data[:100] == data).all()
455
+ assert (hdul[0].data[100:] == 0).all()
456
+
457
+ def test_extname(self):
458
+ """Test getting/setting the EXTNAME of an HDU."""
459
+
460
+ h1 = fits.PrimaryHDU()
461
+ assert h1.name == 'PRIMARY'
462
+ # Normally a PRIMARY HDU should not have an EXTNAME, though it should
463
+ # have a default .name attribute
464
+ assert 'EXTNAME' not in h1.header
465
+
466
+ # The current version of the FITS standard does allow PRIMARY HDUs to
467
+ # have an EXTNAME, however.
468
+ h1.name = 'NOTREAL'
469
+ assert h1.name == 'NOTREAL'
470
+ assert h1.header.get('EXTNAME') == 'NOTREAL'
471
+
472
+ # Updating the EXTNAME in the header should update the .name
473
+ h1.header['EXTNAME'] = 'TOOREAL'
474
+ assert h1.name == 'TOOREAL'
475
+
476
+ # If we delete an EXTNAME keyword from a PRIMARY HDU it should go back
477
+ # to the default
478
+ del h1.header['EXTNAME']
479
+ assert h1.name == 'PRIMARY'
480
+
481
+ # For extension HDUs the situation is a bit simpler:
482
+ h2 = fits.ImageHDU()
483
+ assert h2.name == ''
484
+ assert 'EXTNAME' not in h2.header
485
+ h2.name = 'HELLO'
486
+ assert h2.name == 'HELLO'
487
+ assert h2.header.get('EXTNAME') == 'HELLO'
488
+ h2.header['EXTNAME'] = 'GOODBYE'
489
+ assert h2.name == 'GOODBYE'
490
+
491
+ def test_extver_extlevel(self):
492
+ """Test getting/setting the EXTVER and EXTLEVEL of and HDU."""
493
+
494
+ # EXTVER and EXTNAME work exactly the same; their semantics are, for
495
+ # now, to be inferred by the user. Although they should never be less
496
+ # than 1, the standard does not explicitly forbid any value so long as
497
+ # it's an integer
498
+ h1 = fits.PrimaryHDU()
499
+ assert h1.ver == 1
500
+ assert h1.level == 1
501
+ assert 'EXTVER' not in h1.header
502
+ assert 'EXTLEVEL' not in h1.header
503
+
504
+ h1.ver = 2
505
+ assert h1.header.get('EXTVER') == 2
506
+ h1.header['EXTVER'] = 3
507
+ assert h1.ver == 3
508
+ del h1.header['EXTVER']
509
+ h1.ver == 1
510
+
511
+ h1.level = 2
512
+ assert h1.header.get('EXTLEVEL') == 2
513
+ h1.header['EXTLEVEL'] = 3
514
+ assert h1.level == 3
515
+ del h1.header['EXTLEVEL']
516
+ assert h1.level == 1
517
+
518
+ pytest.raises(TypeError, setattr, h1, 'ver', 'FOO')
519
+ pytest.raises(TypeError, setattr, h1, 'level', 'BAR')
520
+
521
+ def test_consecutive_writeto(self):
522
+ """
523
+ Regression test for an issue where calling writeto twice on the same
524
+ HDUList could write a corrupted file.
525
+
526
+ https://github.com/spacetelescope/PyFITS/issues/40 is actually a
527
+ particular instance of this problem, though isn't unique to sys.stdout.
528
+ """
529
+
530
+ with fits.open(self.data('test0.fits')) as hdul1:
531
+ # Add a bunch of header keywords so that the data will be forced to
532
+ # new offsets within the file:
533
+ for idx in range(40):
534
+ hdul1[1].header['TEST{}'.format(idx)] = 'test'
535
+
536
+ hdul1.writeto(self.temp('test1.fits'))
537
+ hdul1.writeto(self.temp('test2.fits'))
538
+
539
+ # Open a second handle to the original file and compare it to hdul1
540
+ # (We only compare part of the one header that was modified)
541
+ # Compare also with the second writeto output
542
+ with fits.open(self.data('test0.fits')) as hdul2:
543
+ with fits.open(self.temp('test2.fits')) as hdul3:
544
+ for hdul in (hdul1, hdul3):
545
+ for idx, hdus in enumerate(zip(hdul2, hdul)):
546
+ hdu2, hdu = hdus
547
+ if idx != 1:
548
+ assert hdu.header == hdu2.header
549
+ else:
550
+ assert (hdu2.header ==
551
+ hdu.header[:len(hdu2.header)])
552
+ assert np.all(hdu.data == hdu2.data)
553
+
554
+
555
+ class TestConvenienceFunctions(FitsTestCase):
556
+ def test_writeto(self):
557
+ """
558
+ Simple test for writing a trivial header and some data to a file
559
+ with the `writeto()` convenience function.
560
+ """
561
+ filename = self.temp('array.fits')
562
+ data = np.zeros((100, 100))
563
+ header = fits.Header()
564
+ fits.writeto(filename, data, header=header, overwrite=True)
565
+ with fits.open(filename) as hdul:
566
+ assert len(hdul) == 1
567
+ assert (data == hdul[0].data).all()
568
+
569
+ def test_writeto_2(self):
570
+ """
571
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/107
572
+
573
+ Test of `writeto()` with a trivial header containing a single keyword.
574
+ """
575
+ filename = self.temp('array.fits')
576
+ data = np.zeros((100, 100))
577
+ header = fits.Header()
578
+ header.set('CRPIX1', 1.)
579
+ fits.writeto(filename, data, header=header,
580
+ overwrite=True, output_verify='silentfix')
581
+ with fits.open(filename) as hdul:
582
+ assert len(hdul) == 1
583
+ assert (data == hdul[0].data).all()
584
+ assert 'CRPIX1' in hdul[0].header
585
+ assert hdul[0].header['CRPIX1'] == 1.0
586
+
587
+
588
+ class TestFileFunctions(FitsTestCase):
589
+ """
590
+ Tests various basic I/O operations, specifically in the
591
+ astropy.io.fits.file._File class.
592
+ """
593
+
594
+ def test_open_nonexistent(self):
595
+ """Test that trying to open a non-existent file results in an
596
+ OSError (and not some other arbitrary exception).
597
+ """
598
+
599
+ try:
600
+ fits.open(self.temp('foobar.fits'))
601
+ except OSError as e:
602
+ assert 'No such file or directory' in str(e)
603
+
604
+ # But opening in ostream or append mode should be okay, since they
605
+ # allow writing new files
606
+ for mode in ('ostream', 'append'):
607
+ with fits.open(self.temp('foobar.fits'), mode=mode) as h:
608
+ pass
609
+
610
+ assert os.path.exists(self.temp('foobar.fits'))
611
+ os.remove(self.temp('foobar.fits'))
612
+
613
+ def test_open_file_handle(self):
614
+ # Make sure we can open a FITS file from an open file handle
615
+ with open(self.data('test0.fits'), 'rb') as handle:
616
+ with fits.open(handle) as fitsfile:
617
+ pass
618
+
619
+ with open(self.temp('temp.fits'), 'wb') as handle:
620
+ with fits.open(handle, mode='ostream') as fitsfile:
621
+ pass
622
+
623
+ # Opening without explicitly specifying binary mode should fail
624
+ with pytest.raises(ValueError):
625
+ with open(self.data('test0.fits')) as handle:
626
+ with fits.open(handle) as fitsfile:
627
+ pass
628
+
629
+ # All of these read modes should fail
630
+ for mode in ['r', 'rt']:
631
+ with pytest.raises(ValueError):
632
+ with open(self.data('test0.fits'), mode=mode) as handle:
633
+ with fits.open(handle) as fitsfile:
634
+ pass
635
+
636
+ # These update or write modes should fail as well
637
+ for mode in ['w', 'wt', 'w+', 'wt+', 'r+', 'rt+',
638
+ 'a', 'at', 'a+', 'at+']:
639
+ with pytest.raises(ValueError):
640
+ with open(self.temp('temp.fits'), mode=mode) as handle:
641
+ with fits.open(handle) as fitsfile:
642
+ pass
643
+
644
+ def test_fits_file_handle_mode_combo(self):
645
+ # This should work fine since no mode is given
646
+ with open(self.data('test0.fits'), 'rb') as handle:
647
+ with fits.open(handle) as fitsfile:
648
+ pass
649
+
650
+ # This should work fine since the modes are compatible
651
+ with open(self.data('test0.fits'), 'rb') as handle:
652
+ with fits.open(handle, mode='readonly') as fitsfile:
653
+ pass
654
+
655
+ # This should not work since the modes conflict
656
+ with pytest.raises(ValueError):
657
+ with open(self.data('test0.fits'), 'rb') as handle:
658
+ with fits.open(handle, mode='ostream') as fitsfile:
659
+ pass
660
+
661
+ def test_open_from_url(self):
662
+ import urllib.request
663
+ file_url = "file:///" + self.data('test0.fits')
664
+ with urllib.request.urlopen(file_url) as urlobj:
665
+ with fits.open(urlobj) as fits_handle:
666
+ pass
667
+
668
+ # It will not be possible to write to a file that is from a URL object
669
+ for mode in ('ostream', 'append', 'update'):
670
+ with pytest.raises(ValueError):
671
+ with urllib.request.urlopen(file_url) as urlobj:
672
+ with fits.open(urlobj, mode=mode) as fits_handle:
673
+ pass
674
+
675
+ @pytest.mark.remote_data(source='astropy')
676
+ def test_open_from_remote_url(self):
677
+
678
+ import urllib.request
679
+
680
+ for dataurl in (conf.dataurl, conf.dataurl_mirror):
681
+
682
+ remote_url = '{}/{}'.format(dataurl, 'allsky/allsky_rosat.fits')
683
+
684
+ try:
685
+
686
+ with urllib.request.urlopen(remote_url) as urlobj:
687
+ with fits.open(urlobj) as fits_handle:
688
+ assert len(fits_handle) == 1
689
+
690
+ for mode in ('ostream', 'append', 'update'):
691
+ with pytest.raises(ValueError):
692
+ with urllib.request.urlopen(remote_url) as urlobj:
693
+ with fits.open(urlobj, mode=mode) as fits_handle:
694
+ assert len(fits_handle) == 1
695
+
696
+ except (urllib.error.HTTPError, urllib.error.URLError):
697
+ continue
698
+ else:
699
+ break
700
+ else:
701
+ raise Exception("Could not download file")
702
+
703
+ def test_open_gzipped(self):
704
+ gzip_file = self._make_gzip_file()
705
+ with ignore_warnings():
706
+ with fits.open(gzip_file) as fits_handle:
707
+ assert fits_handle._file.compression == 'gzip'
708
+ assert len(fits_handle) == 5
709
+ with fits.open(gzip.GzipFile(gzip_file)) as fits_handle:
710
+ assert fits_handle._file.compression == 'gzip'
711
+ assert len(fits_handle) == 5
712
+
713
+ def test_open_gzipped_from_handle(self):
714
+ with open(self._make_gzip_file(), 'rb') as handle:
715
+ with fits.open(handle) as fits_handle:
716
+ assert fits_handle._file.compression == 'gzip'
717
+
718
+ def test_detect_gzipped(self):
719
+ """Test detection of a gzip file when the extension is not .gz."""
720
+ with ignore_warnings():
721
+ with fits.open(self._make_gzip_file('test0.fz')) as fits_handle:
722
+ assert fits_handle._file.compression == 'gzip'
723
+ assert len(fits_handle) == 5
724
+
725
+ def test_writeto_append_mode_gzip(self):
726
+ """Regression test for
727
+ https://github.com/spacetelescope/PyFITS/issues/33
728
+
729
+ Check that a new GzipFile opened in append mode can be used to write
730
+ out a new FITS file.
731
+ """
732
+
733
+ # Note: when opening a GzipFile the 'b+' is superfluous, but this was
734
+ # still how the original test case looked
735
+ # Note: with statement not supported on GzipFile in older Python
736
+ # versions
737
+ fileobj = gzip.GzipFile(self.temp('test.fits.gz'), 'ab+')
738
+ h = fits.PrimaryHDU()
739
+ try:
740
+ h.writeto(fileobj)
741
+ finally:
742
+ fileobj.close()
743
+
744
+ with fits.open(self.temp('test.fits.gz')) as hdul:
745
+ assert hdul[0].header == h.header
746
+
747
+ def test_fits_update_mode_gzip(self):
748
+ """Test updating a GZipped FITS file"""
749
+
750
+ with fits.open(self._make_gzip_file('update.gz'), mode='update') as fits_handle:
751
+ hdu = fits.ImageHDU(data=[x for x in range(100)])
752
+ fits_handle.append(hdu)
753
+
754
+ with fits.open(self.temp('update.gz')) as new_handle:
755
+ assert len(new_handle) == 6
756
+ assert (new_handle[-1].data == [x for x in range(100)]).all()
757
+
758
+ def test_fits_append_mode_gzip(self):
759
+ """Make sure that attempting to open an existing GZipped FITS file in
760
+ 'append' mode raises an error"""
761
+
762
+ with pytest.raises(OSError):
763
+ with fits.open(self._make_gzip_file('append.gz'), mode='append') as fits_handle:
764
+ pass
765
+
766
+ def test_open_bzipped(self):
767
+ bzip_file = self._make_bzip2_file()
768
+ with ignore_warnings():
769
+ with fits.open(bzip_file) as fits_handle:
770
+ assert fits_handle._file.compression == 'bzip2'
771
+ assert len(fits_handle) == 5
772
+
773
+ with fits.open(bz2.BZ2File(bzip_file)) as fits_handle:
774
+ assert fits_handle._file.compression == 'bzip2'
775
+ assert len(fits_handle) == 5
776
+
777
+ def test_open_bzipped_from_handle(self):
778
+ with open(self._make_bzip2_file(), 'rb') as handle:
779
+ with fits.open(handle) as fits_handle:
780
+ assert fits_handle._file.compression == 'bzip2'
781
+ assert len(fits_handle) == 5
782
+
783
+ def test_detect_bzipped(self):
784
+ """Test detection of a bzip2 file when the extension is not .bz2."""
785
+ with ignore_warnings():
786
+ with fits.open(self._make_bzip2_file('test0.xx')) as fits_handle:
787
+ assert fits_handle._file.compression == 'bzip2'
788
+ assert len(fits_handle) == 5
789
+
790
+ def test_writeto_bzip2_fileobj(self):
791
+ """Test writing to a bz2.BZ2File file like object"""
792
+ fileobj = bz2.BZ2File(self.temp('test.fits.bz2'), 'w')
793
+ h = fits.PrimaryHDU()
794
+ try:
795
+ h.writeto(fileobj)
796
+ finally:
797
+ fileobj.close()
798
+
799
+ with fits.open(self.temp('test.fits.bz2')) as hdul:
800
+ assert hdul[0].header == h.header
801
+
802
+ def test_writeto_bzip2_filename(self):
803
+ """Test writing to a bzip2 file by name"""
804
+ filename = self.temp('testname.fits.bz2')
805
+ h = fits.PrimaryHDU()
806
+ h.writeto(filename)
807
+
808
+ with fits.open(self.temp('testname.fits.bz2')) as hdul:
809
+ assert hdul[0].header == h.header
810
+
811
+ def test_open_zipped(self):
812
+ zip_file = self._make_zip_file()
813
+ with ignore_warnings():
814
+ with fits.open(zip_file) as fits_handle:
815
+ assert fits_handle._file.compression == 'zip'
816
+ assert len(fits_handle) == 5
817
+ with fits.open(zipfile.ZipFile(zip_file)) as fits_handle:
818
+ assert fits_handle._file.compression == 'zip'
819
+ assert len(fits_handle) == 5
820
+
821
+ def test_open_zipped_from_handle(self):
822
+ with open(self._make_zip_file(), 'rb') as handle:
823
+ with fits.open(handle) as fits_handle:
824
+ assert fits_handle._file.compression == 'zip'
825
+ assert len(fits_handle) == 5
826
+
827
+ def test_detect_zipped(self):
828
+ """Test detection of a zip file when the extension is not .zip."""
829
+
830
+ zf = self._make_zip_file(filename='test0.fz')
831
+ with ignore_warnings():
832
+ assert len(fits.open(zf)) == 5
833
+
834
+ def test_open_zipped_writeable(self):
835
+ """Opening zipped files in a writeable mode should fail."""
836
+
837
+ zf = self._make_zip_file()
838
+ pytest.raises(OSError, fits.open, zf, 'update')
839
+ pytest.raises(OSError, fits.open, zf, 'append')
840
+
841
+ zf = zipfile.ZipFile(zf, 'a')
842
+ pytest.raises(OSError, fits.open, zf, 'update')
843
+ pytest.raises(OSError, fits.open, zf, 'append')
844
+
845
+ def test_read_open_astropy_gzip_file(self):
846
+ """
847
+ Regression test for https://github.com/astropy/astropy/issues/2774
848
+
849
+ This tests reading from a ``GzipFile`` object from Astropy's
850
+ compatibility copy of the ``gzip`` module.
851
+ """
852
+ gf = gzip.GzipFile(self._make_gzip_file())
853
+ try:
854
+ assert len(fits.open(gf)) == 5
855
+ finally:
856
+ gf.close()
857
+
858
+ @raises(OSError)
859
+ def test_open_multiple_member_zipfile(self):
860
+ """
861
+ Opening zip files containing more than one member files should fail
862
+ as there's no obvious way to specify which file is the FITS file to
863
+ read.
864
+ """
865
+
866
+ zfile = zipfile.ZipFile(self.temp('test0.zip'), 'w')
867
+ zfile.write(self.data('test0.fits'))
868
+ zfile.writestr('foo', 'bar')
869
+ zfile.close()
870
+
871
+ fits.open(zfile.filename)
872
+
873
+ def test_read_open_file(self):
874
+ """Read from an existing file object."""
875
+
876
+ with open(self.data('test0.fits'), 'rb') as f:
877
+ assert len(fits.open(f)) == 5
878
+
879
+ def test_read_closed_file(self):
880
+ """Read from an existing file object that's been closed."""
881
+
882
+ f = open(self.data('test0.fits'), 'rb')
883
+ f.close()
884
+ with fits.open(f) as f2:
885
+ assert len(f2) == 5
886
+
887
+ def test_read_open_gzip_file(self):
888
+ """Read from an open gzip file object."""
889
+
890
+ gf = gzip.GzipFile(self._make_gzip_file())
891
+ try:
892
+ assert len(fits.open(gf)) == 5
893
+ finally:
894
+ gf.close()
895
+
896
+ def test_open_gzip_file_for_writing(self):
897
+ """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/195."""
898
+
899
+ gf = self._make_gzip_file()
900
+ with fits.open(gf, mode='update') as h:
901
+ h[0].header['EXPFLAG'] = 'ABNORMAL'
902
+ h[1].data[0, 0] = 1
903
+ with fits.open(gf) as h:
904
+ # Just to make sur ethe update worked; if updates work
905
+ # normal writes should work too...
906
+ assert h[0].header['EXPFLAG'] == 'ABNORMAL'
907
+ assert h[1].data[0, 0] == 1
908
+
909
+ def test_write_read_gzip_file(self):
910
+ """
911
+ Regression test for https://github.com/astropy/astropy/issues/2794
912
+
913
+ Ensure files written through gzip are readable.
914
+ """
915
+
916
+ data = np.arange(100)
917
+ hdu = fits.PrimaryHDU(data=data)
918
+ hdu.writeto(self.temp('test.fits.gz'))
919
+
920
+ with open(self.temp('test.fits.gz'), 'rb') as f:
921
+ assert f.read(3) == GZIP_MAGIC
922
+
923
+ with fits.open(self.temp('test.fits.gz')) as hdul:
924
+ assert np.all(hdul[0].data == data)
925
+
926
+ def test_read_file_like_object(self):
927
+ """Test reading a FITS file from a file-like object."""
928
+
929
+ filelike = io.BytesIO()
930
+ with open(self.data('test0.fits'), 'rb') as f:
931
+ filelike.write(f.read())
932
+ filelike.seek(0)
933
+ with ignore_warnings():
934
+ assert len(fits.open(filelike)) == 5
935
+
936
+ def test_updated_file_permissions(self):
937
+ """
938
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/79
939
+
940
+ Tests that when a FITS file is modified in update mode, the file
941
+ permissions are preserved.
942
+ """
943
+
944
+ filename = self.temp('test.fits')
945
+ hdul = [fits.PrimaryHDU(), fits.ImageHDU()]
946
+ hdul = fits.HDUList(hdul)
947
+ hdul.writeto(filename)
948
+
949
+ old_mode = os.stat(filename).st_mode
950
+
951
+ hdul = fits.open(filename, mode='update')
952
+ hdul.insert(1, fits.ImageHDU())
953
+ hdul.flush()
954
+ hdul.close()
955
+
956
+ assert old_mode == os.stat(filename).st_mode
957
+
958
+ def test_fileobj_mode_guessing(self):
959
+ """Tests whether a file opened without a specified io.fits mode
960
+ ('readonly', etc.) is opened in a mode appropriate for the given file
961
+ object.
962
+ """
963
+
964
+ self.copy_file('test0.fits')
965
+
966
+ # Opening in text mode should outright fail
967
+ for mode in ('r', 'w', 'a'):
968
+ with open(self.temp('test0.fits'), mode) as f:
969
+ pytest.raises(ValueError, fits.HDUList.fromfile, f)
970
+
971
+ # Need to re-copy the file since opening it in 'w' mode blew it away
972
+ self.copy_file('test0.fits')
973
+
974
+ with open(self.temp('test0.fits'), 'rb') as f:
975
+ with fits.HDUList.fromfile(f) as h:
976
+ assert h.fileinfo(0)['filemode'] == 'readonly'
977
+
978
+ for mode in ('wb', 'ab'):
979
+ with open(self.temp('test0.fits'), mode) as f:
980
+ with fits.HDUList.fromfile(f) as h:
981
+ # Basically opening empty files for output streaming
982
+ assert len(h) == 0
983
+
984
+ # Need to re-copy the file since opening it in 'w' mode blew it away
985
+ self.copy_file('test0.fits')
986
+
987
+ with open(self.temp('test0.fits'), 'wb+') as f:
988
+ with fits.HDUList.fromfile(f) as h:
989
+ # wb+ still causes an existing file to be overwritten so there
990
+ # are no HDUs
991
+ assert len(h) == 0
992
+
993
+ # Need to re-copy the file since opening it in 'w' mode blew it away
994
+ self.copy_file('test0.fits')
995
+
996
+ with open(self.temp('test0.fits'), 'rb+') as f:
997
+ with fits.HDUList.fromfile(f) as h:
998
+ assert h.fileinfo(0)['filemode'] == 'update'
999
+
1000
+ with open(self.temp('test0.fits'), 'ab+') as f:
1001
+ with fits.HDUList.fromfile(f) as h:
1002
+ assert h.fileinfo(0)['filemode'] == 'append'
1003
+
1004
+ def test_mmap_unwriteable(self):
1005
+ """Regression test for https://github.com/astropy/astropy/issues/968
1006
+
1007
+ Temporarily patches mmap.mmap to exhibit platform-specific bad
1008
+ behavior.
1009
+ """
1010
+
1011
+ class MockMmap(mmap.mmap):
1012
+ def flush(self):
1013
+ raise OSError('flush is broken on this platform')
1014
+
1015
+ old_mmap = mmap.mmap
1016
+ mmap.mmap = MockMmap
1017
+
1018
+ # Force the mmap test to be rerun
1019
+ _File.__dict__['_mmap_available']._cache.clear()
1020
+
1021
+ try:
1022
+ self.copy_file('test0.fits')
1023
+ with catch_warnings() as w:
1024
+ with fits.open(self.temp('test0.fits'), mode='update',
1025
+ memmap=True) as h:
1026
+ h[1].data[0, 0] = 999
1027
+
1028
+ assert len(w) == 1
1029
+ assert 'mmap.flush is unavailable' in str(w[0].message)
1030
+
1031
+ # Double check that writing without mmap still worked
1032
+ with fits.open(self.temp('test0.fits')) as h:
1033
+ assert h[1].data[0, 0] == 999
1034
+ finally:
1035
+ mmap.mmap = old_mmap
1036
+ _File.__dict__['_mmap_available']._cache.clear()
1037
+
1038
+ @pytest.mark.openfiles_ignore
1039
+ def test_mmap_allocate_error(self):
1040
+ """
1041
+ Regression test for https://github.com/astropy/astropy/issues/1380
1042
+
1043
+ Temporarily patches mmap.mmap to raise an OSError if mode is ACCESS_COPY.
1044
+ """
1045
+
1046
+ mmap_original = mmap.mmap
1047
+
1048
+ # We patch mmap here to raise an error if access=mmap.ACCESS_COPY, which
1049
+ # emulates an issue that an OSError is raised if the available address
1050
+ # space is less than the size of the file even if memory mapping is used.
1051
+
1052
+ def mmap_patched(*args, **kwargs):
1053
+ if kwargs.get('access') == mmap.ACCESS_COPY:
1054
+ exc = OSError()
1055
+ exc.errno = errno.ENOMEM
1056
+ raise exc
1057
+ else:
1058
+ return mmap_original(*args, **kwargs)
1059
+
1060
+ with fits.open(self.data('test0.fits'), memmap=True) as hdulist:
1061
+ with patch.object(mmap, 'mmap', side_effect=mmap_patched) as p:
1062
+ with pytest.warns(AstropyUserWarning, match="Could not memory "
1063
+ "map array with mode='readonly'"):
1064
+ data = hdulist[1].data
1065
+ p.reset_mock()
1066
+ assert not data.flags.writeable
1067
+
1068
+ def test_mmap_closing(self):
1069
+ """
1070
+ Tests that the mmap reference is closed/removed when there aren't any
1071
+ HDU data references left.
1072
+ """
1073
+
1074
+ if not _File._mmap_available:
1075
+ pytest.xfail('not expected to work on platforms without mmap '
1076
+ 'support')
1077
+
1078
+ with fits.open(self.data('test0.fits'), memmap=True) as hdul:
1079
+ assert hdul._file._mmap is None
1080
+
1081
+ hdul[1].data
1082
+ assert hdul._file._mmap is not None
1083
+
1084
+ del hdul[1].data
1085
+ # Should be no more references to data in the file so close the
1086
+ # mmap
1087
+ assert hdul._file._mmap is None
1088
+
1089
+ hdul[1].data
1090
+ hdul[2].data
1091
+ del hdul[1].data
1092
+ # hdul[2].data is still references so keep the mmap open
1093
+ assert hdul._file._mmap is not None
1094
+ del hdul[2].data
1095
+ assert hdul._file._mmap is None
1096
+
1097
+ assert hdul._file._mmap is None
1098
+
1099
+ with fits.open(self.data('test0.fits'), memmap=True) as hdul:
1100
+ hdul[1].data
1101
+
1102
+ # When the only reference to the data is on the hdu object, and the
1103
+ # hdulist it belongs to has been closed, the mmap should be closed as
1104
+ # well
1105
+ assert hdul._file._mmap is None
1106
+
1107
+ with fits.open(self.data('test0.fits'), memmap=True) as hdul:
1108
+ data = hdul[1].data
1109
+ # also make a copy
1110
+ data_copy = data.copy()
1111
+
1112
+ # The HDUList is closed; in fact, get rid of it completely
1113
+ del hdul
1114
+
1115
+ # The data array should still work though...
1116
+ assert np.all(data == data_copy)
1117
+
1118
+ def test_uncloseable_file(self):
1119
+ """
1120
+ Regression test for https://github.com/astropy/astropy/issues/2356
1121
+
1122
+ Demonstrates that FITS files can still be read from "file-like" objects
1123
+ that don't have an obvious "open" or "closed" state.
1124
+ """
1125
+
1126
+ class MyFileLike:
1127
+ def __init__(self, foobar):
1128
+ self._foobar = foobar
1129
+
1130
+ def read(self, n):
1131
+ return self._foobar.read(n)
1132
+
1133
+ def seek(self, offset, whence=os.SEEK_SET):
1134
+ self._foobar.seek(offset, whence)
1135
+
1136
+ def tell(self):
1137
+ return self._foobar.tell()
1138
+
1139
+ with open(self.data('test0.fits'), 'rb') as f:
1140
+ fileobj = MyFileLike(f)
1141
+
1142
+ with fits.open(fileobj) as hdul1:
1143
+ with fits.open(self.data('test0.fits')) as hdul2:
1144
+ assert hdul1.info(output=False) == hdul2.info(output=False)
1145
+ for hdu1, hdu2 in zip(hdul1, hdul2):
1146
+ assert hdu1.header == hdu2.header
1147
+ if hdu1.data is not None and hdu2.data is not None:
1148
+ assert np.all(hdu1.data == hdu2.data)
1149
+
1150
+ def test_write_bytesio_discontiguous(self):
1151
+ """
1152
+ Regression test related to
1153
+ https://github.com/astropy/astropy/issues/2794#issuecomment-55441539
1154
+
1155
+ Demonstrates that writing an HDU containing a discontiguous Numpy array
1156
+ should work properly.
1157
+ """
1158
+
1159
+ data = np.arange(100)[::3]
1160
+ hdu = fits.PrimaryHDU(data=data)
1161
+ fileobj = io.BytesIO()
1162
+ hdu.writeto(fileobj)
1163
+
1164
+ fileobj.seek(0)
1165
+
1166
+ with fits.open(fileobj) as h:
1167
+ assert np.all(h[0].data == data)
1168
+
1169
+ def test_write_bytesio(self):
1170
+ """
1171
+ Regression test for https://github.com/astropy/astropy/issues/2463
1172
+
1173
+ Test againt `io.BytesIO`. `io.StringIO` is not supported.
1174
+ """
1175
+
1176
+ self._test_write_string_bytes_io(io.BytesIO())
1177
+
1178
+ @pytest.mark.skipif(str('sys.platform.startswith("win32")'))
1179
+ def test_filename_with_colon(self):
1180
+ """
1181
+ Test reading and writing a file with a colon in the filename.
1182
+
1183
+ Regression test for https://github.com/astropy/astropy/issues/3122
1184
+ """
1185
+
1186
+ # Skip on Windows since colons in filenames makes NTFS sad.
1187
+
1188
+ filename = 'APEXHET.2014-04-01T15:18:01.000.fits'
1189
+ hdu = fits.PrimaryHDU(data=np.arange(10))
1190
+ hdu.writeto(self.temp(filename))
1191
+
1192
+ with fits.open(self.temp(filename)) as hdul:
1193
+ assert np.all(hdul[0].data == hdu.data)
1194
+
1195
+ def test_writeto_full_disk(self, monkeypatch):
1196
+ """
1197
+ Test that it gives a readable error when trying to write an hdulist
1198
+ to a full disk.
1199
+ """
1200
+
1201
+ def _writeto(self, array):
1202
+ raise OSError("Fake error raised when writing file.")
1203
+
1204
+ def get_free_space_in_dir(path):
1205
+ return 0
1206
+
1207
+ with pytest.raises(OSError) as exc:
1208
+ monkeypatch.setattr(fits.hdu.base._BaseHDU, "_writeto", _writeto)
1209
+ monkeypatch.setattr(data, "get_free_space_in_dir", get_free_space_in_dir)
1210
+
1211
+ n = np.arange(0, 1000, dtype='int64')
1212
+ hdu = fits.PrimaryHDU(n)
1213
+ hdulist = fits.HDUList(hdu)
1214
+ filename = self.temp('test.fits')
1215
+
1216
+ with open(filename, mode='wb') as fileobj:
1217
+ hdulist.writeto(fileobj)
1218
+
1219
+ assert ("Not enough space on disk: requested 8000, available 0. "
1220
+ "Fake error raised when writing file.") == exc.value.args[0]
1221
+
1222
+ def test_flush_full_disk(self, monkeypatch):
1223
+ """
1224
+ Test that it gives a readable error when trying to update an hdulist
1225
+ to a full disk.
1226
+ """
1227
+ filename = self.temp('test.fits')
1228
+ hdul = [fits.PrimaryHDU(), fits.ImageHDU()]
1229
+ hdul = fits.HDUList(hdul)
1230
+ hdul[0].data = np.arange(0, 1000, dtype='int64')
1231
+ hdul.writeto(filename)
1232
+
1233
+ def _writedata(self, fileobj):
1234
+ raise OSError("Fake error raised when writing file.")
1235
+
1236
+ def get_free_space_in_dir(path):
1237
+ return 0
1238
+
1239
+ monkeypatch.setattr(fits.hdu.base._BaseHDU, "_writedata", _writedata)
1240
+ monkeypatch.setattr(data, "get_free_space_in_dir",
1241
+ get_free_space_in_dir)
1242
+
1243
+ with pytest.raises(OSError) as exc:
1244
+ with fits.open(filename, mode='update') as hdul:
1245
+ hdul[0].data = np.arange(0, 1000, dtype='int64')
1246
+ hdul.insert(1, fits.ImageHDU())
1247
+ hdul.flush()
1248
+
1249
+ assert ("Not enough space on disk: requested 8000, available 0. "
1250
+ "Fake error raised when writing file.") == exc.value.args[0]
1251
+
1252
+ def _test_write_string_bytes_io(self, fileobj):
1253
+ """
1254
+ Implemented for both test_write_stringio and test_write_bytesio.
1255
+ """
1256
+
1257
+ with fits.open(self.data('test0.fits')) as hdul:
1258
+ hdul.writeto(fileobj)
1259
+ hdul2 = fits.HDUList.fromstring(fileobj.getvalue())
1260
+ assert FITSDiff(hdul, hdul2).identical
1261
+
1262
+ def _make_gzip_file(self, filename='test0.fits.gz'):
1263
+ gzfile = self.temp(filename)
1264
+ with open(self.data('test0.fits'), 'rb') as f:
1265
+ gz = gzip.open(gzfile, 'wb')
1266
+ gz.write(f.read())
1267
+ gz.close()
1268
+
1269
+ return gzfile
1270
+
1271
+ def _make_zip_file(self, mode='copyonwrite', filename='test0.fits.zip'):
1272
+ zfile = zipfile.ZipFile(self.temp(filename), 'w')
1273
+ zfile.write(self.data('test0.fits'))
1274
+ zfile.close()
1275
+
1276
+ return zfile.filename
1277
+
1278
+ def _make_bzip2_file(self, filename='test0.fits.bz2'):
1279
+ bzfile = self.temp(filename)
1280
+ with open(self.data('test0.fits'), 'rb') as f:
1281
+ bz = bz2.BZ2File(bzfile, 'w')
1282
+ bz.write(f.read())
1283
+ bz.close()
1284
+
1285
+ return bzfile
1286
+
1287
+
1288
+ class TestStreamingFunctions(FitsTestCase):
1289
+ """Test functionality of the StreamingHDU class."""
1290
+
1291
+ def test_streaming_hdu(self):
1292
+ shdu = self._make_streaming_hdu(self.temp('new.fits'))
1293
+ assert isinstance(shdu.size, int)
1294
+ assert shdu.size == 100
1295
+ shdu.close()
1296
+
1297
+ @raises(ValueError)
1298
+ def test_streaming_hdu_file_wrong_mode(self):
1299
+ """
1300
+ Test that streaming an HDU to a file opened in the wrong mode fails as
1301
+ expected.
1302
+ """
1303
+
1304
+ with open(self.temp('new.fits'), 'wb') as f:
1305
+ header = fits.Header()
1306
+ fits.StreamingHDU(f, header)
1307
+
1308
+ def test_streaming_hdu_write_file(self):
1309
+ """Test streaming an HDU to an open file object."""
1310
+
1311
+ arr = np.zeros((5, 5), dtype=np.int32)
1312
+ with open(self.temp('new.fits'), 'ab+') as f:
1313
+ shdu = self._make_streaming_hdu(f)
1314
+ shdu.write(arr)
1315
+ assert shdu.writecomplete
1316
+ assert shdu.size == 100
1317
+ with fits.open(self.temp('new.fits')) as hdul:
1318
+ assert len(hdul) == 1
1319
+ assert (hdul[0].data == arr).all()
1320
+
1321
+ def test_streaming_hdu_write_file_like(self):
1322
+ """Test streaming an HDU to an open file-like object."""
1323
+
1324
+ arr = np.zeros((5, 5), dtype=np.int32)
1325
+ # The file-like object underlying a StreamingHDU must be in binary mode
1326
+ sf = io.BytesIO()
1327
+ shdu = self._make_streaming_hdu(sf)
1328
+ shdu.write(arr)
1329
+ assert shdu.writecomplete
1330
+ assert shdu.size == 100
1331
+
1332
+ sf.seek(0)
1333
+ hdul = fits.open(sf)
1334
+ assert len(hdul) == 1
1335
+ assert (hdul[0].data == arr).all()
1336
+
1337
+ def test_streaming_hdu_append_extension(self):
1338
+ arr = np.zeros((5, 5), dtype=np.int32)
1339
+ with open(self.temp('new.fits'), 'ab+') as f:
1340
+ shdu = self._make_streaming_hdu(f)
1341
+ shdu.write(arr)
1342
+ # Doing this again should update the file with an extension
1343
+ with open(self.temp('new.fits'), 'ab+') as f:
1344
+ shdu = self._make_streaming_hdu(f)
1345
+ shdu.write(arr)
1346
+
1347
+ def test_fix_invalid_extname(self, capsys):
1348
+ phdu = fits.PrimaryHDU()
1349
+ ihdu = fits.ImageHDU()
1350
+ ihdu.header['EXTNAME'] = 12345678
1351
+ hdul = fits.HDUList([phdu, ihdu])
1352
+ filename = self.temp('temp.fits')
1353
+
1354
+ pytest.raises(fits.VerifyError, hdul.writeto, filename,
1355
+ output_verify='exception')
1356
+ with pytest.warns(fits.verify.VerifyWarning,
1357
+ match='Verification reported errors'):
1358
+ hdul.writeto(filename, output_verify='fix')
1359
+ with fits.open(filename):
1360
+ assert hdul[1].name == '12345678'
1361
+ assert hdul[1].header['EXTNAME'] == '12345678'
1362
+
1363
+ hdul.close()
1364
+
1365
+ def _make_streaming_hdu(self, fileobj):
1366
+ hd = fits.Header()
1367
+ hd['SIMPLE'] = (True, 'conforms to FITS standard')
1368
+ hd['BITPIX'] = (32, 'array data type')
1369
+ hd['NAXIS'] = (2, 'number of array dimensions')
1370
+ hd['NAXIS1'] = 5
1371
+ hd['NAXIS2'] = 5
1372
+ hd['EXTEND'] = True
1373
+ return fits.StreamingHDU(fileobj, hd)
1374
+
1375
+ def test_blank_ignore(self):
1376
+
1377
+ with fits.open(self.data('blank.fits'), ignore_blank=True) as f:
1378
+ assert f[0].data.flat[0] == 2
1379
+
1380
+ def test_error_if_memmap_impossible(self):
1381
+ pth = self.data('blank.fits')
1382
+ with fits.open(pth, memmap=True) as hdul:
1383
+ with pytest.raises(ValueError):
1384
+ hdul[0].data
1385
+
1386
+ # However, it should not fail if do_not_scale_image_data was used:
1387
+ # See https://github.com/astropy/astropy/issues/3766
1388
+ with fits.open(pth, memmap=True, do_not_scale_image_data=True) as hdul:
1389
+ hdul[0].data # Just make sure it doesn't crash
testbed/astropy__astropy/astropy/io/fits/tests/test_division.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import numpy as np
4
+
5
+ from astropy.io import fits
6
+ from . import FitsTestCase
7
+ from astropy.tests.helper import catch_warnings
8
+
9
+
10
+ class TestDivisionFunctions(FitsTestCase):
11
+ """Test code units that rely on correct integer division."""
12
+
13
+ def test_rec_from_string(self):
14
+ with fits.open(self.data('tb.fits')) as t1:
15
+ s = t1[1].data.tostring()
16
+ np.rec.array(
17
+ s,
18
+ dtype=np.dtype([('c1', '>i4'), ('c2', '|S3'),
19
+ ('c3', '>f4'), ('c4', '|i1')]),
20
+ shape=len(s) // 12)
21
+
22
+ def test_card_with_continue(self):
23
+ h = fits.PrimaryHDU()
24
+ with catch_warnings() as w:
25
+ h.header['abc'] = 'abcdefg' * 20
26
+ assert len(w) == 0
27
+
28
+ def test_valid_hdu_size(self):
29
+ with fits.open(self.data('tb.fits')) as t1:
30
+ assert type(t1[1].size) is type(1) # noqa
31
+
32
+ def test_hdu_get_size(self):
33
+ with catch_warnings() as w:
34
+ t1 = fits.open(self.data('tb.fits'))
35
+ assert len(w) == 0
36
+
37
+ def test_section(self, capsys):
38
+ # section testing
39
+ fs = fits.open(self.data('arange.fits'))
40
+ with catch_warnings() as w:
41
+ assert np.all(fs[0].section[3, 2, 5] == np.array([357]))
42
+ assert len(w) == 0
testbed/astropy__astropy/astropy/io/fits/tests/test_fitscheck.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ import pytest
4
+ from . import FitsTestCase
5
+ from astropy.io.fits.scripts import fitscheck
6
+ from astropy.io import fits
7
+
8
+
9
+ class TestFitscheck(FitsTestCase):
10
+ def test_noargs(self):
11
+ with pytest.raises(SystemExit) as e:
12
+ fitscheck.main(['-h'])
13
+ assert e.value.code == 0
14
+
15
+ def test_missing_file(self, capsys):
16
+ assert fitscheck.main(['missing.fits']) == 1
17
+ stdout, stderr = capsys.readouterr()
18
+ assert 'No such file or directory' in stderr
19
+
20
+ def test_valid_file(self, capsys):
21
+ testfile = self.data('checksum.fits')
22
+
23
+ assert fitscheck.main([testfile]) == 0
24
+ assert fitscheck.main([testfile, '--compliance']) == 0
25
+
26
+ assert fitscheck.main([testfile, '-v']) == 0
27
+ stdout, stderr = capsys.readouterr()
28
+ assert 'OK' in stderr
29
+
30
+ def test_remove_checksums(self, capsys):
31
+ self.copy_file('checksum.fits')
32
+ testfile = self.temp('checksum.fits')
33
+ assert fitscheck.main([testfile, '--checksum', 'remove']) == 1
34
+ assert fitscheck.main([testfile]) == 1
35
+ stdout, stderr = capsys.readouterr()
36
+ assert 'MISSING' in stderr
37
+
38
+ def test_no_checksums(self, capsys):
39
+ testfile = self.data('arange.fits')
40
+
41
+ assert fitscheck.main([testfile]) == 1
42
+ stdout, stderr = capsys.readouterr()
43
+ assert 'Checksum not found' in stderr
44
+
45
+ assert fitscheck.main([testfile, '--ignore-missing']) == 0
46
+ stdout, stderr = capsys.readouterr()
47
+ assert stderr == ''
48
+
49
+ def test_overwrite_invalid(self, capsys):
50
+ """
51
+ Tests that invalid checksum or datasum are overwriten when the file is
52
+ saved.
53
+ """
54
+ reffile = self.temp('ref.fits')
55
+ with fits.open(self.data('tb.fits')) as hdul:
56
+ hdul.writeto(reffile, checksum=True)
57
+
58
+ # replace checksums with wrong ones
59
+ testfile = self.temp('test.fits')
60
+ with fits.open(self.data('tb.fits')) as hdul:
61
+ hdul[0].header['DATASUM'] = '1 '
62
+ hdul[0].header['CHECKSUM'] = '8UgqATfo7TfoATfo'
63
+ hdul[1].header['DATASUM'] = '2349680925'
64
+ hdul[1].header['CHECKSUM'] = '11daD8bX98baA8bU'
65
+ hdul.writeto(testfile)
66
+
67
+ assert fitscheck.main([testfile]) == 1
68
+ stdout, stderr = capsys.readouterr()
69
+ assert 'BAD' in stderr
70
+ assert 'Checksum verification failed' in stderr
71
+
72
+ assert fitscheck.main([testfile, '--write', '--force']) == 1
73
+ stdout, stderr = capsys.readouterr()
74
+ assert 'BAD' in stderr
75
+
76
+ # check that the file was fixed
77
+ assert fitscheck.main([testfile]) == 0
testbed/astropy__astropy/astropy/io/fits/tests/test_fitsdiff.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ import numpy as np
4
+ import pytest
5
+ import os
6
+
7
+ from . import FitsTestCase
8
+ from astropy.io.fits.convenience import writeto
9
+ from astropy.io.fits.hdu import PrimaryHDU, hdulist
10
+ from astropy.io.fits import Header, ImageHDU, HDUList
11
+ from astropy.io.fits.scripts import fitsdiff
12
+ from astropy.tests.helper import catch_warnings
13
+ from astropy.utils.exceptions import AstropyDeprecationWarning
14
+ from astropy.version import version
15
+
16
+
17
+ class TestFITSDiff_script(FitsTestCase):
18
+
19
+ def test_noargs(self):
20
+ with pytest.raises(SystemExit) as e:
21
+ fitsdiff.main()
22
+ assert e.value.code == 2
23
+
24
+ def test_oneargargs(self):
25
+ with pytest.raises(SystemExit) as e:
26
+ fitsdiff.main(["file1"])
27
+ assert e.value.code == 2
28
+
29
+ def test_nodiff(self):
30
+ a = np.arange(100).reshape(10, 10)
31
+ hdu_a = PrimaryHDU(data=a)
32
+ b = a.copy()
33
+ hdu_b = PrimaryHDU(data=b)
34
+ tmp_a = self.temp('testa.fits')
35
+ tmp_b = self.temp('testb.fits')
36
+ hdu_a.writeto(tmp_a)
37
+ hdu_b.writeto(tmp_b)
38
+ numdiff = fitsdiff.main([tmp_a, tmp_b])
39
+ assert numdiff == 0
40
+
41
+ def test_onediff(self):
42
+ a = np.arange(100).reshape(10, 10)
43
+ hdu_a = PrimaryHDU(data=a)
44
+ b = a.copy()
45
+ b[1, 0] = 12
46
+ hdu_b = PrimaryHDU(data=b)
47
+ tmp_a = self.temp('testa.fits')
48
+ tmp_b = self.temp('testb.fits')
49
+ hdu_a.writeto(tmp_a)
50
+ hdu_b.writeto(tmp_b)
51
+ numdiff = fitsdiff.main([tmp_a, tmp_b])
52
+ assert numdiff == 1
53
+
54
+ def test_manydiff(self, capsys):
55
+ a = np.arange(100).reshape(10, 10)
56
+ hdu_a = PrimaryHDU(data=a)
57
+ b = a + 1
58
+ hdu_b = PrimaryHDU(data=b)
59
+ tmp_a = self.temp('testa.fits')
60
+ tmp_b = self.temp('testb.fits')
61
+ hdu_a.writeto(tmp_a)
62
+ hdu_b.writeto(tmp_b)
63
+
64
+ numdiff = fitsdiff.main([tmp_a, tmp_b])
65
+ out, err = capsys.readouterr()
66
+ assert numdiff == 1
67
+ assert out.splitlines()[-4:] == [
68
+ ' a> 9',
69
+ ' b> 10',
70
+ ' ...',
71
+ ' 100 different pixels found (100.00% different).']
72
+
73
+ numdiff = fitsdiff.main(['-n', '1', tmp_a, tmp_b])
74
+ out, err = capsys.readouterr()
75
+ assert numdiff == 1
76
+ assert out.splitlines()[-4:] == [
77
+ ' a> 0',
78
+ ' b> 1',
79
+ ' ...',
80
+ ' 100 different pixels found (100.00% different).']
81
+
82
+ def test_outputfile(self):
83
+ a = np.arange(100).reshape(10, 10)
84
+ hdu_a = PrimaryHDU(data=a)
85
+ b = a.copy()
86
+ b[1, 0] = 12
87
+ hdu_b = PrimaryHDU(data=b)
88
+ tmp_a = self.temp('testa.fits')
89
+ tmp_b = self.temp('testb.fits')
90
+ hdu_a.writeto(tmp_a)
91
+ hdu_b.writeto(tmp_b)
92
+
93
+ numdiff = fitsdiff.main(['-o', self.temp('diff.txt'), tmp_a, tmp_b])
94
+ assert numdiff == 1
95
+ with open(self.temp('diff.txt')) as f:
96
+ out = f.read()
97
+ assert out.splitlines()[-4:] == [
98
+ ' Data differs at [1, 2]:',
99
+ ' a> 10',
100
+ ' b> 12',
101
+ ' 1 different pixels found (1.00% different).']
102
+
103
+ def test_atol(self):
104
+ a = np.arange(100, dtype=float).reshape(10, 10)
105
+ hdu_a = PrimaryHDU(data=a)
106
+ b = a.copy()
107
+ b[1, 0] = 11
108
+ hdu_b = PrimaryHDU(data=b)
109
+ tmp_a = self.temp('testa.fits')
110
+ tmp_b = self.temp('testb.fits')
111
+ hdu_a.writeto(tmp_a)
112
+ hdu_b.writeto(tmp_b)
113
+
114
+ numdiff = fitsdiff.main(["-a", "1", tmp_a, tmp_b])
115
+ assert numdiff == 0
116
+
117
+ numdiff = fitsdiff.main(["--exact", "-a", "1", tmp_a, tmp_b])
118
+ assert numdiff == 1
119
+
120
+ def test_rtol(self):
121
+ a = np.arange(100, dtype=float).reshape(10, 10)
122
+ hdu_a = PrimaryHDU(data=a)
123
+ b = a.copy()
124
+ b[1, 0] = 11
125
+ hdu_b = PrimaryHDU(data=b)
126
+ tmp_a = self.temp('testa.fits')
127
+ tmp_b = self.temp('testb.fits')
128
+ hdu_a.writeto(tmp_a)
129
+ hdu_b.writeto(tmp_b)
130
+ numdiff = fitsdiff.main(["-r", "1e-1", tmp_a, tmp_b])
131
+ assert numdiff == 0
132
+
133
+ def test_rtol_diff(self, capsys):
134
+ a = np.arange(100, dtype=float).reshape(10, 10)
135
+ hdu_a = PrimaryHDU(data=a)
136
+ b = a.copy()
137
+ b[1, 0] = 11
138
+ hdu_b = PrimaryHDU(data=b)
139
+ tmp_a = self.temp('testa.fits')
140
+ tmp_b = self.temp('testb.fits')
141
+ hdu_a.writeto(tmp_a)
142
+ hdu_b.writeto(tmp_b)
143
+ numdiff = fitsdiff.main(["-r", "1e-2", tmp_a, tmp_b])
144
+ assert numdiff == 1
145
+ out, err = capsys.readouterr()
146
+ assert out == """
147
+ fitsdiff: {}
148
+ a: {}
149
+ b: {}
150
+ Maximum number of different data values to be reported: 10
151
+ Relative tolerance: 0.01, Absolute tolerance: 0.0
152
+
153
+ Primary HDU:\n\n Data contains differences:
154
+ Data differs at [1, 2]:
155
+ a> 10.0
156
+ ? ^
157
+ b> 11.0
158
+ ? ^
159
+ 1 different pixels found (1.00% different).\n""".format(version, tmp_a, tmp_b)
160
+ assert err == ""
161
+
162
+ def test_fitsdiff_script_both_d_and_r(self, capsys):
163
+ a = np.arange(100).reshape(10, 10)
164
+ hdu_a = PrimaryHDU(data=a)
165
+ b = a.copy()
166
+ hdu_b = PrimaryHDU(data=b)
167
+ tmp_a = self.temp('testa.fits')
168
+ tmp_b = self.temp('testb.fits')
169
+ hdu_a.writeto(tmp_a)
170
+ hdu_b.writeto(tmp_b)
171
+ with catch_warnings(AstropyDeprecationWarning) as warning_lines:
172
+ fitsdiff.main(["-r", "1e-4", "-d", "1e-2", tmp_a, tmp_b])
173
+ # `rtol` is always ignored when `tolerance` is provided
174
+ assert warning_lines[0].category == AstropyDeprecationWarning
175
+ assert (str(warning_lines[0].message) ==
176
+ '"-d" ("--difference-tolerance") was deprecated in version 2.0 '
177
+ 'and will be removed in a future version. '
178
+ 'Use "-r" ("--relative-tolerance") instead.')
179
+ out, err = capsys.readouterr()
180
+ assert out == """
181
+ fitsdiff: {}
182
+ a: {}
183
+ b: {}
184
+ Maximum number of different data values to be reported: 10
185
+ Relative tolerance: 0.01, Absolute tolerance: 0.0
186
+
187
+ No differences found.\n""".format(version, tmp_a, tmp_b)
188
+
189
+ def test_wildcard(self):
190
+ tmp1 = self.temp("tmp_file1")
191
+ with pytest.raises(SystemExit) as e:
192
+ fitsdiff.main([tmp1+"*", "ACME"])
193
+ assert e.value.code == 2
194
+
195
+ def test_not_quiet(self, capsys):
196
+ a = np.arange(100).reshape(10, 10)
197
+ hdu_a = PrimaryHDU(data=a)
198
+ b = a.copy()
199
+ hdu_b = PrimaryHDU(data=b)
200
+ tmp_a = self.temp('testa.fits')
201
+ tmp_b = self.temp('testb.fits')
202
+ hdu_a.writeto(tmp_a)
203
+ hdu_b.writeto(tmp_b)
204
+ numdiff = fitsdiff.main([tmp_a, tmp_b])
205
+ assert numdiff == 0
206
+ out, err = capsys.readouterr()
207
+ assert out == """
208
+ fitsdiff: {}
209
+ a: {}
210
+ b: {}
211
+ Maximum number of different data values to be reported: 10
212
+ Relative tolerance: 0.0, Absolute tolerance: 0.0
213
+
214
+ No differences found.\n""".format(version, tmp_a, tmp_b)
215
+ assert err == ""
216
+
217
+ def test_quiet(self, capsys):
218
+ a = np.arange(100).reshape(10, 10)
219
+ hdu_a = PrimaryHDU(data=a)
220
+ b = a.copy()
221
+ hdu_b = PrimaryHDU(data=b)
222
+ tmp_a = self.temp('testa.fits')
223
+ tmp_b = self.temp('testb.fits')
224
+ hdu_a.writeto(tmp_a)
225
+ hdu_b.writeto(tmp_b)
226
+ numdiff = fitsdiff.main(["-q", tmp_a, tmp_b])
227
+ assert numdiff == 0
228
+ out, err = capsys.readouterr()
229
+ assert out == ""
230
+ assert err == ""
231
+
232
+ def test_path(self, capsys):
233
+ os.mkdir(self.temp('sub/'))
234
+ tmp_b = self.temp('sub/ascii.fits')
235
+
236
+ tmp_g = self.temp('sub/group.fits')
237
+ tmp_h = self.data('group.fits')
238
+ with hdulist.fitsopen(tmp_h) as hdu_b:
239
+ hdu_b.writeto(tmp_g)
240
+
241
+ writeto(tmp_b, np.arange(100).reshape(10, 10))
242
+
243
+ # one modified file and a directory
244
+ assert fitsdiff.main(["-q", self.data_dir, tmp_b]) == 1
245
+ assert fitsdiff.main(["-q", tmp_b, self.data_dir]) == 1
246
+
247
+ # two directories
248
+ tmp_d = self.temp('sub/')
249
+ assert fitsdiff.main(["-q", self.data_dir, tmp_d]) == 1
250
+ assert fitsdiff.main(["-q", tmp_d, self.data_dir]) == 1
251
+ with pytest.warns(UserWarning, match="Field 'ORBPARM' has a repeat "
252
+ "count of 0 in its format code"):
253
+ assert fitsdiff.main(["-q", self.data_dir, self.data_dir]) == 0
254
+
255
+ # no match
256
+ tmp_c = self.data('arange.fits')
257
+ fitsdiff.main([tmp_c, tmp_d])
258
+ out, err = capsys.readouterr()
259
+ assert "'arange.fits' has no match in" in err
260
+
261
+ # globbing
262
+ with pytest.warns(UserWarning, match="Field 'ORBPARM' has a repeat "
263
+ "count of 0 in its format code"):
264
+ assert fitsdiff.main(["-q", self.data_dir+'/*.fits',
265
+ self.data_dir]) == 0
266
+ assert fitsdiff.main(["-q", self.data_dir+'/g*.fits', tmp_d]) == 0
267
+
268
+ # one file and a directory
269
+ tmp_f = self.data('tb.fits')
270
+ assert fitsdiff.main(["-q", tmp_f, self.data_dir]) == 0
271
+ assert fitsdiff.main(["-q", self.data_dir, tmp_f]) == 0
272
+
273
+ def test_ignore_hdus(self):
274
+ a = np.arange(100).reshape(10, 10)
275
+ b = a.copy() + 1
276
+ ha = Header([('A', 1), ('B', 2), ('C', 3)])
277
+ phdu_a = PrimaryHDU(header=ha)
278
+ phdu_b = PrimaryHDU(header=ha)
279
+ ihdu_a = ImageHDU(data=a, name='SCI')
280
+ ihdu_b = ImageHDU(data=b, name='SCI')
281
+ hdulist_a = HDUList([phdu_a, ihdu_a])
282
+ hdulist_b = HDUList([phdu_b, ihdu_b])
283
+ tmp_a = self.temp('testa.fits')
284
+ tmp_b = self.temp('testb.fits')
285
+ hdulist_a.writeto(tmp_a)
286
+ hdulist_b.writeto(tmp_b)
287
+
288
+ numdiff = fitsdiff.main([tmp_a, tmp_b])
289
+ assert numdiff == 1
290
+
291
+ numdiff = fitsdiff.main([tmp_a, tmp_b, "-u", "SCI"])
292
+ assert numdiff == 0
293
+
294
+ def test_ignore_hdus_report(self, capsys):
295
+ a = np.arange(100).reshape(10, 10)
296
+ b = a.copy() + 1
297
+ ha = Header([('A', 1), ('B', 2), ('C', 3)])
298
+ phdu_a = PrimaryHDU(header=ha)
299
+ phdu_b = PrimaryHDU(header=ha)
300
+ ihdu_a = ImageHDU(data=a, name='SCI')
301
+ ihdu_b = ImageHDU(data=b, name='SCI')
302
+ hdulist_a = HDUList([phdu_a, ihdu_a])
303
+ hdulist_b = HDUList([phdu_b, ihdu_b])
304
+ tmp_a = self.temp('testa.fits')
305
+ tmp_b = self.temp('testb.fits')
306
+ hdulist_a.writeto(tmp_a)
307
+ hdulist_b.writeto(tmp_b)
308
+
309
+ numdiff = fitsdiff.main([tmp_a, tmp_b, "-u", "SCI"])
310
+ assert numdiff == 0
311
+ out, err = capsys.readouterr()
312
+ assert "testa.fits" in out
313
+ assert "testb.fits" in out
testbed/astropy__astropy/astropy/io/fits/tests/test_fitsheader.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ import pytest
4
+
5
+ from . import FitsTestCase
6
+ from astropy.io.fits.scripts import fitsheader
7
+
8
+
9
+ class TestFITSheader_script(FitsTestCase):
10
+
11
+ def test_noargs(self):
12
+ with pytest.raises(SystemExit) as e:
13
+ fitsheader.main(['-h'])
14
+ assert e.value.code == 0
15
+
16
+ def test_file_exists(self, capsys):
17
+ fitsheader.main([self.data('arange.fits')])
18
+ out, err = capsys.readouterr()
19
+ assert out.splitlines()[1].startswith(
20
+ 'SIMPLE = T / conforms to FITS standard')
21
+ assert err == ''
22
+
23
+ def test_by_keyword(self, capsys):
24
+ fitsheader.main(['-k', 'NAXIS', self.data('arange.fits')])
25
+ out, err = capsys.readouterr()
26
+ assert out.splitlines()[1].startswith(
27
+ 'NAXIS = 3 / number of array dimensions')
28
+
29
+ fitsheader.main(['-k', 'NAXIS*', self.data('arange.fits')])
30
+ out, err = capsys.readouterr()
31
+ out = out.splitlines()
32
+ assert len(out) == 5
33
+ assert out[1].startswith('NAXIS')
34
+ assert out[2].startswith('NAXIS1')
35
+ assert out[3].startswith('NAXIS2')
36
+ assert out[4].startswith('NAXIS3')
37
+
38
+ fitsheader.main(['-k', 'RANDOMKEY', self.data('arange.fits')])
39
+ out, err = capsys.readouterr()
40
+ assert err.startswith('WARNING') and 'RANDOMKEY' in err
41
+ assert not err.startswith('ERROR')
42
+
43
+ def test_by_extension(self, capsys):
44
+ fitsheader.main(['-e', '1', self.data('test0.fits')])
45
+ out, err = capsys.readouterr()
46
+ assert len(out.splitlines()) == 62
47
+
48
+ fitsheader.main(['-e', '3', '-k', 'BACKGRND', self.data('test0.fits')])
49
+ out, err = capsys.readouterr()
50
+ assert out.splitlines()[1].startswith('BACKGRND= 312.')
51
+
52
+ fitsheader.main(['-e', '0', '-k', 'BACKGRND', self.data('test0.fits')])
53
+ out, err = capsys.readouterr()
54
+ assert err.startswith('WARNING')
55
+
56
+ fitsheader.main(['-e', '3', '-k', 'FOO', self.data('test0.fits')])
57
+ out, err = capsys.readouterr()
58
+ assert err.startswith('WARNING')
59
+
60
+ def test_table(self, capsys):
61
+ fitsheader.main(['-t', '-k', 'BACKGRND', self.data('test0.fits')])
62
+ out, err = capsys.readouterr()
63
+ out = out.splitlines()
64
+ assert len(out) == 5
65
+ assert out[1].endswith('| 1 | BACKGRND | 316.0 |')
66
+ assert out[2].endswith('| 2 | BACKGRND | 351.0 |')
67
+ assert out[3].endswith('| 3 | BACKGRND | 312.0 |')
68
+ assert out[4].endswith('| 4 | BACKGRND | 323.0 |')
69
+
70
+ fitsheader.main(['-t', '-e', '0', '-k', 'NAXIS',
71
+ self.data('arange.fits'),
72
+ self.data('ascii.fits'),
73
+ self.data('blank.fits')])
74
+ out, err = capsys.readouterr()
75
+ out = out.splitlines()
76
+ assert len(out) == 4
77
+ assert out[1].endswith('| 0 | NAXIS | 3 |')
78
+ assert out[2].endswith('| 0 | NAXIS | 0 |')
79
+ assert out[3].endswith('| 0 | NAXIS | 2 |')
80
+
81
+ def test_fitsort(self, capsys):
82
+ fitsheader.main(['-e', '0', '-f', '-k', 'EXPSTART', '-k', 'EXPTIME',
83
+ self.data('test0.fits'), self.data('test1.fits')])
84
+ out, err = capsys.readouterr()
85
+ out = out.splitlines()
86
+ assert len(out) == 4
87
+ assert out[2].endswith('test0.fits 49491.65366175 0.23')
88
+ assert out[3].endswith('test1.fits 49492.65366175 0.22')
89
+
90
+ fitsheader.main(['-e', '0', '-f', '-k', 'EXPSTART', '-k', 'EXPTIME',
91
+ self.data('test0.fits')])
92
+ out, err = capsys.readouterr()
93
+ out = out.splitlines()
94
+ assert len(out) == 3
95
+ assert out[2].endswith('test0.fits 49491.65366175 0.23')
96
+
97
+ fitsheader.main(['-f', '-k', 'NAXIS',
98
+ self.data('tdim.fits'), self.data('test1.fits')])
99
+ out, err = capsys.readouterr()
100
+ out = out.splitlines()
101
+ assert len(out) == 4
102
+ assert out[0].endswith('0:NAXIS 1:NAXIS 2:NAXIS 3:NAXIS 4:NAXIS')
103
+ assert out[2].endswith('tdim.fits 0 2 -- -- --')
104
+ assert out[3].endswith('test1.fits 0 2 2 2 2')
105
+
106
+ # check that files without required keyword are present
107
+ fitsheader.main(['-f', '-k', 'DATE-OBS',
108
+ self.data('table.fits'), self.data('test0.fits')])
109
+ out, err = capsys.readouterr()
110
+ out = out.splitlines()
111
+ assert len(out) == 4
112
+ assert out[2].endswith('table.fits --')
113
+ assert out[3].endswith('test0.fits 19/05/94')
114
+
115
+ # check that COMMENT and HISTORY are excluded
116
+ fitsheader.main(['-e', '0', '-f', self.data('tb.fits')])
117
+ out, err = capsys.readouterr()
118
+ out = out.splitlines()
119
+ assert len(out) == 3
120
+ assert out[2].endswith('tb.fits True 16 0 True '
121
+ 'STScI-STSDAS/TABLES tb.fits 1')
122
+
123
+ def test_dotkeyword(self, capsys):
124
+ fitsheader.main(['-e', '0', '-k', 'ESO DET ID',
125
+ self.data('fixed-1890.fits')])
126
+ out, err = capsys.readouterr()
127
+ out = out.splitlines()
128
+ assert len(out) == 2
129
+ assert out[1].strip().endswith("HIERARCH ESO DET ID = 'DV13' / Detector system Id")
130
+
131
+ fitsheader.main(['-e', '0', '-k', 'ESO.DET.ID',
132
+ self.data('fixed-1890.fits')])
133
+ out, err = capsys.readouterr()
134
+ out = out.splitlines()
135
+ assert len(out) == 2
136
+ assert out[1].strip().endswith("HIERARCH ESO DET ID = 'DV13' / Detector system Id")
testbed/astropy__astropy/astropy/io/fits/tests/test_fitsinfo.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ from . import FitsTestCase
4
+ from astropy.io.fits.scripts import fitsinfo
5
+
6
+
7
+ class TestFitsinfo(FitsTestCase):
8
+
9
+ def test_onefile(self, capsys):
10
+ fitsinfo.main([self.data('arange.fits')])
11
+ out, err = capsys.readouterr()
12
+ out = out.splitlines()
13
+ assert len(out) == 3
14
+ assert out[1].startswith(
15
+ 'No. Name Ver Type Cards Dimensions Format')
16
+ assert out[2].startswith(
17
+ ' 0 PRIMARY 1 PrimaryHDU 7 (11, 10, 7) int32')
18
+
19
+ def test_multiplefiles(self, capsys):
20
+ fitsinfo.main([self.data('arange.fits'),
21
+ self.data('ascii.fits')])
22
+ out, err = capsys.readouterr()
23
+ out = out.splitlines()
24
+ assert len(out) == 8
25
+ assert out[1].startswith(
26
+ 'No. Name Ver Type Cards Dimensions Format')
27
+ assert out[2].startswith(
28
+ ' 0 PRIMARY 1 PrimaryHDU 7 (11, 10, 7) int32')
29
+ assert out[3] == ''
30
+ assert out[7].startswith(
31
+ ' 1 1 TableHDU 20 5R x 2C [E10.4, I5]')
testbed/astropy__astropy/astropy/io/fits/tests/test_fitstime.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ import pytest
4
+ import numpy as np
5
+
6
+ from . import FitsTestCase
7
+
8
+ from astropy.io.fits.fitstime import GLOBAL_TIME_INFO, time_to_fits, is_time_column_keyword
9
+ from astropy.coordinates import EarthLocation
10
+ from astropy.io import fits
11
+ from astropy.table import Table, QTable
12
+ from astropy.time import Time, TimeDelta
13
+ from astropy.time.core import BARYCENTRIC_SCALES
14
+ from astropy.time.formats import FITS_DEPRECATED_SCALES
15
+ from astropy.tests.helper import catch_warnings
16
+ from astropy.utils.exceptions import AstropyUserWarning, AstropyDeprecationWarning
17
+
18
+
19
+ class TestFitsTime(FitsTestCase):
20
+
21
+ def setup_class(self):
22
+ self.time = np.array(['1999-01-01T00:00:00.123456789', '2010-01-01T00:00:00'])
23
+ self.time_3d = np.array([[[1, 2], [1, 3], [3, 4]]])
24
+
25
+ def test_is_time_column_keyword(self):
26
+ # Time column keyword without column number
27
+ assert is_time_column_keyword('TRPOS') is False
28
+
29
+ # Global time column keyword
30
+ assert is_time_column_keyword('TIMESYS') is False
31
+
32
+ # Valid time column keyword
33
+ assert is_time_column_keyword('TRPOS12') is True
34
+
35
+ @pytest.mark.parametrize('table_types', (Table, QTable))
36
+ def test_time_to_fits_loc(self, table_types):
37
+ """
38
+ Test all the unusual conditions for locations of ``Time``
39
+ columns in a ``Table``.
40
+ """
41
+ t = table_types()
42
+ t['a'] = Time(self.time, format='isot', scale='utc')
43
+ t['b'] = Time(self.time, format='isot', scale='tt')
44
+
45
+ # Check that vectorized location is stored using Green Bank convention
46
+ t['a'].location = EarthLocation([1., 2.], [2., 3.], [3., 4.],
47
+ unit='Mm')
48
+
49
+ with pytest.warns(AstropyUserWarning, match='Time Column "b" has no '
50
+ 'specified location, but global Time Position is present'):
51
+ table, hdr = time_to_fits(t)
52
+ assert (table['OBSGEO-X'] == t['a'].location.x.to_value(unit='m')).all()
53
+ assert (table['OBSGEO-Y'] == t['a'].location.y.to_value(unit='m')).all()
54
+ assert (table['OBSGEO-Z'] == t['a'].location.z.to_value(unit='m')).all()
55
+
56
+ with pytest.warns(AstropyUserWarning, match='Time Column "b" has no '
57
+ 'specified location, but global Time Position is present'):
58
+ t.write(self.temp('time.fits'), format='fits', overwrite=True)
59
+
60
+ with pytest.warns(fits.verify.VerifyWarning,
61
+ match='Invalid keyword for column 2'):
62
+ tm = table_types.read(self.temp('time.fits'), format='fits',
63
+ astropy_native=True)
64
+
65
+ assert (tm['a'].location == t['a'].location).all()
66
+ assert tm['b'].location == t['b'].location
67
+
68
+ # Check that multiple Time columns with different locations raise an exception
69
+ t['a'].location = EarthLocation(1, 2, 3)
70
+ t['b'].location = EarthLocation(2, 3, 4)
71
+
72
+ with pytest.raises(ValueError) as err:
73
+ table, hdr = time_to_fits(t)
74
+ assert 'Multiple Time Columns with different geocentric' in str(err.value)
75
+
76
+ # Check that Time column with no location specified will assume global location
77
+ t['b'].location = None
78
+
79
+ with catch_warnings() as w:
80
+ table, hdr = time_to_fits(t)
81
+ assert len(w) == 1
82
+ assert str(w[0].message).startswith('Time Column "b" has no specified '
83
+ 'location, but global Time Position '
84
+ 'is present')
85
+
86
+ # Check that multiple Time columns with same location can be written
87
+ t['b'].location = EarthLocation(1, 2, 3)
88
+
89
+ with catch_warnings() as w:
90
+ table, hdr = time_to_fits(t)
91
+ assert len(w) == 0
92
+
93
+ # Check compatibility of Time Scales and Reference Positions
94
+
95
+ for scale in BARYCENTRIC_SCALES:
96
+ t.replace_column('a', getattr(t['a'], scale))
97
+ with catch_warnings() as w:
98
+ table, hdr = time_to_fits(t)
99
+ assert len(w) == 1
100
+ assert str(w[0].message).startswith('Earth Location "TOPOCENTER" '
101
+ 'for Time Column')
102
+
103
+ # Check that multidimensional vectorized location (ndim=3) is stored
104
+ # using Green Bank convention.
105
+ t = table_types()
106
+ location = EarthLocation([[[1., 2.], [1., 3.], [3., 4.]]],
107
+ [[[1., 2.], [1., 3.], [3., 4.]]],
108
+ [[[1., 2.], [1., 3.], [3., 4.]]], unit='Mm')
109
+ t['a'] = Time(self.time_3d, format='jd', location=location)
110
+
111
+ table, hdr = time_to_fits(t)
112
+ assert (table['OBSGEO-X'] == t['a'].location.x.to_value(unit='m')).all()
113
+ assert (table['OBSGEO-Y'] == t['a'].location.y.to_value(unit='m')).all()
114
+ assert (table['OBSGEO-Z'] == t['a'].location.z.to_value(unit='m')).all()
115
+
116
+ t.write(self.temp('time.fits'), format='fits', overwrite=True)
117
+ tm = table_types.read(self.temp('time.fits'), format='fits',
118
+ astropy_native=True)
119
+
120
+ assert (tm['a'].location == t['a'].location).all()
121
+
122
+ # Check that singular location with ndim>1 can be written
123
+ t['a'] = Time(self.time, location=EarthLocation([[[1.]]], [[[2.]]],
124
+ [[[3.]]], unit='Mm'))
125
+
126
+ table, hdr = time_to_fits(t)
127
+ assert hdr['OBSGEO-X'] == t['a'].location.x.to_value(unit='m')
128
+ assert hdr['OBSGEO-Y'] == t['a'].location.y.to_value(unit='m')
129
+ assert hdr['OBSGEO-Z'] == t['a'].location.z.to_value(unit='m')
130
+
131
+ t.write(self.temp('time.fits'), format='fits', overwrite=True)
132
+ tm = table_types.read(self.temp('time.fits'), format='fits',
133
+ astropy_native=True)
134
+
135
+ assert tm['a'].location == t['a'].location
136
+
137
+ @pytest.mark.parametrize('table_types', (Table, QTable))
138
+ def test_time_to_fits_header(self, table_types):
139
+ """
140
+ Test the header and metadata returned by ``time_to_fits``.
141
+ """
142
+ t = table_types()
143
+ t['a'] = Time(self.time, format='isot', scale='utc',
144
+ location=EarthLocation(-2446354,
145
+ 4237210, 4077985, unit='m'))
146
+ t['b'] = Time([1,2], format='cxcsec', scale='tt')
147
+
148
+ ideal_col_hdr = {'OBSGEO-X' : t['a'].location.x.value,
149
+ 'OBSGEO-Y' : t['a'].location.y.value,
150
+ 'OBSGEO-Z' : t['a'].location.z.value}
151
+
152
+ with pytest.warns(AstropyUserWarning, match='Time Column "b" has no '
153
+ 'specified location, but global Time Position is present'):
154
+ table, hdr = time_to_fits(t)
155
+
156
+ # Check the global time keywords in hdr
157
+ for key, value in GLOBAL_TIME_INFO.items():
158
+ assert hdr[key] == value[0]
159
+ assert hdr.comments[key] == value[1]
160
+ hdr.remove(key)
161
+
162
+ for key, value in ideal_col_hdr.items():
163
+ assert hdr[key] == value
164
+ hdr.remove(key)
165
+
166
+ # Check the column-specific time metadata
167
+ coord_info = table.meta['__coordinate_columns__']
168
+ for colname in coord_info:
169
+ assert coord_info[colname]['coord_type'] == t[colname].scale.upper()
170
+ assert coord_info[colname]['coord_unit'] == 'd'
171
+
172
+ assert coord_info['a']['time_ref_pos'] == 'TOPOCENTER'
173
+
174
+ assert len(hdr) == 0
175
+
176
+ @pytest.mark.parametrize('table_types', (Table, QTable))
177
+ def test_fits_to_time_meta(self, table_types):
178
+ """
179
+ Test that the relevant global time metadata is read into
180
+ ``Table.meta`` as ``Time``.
181
+ """
182
+ t = table_types()
183
+ t['a'] = Time(self.time, format='isot', scale='utc')
184
+ t.meta['DATE'] = '1999-01-01T00:00:00'
185
+ t.meta['MJD-OBS'] = 56670
186
+
187
+ # Test for default write behavior (full precision) and read it
188
+ # back using native astropy objects; thus, ensure its round-trip
189
+ t.write(self.temp('time.fits'), format='fits', overwrite=True)
190
+
191
+ with pytest.warns(fits.verify.VerifyWarning,
192
+ match='Invalid keyword for column 1'):
193
+ tm = table_types.read(self.temp('time.fits'), format='fits',
194
+ astropy_native=True)
195
+
196
+ # Test DATE
197
+ assert isinstance(tm.meta['DATE'], Time)
198
+ assert tm.meta['DATE'].value == t.meta['DATE']
199
+ assert tm.meta['DATE'].format == 'fits'
200
+ # Default time scale according to the FITS standard is UTC
201
+ assert tm.meta['DATE'].scale == 'utc'
202
+
203
+ # Test MJD-xxx
204
+ assert isinstance(tm.meta['MJD-OBS'], Time)
205
+ assert tm.meta['MJD-OBS'].value == t.meta['MJD-OBS']
206
+ assert tm.meta['MJD-OBS'].format == 'mjd'
207
+ assert tm.meta['MJD-OBS'].scale == 'utc'
208
+
209
+ # Explicitly specified Time Scale
210
+ t.meta['TIMESYS'] = 'ET'
211
+
212
+ t.write(self.temp('time.fits'), format='fits', overwrite=True)
213
+
214
+ with pytest.warns(fits.verify.VerifyWarning,
215
+ match='Invalid keyword for column 1'):
216
+ tm = table_types.read(self.temp('time.fits'), format='fits',
217
+ astropy_native=True)
218
+
219
+ # Test DATE
220
+ assert isinstance(tm.meta['DATE'], Time)
221
+ assert tm.meta['DATE'].value == t.meta['DATE']
222
+ assert tm.meta['DATE'].scale == 'utc'
223
+
224
+ # Test MJD-xxx
225
+ assert isinstance(tm.meta['MJD-OBS'], Time)
226
+ assert tm.meta['MJD-OBS'].value == t.meta['MJD-OBS']
227
+ assert tm.meta['MJD-OBS'].scale == FITS_DEPRECATED_SCALES[t.meta['TIMESYS']]
228
+
229
+ # Test for conversion of time data to its value, as defined by its format
230
+ t['a'].info.serialize_method['fits'] = 'formatted_value'
231
+ t.write(self.temp('time.fits'), format='fits', overwrite=True)
232
+ tm = table_types.read(self.temp('time.fits'), format='fits')
233
+
234
+ # Test DATE
235
+ assert not isinstance(tm.meta['DATE'], Time)
236
+ assert tm.meta['DATE'] == t.meta['DATE']
237
+
238
+ # Test MJD-xxx
239
+ assert not isinstance(tm.meta['MJD-OBS'], Time)
240
+ assert tm.meta['MJD-OBS'] == t.meta['MJD-OBS']
241
+
242
+ assert (tm['a'] == t['a'].value).all()
243
+
244
+ @pytest.mark.parametrize('table_types', (Table, QTable))
245
+ def test_time_loc_unit(self, table_types):
246
+ """
247
+ Test that ``location`` specified by using any valid unit
248
+ (length/angle) in ``Time`` columns gets stored in FITS
249
+ as ITRS Cartesian coordinates (X, Y, Z), each in m.
250
+ Test that it round-trips through FITS.
251
+ """
252
+ t = table_types()
253
+ t['a'] = Time(self.time, format='isot', scale='utc',
254
+ location=EarthLocation(1,2,3, unit='km'))
255
+
256
+ table, hdr = time_to_fits(t)
257
+
258
+ # Check the header
259
+ assert hdr['OBSGEO-X'] == t['a'].location.x.to_value(unit='m')
260
+ assert hdr['OBSGEO-Y'] == t['a'].location.y.to_value(unit='m')
261
+ assert hdr['OBSGEO-Z'] == t['a'].location.z.to_value(unit='m')
262
+
263
+ t.write(self.temp('time.fits'), format='fits', overwrite=True)
264
+ tm = table_types.read(self.temp('time.fits'), format='fits',
265
+ astropy_native=True)
266
+
267
+ # Check the round-trip of location
268
+ assert (tm['a'].location == t['a'].location).all()
269
+ assert tm['a'].location.x.value == t['a'].location.x.to_value(unit='m')
270
+ assert tm['a'].location.y.value == t['a'].location.y.to_value(unit='m')
271
+ assert tm['a'].location.z.value == t['a'].location.z.to_value(unit='m')
272
+
273
+ @pytest.mark.parametrize('table_types', (Table, QTable))
274
+ def test_io_time_read_fits(self, table_types):
275
+ """
276
+ Test that FITS table with time columns (standard compliant)
277
+ can be read by io.fits as a table with Time columns.
278
+ This tests the following:
279
+ 1. The special-case where a column has the name 'TIME' and a
280
+ time unit
281
+ 2. Time from Epoch (Reference time) is appropriately converted.
282
+ 3. Coordinate columns (corresponding to coordinate keywords in the header)
283
+ other than time, that is, spatial coordinates, are not mistaken
284
+ to be time.
285
+ """
286
+ filename = self.data('chandra_time.fits')
287
+ with pytest.warns(AstropyUserWarning, match='Time column "time" reference '
288
+ 'position will be ignored'):
289
+ tm = table_types.read(filename, astropy_native=True)
290
+
291
+ # Test case 1
292
+ assert isinstance(tm['time'], Time)
293
+ assert tm['time'].scale == 'tt'
294
+ assert tm['time'].format == 'mjd'
295
+
296
+ non_native = table_types.read(filename)
297
+
298
+ # Test case 2
299
+ ref_time = Time(non_native.meta['MJDREF'], format='mjd',
300
+ scale=non_native.meta['TIMESYS'].lower())
301
+ delta_time = TimeDelta(non_native['time'])
302
+ assert (ref_time + delta_time == tm['time']).all()
303
+
304
+ # Test case 3
305
+ for colname in ['chipx', 'chipy', 'detx', 'dety', 'x', 'y']:
306
+ assert not isinstance(tm[colname], Time)
307
+
308
+ @pytest.mark.parametrize('table_types', (Table, QTable))
309
+ def test_io_time_read_fits_datetime(self, table_types):
310
+ """
311
+ Test that ISO-8601 Datetime String Columns are read correctly.
312
+ """
313
+ # Datetime column
314
+ c = fits.Column(name='datetime', format='A29', coord_type='TCG',
315
+ time_ref_pos='GEOCENTER', array=self.time)
316
+
317
+ # Explicitly create a FITS Binary Table
318
+ bhdu = fits.BinTableHDU.from_columns([c])
319
+ bhdu.writeto(self.temp('time.fits'), overwrite=True)
320
+
321
+ tm = table_types.read(self.temp('time.fits'), astropy_native=True)
322
+
323
+ assert isinstance(tm['datetime'], Time)
324
+ assert tm['datetime'].scale == 'tcg'
325
+ assert tm['datetime'].format == 'fits'
326
+ assert (tm['datetime'] == self.time).all()
327
+
328
+ @pytest.mark.parametrize('table_types', (Table, QTable))
329
+ def test_io_time_read_fits_location(self, table_types):
330
+ """
331
+ Test that geocentric/geodetic observatory position is read
332
+ properly, as and when it is specified.
333
+ """
334
+ # Datetime column
335
+ c = fits.Column(name='datetime', format='A29', coord_type='TT',
336
+ time_ref_pos='TOPOCENTER', array=self.time)
337
+
338
+ # Observatory position in ITRS Cartesian coordinates (geocentric)
339
+ cards = [('OBSGEO-X', -2446354), ('OBSGEO-Y', 4237210),
340
+ ('OBSGEO-Z', 4077985)]
341
+
342
+ # Explicitly create a FITS Binary Table
343
+ bhdu = fits.BinTableHDU.from_columns([c], header=fits.Header(cards))
344
+ bhdu.writeto(self.temp('time.fits'), overwrite=True)
345
+
346
+ tm = table_types.read(self.temp('time.fits'), astropy_native=True)
347
+
348
+ assert isinstance(tm['datetime'], Time)
349
+ assert tm['datetime'].location.x.value == -2446354
350
+ assert tm['datetime'].location.y.value == 4237210
351
+ assert tm['datetime'].location.z.value == 4077985
352
+
353
+ # Observatory position in geodetic coordinates
354
+ cards = [('OBSGEO-L', 0), ('OBSGEO-B', 0), ('OBSGEO-H', 0)]
355
+
356
+ # Explicitly create a FITS Binary Table
357
+ bhdu = fits.BinTableHDU.from_columns([c], header=fits.Header(cards))
358
+ bhdu.writeto(self.temp('time.fits'), overwrite=True)
359
+
360
+ tm = table_types.read(self.temp('time.fits'), astropy_native=True)
361
+
362
+ assert isinstance(tm['datetime'], Time)
363
+ assert tm['datetime'].location.lon.value == 0
364
+ assert tm['datetime'].location.lat.value == 0
365
+ assert np.isclose(tm['datetime'].location.height.value, 0,
366
+ rtol=0, atol=1e-9)
367
+
368
+ @pytest.mark.parametrize('table_types', (Table, QTable))
369
+ def test_io_time_read_fits_scale(self, table_types):
370
+ """
371
+ Test handling of 'GPS' and 'LOCAL' time scales which are
372
+ recognized by the FITS standard but are not native to astropy.
373
+ """
374
+ # GPS scale column
375
+ gps_time = np.array([630720013, 630720014])
376
+ c = fits.Column(name='gps_time', format='D', unit='s', coord_type='GPS',
377
+ coord_unit='s', time_ref_pos='TOPOCENTER', array=gps_time)
378
+
379
+ cards = [('OBSGEO-L', 0), ('OBSGEO-B', 0), ('OBSGEO-H', 0)]
380
+
381
+ bhdu = fits.BinTableHDU.from_columns([c], header=fits.Header(cards))
382
+ bhdu.writeto(self.temp('time.fits'), overwrite=True)
383
+
384
+ with catch_warnings() as w:
385
+ tm = table_types.read(self.temp('time.fits'), astropy_native=True)
386
+ assert len(w) == 1
387
+ assert 'FITS recognized time scale value "GPS"' in str(w[0].message)
388
+
389
+ assert isinstance(tm['gps_time'], Time)
390
+ assert tm['gps_time'].format == 'gps'
391
+ assert tm['gps_time'].scale == 'tai'
392
+ assert (tm['gps_time'].value == gps_time).all()
393
+
394
+ # LOCAL scale column
395
+ local_time = np.array([1, 2])
396
+ c = fits.Column(name='local_time', format='D', unit='d',
397
+ coord_type='LOCAL', coord_unit='d',
398
+ time_ref_pos='RELOCATABLE', array=local_time)
399
+
400
+ bhdu = fits.BinTableHDU.from_columns([c])
401
+ bhdu.writeto(self.temp('time.fits'), overwrite=True)
402
+
403
+ tm = table_types.read(self.temp('time.fits'), astropy_native=True)
404
+
405
+ assert isinstance(tm['local_time'], Time)
406
+ assert tm['local_time'].format == 'mjd'
407
+
408
+ assert tm['local_time'].scale == 'local'
409
+ assert (tm['local_time'].value == local_time).all()
410
+
411
+ @pytest.mark.parametrize('table_types', (Table, QTable))
412
+ def test_io_time_read_fits_location_warnings(self, table_types):
413
+ """
414
+ Test warnings for time column reference position.
415
+ """
416
+ # Time reference position "TOPOCENTER" without corresponding
417
+ # observatory position.
418
+ c = fits.Column(name='datetime', format='A29', coord_type='TT',
419
+ time_ref_pos='TOPOCENTER', array=self.time)
420
+
421
+ bhdu = fits.BinTableHDU.from_columns([c])
422
+ bhdu.writeto(self.temp('time.fits'), overwrite=True)
423
+
424
+ with catch_warnings() as w:
425
+ tm = table_types.read(self.temp('time.fits'), astropy_native=True)
426
+ assert len(w) == 1
427
+ assert ('observatory position is not properly specified' in
428
+ str(w[0].message))
429
+
430
+ # Default value for time reference position is "TOPOCENTER"
431
+ c = fits.Column(name='datetime', format='A29', coord_type='TT',
432
+ array=self.time)
433
+
434
+ bhdu = fits.BinTableHDU.from_columns([c])
435
+ bhdu.writeto(self.temp('time.fits'), overwrite=True)
436
+ with catch_warnings() as w:
437
+ tm = table_types.read(self.temp('time.fits'), astropy_native=True)
438
+ assert len(w) == 1
439
+ assert ('"TRPOSn" is not specified. The default value for '
440
+ 'it is "TOPOCENTER"' in str(w[0].message))
testbed/astropy__astropy/astropy/io/fits/tests/test_groups.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ import os
4
+ import time
5
+
6
+ import pytest
7
+ import numpy as np
8
+
9
+ from . import FitsTestCase
10
+ from .test_table import comparerecords
11
+ from astropy.io import fits
12
+
13
+
14
+ class TestGroupsFunctions(FitsTestCase):
15
+ def test_open(self):
16
+ with fits.open(self.data('random_groups.fits')) as hdul:
17
+ assert isinstance(hdul[0], fits.GroupsHDU)
18
+ naxes = (3, 1, 128, 1, 1)
19
+ parameters = ['UU', 'VV', 'WW', 'BASELINE', 'DATE']
20
+ info = [(0, 'PRIMARY', 1, 'GroupsHDU', 147, naxes, 'float32',
21
+ '3 Groups 5 Parameters')]
22
+ assert hdul.info(output=False) == info
23
+
24
+ ghdu = hdul[0]
25
+ assert ghdu.parnames == parameters
26
+ assert list(ghdu.data.dtype.names) == parameters + ['DATA']
27
+
28
+ assert isinstance(ghdu.data, fits.GroupData)
29
+ # The data should be equal to the number of groups
30
+ assert ghdu.header['GCOUNT'] == len(ghdu.data)
31
+ assert ghdu.data.data.shape == (len(ghdu.data),) + naxes[::-1]
32
+ assert ghdu.data.parnames == parameters
33
+
34
+ assert isinstance(ghdu.data[0], fits.Group)
35
+ assert len(ghdu.data[0]) == len(parameters) + 1
36
+ assert ghdu.data[0].data.shape == naxes[::-1]
37
+ assert ghdu.data[0].parnames == parameters
38
+
39
+ def test_open_groups_in_update_mode(self):
40
+ """
41
+ Test that opening a file containing a groups HDU in update mode and
42
+ then immediately closing it does not result in any unnecessary file
43
+ modifications.
44
+
45
+ Similar to
46
+ test_image.TestImageFunctions.test_open_scaled_in_update_mode().
47
+ """
48
+
49
+ # Copy the original file before making any possible changes to it
50
+ self.copy_file('random_groups.fits')
51
+ mtime = os.stat(self.temp('random_groups.fits')).st_mtime
52
+
53
+ time.sleep(1)
54
+
55
+ fits.open(self.temp('random_groups.fits'), mode='update',
56
+ memmap=False).close()
57
+
58
+ # Ensure that no changes were made to the file merely by immediately
59
+ # opening and closing it.
60
+ assert mtime == os.stat(self.temp('random_groups.fits')).st_mtime
61
+
62
+ def test_random_groups_data_update(self):
63
+ """
64
+ Regression test for https://github.com/astropy/astropy/issues/3730 and
65
+ for https://github.com/spacetelescope/PyFITS/issues/102
66
+ """
67
+
68
+ self.copy_file('random_groups.fits')
69
+ with fits.open(self.temp('random_groups.fits'), mode='update') as h:
70
+ h[0].data['UU'] = 0.42
71
+
72
+ with fits.open(self.temp('random_groups.fits'), mode='update') as h:
73
+ assert np.all(h[0].data['UU'] == 0.42)
74
+
75
+ def test_parnames_round_trip(self):
76
+ """
77
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/130
78
+
79
+ Ensures that opening a random groups file in update mode or writing it
80
+ to a new file does not cause any change to the parameter names.
81
+ """
82
+
83
+ # Because this test tries to update the random_groups.fits file, let's
84
+ # make a copy of it first (so that the file doesn't actually get
85
+ # modified in the off chance that the test fails
86
+ self.copy_file('random_groups.fits')
87
+
88
+ parameters = ['UU', 'VV', 'WW', 'BASELINE', 'DATE']
89
+ with fits.open(self.temp('random_groups.fits'), mode='update') as h:
90
+ assert h[0].parnames == parameters
91
+ h.flush()
92
+ # Open again just in read-only mode to ensure the parnames didn't
93
+ # change
94
+ with fits.open(self.temp('random_groups.fits')) as h:
95
+ assert h[0].parnames == parameters
96
+ h.writeto(self.temp('test.fits'))
97
+
98
+ with fits.open(self.temp('test.fits')) as h:
99
+ assert h[0].parnames == parameters
100
+
101
+ def test_groupdata_slice(self):
102
+ """
103
+ A simple test to ensure that slicing GroupData returns a new, smaller
104
+ GroupData object, as is the case with a normal FITS_rec. This is a
105
+ regression test for an as-of-yet unreported issue where slicing
106
+ GroupData returned a single Group record.
107
+ """
108
+
109
+ with fits.open(self.data('random_groups.fits')) as hdul:
110
+ s = hdul[0].data[1:]
111
+ assert isinstance(s, fits.GroupData)
112
+ assert len(s) == 2
113
+ assert hdul[0].data.parnames == s.parnames
114
+
115
+ def test_group_slice(self):
116
+ """
117
+ Tests basic slicing a single group record.
118
+ """
119
+
120
+ # A very basic slice test
121
+ with fits.open(self.data('random_groups.fits')) as hdul:
122
+ g = hdul[0].data[0]
123
+ s = g[2:4]
124
+ assert len(s) == 2
125
+ assert s[0] == g[2]
126
+ assert s[-1] == g[-3]
127
+ s = g[::-1]
128
+ assert len(s) == 6
129
+ assert (s[0] == g[-1]).all()
130
+ assert s[-1] == g[0]
131
+ s = g[::2]
132
+ assert len(s) == 3
133
+ assert s[0] == g[0]
134
+ assert s[1] == g[2]
135
+ assert s[2] == g[4]
136
+
137
+ def test_create_groupdata(self):
138
+ """
139
+ Basic test for creating GroupData from scratch.
140
+ """
141
+
142
+ imdata = np.arange(100.0)
143
+ imdata.shape = (10, 1, 1, 2, 5)
144
+ pdata1 = np.arange(10, dtype=np.float32) + 0.1
145
+ pdata2 = 42.0
146
+ x = fits.hdu.groups.GroupData(imdata, parnames=['abc', 'xyz'],
147
+ pardata=[pdata1, pdata2], bitpix=-32)
148
+ assert x.parnames == ['abc', 'xyz']
149
+ assert (x.par('abc') == pdata1).all()
150
+ assert (x.par('xyz') == ([pdata2] * len(x))).all()
151
+ assert (x.data == imdata).all()
152
+
153
+ # Test putting the data into a GroupsHDU and round-tripping it
154
+ ghdu = fits.GroupsHDU(data=x)
155
+ ghdu.writeto(self.temp('test.fits'))
156
+
157
+ with fits.open(self.temp('test.fits')) as h:
158
+ hdr = h[0].header
159
+ assert hdr['GCOUNT'] == 10
160
+ assert hdr['PCOUNT'] == 2
161
+ assert hdr['NAXIS'] == 5
162
+ assert hdr['NAXIS1'] == 0
163
+ assert hdr['NAXIS2'] == 5
164
+ assert hdr['NAXIS3'] == 2
165
+ assert hdr['NAXIS4'] == 1
166
+ assert hdr['NAXIS5'] == 1
167
+ assert h[0].data.parnames == ['abc', 'xyz']
168
+ assert comparerecords(h[0].data, x)
169
+
170
+ def test_duplicate_parameter(self):
171
+ """
172
+ Tests support for multiple parameters of the same name, and ensures
173
+ that the data in duplicate parameters are returned as a single summed
174
+ value.
175
+ """
176
+
177
+ imdata = np.arange(100.0)
178
+ imdata.shape = (10, 1, 1, 2, 5)
179
+ pdata1 = np.arange(10, dtype=np.float32) + 1
180
+ pdata2 = 42.0
181
+ x = fits.hdu.groups.GroupData(imdata, parnames=['abc', 'xyz', 'abc'],
182
+ pardata=[pdata1, pdata2, pdata1],
183
+ bitpix=-32)
184
+
185
+ assert x.parnames == ['abc', 'xyz', 'abc']
186
+ assert (x.par('abc') == pdata1 * 2).all()
187
+ assert x[0].par('abc') == 2
188
+
189
+ # Test setting a parameter
190
+ x[0].setpar(0, 2)
191
+ assert x[0].par('abc') == 3
192
+ pytest.raises(ValueError, x[0].setpar, 'abc', 2)
193
+ x[0].setpar('abc', (2, 3))
194
+ assert x[0].par('abc') == 5
195
+ assert x.par('abc')[0] == 5
196
+ assert (x.par('abc')[1:] == pdata1[1:] * 2).all()
197
+
198
+ # Test round-trip
199
+ ghdu = fits.GroupsHDU(data=x)
200
+ ghdu.writeto(self.temp('test.fits'))
201
+
202
+ with fits.open(self.temp('test.fits')) as h:
203
+ hdr = h[0].header
204
+ assert hdr['PCOUNT'] == 3
205
+ assert hdr['PTYPE1'] == 'abc'
206
+ assert hdr['PTYPE2'] == 'xyz'
207
+ assert hdr['PTYPE3'] == 'abc'
208
+ assert x.parnames == ['abc', 'xyz', 'abc']
209
+ assert x.dtype.names == ('abc', 'xyz', '_abc', 'DATA')
210
+ assert x.par('abc')[0] == 5
211
+ assert (x.par('abc')[1:] == pdata1[1:] * 2).all()
testbed/astropy__astropy/astropy/io/fits/tests/test_hdulist.py ADDED
@@ -0,0 +1,1055 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import glob
4
+ import io
5
+ import os
6
+ import platform
7
+ import sys
8
+ import copy
9
+ import subprocess
10
+
11
+ import pytest
12
+ import numpy as np
13
+
14
+ from astropy.io.fits.verify import VerifyError
15
+ from astropy.io import fits
16
+ from astropy.tests.helper import raises, catch_warnings, ignore_warnings
17
+ from astropy.utils.exceptions import AstropyUserWarning, AstropyDeprecationWarning
18
+
19
+ from . import FitsTestCase
20
+
21
+
22
+ class TestHDUListFunctions(FitsTestCase):
23
+ def test_update_name(self):
24
+ with fits.open(self.data('o4sp040b0_raw.fits')) as hdul:
25
+ hdul[4].name = 'Jim'
26
+ hdul[4].ver = 9
27
+ assert hdul[('JIM', 9)].header['extname'] == 'JIM'
28
+
29
+ def test_hdu_file_bytes(self):
30
+ with fits.open(self.data('checksum.fits')) as hdul:
31
+ res = hdul[0].filebytes()
32
+ assert res == 11520
33
+ res = hdul[1].filebytes()
34
+ assert res == 8640
35
+
36
+ def test_hdulist_file_info(self):
37
+ def test_fileinfo(**kwargs):
38
+ assert res['datSpan'] == kwargs.get('datSpan', 2880)
39
+ assert res['resized'] == kwargs.get('resized', False)
40
+ assert res['filename'] == self.data('checksum.fits')
41
+ assert res['datLoc'] == kwargs.get('datLoc', 8640)
42
+ assert res['hdrLoc'] == kwargs.get('hdrLoc', 0)
43
+ assert res['filemode'] == 'readonly'
44
+
45
+ with fits.open(self.data('checksum.fits')) as hdul:
46
+ res = hdul.fileinfo(0)
47
+
48
+ res = hdul.fileinfo(1)
49
+ test_fileinfo(datLoc=17280, hdrLoc=11520)
50
+
51
+ hdu = fits.ImageHDU(data=hdul[0].data)
52
+ hdul.insert(1, hdu)
53
+
54
+ res = hdul.fileinfo(0)
55
+ test_fileinfo(resized=True)
56
+
57
+ res = hdul.fileinfo(1)
58
+ test_fileinfo(datSpan=None, resized=True, datLoc=None, hdrLoc=None)
59
+
60
+ res = hdul.fileinfo(2)
61
+ test_fileinfo(resized=1, datLoc=17280, hdrLoc=11520)
62
+
63
+ def test_create_from_multiple_primary(self):
64
+ """
65
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/145
66
+
67
+ Ensure that a validation error occurs when saving an HDUList containing
68
+ multiple PrimaryHDUs.
69
+ """
70
+
71
+ hdul = fits.HDUList([fits.PrimaryHDU(), fits.PrimaryHDU()])
72
+ pytest.raises(VerifyError, hdul.writeto, self.temp('temp.fits'),
73
+ output_verify='exception')
74
+
75
+ def test_append_primary_to_empty_list(self):
76
+ # Tests appending a Simple PrimaryHDU to an empty HDUList.
77
+ hdul = fits.HDUList()
78
+ hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32))
79
+ hdul.append(hdu)
80
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 5, (100,), 'int32', '')]
81
+ assert hdul.info(output=False) == info
82
+
83
+ hdul.writeto(self.temp('test-append.fits'))
84
+
85
+ assert fits.info(self.temp('test-append.fits'), output=False) == info
86
+
87
+ def test_append_extension_to_empty_list(self):
88
+ """Tests appending a Simple ImageHDU to an empty HDUList."""
89
+
90
+ hdul = fits.HDUList()
91
+ hdu = fits.ImageHDU(np.arange(100, dtype=np.int32))
92
+ hdul.append(hdu)
93
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 4, (100,), 'int32', '')]
94
+ assert hdul.info(output=False) == info
95
+
96
+ hdul.writeto(self.temp('test-append.fits'))
97
+
98
+ assert fits.info(self.temp('test-append.fits'), output=False) == info
99
+
100
+ def test_append_table_extension_to_empty_list(self):
101
+ """Tests appending a Simple Table ExtensionHDU to a empty HDUList."""
102
+
103
+ hdul = fits.HDUList()
104
+ with fits.open(self.data('tb.fits')) as hdul1:
105
+ hdul.append(hdul1[1])
106
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 4, (), '', ''),
107
+ (1, '', 1, 'BinTableHDU', 24, '2R x 4C', '[1J, 3A, 1E, 1L]', '')]
108
+
109
+ assert hdul.info(output=False) == info
110
+
111
+ hdul.writeto(self.temp('test-append.fits'))
112
+
113
+ assert fits.info(self.temp('test-append.fits'), output=False) == info
114
+
115
+ def test_append_groupshdu_to_empty_list(self):
116
+ """Tests appending a Simple GroupsHDU to an empty HDUList."""
117
+
118
+ hdul = fits.HDUList()
119
+ hdu = fits.GroupsHDU()
120
+ hdul.append(hdu)
121
+
122
+ info = [(0, 'PRIMARY', 1, 'GroupsHDU', 8, (), '',
123
+ '1 Groups 0 Parameters')]
124
+
125
+ assert hdul.info(output=False) == info
126
+
127
+ hdul.writeto(self.temp('test-append.fits'))
128
+
129
+ assert fits.info(self.temp('test-append.fits'), output=False) == info
130
+
131
+ def test_append_primary_to_non_empty_list(self):
132
+ """Tests appending a Simple PrimaryHDU to a non-empty HDUList."""
133
+
134
+ with fits.open(self.data('arange.fits')) as hdul:
135
+ hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32))
136
+ hdul.append(hdu)
137
+
138
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 7, (11, 10, 7), 'int32', ''),
139
+ (1, '', 1, 'ImageHDU', 6, (100,), 'int32', '')]
140
+
141
+ assert hdul.info(output=False) == info
142
+
143
+ hdul.writeto(self.temp('test-append.fits'))
144
+
145
+ assert fits.info(self.temp('test-append.fits'), output=False) == info
146
+
147
+ def test_append_extension_to_non_empty_list(self):
148
+ """Tests appending a Simple ExtensionHDU to a non-empty HDUList."""
149
+
150
+ with fits.open(self.data('tb.fits')) as hdul:
151
+ hdul.append(hdul[1])
152
+
153
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 11, (), '', ''),
154
+ (1, '', 1, 'BinTableHDU', 24, '2R x 4C', '[1J, 3A, 1E, 1L]', ''),
155
+ (2, '', 1, 'BinTableHDU', 24, '2R x 4C', '[1J, 3A, 1E, 1L]', '')]
156
+
157
+ assert hdul.info(output=False) == info
158
+
159
+ hdul.writeto(self.temp('test-append.fits'))
160
+
161
+ assert fits.info(self.temp('test-append.fits'), output=False) == info
162
+
163
+ @raises(ValueError)
164
+ def test_append_groupshdu_to_non_empty_list(self):
165
+ """Tests appending a Simple GroupsHDU to an empty HDUList."""
166
+
167
+ hdul = fits.HDUList()
168
+ hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32))
169
+ hdul.append(hdu)
170
+ hdu = fits.GroupsHDU()
171
+ hdul.append(hdu)
172
+
173
+ def test_insert_primary_to_empty_list(self):
174
+ """Tests inserting a Simple PrimaryHDU to an empty HDUList."""
175
+ hdul = fits.HDUList()
176
+ hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32))
177
+ hdul.insert(0, hdu)
178
+
179
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 5, (100,), 'int32', '')]
180
+
181
+ assert hdul.info(output=False) == info
182
+
183
+ hdul.writeto(self.temp('test-insert.fits'))
184
+
185
+ assert fits.info(self.temp('test-insert.fits'), output=False) == info
186
+
187
+ def test_insert_extension_to_empty_list(self):
188
+ """Tests inserting a Simple ImageHDU to an empty HDUList."""
189
+
190
+ hdul = fits.HDUList()
191
+ hdu = fits.ImageHDU(np.arange(100, dtype=np.int32))
192
+ hdul.insert(0, hdu)
193
+
194
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 4, (100,), 'int32', '')]
195
+
196
+ assert hdul.info(output=False) == info
197
+
198
+ hdul.writeto(self.temp('test-insert.fits'))
199
+
200
+ assert fits.info(self.temp('test-insert.fits'), output=False) == info
201
+
202
+ def test_insert_table_extension_to_empty_list(self):
203
+ """Tests inserting a Simple Table ExtensionHDU to a empty HDUList."""
204
+
205
+ hdul = fits.HDUList()
206
+ with fits.open(self.data('tb.fits')) as hdul1:
207
+ hdul.insert(0, hdul1[1])
208
+
209
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 4, (), '', ''),
210
+ (1, '', 1, 'BinTableHDU', 24, '2R x 4C', '[1J, 3A, 1E, 1L]', '')]
211
+
212
+ assert hdul.info(output=False) == info
213
+
214
+ hdul.writeto(self.temp('test-insert.fits'))
215
+
216
+ assert fits.info(self.temp('test-insert.fits'), output=False) == info
217
+
218
+ def test_insert_groupshdu_to_empty_list(self):
219
+ """Tests inserting a Simple GroupsHDU to an empty HDUList."""
220
+
221
+ hdul = fits.HDUList()
222
+ hdu = fits.GroupsHDU()
223
+ hdul.insert(0, hdu)
224
+
225
+ info = [(0, 'PRIMARY', 1, 'GroupsHDU', 8, (), '',
226
+ '1 Groups 0 Parameters')]
227
+
228
+ assert hdul.info(output=False) == info
229
+
230
+ hdul.writeto(self.temp('test-insert.fits'))
231
+
232
+ assert fits.info(self.temp('test-insert.fits'), output=False) == info
233
+
234
+ def test_insert_primary_to_non_empty_list(self):
235
+ """Tests inserting a Simple PrimaryHDU to a non-empty HDUList."""
236
+
237
+ with fits.open(self.data('arange.fits')) as hdul:
238
+ hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32))
239
+ hdul.insert(1, hdu)
240
+
241
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 7, (11, 10, 7), 'int32', ''),
242
+ (1, '', 1, 'ImageHDU', 6, (100,), 'int32', '')]
243
+
244
+ assert hdul.info(output=False) == info
245
+
246
+ hdul.writeto(self.temp('test-insert.fits'))
247
+
248
+ assert fits.info(self.temp('test-insert.fits'), output=False) == info
249
+
250
+ def test_insert_extension_to_non_empty_list(self):
251
+ """Tests inserting a Simple ExtensionHDU to a non-empty HDUList."""
252
+
253
+ with fits.open(self.data('tb.fits')) as hdul:
254
+ hdul.insert(1, hdul[1])
255
+
256
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 11, (), '', ''),
257
+ (1, '', 1, 'BinTableHDU', 24, '2R x 4C', '[1J, 3A, 1E, 1L]', ''),
258
+ (2, '', 1, 'BinTableHDU', 24, '2R x 4C', '[1J, 3A, 1E, 1L]', '')]
259
+
260
+ assert hdul.info(output=False) == info
261
+
262
+ hdul.writeto(self.temp('test-insert.fits'))
263
+
264
+ assert fits.info(self.temp('test-insert.fits'), output=False) == info
265
+
266
+ def test_insert_groupshdu_to_non_empty_list(self):
267
+ """Tests inserting a Simple GroupsHDU to an empty HDUList."""
268
+
269
+ hdul = fits.HDUList()
270
+ hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32))
271
+ hdul.insert(0, hdu)
272
+ hdu = fits.GroupsHDU()
273
+
274
+ with pytest.raises(ValueError):
275
+ hdul.insert(1, hdu)
276
+
277
+ info = [(0, 'PRIMARY', 1, 'GroupsHDU', 8, (), '',
278
+ '1 Groups 0 Parameters'),
279
+ (1, '', 1, 'ImageHDU', 6, (100,), 'int32', '')]
280
+
281
+ hdul.insert(0, hdu)
282
+
283
+ assert hdul.info(output=False) == info
284
+
285
+ hdul.writeto(self.temp('test-insert.fits'))
286
+
287
+ assert fits.info(self.temp('test-insert.fits'), output=False) == info
288
+
289
+ @raises(ValueError)
290
+ def test_insert_groupshdu_to_begin_of_hdulist_with_groupshdu(self):
291
+ """
292
+ Tests inserting a Simple GroupsHDU to the beginning of an HDUList
293
+ that that already contains a GroupsHDU.
294
+ """
295
+
296
+ hdul = fits.HDUList()
297
+ hdu = fits.GroupsHDU()
298
+ hdul.insert(0, hdu)
299
+ hdul.insert(0, hdu)
300
+
301
+ def test_insert_extension_to_primary_in_non_empty_list(self):
302
+ # Tests inserting a Simple ExtensionHDU to a non-empty HDUList.
303
+ with fits.open(self.data('tb.fits')) as hdul:
304
+ hdul.insert(0, hdul[1])
305
+
306
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 4, (), '', ''),
307
+ (1, '', 1, 'BinTableHDU', 24, '2R x 4C', '[1J, 3A, 1E, 1L]', ''),
308
+ (2, '', 1, 'ImageHDU', 12, (), '', ''),
309
+ (3, '', 1, 'BinTableHDU', 24, '2R x 4C', '[1J, 3A, 1E, 1L]', '')]
310
+
311
+ assert hdul.info(output=False) == info
312
+
313
+ hdul.writeto(self.temp('test-insert.fits'))
314
+
315
+ assert fits.info(self.temp('test-insert.fits'), output=False) == info
316
+
317
+ def test_insert_image_extension_to_primary_in_non_empty_list(self):
318
+ """
319
+ Tests inserting a Simple Image ExtensionHDU to a non-empty HDUList
320
+ as the primary HDU.
321
+ """
322
+
323
+ with fits.open(self.data('tb.fits')) as hdul:
324
+ hdu = fits.ImageHDU(np.arange(100, dtype=np.int32))
325
+ hdul.insert(0, hdu)
326
+
327
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 5, (100,), 'int32', ''),
328
+ (1, '', 1, 'ImageHDU', 12, (), '', ''),
329
+ (2, '', 1, 'BinTableHDU', 24, '2R x 4C', '[1J, 3A, 1E, 1L]', '')]
330
+
331
+ assert hdul.info(output=False) == info
332
+
333
+ hdul.writeto(self.temp('test-insert.fits'))
334
+
335
+ assert fits.info(self.temp('test-insert.fits'), output=False) == info
336
+
337
+ def test_filename(self):
338
+ """Tests the HDUList filename method."""
339
+
340
+ with fits.open(self.data('tb.fits')) as hdul:
341
+ name = hdul.filename()
342
+ assert name == self.data('tb.fits')
343
+
344
+ def test_file_like(self):
345
+ """
346
+ Tests the use of a file like object with no tell or seek methods
347
+ in HDUList.writeto(), HDULIST.flush() or astropy.io.fits.writeto()
348
+ """
349
+
350
+ hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32))
351
+ hdul = fits.HDUList()
352
+ hdul.append(hdu)
353
+ tmpfile = open(self.temp('tmpfile.fits'), 'wb')
354
+ hdul.writeto(tmpfile)
355
+ tmpfile.close()
356
+
357
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 5, (100,), 'int32', '')]
358
+
359
+ assert fits.info(self.temp('tmpfile.fits'), output=False) == info
360
+
361
+ def test_file_like_2(self):
362
+ hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32))
363
+ tmpfile = open(self.temp('tmpfile.fits'), 'wb')
364
+ hdul = fits.open(tmpfile, mode='ostream')
365
+ hdul.append(hdu)
366
+ hdul.flush()
367
+ tmpfile.close()
368
+ hdul.close()
369
+
370
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 5, (100,), 'int32', '')]
371
+ assert fits.info(self.temp('tmpfile.fits'), output=False) == info
372
+
373
+ def test_file_like_3(self):
374
+ tmpfile = open(self.temp('tmpfile.fits'), 'wb')
375
+ fits.writeto(tmpfile, np.arange(100, dtype=np.int32))
376
+ tmpfile.close()
377
+ info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 5, (100,), 'int32', '')]
378
+ assert fits.info(self.temp('tmpfile.fits'), output=False) == info
379
+
380
+ def test_shallow_copy(self):
381
+ """
382
+ Tests that `HDUList.__copy__()` and `HDUList.copy()` return a
383
+ shallow copy (regression test for #7211).
384
+ """
385
+
386
+ n = np.arange(10.0)
387
+ primary_hdu = fits.PrimaryHDU(n)
388
+ hdu = fits.ImageHDU(n)
389
+ hdul = fits.HDUList([primary_hdu, hdu])
390
+
391
+ for hdulcopy in (hdul.copy(), copy.copy(hdul)):
392
+ assert isinstance(hdulcopy, fits.HDUList)
393
+ assert hdulcopy is not hdul
394
+ assert hdulcopy[0] is hdul[0]
395
+ assert hdulcopy[1] is hdul[1]
396
+
397
+ def test_deep_copy(self):
398
+ """
399
+ Tests that `HDUList.__deepcopy__()` returns a deep copy.
400
+ """
401
+
402
+ n = np.arange(10.0)
403
+ primary_hdu = fits.PrimaryHDU(n)
404
+ hdu = fits.ImageHDU(n)
405
+ hdul = fits.HDUList([primary_hdu, hdu])
406
+
407
+ hdulcopy = copy.deepcopy(hdul)
408
+
409
+ assert isinstance(hdulcopy, fits.HDUList)
410
+ assert hdulcopy is not hdul
411
+
412
+ for index in range(len(hdul)):
413
+ assert hdulcopy[index] is not hdul[index]
414
+ assert hdulcopy[index].header == hdul[index].header
415
+ np.testing.assert_array_equal(hdulcopy[index].data, hdul[index].data)
416
+
417
+ def test_new_hdu_extname(self):
418
+ """
419
+ Tests that new extension HDUs that are added to an HDUList can be
420
+ properly indexed by their EXTNAME/EXTVER (regression test for
421
+ ticket:48).
422
+ """
423
+
424
+ with fits.open(self.data('test0.fits')) as f:
425
+ hdul = fits.HDUList()
426
+ hdul.append(f[0].copy())
427
+ hdu = fits.ImageHDU(header=f[1].header)
428
+ hdul.append(hdu)
429
+
430
+ assert hdul[1].header['EXTNAME'] == 'SCI'
431
+ assert hdul[1].header['EXTVER'] == 1
432
+ assert hdul.index_of(('SCI', 1)) == 1
433
+ assert hdul.index_of(hdu) == len(hdul) - 1
434
+
435
+ def test_update_filelike(self):
436
+ """Test opening a file-like object in update mode and resizing the
437
+ HDU.
438
+ """
439
+
440
+ sf = io.BytesIO()
441
+ arr = np.zeros((100, 100))
442
+ hdu = fits.PrimaryHDU(data=arr)
443
+ hdu.writeto(sf)
444
+
445
+ sf.seek(0)
446
+ arr = np.zeros((200, 200))
447
+ hdul = fits.open(sf, mode='update')
448
+ hdul[0].data = arr
449
+ hdul.flush()
450
+
451
+ sf.seek(0)
452
+ hdul = fits.open(sf)
453
+ assert len(hdul) == 1
454
+ assert (hdul[0].data == arr).all()
455
+
456
+ def test_flush_readonly(self):
457
+ """Test flushing changes to a file opened in a read only mode."""
458
+
459
+ oldmtime = os.stat(self.data('test0.fits')).st_mtime
460
+ hdul = fits.open(self.data('test0.fits'))
461
+ hdul[0].header['FOO'] = 'BAR'
462
+ with catch_warnings(AstropyUserWarning) as w:
463
+ hdul.flush()
464
+ assert len(w) == 1
465
+ assert 'mode is not supported' in str(w[0].message)
466
+ assert oldmtime == os.stat(self.data('test0.fits')).st_mtime
467
+
468
+ def test_fix_extend_keyword(self):
469
+ hdul = fits.HDUList()
470
+ hdul.append(fits.PrimaryHDU())
471
+ hdul.append(fits.ImageHDU())
472
+ del hdul[0].header['EXTEND']
473
+ hdul.verify('silentfix')
474
+
475
+ assert 'EXTEND' in hdul[0].header
476
+ assert hdul[0].header['EXTEND'] is True
477
+
478
+ def test_fix_malformed_naxisj(self):
479
+ """
480
+ Tests that malformed NAXISj values are fixed sensibly.
481
+ """
482
+
483
+ hdu = fits.open(self.data('arange.fits'))
484
+
485
+ # Malform NAXISj header data
486
+ hdu[0].header['NAXIS1'] = 11.0
487
+ hdu[0].header['NAXIS2'] = '10.0'
488
+ hdu[0].header['NAXIS3'] = '7'
489
+
490
+ # Axes cache needs to be malformed as well
491
+ hdu[0]._axes = [11.0, '10.0', '7']
492
+
493
+ # Perform verification including the fix
494
+ hdu.verify('silentfix')
495
+
496
+ # Check that malformed data was converted
497
+ assert hdu[0].header['NAXIS1'] == 11
498
+ assert hdu[0].header['NAXIS2'] == 10
499
+ assert hdu[0].header['NAXIS3'] == 7
500
+ hdu.close()
501
+
502
+ def test_fix_wellformed_naxisj(self):
503
+ """
504
+ Tests that wellformed NAXISj values are not modified.
505
+ """
506
+
507
+ hdu = fits.open(self.data('arange.fits'))
508
+
509
+ # Fake new NAXISj header data
510
+ hdu[0].header['NAXIS1'] = 768
511
+ hdu[0].header['NAXIS2'] = 64
512
+ hdu[0].header['NAXIS3'] = 8
513
+
514
+ # Axes cache needs to be faked as well
515
+ hdu[0]._axes = [768, 64, 8]
516
+
517
+ # Perform verification including the fix
518
+ hdu.verify('silentfix')
519
+
520
+ # Check that malformed data was converted
521
+ assert hdu[0].header['NAXIS1'] == 768
522
+ assert hdu[0].header['NAXIS2'] == 64
523
+ assert hdu[0].header['NAXIS3'] == 8
524
+ hdu.close()
525
+
526
+ def test_new_hdulist_extend_keyword(self):
527
+ """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/114
528
+
529
+ Tests that adding a PrimaryHDU to a new HDUList object updates the
530
+ EXTEND keyword on that HDU.
531
+ """
532
+
533
+ h0 = fits.Header()
534
+ hdu = fits.PrimaryHDU(header=h0)
535
+ sci = fits.ImageHDU(data=np.array(10))
536
+ image = fits.HDUList([hdu, sci])
537
+ image.writeto(self.temp('temp.fits'))
538
+ assert 'EXTEND' in hdu.header
539
+ assert hdu.header['EXTEND'] is True
540
+
541
+ def test_replace_memmaped_array(self):
542
+ # Copy the original before we modify it
543
+ with fits.open(self.data('test0.fits')) as hdul:
544
+ hdul.writeto(self.temp('temp.fits'))
545
+
546
+ hdul = fits.open(self.temp('temp.fits'), mode='update', memmap=True)
547
+ old_data = hdul[1].data.copy()
548
+ hdul[1].data = hdul[1].data + 1
549
+ hdul.close()
550
+
551
+ with fits.open(self.temp('temp.fits'), memmap=True) as hdul:
552
+ assert ((old_data + 1) == hdul[1].data).all()
553
+
554
+ def test_open_file_with_end_padding(self):
555
+ """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/106
556
+
557
+ Open files with end padding bytes.
558
+ """
559
+
560
+ with fits.open(self.data('test0.fits'),
561
+ do_not_scale_image_data=True) as hdul:
562
+ info = hdul.info(output=False)
563
+ hdul.writeto(self.temp('temp.fits'))
564
+
565
+ with open(self.temp('temp.fits'), 'ab') as f:
566
+ f.seek(0, os.SEEK_END)
567
+ f.write(b'\0' * 2880)
568
+ with ignore_warnings():
569
+ assert info == fits.info(self.temp('temp.fits'), output=False,
570
+ do_not_scale_image_data=True)
571
+
572
+ def test_open_file_with_bad_header_padding(self):
573
+ """
574
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/136
575
+
576
+ Open files with nulls for header block padding instead of spaces.
577
+ """
578
+
579
+ a = np.arange(100).reshape(10, 10)
580
+ hdu = fits.PrimaryHDU(data=a)
581
+ hdu.writeto(self.temp('temp.fits'))
582
+
583
+ # Figure out where the header padding begins and fill it with nulls
584
+ end_card_pos = str(hdu.header).index('END' + ' ' * 77)
585
+ padding_start = end_card_pos + 80
586
+ padding_len = 2880 - padding_start
587
+ with open(self.temp('temp.fits'), 'r+b') as f:
588
+ f.seek(padding_start)
589
+ f.write('\0'.encode('ascii') * padding_len)
590
+
591
+ with catch_warnings(AstropyUserWarning) as w:
592
+ with fits.open(self.temp('temp.fits')) as hdul:
593
+ assert (hdul[0].data == a).all()
594
+ assert ('contains null bytes instead of spaces' in
595
+ str(w[0].message))
596
+ assert len(w) == 1
597
+ assert len(hdul) == 1
598
+ assert str(hdul[0].header) == str(hdu.header)
599
+
600
+ def test_update_with_truncated_header(self):
601
+ """
602
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/148
603
+
604
+ Test that saving an update where the header is shorter than the
605
+ original header doesn't leave a stump from the old header in the file.
606
+ """
607
+
608
+ data = np.arange(100)
609
+ hdu = fits.PrimaryHDU(data=data)
610
+ idx = 1
611
+ while len(hdu.header) < 34:
612
+ hdu.header['TEST{}'.format(idx)] = idx
613
+ idx += 1
614
+ hdu.writeto(self.temp('temp.fits'), checksum=True)
615
+
616
+ with fits.open(self.temp('temp.fits'), mode='update') as hdul:
617
+ # Modify the header, forcing it to be rewritten
618
+ hdul[0].header['TEST1'] = 2
619
+
620
+ with fits.open(self.temp('temp.fits')) as hdul:
621
+ assert (hdul[0].data == data).all()
622
+
623
+ @pytest.mark.xfail(platform.system() == 'Windows',
624
+ reason='https://github.com/astropy/astropy/issues/5797')
625
+ def test_update_resized_header(self):
626
+ """
627
+ Test saving updates to a file where the header is one block smaller
628
+ than before, and in the case where the heade ris one block larger than
629
+ before.
630
+ """
631
+
632
+ data = np.arange(100)
633
+ hdu = fits.PrimaryHDU(data=data)
634
+ idx = 1
635
+ while len(str(hdu.header)) <= 2880:
636
+ hdu.header['TEST{}'.format(idx)] = idx
637
+ idx += 1
638
+ orig_header = hdu.header.copy()
639
+ hdu.writeto(self.temp('temp.fits'))
640
+
641
+ with fits.open(self.temp('temp.fits'), mode='update') as hdul:
642
+ while len(str(hdul[0].header)) > 2880:
643
+ del hdul[0].header[-1]
644
+
645
+ with fits.open(self.temp('temp.fits')) as hdul:
646
+ assert hdul[0].header == orig_header[:-1]
647
+ assert (hdul[0].data == data).all()
648
+
649
+ with fits.open(self.temp('temp.fits'), mode='update') as hdul:
650
+ idx = 101
651
+ while len(str(hdul[0].header)) <= 2880 * 2:
652
+ hdul[0].header['TEST{}'.format(idx)] = idx
653
+ idx += 1
654
+ # Touch something in the data too so that it has to be rewritten
655
+ hdul[0].data[0] = 27
656
+
657
+ with fits.open(self.temp('temp.fits')) as hdul:
658
+ assert hdul[0].header[:-37] == orig_header[:-1]
659
+ assert hdul[0].data[0] == 27
660
+ assert (hdul[0].data[1:] == data[1:]).all()
661
+
662
+ def test_update_resized_header2(self):
663
+ """
664
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/150
665
+
666
+ This is similar to test_update_resized_header, but specifically tests a
667
+ case of multiple consecutive flush() calls on the same HDUList object,
668
+ where each flush() requires a resize.
669
+ """
670
+
671
+ data1 = np.arange(100)
672
+ data2 = np.arange(100) + 100
673
+ phdu = fits.PrimaryHDU(data=data1)
674
+ hdu = fits.ImageHDU(data=data2)
675
+
676
+ phdu.writeto(self.temp('temp.fits'))
677
+
678
+ with fits.open(self.temp('temp.fits'), mode='append') as hdul:
679
+ hdul.append(hdu)
680
+
681
+ with fits.open(self.temp('temp.fits'), mode='update') as hdul:
682
+ idx = 1
683
+ while len(str(hdul[0].header)) <= 2880 * 2:
684
+ hdul[0].header['TEST{}'.format(idx)] = idx
685
+ idx += 1
686
+ hdul.flush()
687
+ hdul.append(hdu)
688
+
689
+ with fits.open(self.temp('temp.fits')) as hdul:
690
+ assert (hdul[0].data == data1).all()
691
+ assert hdul[1].header == hdu.header
692
+ assert (hdul[1].data == data2).all()
693
+ assert (hdul[2].data == data2).all()
694
+
695
+ @ignore_warnings()
696
+ def test_hdul_fromstring(self):
697
+ """
698
+ Test creating the HDUList structure in memory from a string containing
699
+ an entire FITS file. This is similar to test_hdu_fromstring but for an
700
+ entire multi-extension FITS file at once.
701
+ """
702
+
703
+ # Tests HDUList.fromstring for all of Astropy's built in test files
704
+ def test_fromstring(filename):
705
+ with fits.open(filename) as hdul:
706
+ orig_info = hdul.info(output=False)
707
+ with open(filename, 'rb') as f:
708
+ dat = f.read()
709
+
710
+ hdul2 = fits.HDUList.fromstring(dat)
711
+
712
+ assert orig_info == hdul2.info(output=False)
713
+ for idx in range(len(hdul)):
714
+ assert hdul[idx].header == hdul2[idx].header
715
+ if hdul[idx].data is None or hdul2[idx].data is None:
716
+ assert hdul[idx].data == hdul2[idx].data
717
+ elif (hdul[idx].data.dtype.fields and
718
+ hdul2[idx].data.dtype.fields):
719
+ # Compare tables
720
+ for n in hdul[idx].data.names:
721
+ c1 = hdul[idx].data[n]
722
+ c2 = hdul2[idx].data[n]
723
+ assert (c1 == c2).all()
724
+ elif (any(dim == 0 for dim in hdul[idx].data.shape) or
725
+ any(dim == 0 for dim in hdul2[idx].data.shape)):
726
+ # For some reason some combinations of Python and Numpy
727
+ # on Windows result in MemoryErrors when trying to work
728
+ # on memmap arrays with more than one dimension but
729
+ # some dimensions of size zero, so include a special
730
+ # case for that
731
+ return hdul[idx].data.shape == hdul2[idx].data.shape
732
+ else:
733
+ np.testing.assert_array_equal(hdul[idx].data,
734
+ hdul2[idx].data)
735
+
736
+ for filename in glob.glob(os.path.join(self.data_dir, '*.fits')):
737
+ if sys.platform == 'win32' and filename == 'zerowidth.fits':
738
+ # Running this test on this file causes a crash in some
739
+ # versions of Numpy on Windows. See ticket:
740
+ # https://aeon.stsci.edu/ssb/trac/pyfits/ticket/174
741
+ continue
742
+ elif filename.endswith('variable_length_table.fits'):
743
+ # Comparing variable length arrays is non-trivial and thus
744
+ # skipped at this point.
745
+ # TODO: That's probably possible, so one could make it work.
746
+ continue
747
+ test_fromstring(filename)
748
+
749
+ # Test that creating an HDUList from something silly raises a TypeError
750
+ pytest.raises(TypeError, fits.HDUList.fromstring, ['a', 'b', 'c'])
751
+
752
+ def test_save_backup(self):
753
+ """Test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/121
754
+
755
+ Save backup of file before flushing changes.
756
+ """
757
+
758
+ self.copy_file('scale.fits')
759
+
760
+ with ignore_warnings():
761
+ with fits.open(self.temp('scale.fits'), mode='update',
762
+ save_backup=True) as hdul:
763
+ # Make some changes to the original file to force its header
764
+ # and data to be rewritten
765
+ hdul[0].header['TEST'] = 'TEST'
766
+ hdul[0].data[0] = 0
767
+
768
+ assert os.path.exists(self.temp('scale.fits.bak'))
769
+ with fits.open(self.data('scale.fits'),
770
+ do_not_scale_image_data=True) as hdul1:
771
+ with fits.open(self.temp('scale.fits.bak'),
772
+ do_not_scale_image_data=True) as hdul2:
773
+ assert hdul1[0].header == hdul2[0].header
774
+ assert (hdul1[0].data == hdul2[0].data).all()
775
+
776
+ with ignore_warnings():
777
+ with fits.open(self.temp('scale.fits'), mode='update',
778
+ save_backup=True) as hdul:
779
+ # One more time to see if multiple backups are made
780
+ hdul[0].header['TEST2'] = 'TEST'
781
+ hdul[0].data[0] = 1
782
+
783
+ assert os.path.exists(self.temp('scale.fits.bak'))
784
+ assert os.path.exists(self.temp('scale.fits.bak.1'))
785
+
786
+ def test_replace_mmap_data(self):
787
+ """Regression test for
788
+ https://github.com/spacetelescope/PyFITS/issues/25
789
+
790
+ Replacing the mmap'd data of one file with mmap'd data from a
791
+ different file should work.
792
+ """
793
+
794
+ arr_a = np.arange(10)
795
+ arr_b = arr_a * 2
796
+
797
+ def test(mmap_a, mmap_b):
798
+ hdu_a = fits.PrimaryHDU(data=arr_a)
799
+ hdu_a.writeto(self.temp('test_a.fits'), overwrite=True)
800
+ hdu_b = fits.PrimaryHDU(data=arr_b)
801
+ hdu_b.writeto(self.temp('test_b.fits'), overwrite=True)
802
+
803
+ with fits.open(self.temp('test_a.fits'), mode='update',
804
+ memmap=mmap_a) as hdul_a:
805
+ with fits.open(self.temp('test_b.fits'),
806
+ memmap=mmap_b) as hdul_b:
807
+ hdul_a[0].data = hdul_b[0].data
808
+
809
+ with fits.open(self.temp('test_a.fits')) as hdul_a:
810
+ assert np.all(hdul_a[0].data == arr_b)
811
+
812
+ with ignore_warnings():
813
+ test(True, True)
814
+
815
+ # Repeat the same test but this time don't mmap A
816
+ test(False, True)
817
+
818
+ # Finally, without mmaping B
819
+ test(True, False)
820
+
821
+ def test_replace_mmap_data_2(self):
822
+ """Regression test for
823
+ https://github.com/spacetelescope/PyFITS/issues/25
824
+
825
+ Replacing the mmap'd data of one file with mmap'd data from a
826
+ different file should work. Like test_replace_mmap_data but with
827
+ table data instead of image data.
828
+ """
829
+
830
+ arr_a = np.arange(10)
831
+ arr_b = arr_a * 2
832
+
833
+ def test(mmap_a, mmap_b):
834
+ col_a = fits.Column(name='a', format='J', array=arr_a)
835
+ col_b = fits.Column(name='b', format='J', array=arr_b)
836
+ hdu_a = fits.BinTableHDU.from_columns([col_a])
837
+ hdu_a.writeto(self.temp('test_a.fits'), overwrite=True)
838
+ hdu_b = fits.BinTableHDU.from_columns([col_b])
839
+ hdu_b.writeto(self.temp('test_b.fits'), overwrite=True)
840
+
841
+ with fits.open(self.temp('test_a.fits'), mode='update',
842
+ memmap=mmap_a) as hdul_a:
843
+ with fits.open(self.temp('test_b.fits'),
844
+ memmap=mmap_b) as hdul_b:
845
+ hdul_a[1].data = hdul_b[1].data
846
+
847
+ with fits.open(self.temp('test_a.fits')) as hdul_a:
848
+ assert 'b' in hdul_a[1].columns.names
849
+ assert 'a' not in hdul_a[1].columns.names
850
+ assert np.all(hdul_a[1].data['b'] == arr_b)
851
+
852
+ with ignore_warnings():
853
+ test(True, True)
854
+
855
+ # Repeat the same test but this time don't mmap A
856
+ test(False, True)
857
+
858
+ # Finally, without mmaping B
859
+ test(True, False)
860
+
861
+ def test_extname_in_hdulist(self):
862
+ """
863
+ Tests to make sure that the 'in' operator works.
864
+
865
+ Regression test for https://github.com/astropy/astropy/issues/3060
866
+ """
867
+ with fits.open(self.data('o4sp040b0_raw.fits')) as hdulist:
868
+ hdulist.append(fits.ImageHDU(name='a'))
869
+
870
+ assert 'a' in hdulist
871
+ assert 'A' in hdulist
872
+ assert ('a', 1) in hdulist
873
+ assert ('A', 1) in hdulist
874
+ assert 'b' not in hdulist
875
+ assert ('a', 2) not in hdulist
876
+ assert ('b', 1) not in hdulist
877
+ assert ('b', 2) not in hdulist
878
+ assert hdulist[0] in hdulist
879
+ assert fits.ImageHDU() not in hdulist
880
+
881
+ def test_overwrite_vs_clobber(self):
882
+ hdulist = fits.HDUList([fits.PrimaryHDU()])
883
+ hdulist.writeto(self.temp('test_overwrite.fits'))
884
+ hdulist.writeto(self.temp('test_overwrite.fits'), overwrite=True)
885
+ with catch_warnings(AstropyDeprecationWarning) as warning_lines:
886
+ hdulist.writeto(self.temp('test_overwrite.fits'), clobber=True)
887
+ assert warning_lines[0].category == AstropyDeprecationWarning
888
+ assert (str(warning_lines[0].message) == '"clobber" was '
889
+ 'deprecated in version 2.0 and will be removed in a '
890
+ 'future version. Use argument "overwrite" instead.')
891
+
892
+ def test_invalid_hdu_key_in_contains(self):
893
+ """
894
+ Make sure invalid keys in the 'in' operator return False.
895
+ Regression test for https://github.com/astropy/astropy/issues/5583
896
+ """
897
+ hdulist = fits.HDUList(fits.PrimaryHDU())
898
+ hdulist.append(fits.ImageHDU())
899
+ hdulist.append(fits.ImageHDU())
900
+
901
+ # A more or less random assortment of things which are not valid keys.
902
+ bad_keys = [None, 3.5, {}]
903
+
904
+ for key in bad_keys:
905
+ assert not (key in hdulist)
906
+
907
+ def test_iteration_of_lazy_loaded_hdulist(self):
908
+ """
909
+ Regression test for https://github.com/astropy/astropy/issues/5585
910
+ """
911
+ hdulist = fits.HDUList(fits.PrimaryHDU())
912
+ hdulist.append(fits.ImageHDU(name='SCI'))
913
+ hdulist.append(fits.ImageHDU(name='SCI'))
914
+ hdulist.append(fits.ImageHDU(name='nada'))
915
+ hdulist.append(fits.ImageHDU(name='SCI'))
916
+
917
+ filename = self.temp('many_extension.fits')
918
+ hdulist.writeto(filename)
919
+ f = fits.open(filename)
920
+
921
+ # Check that all extensions are read if f is not sliced
922
+ all_exts = [ext for ext in f]
923
+ assert len(all_exts) == 5
924
+
925
+ # Reload the file to ensure we are still lazy loading
926
+ f.close()
927
+ f = fits.open(filename)
928
+
929
+ # Try a simple slice with no conditional on the ext. This is essentially
930
+ # the reported failure.
931
+ all_exts_but_zero = [ext for ext in f[1:]]
932
+ assert len(all_exts_but_zero) == 4
933
+
934
+ # Reload the file to ensure we are still lazy loading
935
+ f.close()
936
+ f = fits.open(filename)
937
+
938
+ # Check whether behavior is proper if the upper end of the slice is not
939
+ # omitted.
940
+ read_exts = [ext for ext in f[1:4] if ext.header['EXTNAME'] == 'SCI']
941
+ assert len(read_exts) == 2
942
+ f.close()
943
+
944
+ def test_proper_error_raised_on_non_fits_file_with_unicode(self):
945
+ """
946
+ Regression test for https://github.com/astropy/astropy/issues/5594
947
+
948
+ The failure shows up when (in python 3+) you try to open a file
949
+ with unicode content that is not actually a FITS file. See:
950
+ https://github.com/astropy/astropy/issues/5594#issuecomment-266583218
951
+ """
952
+ import codecs
953
+ filename = self.temp('not-fits-with-unicode.fits')
954
+ with codecs.open(filename, mode='w', encoding='utf=8') as f:
955
+ f.write(u'Ce\xe7i ne marche pas')
956
+
957
+ # This should raise an OSError because there is no end card.
958
+ with pytest.raises(OSError):
959
+ with pytest.warns(AstropyUserWarning, match='non-ASCII characters '
960
+ 'are present in the FITS file header'):
961
+ fits.open(filename)
962
+
963
+ def test_no_resource_warning_raised_on_non_fits_file(self):
964
+ """
965
+ Regression test for https://github.com/astropy/astropy/issues/6168
966
+
967
+ The ResourceWarning shows up when (in python 3+) you try to
968
+ open a non-FITS file when using a filename.
969
+ """
970
+
971
+ # To avoid creating the file multiple times the tests are
972
+ # all included in one test file. See the discussion to the
973
+ # PR at https://github.com/astropy/astropy/issues/6168
974
+ #
975
+ filename = self.temp('not-fits.fits')
976
+ with open(filename, mode='w') as f:
977
+ f.write('# header line\n')
978
+ f.write('0.1 0.2\n')
979
+
980
+ # Opening the file should raise an OSError however the file
981
+ # is opened (there are two distinct code paths, depending on
982
+ # whether ignore_missing_end is True or False).
983
+ #
984
+ # Explicit tests are added to make sure the file handle is not
985
+ # closed when passed in to fits.open. In this case the ResourceWarning
986
+ # was not raised, but a check is still included.
987
+ #
988
+ with catch_warnings(ResourceWarning) as ws:
989
+
990
+ # Make sure that files opened by the user are not closed
991
+ with open(filename, mode='rb') as f:
992
+ with pytest.raises(OSError):
993
+ fits.open(f, ignore_missing_end=False)
994
+
995
+ assert not f.closed
996
+
997
+ with open(filename, mode='rb') as f:
998
+ with pytest.raises(OSError):
999
+ fits.open(f, ignore_missing_end=True)
1000
+
1001
+ assert not f.closed
1002
+
1003
+ with pytest.raises(OSError):
1004
+ fits.open(filename, ignore_missing_end=False)
1005
+
1006
+ with pytest.raises(OSError):
1007
+ fits.open(filename, ignore_missing_end=True)
1008
+
1009
+ assert len(ws) == 0
1010
+
1011
+ def test_pop_with_lazy_load(self):
1012
+ filename = self.data('checksum.fits')
1013
+
1014
+ with fits.open(filename) as hdul:
1015
+ # Try popping the hdulist before doing anything else. This makes sure
1016
+ # that https://github.com/astropy/astropy/issues/7185 is fixed.
1017
+ hdu = hdul.pop()
1018
+ assert len(hdul) == 1
1019
+
1020
+ # Read the file again and try popping from the beginning
1021
+ with fits.open(filename) as hdul2:
1022
+ hdu2 = hdul2.pop(0)
1023
+ assert len(hdul2) == 1
1024
+
1025
+ # Just a sanity check
1026
+ with fits.open(filename) as hdul3:
1027
+ assert len(hdul3) == 2
1028
+ assert hdul3[0].header == hdu2.header
1029
+ assert hdul3[1].header == hdu.header
1030
+
1031
+ def test_pop_extname(self):
1032
+ with fits.open(self.data('o4sp040b0_raw.fits')) as hdul:
1033
+ assert len(hdul) == 7
1034
+ hdu1 = hdul[1]
1035
+ hdu4 = hdul[4]
1036
+ hdu_popped = hdul.pop(('SCI', 2))
1037
+ assert len(hdul) == 6
1038
+ assert hdu_popped is hdu4
1039
+ hdu_popped = hdul.pop('SCI')
1040
+ assert len(hdul) == 5
1041
+ assert hdu_popped is hdu1
1042
+
1043
+ def test_write_hdulist_to_stream(self):
1044
+ """
1045
+ Unit test for https://github.com/astropy/astropy/issues/7435
1046
+ Ensure that an HDUList can be written to a stream in Python 2
1047
+ """
1048
+ data = np.array([[1,2,3],[4,5,6]])
1049
+ hdu = fits.PrimaryHDU(data)
1050
+ hdulist = fits.HDUList([hdu])
1051
+
1052
+ with open(self.temp('test.fits'), 'wb') as fout:
1053
+ with subprocess.Popen(["cat"], stdin=subprocess.PIPE,
1054
+ stdout=fout) as p:
1055
+ hdulist.writeto(p.stdin)
testbed/astropy__astropy/astropy/io/fits/tests/test_header.py ADDED
The diff for this file is too large to render. See raw diff
 
testbed/astropy__astropy/astropy/io/fits/tests/test_image.py ADDED
@@ -0,0 +1,1968 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+
4
+ import math
5
+ import os
6
+ import platform
7
+ import re
8
+ import time
9
+ import warnings
10
+
11
+ import pytest
12
+ import numpy as np
13
+ from numpy.testing import assert_equal
14
+
15
+ from astropy.io import fits
16
+ from astropy.tests.helper import catch_warnings, ignore_warnings
17
+ from astropy.io.fits.hdu.compressed import SUBTRACTIVE_DITHER_1, DITHER_SEED_CHECKSUM
18
+ from .test_table import comparerecords
19
+
20
+ from . import FitsTestCase
21
+
22
+ try:
23
+ import scipy # noqa
24
+ except ImportError:
25
+ HAS_SCIPY = False
26
+ else:
27
+ HAS_SCIPY = True
28
+
29
+
30
+ class TestImageFunctions(FitsTestCase):
31
+ def test_constructor_name_arg(self):
32
+ """Like the test of the same name in test_table.py"""
33
+
34
+ hdu = fits.ImageHDU()
35
+ assert hdu.name == ''
36
+ assert 'EXTNAME' not in hdu.header
37
+ hdu.name = 'FOO'
38
+ assert hdu.name == 'FOO'
39
+ assert hdu.header['EXTNAME'] == 'FOO'
40
+
41
+ # Passing name to constructor
42
+ hdu = fits.ImageHDU(name='FOO')
43
+ assert hdu.name == 'FOO'
44
+ assert hdu.header['EXTNAME'] == 'FOO'
45
+
46
+ # And overriding a header with a different extname
47
+ hdr = fits.Header()
48
+ hdr['EXTNAME'] = 'EVENTS'
49
+ hdu = fits.ImageHDU(header=hdr, name='FOO')
50
+ assert hdu.name == 'FOO'
51
+ assert hdu.header['EXTNAME'] == 'FOO'
52
+
53
+ def test_constructor_ver_arg(self):
54
+ def assert_ver_is(hdu, reference_ver):
55
+ assert hdu.ver == reference_ver
56
+ assert hdu.header['EXTVER'] == reference_ver
57
+
58
+ hdu = fits.ImageHDU()
59
+ assert hdu.ver == 1 # defaults to 1
60
+ assert 'EXTVER' not in hdu.header
61
+
62
+ hdu.ver = 1
63
+ assert_ver_is(hdu, 1)
64
+
65
+ # Passing name to constructor
66
+ hdu = fits.ImageHDU(ver=2)
67
+ assert_ver_is(hdu, 2)
68
+
69
+ # And overriding a header with a different extver
70
+ hdr = fits.Header()
71
+ hdr['EXTVER'] = 3
72
+ hdu = fits.ImageHDU(header=hdr, ver=4)
73
+ assert_ver_is(hdu, 4)
74
+
75
+ # The header card is not overridden if ver is None or not passed in
76
+ hdr = fits.Header()
77
+ hdr['EXTVER'] = 5
78
+ hdu = fits.ImageHDU(header=hdr, ver=None)
79
+ assert_ver_is(hdu, 5)
80
+ hdu = fits.ImageHDU(header=hdr)
81
+ assert_ver_is(hdu, 5)
82
+
83
+ def test_constructor_copies_header(self):
84
+ """
85
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/153
86
+
87
+ Ensure that a header from one HDU is copied when used to initialize new
88
+ HDU.
89
+ """
90
+
91
+ ifd = fits.HDUList(fits.PrimaryHDU())
92
+ phdr = ifd[0].header
93
+ phdr['FILENAME'] = 'labq01i3q_rawtag.fits'
94
+
95
+ primary_hdu = fits.PrimaryHDU(header=phdr)
96
+ ofd = fits.HDUList(primary_hdu)
97
+ ofd[0].header['FILENAME'] = 'labq01i3q_flt.fits'
98
+
99
+ # Original header should be unchanged
100
+ assert phdr['FILENAME'] == 'labq01i3q_rawtag.fits'
101
+
102
+ def test_open(self):
103
+ # The function "open" reads a FITS file into an HDUList object. There
104
+ # are three modes to open: "readonly" (the default), "append", and
105
+ # "update".
106
+
107
+ # Open a file read-only (the default mode), the content of the FITS
108
+ # file are read into memory.
109
+ r = fits.open(self.data('test0.fits')) # readonly
110
+
111
+ # data parts are latent instantiation, so if we close the HDUList
112
+ # without touching data, data can not be accessed.
113
+ r.close()
114
+
115
+ with pytest.raises(IndexError) as exc_info:
116
+ r[1].data[:2, :2]
117
+
118
+ # Check that the exception message is the enhanced version, not the
119
+ # default message from list.__getitem__
120
+ assert str(exc_info.value) == ('HDU not found, possibly because the index '
121
+ 'is out of range, or because the file was '
122
+ 'closed before all HDUs were read')
123
+
124
+ def test_open_2(self):
125
+ r = fits.open(self.data('test0.fits'))
126
+
127
+ info = ([(0, 'PRIMARY', 1, 'PrimaryHDU', 138, (), '', '')] +
128
+ [(x, 'SCI', x, 'ImageHDU', 61, (40, 40), 'int16', '')
129
+ for x in range(1, 5)])
130
+
131
+ try:
132
+ assert r.info(output=False) == info
133
+ finally:
134
+ r.close()
135
+
136
+ def test_open_3(self):
137
+ # Test that HDUs cannot be accessed after the file was closed
138
+ r = fits.open(self.data('test0.fits'))
139
+ r.close()
140
+ with pytest.raises(IndexError) as exc_info:
141
+ r[1]
142
+
143
+ # Check that the exception message is the enhanced version, not the
144
+ # default message from list.__getitem__
145
+ assert str(exc_info.value) == ('HDU not found, possibly because the index '
146
+ 'is out of range, or because the file was '
147
+ 'closed before all HDUs were read')
148
+
149
+ # Test that HDUs can be accessed with lazy_load_hdus=False
150
+ r = fits.open(self.data('test0.fits'), lazy_load_hdus=False)
151
+ r.close()
152
+ assert isinstance(r[1], fits.ImageHDU)
153
+ assert len(r) == 5
154
+
155
+ with pytest.raises(IndexError) as exc_info:
156
+ r[6]
157
+ assert str(exc_info.value) == 'list index out of range'
158
+
159
+ # And the same with the global config item
160
+ assert fits.conf.lazy_load_hdus # True by default
161
+ fits.conf.lazy_load_hdus = False
162
+ try:
163
+ r = fits.open(self.data('test0.fits'))
164
+ r.close()
165
+ assert isinstance(r[1], fits.ImageHDU)
166
+ assert len(r) == 5
167
+ finally:
168
+ fits.conf.lazy_load_hdus = True
169
+
170
+ def test_fortran_array(self):
171
+ # Test that files are being correctly written+read for "C" and "F" order arrays
172
+ a = np.arange(21).reshape(3,7)
173
+ b = np.asfortranarray(a)
174
+
175
+ afits = self.temp('a_str.fits')
176
+ bfits = self.temp('b_str.fits')
177
+ # writting to str specified files
178
+ fits.PrimaryHDU(data=a).writeto(afits)
179
+ fits.PrimaryHDU(data=b).writeto(bfits)
180
+ np.testing.assert_array_equal(fits.getdata(afits), a)
181
+ np.testing.assert_array_equal(fits.getdata(bfits), a)
182
+
183
+ # writting to fileobjs
184
+ aafits = self.temp('a_fileobj.fits')
185
+ bbfits = self.temp('b_fileobj.fits')
186
+ with open(aafits, mode='wb') as fd:
187
+ fits.PrimaryHDU(data=a).writeto(fd)
188
+ with open(bbfits, mode='wb') as fd:
189
+ fits.PrimaryHDU(data=b).writeto(fd)
190
+ np.testing.assert_array_equal(fits.getdata(aafits), a)
191
+ np.testing.assert_array_equal(fits.getdata(bbfits), a)
192
+
193
+ def test_fortran_array_non_contiguous(self):
194
+ # Test that files are being correctly written+read for 'C' and 'F' order arrays
195
+ a = np.arange(105).reshape(3,5,7)
196
+ b = np.asfortranarray(a)
197
+
198
+ # writting to str specified files
199
+ afits = self.temp('a_str_slice.fits')
200
+ bfits = self.temp('b_str_slice.fits')
201
+ fits.PrimaryHDU(data=a[::2, ::2]).writeto(afits)
202
+ fits.PrimaryHDU(data=b[::2, ::2]).writeto(bfits)
203
+ np.testing.assert_array_equal(fits.getdata(afits), a[::2, ::2])
204
+ np.testing.assert_array_equal(fits.getdata(bfits), a[::2, ::2])
205
+
206
+ # writting to fileobjs
207
+ aafits = self.temp('a_fileobj_slice.fits')
208
+ bbfits = self.temp('b_fileobj_slice.fits')
209
+ with open(aafits, mode='wb') as fd:
210
+ fits.PrimaryHDU(data=a[::2, ::2]).writeto(fd)
211
+ with open(bbfits, mode='wb') as fd:
212
+ fits.PrimaryHDU(data=b[::2, ::2]).writeto(fd)
213
+ np.testing.assert_array_equal(fits.getdata(aafits), a[::2, ::2])
214
+ np.testing.assert_array_equal(fits.getdata(bbfits), a[::2, ::2])
215
+
216
+
217
+ def test_primary_with_extname(self):
218
+ """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/151
219
+
220
+ Tests that the EXTNAME keyword works with Primary HDUs as well, and
221
+ interacts properly with the .name attribute. For convenience
222
+ hdulist['PRIMARY'] will still refer to the first HDU even if it has an
223
+ EXTNAME not equal to 'PRIMARY'.
224
+ """
225
+
226
+ prihdr = fits.Header([('EXTNAME', 'XPRIMARY'), ('EXTVER', 1)])
227
+ hdul = fits.HDUList([fits.PrimaryHDU(header=prihdr)])
228
+ assert 'EXTNAME' in hdul[0].header
229
+ assert hdul[0].name == 'XPRIMARY'
230
+ assert hdul[0].name == hdul[0].header['EXTNAME']
231
+
232
+ info = [(0, 'XPRIMARY', 1, 'PrimaryHDU', 5, (), '', '')]
233
+ assert hdul.info(output=False) == info
234
+
235
+ assert hdul['PRIMARY'] is hdul['XPRIMARY']
236
+ assert hdul['PRIMARY'] is hdul[('XPRIMARY', 1)]
237
+
238
+ hdul[0].name = 'XPRIMARY2'
239
+ assert hdul[0].header['EXTNAME'] == 'XPRIMARY2'
240
+
241
+ hdul.writeto(self.temp('test.fits'))
242
+ with fits.open(self.temp('test.fits')) as hdul:
243
+ assert hdul[0].name == 'XPRIMARY2'
244
+
245
+ @pytest.mark.xfail(platform.system() == 'Windows',
246
+ reason='https://github.com/astropy/astropy/issues/5797')
247
+ def test_io_manipulation(self):
248
+ # Get a keyword value. An extension can be referred by name or by
249
+ # number. Both extension and keyword names are case insensitive.
250
+ with fits.open(self.data('test0.fits')) as r:
251
+ assert r['primary'].header['naxis'] == 0
252
+ assert r[0].header['naxis'] == 0
253
+
254
+ # If there are more than one extension with the same EXTNAME value,
255
+ # the EXTVER can be used (as the second argument) to distinguish
256
+ # the extension.
257
+ assert r['sci', 1].header['detector'] == 1
258
+
259
+ # append (using "update()") a new card
260
+ r[0].header['xxx'] = 1.234e56
261
+
262
+ assert ('\n'.join(str(x) for x in r[0].header.cards[-3:]) ==
263
+ "EXPFLAG = 'NORMAL ' / Exposure interruption indicator \n"
264
+ "FILENAME= 'vtest3.fits' / File name \n"
265
+ "XXX = 1.234E+56 ")
266
+
267
+ # rename a keyword
268
+ r[0].header.rename_keyword('filename', 'fname')
269
+ pytest.raises(ValueError, r[0].header.rename_keyword, 'fname',
270
+ 'history')
271
+
272
+ pytest.raises(ValueError, r[0].header.rename_keyword, 'fname',
273
+ 'simple')
274
+ r[0].header.rename_keyword('fname', 'filename')
275
+
276
+ # get a subsection of data
277
+ assert np.array_equal(r[2].data[:3, :3],
278
+ np.array([[349, 349, 348],
279
+ [349, 349, 347],
280
+ [347, 350, 349]], dtype=np.int16))
281
+
282
+ # We can create a new FITS file by opening a new file with "append"
283
+ # mode.
284
+ with fits.open(self.temp('test_new.fits'), mode='append') as n:
285
+ # Append the primary header and the 2nd extension to the new
286
+ # file.
287
+ n.append(r[0])
288
+ n.append(r[2])
289
+
290
+ # The flush method will write the current HDUList object back
291
+ # to the newly created file on disk. The HDUList is still open
292
+ # and can be further operated.
293
+ n.flush()
294
+ assert n[1].data[1, 1] == 349
295
+
296
+ # modify a data point
297
+ n[1].data[1, 1] = 99
298
+
299
+ # When the file is closed, the most recent additions of
300
+ # extension(s) since last flush() will be appended, but any HDU
301
+ # already existed at the last flush will not be modified
302
+ del n
303
+
304
+ # If an existing file is opened with "append" mode, like the
305
+ # readonly mode, the HDU's will be read into the HDUList which can
306
+ # be modified in memory but can not be written back to the original
307
+ # file. A file opened with append mode can only add new HDU's.
308
+ os.rename(self.temp('test_new.fits'),
309
+ self.temp('test_append.fits'))
310
+
311
+ with fits.open(self.temp('test_append.fits'), mode='append') as a:
312
+
313
+ # The above change did not take effect since this was made
314
+ # after the flush().
315
+ assert a[1].data[1, 1] == 349
316
+ a.append(r[1])
317
+ del a
318
+
319
+ # When changes are made to an HDUList which was opened with
320
+ # "update" mode, they will be written back to the original file
321
+ # when a flush/close is called.
322
+ os.rename(self.temp('test_append.fits'),
323
+ self.temp('test_update.fits'))
324
+
325
+ with fits.open(self.temp('test_update.fits'), mode='update') as u:
326
+
327
+ # When the changes do not alter the size structures of the
328
+ # original (or since last flush) HDUList, the changes are
329
+ # written back "in place".
330
+ assert u[0].header['rootname'] == 'U2EQ0201T'
331
+ u[0].header['rootname'] = 'abc'
332
+ assert u[1].data[1, 1] == 349
333
+ u[1].data[1, 1] = 99
334
+ u.flush()
335
+
336
+ # If the changes affect the size structure, e.g. adding or
337
+ # deleting HDU(s), header was expanded or reduced beyond
338
+ # existing number of blocks (2880 bytes in each block), or
339
+ # change the data size, the HDUList is written to a temporary
340
+ # file, the original file is deleted, and the temporary file is
341
+ # renamed to the original file name and reopened in the update
342
+ # mode. To a user, these two kinds of updating writeback seem
343
+ # to be the same, unless the optional argument in flush or
344
+ # close is set to 1.
345
+ del u[2]
346
+ u.flush()
347
+
348
+ # the write method in HDUList class writes the current HDUList,
349
+ # with all changes made up to now, to a new file. This method
350
+ # works the same disregard the mode the HDUList was opened
351
+ # with.
352
+ u.append(r[3])
353
+ u.writeto(self.temp('test_new.fits'))
354
+ del u
355
+
356
+ # Another useful new HDUList method is readall. It will "touch" the
357
+ # data parts in all HDUs, so even if the HDUList is closed, we can
358
+ # still operate on the data.
359
+ with fits.open(self.data('test0.fits')) as r:
360
+ r.readall()
361
+ assert r[1].data[1, 1] == 315
362
+
363
+ # create an HDU with data only
364
+ data = np.ones((3, 5), dtype=np.float32)
365
+ hdu = fits.ImageHDU(data=data, name='SCI')
366
+ assert np.array_equal(hdu.data,
367
+ np.array([[1., 1., 1., 1., 1.],
368
+ [1., 1., 1., 1., 1.],
369
+ [1., 1., 1., 1., 1.]],
370
+ dtype=np.float32))
371
+
372
+ # create an HDU with header and data
373
+ # notice that the header has the right NAXIS's since it is constructed
374
+ # with ImageHDU
375
+ hdu2 = fits.ImageHDU(header=r[1].header, data=np.array([1, 2],
376
+ dtype='int32'))
377
+
378
+ assert ('\n'.join(str(x) for x in hdu2.header.cards[1:5]) ==
379
+ "BITPIX = 32 / array data type \n"
380
+ "NAXIS = 1 / number of array dimensions \n"
381
+ "NAXIS1 = 2 \n"
382
+ "PCOUNT = 0 / number of parameters ")
383
+
384
+ def test_memory_mapping(self):
385
+ # memory mapping
386
+ f1 = fits.open(self.data('test0.fits'), memmap=1)
387
+ f1.close()
388
+
389
+ def test_verification_on_output(self):
390
+ # verification on output
391
+ # make a defect HDUList first
392
+ x = fits.ImageHDU()
393
+ hdu = fits.HDUList(x) # HDUList can take a list or one single HDU
394
+ with catch_warnings() as w:
395
+ hdu.verify()
396
+ text = "HDUList's 0th element is not a primary HDU."
397
+ assert len(w) == 3
398
+ assert text in str(w[1].message)
399
+
400
+ with catch_warnings() as w:
401
+ hdu.writeto(self.temp('test_new2.fits'), 'fix')
402
+ text = ("HDUList's 0th element is not a primary HDU. "
403
+ "Fixed by inserting one as 0th HDU.")
404
+ assert len(w) == 3
405
+ assert text in str(w[1].message)
406
+
407
+ def test_section(self):
408
+ # section testing
409
+ fs = fits.open(self.data('arange.fits'))
410
+ assert np.array_equal(fs[0].section[3, 2, 5], 357)
411
+ assert np.array_equal(
412
+ fs[0].section[3, 2, :],
413
+ np.array([352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362]))
414
+ assert np.array_equal(fs[0].section[3, 2, 4:],
415
+ np.array([356, 357, 358, 359, 360, 361, 362]))
416
+ assert np.array_equal(fs[0].section[3, 2, :8],
417
+ np.array([352, 353, 354, 355, 356, 357, 358, 359]))
418
+ assert np.array_equal(fs[0].section[3, 2, -8:8],
419
+ np.array([355, 356, 357, 358, 359]))
420
+ assert np.array_equal(
421
+ fs[0].section[3, 2:5, :],
422
+ np.array([[352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362],
423
+ [363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373],
424
+ [374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384]]))
425
+
426
+ assert np.array_equal(fs[0].section[3, :, :][:3, :3],
427
+ np.array([[330, 331, 332],
428
+ [341, 342, 343],
429
+ [352, 353, 354]]))
430
+
431
+ dat = fs[0].data
432
+ assert np.array_equal(fs[0].section[3, 2:5, :8], dat[3, 2:5, :8])
433
+ assert np.array_equal(fs[0].section[3, 2:5, 3], dat[3, 2:5, 3])
434
+
435
+ assert np.array_equal(fs[0].section[3:6, :, :][:3, :3, :3],
436
+ np.array([[[330, 331, 332],
437
+ [341, 342, 343],
438
+ [352, 353, 354]],
439
+ [[440, 441, 442],
440
+ [451, 452, 453],
441
+ [462, 463, 464]],
442
+ [[550, 551, 552],
443
+ [561, 562, 563],
444
+ [572, 573, 574]]]))
445
+
446
+ assert np.array_equal(fs[0].section[:, :, :][:3, :2, :2],
447
+ np.array([[[0, 1],
448
+ [11, 12]],
449
+ [[110, 111],
450
+ [121, 122]],
451
+ [[220, 221],
452
+ [231, 232]]]))
453
+
454
+ assert np.array_equal(fs[0].section[:, 2, :], dat[:, 2, :])
455
+ assert np.array_equal(fs[0].section[:, 2:5, :], dat[:, 2:5, :])
456
+ assert np.array_equal(fs[0].section[3:6, 3, :], dat[3:6, 3, :])
457
+ assert np.array_equal(fs[0].section[3:6, 3:7, :], dat[3:6, 3:7, :])
458
+
459
+ assert np.array_equal(fs[0].section[:, ::2], dat[:, ::2])
460
+ assert np.array_equal(fs[0].section[:, [1, 2, 4], 3],
461
+ dat[:, [1, 2, 4], 3])
462
+ bool_index = np.array([True, False, True, True, False,
463
+ False, True, True, False, True])
464
+ assert np.array_equal(fs[0].section[:, bool_index, :],
465
+ dat[:, bool_index, :])
466
+
467
+ assert np.array_equal(
468
+ fs[0].section[3:6, 3, :, ...], dat[3:6, 3, :, ...])
469
+ assert np.array_equal(fs[0].section[..., ::2], dat[..., ::2])
470
+ assert np.array_equal(fs[0].section[..., [1, 2, 4], 3],
471
+ dat[..., [1, 2, 4], 3])
472
+ fs.close()
473
+
474
+ def test_section_data_single(self):
475
+ a = np.array([1])
476
+ hdu = fits.PrimaryHDU(a)
477
+ hdu.writeto(self.temp('test_new.fits'))
478
+
479
+ hdul = fits.open(self.temp('test_new.fits'))
480
+ sec = hdul[0].section
481
+ dat = hdul[0].data
482
+ assert np.array_equal(sec[0], dat[0])
483
+ assert np.array_equal(sec[...], dat[...])
484
+ assert np.array_equal(sec[..., 0], dat[..., 0])
485
+ assert np.array_equal(sec[0, ...], dat[0, ...])
486
+ hdul.close()
487
+
488
+ def test_section_data_square(self):
489
+ a = np.arange(4).reshape(2, 2)
490
+ hdu = fits.PrimaryHDU(a)
491
+ hdu.writeto(self.temp('test_new.fits'))
492
+
493
+ hdul = fits.open(self.temp('test_new.fits'))
494
+ d = hdul[0]
495
+ dat = hdul[0].data
496
+ assert (d.section[:, :] == dat[:, :]).all()
497
+ assert (d.section[0, :] == dat[0, :]).all()
498
+ assert (d.section[1, :] == dat[1, :]).all()
499
+ assert (d.section[:, 0] == dat[:, 0]).all()
500
+ assert (d.section[:, 1] == dat[:, 1]).all()
501
+ assert (d.section[0, 0] == dat[0, 0]).all()
502
+ assert (d.section[0, 1] == dat[0, 1]).all()
503
+ assert (d.section[1, 0] == dat[1, 0]).all()
504
+ assert (d.section[1, 1] == dat[1, 1]).all()
505
+ assert (d.section[0:1, 0:1] == dat[0:1, 0:1]).all()
506
+ assert (d.section[0:2, 0:1] == dat[0:2, 0:1]).all()
507
+ assert (d.section[0:1, 0:2] == dat[0:1, 0:2]).all()
508
+ assert (d.section[0:2, 0:2] == dat[0:2, 0:2]).all()
509
+ hdul.close()
510
+
511
+ def test_section_data_cube(self):
512
+ a = np.arange(18).reshape(2, 3, 3)
513
+ hdu = fits.PrimaryHDU(a)
514
+ hdu.writeto(self.temp('test_new.fits'))
515
+
516
+ hdul = fits.open(self.temp('test_new.fits'))
517
+ d = hdul[0]
518
+ dat = hdul[0].data
519
+
520
+ # TODO: Generate these perumtions instead of having them all written
521
+ # out, yeesh!
522
+ assert (d.section[:, :, :] == dat[:, :, :]).all()
523
+ assert (d.section[:, :] == dat[:, :]).all()
524
+ assert (d.section[:] == dat[:]).all()
525
+ assert (d.section[0, :, :] == dat[0, :, :]).all()
526
+ assert (d.section[1, :, :] == dat[1, :, :]).all()
527
+ assert (d.section[0, 0, :] == dat[0, 0, :]).all()
528
+ assert (d.section[0, 1, :] == dat[0, 1, :]).all()
529
+ assert (d.section[0, 2, :] == dat[0, 2, :]).all()
530
+ assert (d.section[1, 0, :] == dat[1, 0, :]).all()
531
+ assert (d.section[1, 1, :] == dat[1, 1, :]).all()
532
+ assert (d.section[1, 2, :] == dat[1, 2, :]).all()
533
+ assert (d.section[0, 0, 0] == dat[0, 0, 0]).all()
534
+ assert (d.section[0, 0, 1] == dat[0, 0, 1]).all()
535
+ assert (d.section[0, 0, 2] == dat[0, 0, 2]).all()
536
+ assert (d.section[0, 1, 0] == dat[0, 1, 0]).all()
537
+ assert (d.section[0, 1, 1] == dat[0, 1, 1]).all()
538
+ assert (d.section[0, 1, 2] == dat[0, 1, 2]).all()
539
+ assert (d.section[0, 2, 0] == dat[0, 2, 0]).all()
540
+ assert (d.section[0, 2, 1] == dat[0, 2, 1]).all()
541
+ assert (d.section[0, 2, 2] == dat[0, 2, 2]).all()
542
+ assert (d.section[1, 0, 0] == dat[1, 0, 0]).all()
543
+ assert (d.section[1, 0, 1] == dat[1, 0, 1]).all()
544
+ assert (d.section[1, 0, 2] == dat[1, 0, 2]).all()
545
+ assert (d.section[1, 1, 0] == dat[1, 1, 0]).all()
546
+ assert (d.section[1, 1, 1] == dat[1, 1, 1]).all()
547
+ assert (d.section[1, 1, 2] == dat[1, 1, 2]).all()
548
+ assert (d.section[1, 2, 0] == dat[1, 2, 0]).all()
549
+ assert (d.section[1, 2, 1] == dat[1, 2, 1]).all()
550
+ assert (d.section[1, 2, 2] == dat[1, 2, 2]).all()
551
+ assert (d.section[:, 0, 0] == dat[:, 0, 0]).all()
552
+ assert (d.section[:, 0, 1] == dat[:, 0, 1]).all()
553
+ assert (d.section[:, 0, 2] == dat[:, 0, 2]).all()
554
+ assert (d.section[:, 1, 0] == dat[:, 1, 0]).all()
555
+ assert (d.section[:, 1, 1] == dat[:, 1, 1]).all()
556
+ assert (d.section[:, 1, 2] == dat[:, 1, 2]).all()
557
+ assert (d.section[:, 2, 0] == dat[:, 2, 0]).all()
558
+ assert (d.section[:, 2, 1] == dat[:, 2, 1]).all()
559
+ assert (d.section[:, 2, 2] == dat[:, 2, 2]).all()
560
+ assert (d.section[0, :, 0] == dat[0, :, 0]).all()
561
+ assert (d.section[0, :, 1] == dat[0, :, 1]).all()
562
+ assert (d.section[0, :, 2] == dat[0, :, 2]).all()
563
+ assert (d.section[1, :, 0] == dat[1, :, 0]).all()
564
+ assert (d.section[1, :, 1] == dat[1, :, 1]).all()
565
+ assert (d.section[1, :, 2] == dat[1, :, 2]).all()
566
+ assert (d.section[:, :, 0] == dat[:, :, 0]).all()
567
+ assert (d.section[:, :, 1] == dat[:, :, 1]).all()
568
+ assert (d.section[:, :, 2] == dat[:, :, 2]).all()
569
+ assert (d.section[:, 0, :] == dat[:, 0, :]).all()
570
+ assert (d.section[:, 1, :] == dat[:, 1, :]).all()
571
+ assert (d.section[:, 2, :] == dat[:, 2, :]).all()
572
+
573
+ assert (d.section[:, :, 0:1] == dat[:, :, 0:1]).all()
574
+ assert (d.section[:, :, 0:2] == dat[:, :, 0:2]).all()
575
+ assert (d.section[:, :, 0:3] == dat[:, :, 0:3]).all()
576
+ assert (d.section[:, :, 1:2] == dat[:, :, 1:2]).all()
577
+ assert (d.section[:, :, 1:3] == dat[:, :, 1:3]).all()
578
+ assert (d.section[:, :, 2:3] == dat[:, :, 2:3]).all()
579
+ assert (d.section[0:1, 0:1, 0:1] == dat[0:1, 0:1, 0:1]).all()
580
+ assert (d.section[0:1, 0:1, 0:2] == dat[0:1, 0:1, 0:2]).all()
581
+ assert (d.section[0:1, 0:1, 0:3] == dat[0:1, 0:1, 0:3]).all()
582
+ assert (d.section[0:1, 0:1, 1:2] == dat[0:1, 0:1, 1:2]).all()
583
+ assert (d.section[0:1, 0:1, 1:3] == dat[0:1, 0:1, 1:3]).all()
584
+ assert (d.section[0:1, 0:1, 2:3] == dat[0:1, 0:1, 2:3]).all()
585
+ assert (d.section[0:1, 0:2, 0:1] == dat[0:1, 0:2, 0:1]).all()
586
+ assert (d.section[0:1, 0:2, 0:2] == dat[0:1, 0:2, 0:2]).all()
587
+ assert (d.section[0:1, 0:2, 0:3] == dat[0:1, 0:2, 0:3]).all()
588
+ assert (d.section[0:1, 0:2, 1:2] == dat[0:1, 0:2, 1:2]).all()
589
+ assert (d.section[0:1, 0:2, 1:3] == dat[0:1, 0:2, 1:3]).all()
590
+ assert (d.section[0:1, 0:2, 2:3] == dat[0:1, 0:2, 2:3]).all()
591
+ assert (d.section[0:1, 0:3, 0:1] == dat[0:1, 0:3, 0:1]).all()
592
+ assert (d.section[0:1, 0:3, 0:2] == dat[0:1, 0:3, 0:2]).all()
593
+ assert (d.section[0:1, 0:3, 0:3] == dat[0:1, 0:3, 0:3]).all()
594
+ assert (d.section[0:1, 0:3, 1:2] == dat[0:1, 0:3, 1:2]).all()
595
+ assert (d.section[0:1, 0:3, 1:3] == dat[0:1, 0:3, 1:3]).all()
596
+ assert (d.section[0:1, 0:3, 2:3] == dat[0:1, 0:3, 2:3]).all()
597
+ assert (d.section[0:1, 1:2, 0:1] == dat[0:1, 1:2, 0:1]).all()
598
+ assert (d.section[0:1, 1:2, 0:2] == dat[0:1, 1:2, 0:2]).all()
599
+ assert (d.section[0:1, 1:2, 0:3] == dat[0:1, 1:2, 0:3]).all()
600
+ assert (d.section[0:1, 1:2, 1:2] == dat[0:1, 1:2, 1:2]).all()
601
+ assert (d.section[0:1, 1:2, 1:3] == dat[0:1, 1:2, 1:3]).all()
602
+ assert (d.section[0:1, 1:2, 2:3] == dat[0:1, 1:2, 2:3]).all()
603
+ assert (d.section[0:1, 1:3, 0:1] == dat[0:1, 1:3, 0:1]).all()
604
+ assert (d.section[0:1, 1:3, 0:2] == dat[0:1, 1:3, 0:2]).all()
605
+ assert (d.section[0:1, 1:3, 0:3] == dat[0:1, 1:3, 0:3]).all()
606
+ assert (d.section[0:1, 1:3, 1:2] == dat[0:1, 1:3, 1:2]).all()
607
+ assert (d.section[0:1, 1:3, 1:3] == dat[0:1, 1:3, 1:3]).all()
608
+ assert (d.section[0:1, 1:3, 2:3] == dat[0:1, 1:3, 2:3]).all()
609
+ assert (d.section[1:2, 0:1, 0:1] == dat[1:2, 0:1, 0:1]).all()
610
+ assert (d.section[1:2, 0:1, 0:2] == dat[1:2, 0:1, 0:2]).all()
611
+ assert (d.section[1:2, 0:1, 0:3] == dat[1:2, 0:1, 0:3]).all()
612
+ assert (d.section[1:2, 0:1, 1:2] == dat[1:2, 0:1, 1:2]).all()
613
+ assert (d.section[1:2, 0:1, 1:3] == dat[1:2, 0:1, 1:3]).all()
614
+ assert (d.section[1:2, 0:1, 2:3] == dat[1:2, 0:1, 2:3]).all()
615
+ assert (d.section[1:2, 0:2, 0:1] == dat[1:2, 0:2, 0:1]).all()
616
+ assert (d.section[1:2, 0:2, 0:2] == dat[1:2, 0:2, 0:2]).all()
617
+ assert (d.section[1:2, 0:2, 0:3] == dat[1:2, 0:2, 0:3]).all()
618
+ assert (d.section[1:2, 0:2, 1:2] == dat[1:2, 0:2, 1:2]).all()
619
+ assert (d.section[1:2, 0:2, 1:3] == dat[1:2, 0:2, 1:3]).all()
620
+ assert (d.section[1:2, 0:2, 2:3] == dat[1:2, 0:2, 2:3]).all()
621
+ assert (d.section[1:2, 0:3, 0:1] == dat[1:2, 0:3, 0:1]).all()
622
+ assert (d.section[1:2, 0:3, 0:2] == dat[1:2, 0:3, 0:2]).all()
623
+ assert (d.section[1:2, 0:3, 0:3] == dat[1:2, 0:3, 0:3]).all()
624
+ assert (d.section[1:2, 0:3, 1:2] == dat[1:2, 0:3, 1:2]).all()
625
+ assert (d.section[1:2, 0:3, 1:3] == dat[1:2, 0:3, 1:3]).all()
626
+ assert (d.section[1:2, 0:3, 2:3] == dat[1:2, 0:3, 2:3]).all()
627
+ assert (d.section[1:2, 1:2, 0:1] == dat[1:2, 1:2, 0:1]).all()
628
+ assert (d.section[1:2, 1:2, 0:2] == dat[1:2, 1:2, 0:2]).all()
629
+ assert (d.section[1:2, 1:2, 0:3] == dat[1:2, 1:2, 0:3]).all()
630
+ assert (d.section[1:2, 1:2, 1:2] == dat[1:2, 1:2, 1:2]).all()
631
+ assert (d.section[1:2, 1:2, 1:3] == dat[1:2, 1:2, 1:3]).all()
632
+ assert (d.section[1:2, 1:2, 2:3] == dat[1:2, 1:2, 2:3]).all()
633
+ assert (d.section[1:2, 1:3, 0:1] == dat[1:2, 1:3, 0:1]).all()
634
+ assert (d.section[1:2, 1:3, 0:2] == dat[1:2, 1:3, 0:2]).all()
635
+ assert (d.section[1:2, 1:3, 0:3] == dat[1:2, 1:3, 0:3]).all()
636
+ assert (d.section[1:2, 1:3, 1:2] == dat[1:2, 1:3, 1:2]).all()
637
+ assert (d.section[1:2, 1:3, 1:3] == dat[1:2, 1:3, 1:3]).all()
638
+ assert (d.section[1:2, 1:3, 2:3] == dat[1:2, 1:3, 2:3]).all()
639
+ hdul.close()
640
+
641
+ def test_section_data_four(self):
642
+ a = np.arange(256).reshape(4, 4, 4, 4)
643
+ hdu = fits.PrimaryHDU(a)
644
+ hdu.writeto(self.temp('test_new.fits'))
645
+
646
+ hdul = fits.open(self.temp('test_new.fits'))
647
+ d = hdul[0]
648
+ dat = hdul[0].data
649
+ assert (d.section[:, :, :, :] == dat[:, :, :, :]).all()
650
+ assert (d.section[:, :, :] == dat[:, :, :]).all()
651
+ assert (d.section[:, :] == dat[:, :]).all()
652
+ assert (d.section[:] == dat[:]).all()
653
+ assert (d.section[0, :, :, :] == dat[0, :, :, :]).all()
654
+ assert (d.section[0, :, 0, :] == dat[0, :, 0, :]).all()
655
+ assert (d.section[:, :, 0, :] == dat[:, :, 0, :]).all()
656
+ assert (d.section[:, 1, 0, :] == dat[:, 1, 0, :]).all()
657
+ assert (d.section[:, :, :, 1] == dat[:, :, :, 1]).all()
658
+ hdul.close()
659
+
660
+ def test_section_data_scaled(self):
661
+ """
662
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/143
663
+
664
+ This is like test_section_data_square but uses a file containing scaled
665
+ image data, to test that sections can work correctly with scaled data.
666
+ """
667
+
668
+ hdul = fits.open(self.data('scale.fits'))
669
+ d = hdul[0]
670
+ dat = hdul[0].data
671
+ assert (d.section[:, :] == dat[:, :]).all()
672
+ assert (d.section[0, :] == dat[0, :]).all()
673
+ assert (d.section[1, :] == dat[1, :]).all()
674
+ assert (d.section[:, 0] == dat[:, 0]).all()
675
+ assert (d.section[:, 1] == dat[:, 1]).all()
676
+ assert (d.section[0, 0] == dat[0, 0]).all()
677
+ assert (d.section[0, 1] == dat[0, 1]).all()
678
+ assert (d.section[1, 0] == dat[1, 0]).all()
679
+ assert (d.section[1, 1] == dat[1, 1]).all()
680
+ assert (d.section[0:1, 0:1] == dat[0:1, 0:1]).all()
681
+ assert (d.section[0:2, 0:1] == dat[0:2, 0:1]).all()
682
+ assert (d.section[0:1, 0:2] == dat[0:1, 0:2]).all()
683
+ assert (d.section[0:2, 0:2] == dat[0:2, 0:2]).all()
684
+ hdul.close()
685
+
686
+ # Test without having accessed the full data first
687
+ hdul = fits.open(self.data('scale.fits'))
688
+ d = hdul[0]
689
+ assert (d.section[:, :] == dat[:, :]).all()
690
+ assert (d.section[0, :] == dat[0, :]).all()
691
+ assert (d.section[1, :] == dat[1, :]).all()
692
+ assert (d.section[:, 0] == dat[:, 0]).all()
693
+ assert (d.section[:, 1] == dat[:, 1]).all()
694
+ assert (d.section[0, 0] == dat[0, 0]).all()
695
+ assert (d.section[0, 1] == dat[0, 1]).all()
696
+ assert (d.section[1, 0] == dat[1, 0]).all()
697
+ assert (d.section[1, 1] == dat[1, 1]).all()
698
+ assert (d.section[0:1, 0:1] == dat[0:1, 0:1]).all()
699
+ assert (d.section[0:2, 0:1] == dat[0:2, 0:1]).all()
700
+ assert (d.section[0:1, 0:2] == dat[0:1, 0:2]).all()
701
+ assert (d.section[0:2, 0:2] == dat[0:2, 0:2]).all()
702
+ assert not d._data_loaded
703
+ hdul.close()
704
+
705
+ def test_do_not_scale_image_data(self):
706
+ with fits.open(self.data('scale.fits'), do_not_scale_image_data=True) as hdul:
707
+ assert hdul[0].data.dtype == np.dtype('>i2')
708
+
709
+ with fits.open(self.data('scale.fits')) as hdul:
710
+ assert hdul[0].data.dtype == np.dtype('float32')
711
+
712
+ def test_append_uint_data(self):
713
+ """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/56
714
+ (BZERO and BSCALE added in the wrong location when appending scaled
715
+ data)
716
+ """
717
+
718
+ fits.writeto(self.temp('test_new.fits'), data=np.array([],
719
+ dtype='uint8'))
720
+ d = np.zeros([100, 100]).astype('uint16')
721
+ fits.append(self.temp('test_new.fits'), data=d)
722
+
723
+ with fits.open(self.temp('test_new.fits'), uint=True) as f:
724
+ assert f[1].data.dtype == 'uint16'
725
+
726
+ def test_scale_with_explicit_bzero_bscale(self):
727
+ """
728
+ Regression test for https://github.com/astropy/astropy/issues/6399
729
+ """
730
+ hdu1 = fits.PrimaryHDU()
731
+ hdu2 = fits.ImageHDU(np.random.rand(100,100))
732
+ # The line below raised an exception in astropy 2.0, so if it does not
733
+ # raise an error here, that is progress.
734
+ hdu2.scale(type='uint8', bscale=1, bzero=0)
735
+
736
+ def test_uint_header_consistency(self):
737
+ """
738
+ Regression test for https://github.com/astropy/astropy/issues/2305
739
+
740
+ This ensures that an HDU containing unsigned integer data always has
741
+ the apppriate BZERO value in its header.
742
+ """
743
+
744
+ for int_size in (16, 32, 64):
745
+ # Just make an array of some unsigned ints that wouldn't fit in a
746
+ # signed int array of the same bit width
747
+ max_uint = (2 ** int_size) - 1
748
+ if int_size == 64:
749
+ max_uint = np.uint64(int_size)
750
+
751
+ dtype = 'uint{}'.format(int_size)
752
+ arr = np.empty(100, dtype=dtype)
753
+ arr.fill(max_uint)
754
+ arr -= np.arange(100, dtype=dtype)
755
+
756
+ uint_hdu = fits.PrimaryHDU(data=arr)
757
+ assert np.all(uint_hdu.data == arr)
758
+ assert uint_hdu.data.dtype.name == 'uint{}'.format(int_size)
759
+ assert 'BZERO' in uint_hdu.header
760
+ assert uint_hdu.header['BZERO'] == (2 ** (int_size - 1))
761
+
762
+ filename = 'uint{}.fits'.format(int_size)
763
+ uint_hdu.writeto(self.temp(filename))
764
+
765
+ with fits.open(self.temp(filename), uint=True) as hdul:
766
+ new_uint_hdu = hdul[0]
767
+ assert np.all(new_uint_hdu.data == arr)
768
+ assert new_uint_hdu.data.dtype.name == 'uint{}'.format(int_size)
769
+ assert 'BZERO' in new_uint_hdu.header
770
+ assert new_uint_hdu.header['BZERO'] == (2 ** (int_size - 1))
771
+
772
+ @pytest.mark.parametrize(('from_file'), (False, True))
773
+ @pytest.mark.parametrize(('do_not_scale'), (False,))
774
+ def test_uint_header_keywords_removed_after_bitpix_change(self,
775
+ from_file,
776
+ do_not_scale):
777
+ """
778
+ Regression test for https://github.com/astropy/astropy/issues/4974
779
+
780
+ BZERO/BSCALE should be removed if data is converted to a floating
781
+ point type.
782
+
783
+ Currently excluding the case where do_not_scale_image_data=True
784
+ because it is not clear what the expectation should be.
785
+ """
786
+
787
+ arr = np.zeros(100, dtype='uint16')
788
+
789
+ if from_file:
790
+ # To generate the proper input file we always want to scale the
791
+ # data before writing it...otherwise when we open it will be
792
+ # regular (signed) int data.
793
+ tmp_uint = fits.PrimaryHDU(arr)
794
+ filename = 'unsigned_int.fits'
795
+ tmp_uint.writeto(self.temp(filename))
796
+ with fits.open(self.temp(filename),
797
+ do_not_scale_image_data=do_not_scale) as f:
798
+ uint_hdu = f[0]
799
+ # Force a read before we close.
800
+ _ = uint_hdu.data
801
+ else:
802
+ uint_hdu = fits.PrimaryHDU(arr,
803
+ do_not_scale_image_data=do_not_scale)
804
+
805
+ # Make sure appropriate keywords are in the header. See
806
+ # https://github.com/astropy/astropy/pull/3916#issuecomment-122414532
807
+ # for discussion.
808
+ assert 'BSCALE' in uint_hdu.header
809
+ assert 'BZERO' in uint_hdu.header
810
+ assert uint_hdu.header['BSCALE'] == 1
811
+ assert uint_hdu.header['BZERO'] == 32768
812
+
813
+ # Convert data to floating point...
814
+ uint_hdu.data = uint_hdu.data * 1.0
815
+
816
+ # ...bitpix should be negative.
817
+ assert uint_hdu.header['BITPIX'] < 0
818
+
819
+ # BSCALE and BZERO should NOT be in header any more.
820
+ assert 'BSCALE' not in uint_hdu.header
821
+ assert 'BZERO' not in uint_hdu.header
822
+
823
+ # This is the main test...the data values should round trip
824
+ # as zero.
825
+ filename = 'test_uint_to_float.fits'
826
+ uint_hdu.writeto(self.temp(filename))
827
+ with fits.open(self.temp(filename)) as hdul:
828
+ assert (hdul[0].data == 0).all()
829
+
830
+ def test_blanks(self):
831
+ """Test image data with blank spots in it (which should show up as
832
+ NaNs in the data array.
833
+ """
834
+
835
+ arr = np.zeros((10, 10), dtype=np.int32)
836
+ # One row will be blanks
837
+ arr[1] = 999
838
+ hdu = fits.ImageHDU(data=arr)
839
+ hdu.header['BLANK'] = 999
840
+ hdu.writeto(self.temp('test_new.fits'))
841
+
842
+ with fits.open(self.temp('test_new.fits')) as hdul:
843
+ assert np.isnan(hdul[1].data[1]).all()
844
+
845
+ def test_invalid_blanks(self):
846
+ """
847
+ Test that invalid use of the BLANK keyword leads to an appropriate
848
+ warning, and that the BLANK keyword is ignored when returning the
849
+ HDU data.
850
+
851
+ Regression test for https://github.com/astropy/astropy/issues/3865
852
+ """
853
+
854
+ arr = np.arange(5, dtype=np.float64)
855
+ hdu = fits.PrimaryHDU(data=arr)
856
+ hdu.header['BLANK'] = 2
857
+
858
+ with catch_warnings() as w:
859
+ hdu.writeto(self.temp('test_new.fits'))
860
+ # Allow the HDU to be written, but there should be a warning
861
+ # when writing a header with BLANK when then data is not
862
+ # int
863
+ assert len(w) == 1
864
+ assert "Invalid 'BLANK' keyword in header" in str(w[0].message)
865
+
866
+ # Should also get a warning when opening the file, and the BLANK
867
+ # value should not be applied
868
+ with catch_warnings() as w:
869
+ with fits.open(self.temp('test_new.fits')) as h:
870
+ assert len(w) == 1
871
+ assert "Invalid 'BLANK' keyword in header" in str(w[0].message)
872
+ assert np.all(arr == h[0].data)
873
+
874
+ def test_scale_back_with_blanks(self):
875
+ """
876
+ Test that when auto-rescaling integer data with "blank" values (where
877
+ the blanks are replaced by NaN in the float data), that the "BLANK"
878
+ keyword is removed from the header.
879
+
880
+ Further, test that when using the ``scale_back=True`` option the blank
881
+ values are restored properly.
882
+
883
+ Regression test for https://github.com/astropy/astropy/issues/3865
884
+ """
885
+
886
+ # Make the sample file
887
+ arr = np.arange(5, dtype=np.int32)
888
+ hdu = fits.PrimaryHDU(data=arr)
889
+ hdu.scale('int16', bscale=1.23)
890
+
891
+ # Creating data that uses BLANK is currently kludgy--a separate issue
892
+ # TODO: Rewrite this test when scaling with blank support is better
893
+ # supported
894
+
895
+ # Let's just add a value to the data that should be converted to NaN
896
+ # when it is read back in:
897
+ filename = self.temp('test.fits')
898
+ hdu.data[0] = 9999
899
+ hdu.header['BLANK'] = 9999
900
+ hdu.writeto(filename)
901
+
902
+ with fits.open(filename) as hdul:
903
+ data = hdul[0].data
904
+ assert np.isnan(data[0])
905
+ with pytest.warns(fits.verify.VerifyWarning,
906
+ match="Invalid 'BLANK' keyword in header"):
907
+ hdul.writeto(self.temp('test2.fits'))
908
+
909
+ # Now reopen the newly written file. It should not have a 'BLANK'
910
+ # keyword
911
+ with catch_warnings() as w:
912
+ with fits.open(self.temp('test2.fits')) as hdul2:
913
+ assert len(w) == 0
914
+ assert 'BLANK' not in hdul2[0].header
915
+ data = hdul2[0].data
916
+ assert np.isnan(data[0])
917
+
918
+ # Finally, test that scale_back keeps the BLANKs correctly
919
+ with fits.open(filename, scale_back=True,
920
+ mode='update') as hdul3:
921
+ data = hdul3[0].data
922
+ assert np.isnan(data[0])
923
+
924
+ with fits.open(filename,
925
+ do_not_scale_image_data=True) as hdul4:
926
+ assert hdul4[0].header['BLANK'] == 9999
927
+ assert hdul4[0].header['BSCALE'] == 1.23
928
+ assert hdul4[0].data[0] == 9999
929
+
930
+ def test_bzero_with_floats(self):
931
+ """Test use of the BZERO keyword in an image HDU containing float
932
+ data.
933
+ """
934
+
935
+ arr = np.zeros((10, 10)) - 1
936
+ hdu = fits.ImageHDU(data=arr)
937
+ hdu.header['BZERO'] = 1.0
938
+ hdu.writeto(self.temp('test_new.fits'))
939
+
940
+ with fits.open(self.temp('test_new.fits')) as hdul:
941
+ arr += 1
942
+ assert (hdul[1].data == arr).all()
943
+
944
+ def test_rewriting_large_scaled_image(self):
945
+ """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/84 and
946
+ https://aeon.stsci.edu/ssb/trac/pyfits/ticket/101
947
+ """
948
+
949
+ hdul = fits.open(self.data('fixed-1890.fits'))
950
+ orig_data = hdul[0].data
951
+ with ignore_warnings():
952
+ hdul.writeto(self.temp('test_new.fits'), overwrite=True)
953
+ hdul.close()
954
+ hdul = fits.open(self.temp('test_new.fits'))
955
+ assert (hdul[0].data == orig_data).all()
956
+ hdul.close()
957
+
958
+ # Just as before, but this time don't touch hdul[0].data before writing
959
+ # back out--this is the case that failed in
960
+ # https://aeon.stsci.edu/ssb/trac/pyfits/ticket/84
961
+ hdul = fits.open(self.data('fixed-1890.fits'))
962
+ with ignore_warnings():
963
+ hdul.writeto(self.temp('test_new.fits'), overwrite=True)
964
+ hdul.close()
965
+ hdul = fits.open(self.temp('test_new.fits'))
966
+ assert (hdul[0].data == orig_data).all()
967
+ hdul.close()
968
+
969
+ # Test opening/closing/reopening a scaled file in update mode
970
+ hdul = fits.open(self.data('fixed-1890.fits'),
971
+ do_not_scale_image_data=True)
972
+ hdul.writeto(self.temp('test_new.fits'), overwrite=True,
973
+ output_verify='silentfix')
974
+ hdul.close()
975
+ hdul = fits.open(self.temp('test_new.fits'))
976
+ orig_data = hdul[0].data
977
+ hdul.close()
978
+ hdul = fits.open(self.temp('test_new.fits'), mode='update')
979
+ hdul.close()
980
+ hdul = fits.open(self.temp('test_new.fits'))
981
+ assert (hdul[0].data == orig_data).all()
982
+ hdul = fits.open(self.temp('test_new.fits'))
983
+ hdul.close()
984
+
985
+ def test_image_update_header(self):
986
+ """
987
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/105
988
+
989
+ Replacing the original header to an image HDU and saving should update
990
+ the NAXISn keywords appropriately and save the image data correctly.
991
+ """
992
+
993
+ # Copy the original file before saving to it
994
+ self.copy_file('test0.fits')
995
+ with fits.open(self.temp('test0.fits'), mode='update') as hdul:
996
+ orig_data = hdul[1].data.copy()
997
+ hdr_copy = hdul[1].header.copy()
998
+ del hdr_copy['NAXIS*']
999
+ hdul[1].header = hdr_copy
1000
+
1001
+ with fits.open(self.temp('test0.fits')) as hdul:
1002
+ assert (orig_data == hdul[1].data).all()
1003
+
1004
+ def test_open_scaled_in_update_mode(self):
1005
+ """
1006
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/119
1007
+ (Don't update scaled image data if the data is not read)
1008
+
1009
+ This ensures that merely opening and closing a file containing scaled
1010
+ image data does not cause any change to the data (or the header).
1011
+ Changes should only occur if the data is accessed.
1012
+ """
1013
+
1014
+ # Copy the original file before making any possible changes to it
1015
+ self.copy_file('scale.fits')
1016
+ mtime = os.stat(self.temp('scale.fits')).st_mtime
1017
+
1018
+ time.sleep(1)
1019
+
1020
+ fits.open(self.temp('scale.fits'), mode='update').close()
1021
+
1022
+ # Ensure that no changes were made to the file merely by immediately
1023
+ # opening and closing it.
1024
+ assert mtime == os.stat(self.temp('scale.fits')).st_mtime
1025
+
1026
+ # Insert a slight delay to ensure the mtime does change when the file
1027
+ # is changed
1028
+ time.sleep(1)
1029
+
1030
+ hdul = fits.open(self.temp('scale.fits'), 'update')
1031
+ orig_data = hdul[0].data
1032
+ hdul.close()
1033
+
1034
+ # Now the file should be updated with the rescaled data
1035
+ assert mtime != os.stat(self.temp('scale.fits')).st_mtime
1036
+ hdul = fits.open(self.temp('scale.fits'), mode='update')
1037
+ assert hdul[0].data.dtype == np.dtype('>f4')
1038
+ assert hdul[0].header['BITPIX'] == -32
1039
+ assert 'BZERO' not in hdul[0].header
1040
+ assert 'BSCALE' not in hdul[0].header
1041
+ assert (orig_data == hdul[0].data).all()
1042
+
1043
+ # Try reshaping the data, then closing and reopening the file; let's
1044
+ # see if all the changes are preseved properly
1045
+ hdul[0].data.shape = (42, 10)
1046
+ hdul.close()
1047
+
1048
+ hdul = fits.open(self.temp('scale.fits'))
1049
+ assert hdul[0].shape == (42, 10)
1050
+ assert hdul[0].data.dtype == np.dtype('>f4')
1051
+ assert hdul[0].header['BITPIX'] == -32
1052
+ assert 'BZERO' not in hdul[0].header
1053
+ assert 'BSCALE' not in hdul[0].header
1054
+ hdul.close()
1055
+
1056
+ def test_scale_back(self):
1057
+ """A simple test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/120
1058
+
1059
+ The scale_back feature for image HDUs.
1060
+ """
1061
+
1062
+ self.copy_file('scale.fits')
1063
+ with fits.open(self.temp('scale.fits'), mode='update',
1064
+ scale_back=True) as hdul:
1065
+ orig_bitpix = hdul[0].header['BITPIX']
1066
+ orig_bzero = hdul[0].header['BZERO']
1067
+ orig_bscale = hdul[0].header['BSCALE']
1068
+ orig_data = hdul[0].data.copy()
1069
+ hdul[0].data[0] = 0
1070
+
1071
+ with fits.open(self.temp('scale.fits'),
1072
+ do_not_scale_image_data=True) as hdul:
1073
+ assert hdul[0].header['BITPIX'] == orig_bitpix
1074
+ assert hdul[0].header['BZERO'] == orig_bzero
1075
+ assert hdul[0].header['BSCALE'] == orig_bscale
1076
+
1077
+ zero_point = int(math.floor(-orig_bzero / orig_bscale))
1078
+ assert (hdul[0].data[0] == zero_point).all()
1079
+
1080
+ with fits.open(self.temp('scale.fits')) as hdul:
1081
+ assert (hdul[0].data[1:] == orig_data[1:]).all()
1082
+
1083
+ def test_image_none(self):
1084
+ """
1085
+ Regression test for https://github.com/spacetelescope/PyFITS/issues/27
1086
+ """
1087
+
1088
+ with fits.open(self.data('test0.fits')) as h:
1089
+ h[1].data
1090
+ h[1].data = None
1091
+ h[1].writeto(self.temp('test.fits'))
1092
+
1093
+ with fits.open(self.temp('test.fits')) as h:
1094
+ assert h[1].data is None
1095
+ assert h[1].header['NAXIS'] == 0
1096
+ assert 'NAXIS1' not in h[1].header
1097
+ assert 'NAXIS2' not in h[1].header
1098
+
1099
+ def test_invalid_blank(self):
1100
+ """
1101
+ Regression test for https://github.com/astropy/astropy/issues/2711
1102
+
1103
+ If the BLANK keyword contains an invalid value it should be ignored for
1104
+ any calculations (though a warning should be issued).
1105
+ """
1106
+
1107
+ data = np.arange(100, dtype=np.float64)
1108
+ hdu = fits.PrimaryHDU(data)
1109
+ hdu.header['BLANK'] = 'nan'
1110
+ with pytest.warns(fits.verify.VerifyWarning, match="Invalid value for "
1111
+ "'BLANK' keyword in header: 'nan'"):
1112
+ hdu.writeto(self.temp('test.fits'))
1113
+
1114
+ with catch_warnings() as w:
1115
+ with fits.open(self.temp('test.fits')) as hdul:
1116
+ assert np.all(hdul[0].data == data)
1117
+
1118
+ assert len(w) == 2
1119
+ msg = "Invalid value for 'BLANK' keyword in header"
1120
+ assert msg in str(w[0].message)
1121
+ msg = "Invalid 'BLANK' keyword"
1122
+ assert msg in str(w[1].message)
1123
+
1124
+ def test_scaled_image_fromfile(self):
1125
+ """
1126
+ Regression test for https://github.com/astropy/astropy/issues/2710
1127
+ """
1128
+
1129
+ # Make some sample data
1130
+ a = np.arange(100, dtype=np.float32)
1131
+
1132
+ hdu = fits.PrimaryHDU(data=a.copy())
1133
+ hdu.scale(bscale=1.1)
1134
+ hdu.writeto(self.temp('test.fits'))
1135
+
1136
+ with open(self.temp('test.fits'), 'rb') as f:
1137
+ file_data = f.read()
1138
+
1139
+ hdul = fits.HDUList.fromstring(file_data)
1140
+ assert np.allclose(hdul[0].data, a)
1141
+
1142
+ def test_set_data(self):
1143
+ """
1144
+ Test data assignment - issue #5087
1145
+ """
1146
+
1147
+ im = fits.ImageHDU()
1148
+ ar = np.arange(12)
1149
+ im.data = ar
1150
+
1151
+ def test_scale_bzero_with_int_data(self):
1152
+ """
1153
+ Regression test for https://github.com/astropy/astropy/issues/4600
1154
+ """
1155
+
1156
+ a = np.arange(100, 200, dtype=np.int16)
1157
+
1158
+ hdu1 = fits.PrimaryHDU(data=a.copy())
1159
+ hdu2 = fits.PrimaryHDU(data=a.copy())
1160
+ # Previously the following line would throw a TypeError,
1161
+ # now it should be identical to the integer bzero case
1162
+ hdu1.scale('int16', bzero=99.0)
1163
+ hdu2.scale('int16', bzero=99)
1164
+ assert np.allclose(hdu1.data, hdu2.data)
1165
+
1166
+ def test_scale_back_uint_assignment(self):
1167
+ """
1168
+ Extend fix for #4600 to assignment to data
1169
+
1170
+ Suggested by:
1171
+ https://github.com/astropy/astropy/pull/4602#issuecomment-208713748
1172
+ """
1173
+
1174
+ a = np.arange(100, 200, dtype=np.uint16)
1175
+ fits.PrimaryHDU(a).writeto(self.temp('test.fits'))
1176
+ with fits.open(self.temp('test.fits'), mode="update",
1177
+ scale_back=True) as (hdu,):
1178
+ hdu.data[:] = 0
1179
+ assert np.allclose(hdu.data, 0)
1180
+
1181
+
1182
+ class TestCompressedImage(FitsTestCase):
1183
+ def test_empty(self):
1184
+ """
1185
+ Regression test for https://github.com/astropy/astropy/issues/2595
1186
+ """
1187
+
1188
+ hdu = fits.CompImageHDU()
1189
+ assert hdu.data is None
1190
+ hdu.writeto(self.temp('test.fits'))
1191
+
1192
+ with fits.open(self.temp('test.fits'), mode='update') as hdul:
1193
+ assert len(hdul) == 2
1194
+ assert isinstance(hdul[1], fits.CompImageHDU)
1195
+ assert hdul[1].data is None
1196
+
1197
+ # Now test replacing the empty data with an array and see what
1198
+ # happens
1199
+ hdul[1].data = np.arange(100, dtype=np.int32)
1200
+
1201
+ with fits.open(self.temp('test.fits')) as hdul:
1202
+ assert len(hdul) == 2
1203
+ assert isinstance(hdul[1], fits.CompImageHDU)
1204
+ assert np.all(hdul[1].data == np.arange(100, dtype=np.int32))
1205
+
1206
+ @pytest.mark.parametrize(
1207
+ ('data', 'compression_type', 'quantize_level'),
1208
+ [(np.zeros((2, 10, 10), dtype=np.float32), 'RICE_1', 16),
1209
+ (np.zeros((2, 10, 10), dtype=np.float32), 'GZIP_1', -0.01),
1210
+ (np.zeros((2, 10, 10), dtype=np.float32), 'GZIP_2', -0.01),
1211
+ (np.zeros((100, 100)) + 1, 'HCOMPRESS_1', 16),
1212
+ (np.zeros((10, 10)), 'PLIO_1', 16)])
1213
+ @pytest.mark.parametrize('byte_order', ['<', '>'])
1214
+ def test_comp_image(self, data, compression_type, quantize_level,
1215
+ byte_order):
1216
+ data = data.newbyteorder(byte_order)
1217
+ primary_hdu = fits.PrimaryHDU()
1218
+ ofd = fits.HDUList(primary_hdu)
1219
+ chdu = fits.CompImageHDU(data, name='SCI',
1220
+ compression_type=compression_type,
1221
+ quantize_level=quantize_level)
1222
+ ofd.append(chdu)
1223
+ ofd.writeto(self.temp('test_new.fits'), overwrite=True)
1224
+ ofd.close()
1225
+ with fits.open(self.temp('test_new.fits')) as fd:
1226
+ assert (fd[1].data == data).all()
1227
+ assert fd[1].header['NAXIS'] == chdu.header['NAXIS']
1228
+ assert fd[1].header['NAXIS1'] == chdu.header['NAXIS1']
1229
+ assert fd[1].header['NAXIS2'] == chdu.header['NAXIS2']
1230
+ assert fd[1].header['BITPIX'] == chdu.header['BITPIX']
1231
+
1232
+ @pytest.mark.skipif('not HAS_SCIPY')
1233
+ def test_comp_image_quantize_level(self):
1234
+ """
1235
+ Regression test for https://github.com/astropy/astropy/issues/5969
1236
+
1237
+ Test that quantize_level is used.
1238
+
1239
+ """
1240
+ import scipy.misc
1241
+ np.random.seed(42)
1242
+ data = scipy.misc.ascent() + np.random.randn(512, 512)*10
1243
+
1244
+ fits.ImageHDU(data).writeto(self.temp('im1.fits'))
1245
+ fits.CompImageHDU(data, compression_type='RICE_1', quantize_method=1,
1246
+ quantize_level=-1, dither_seed=5)\
1247
+ .writeto(self.temp('im2.fits'))
1248
+ fits.CompImageHDU(data, compression_type='RICE_1', quantize_method=1,
1249
+ quantize_level=-100, dither_seed=5)\
1250
+ .writeto(self.temp('im3.fits'))
1251
+
1252
+ im1 = fits.getdata(self.temp('im1.fits'))
1253
+ im2 = fits.getdata(self.temp('im2.fits'))
1254
+ im3 = fits.getdata(self.temp('im3.fits'))
1255
+
1256
+ assert not np.array_equal(im2, im3)
1257
+ assert np.isclose(np.min(im1 - im2), -0.5, atol=1e-3)
1258
+ assert np.isclose(np.max(im1 - im2), 0.5, atol=1e-3)
1259
+ assert np.isclose(np.min(im1 - im3), -50, atol=1e-1)
1260
+ assert np.isclose(np.max(im1 - im3), 50, atol=1e-1)
1261
+
1262
+ def test_comp_image_hcompression_1_invalid_data(self):
1263
+ """
1264
+ Tests compression with the HCOMPRESS_1 algorithm with data that is
1265
+ not 2D and has a non-2D tile size.
1266
+ """
1267
+
1268
+ pytest.raises(ValueError, fits.CompImageHDU,
1269
+ np.zeros((2, 10, 10), dtype=np.float32), name='SCI',
1270
+ compression_type='HCOMPRESS_1', quantize_level=16,
1271
+ tile_size=[2, 10, 10])
1272
+
1273
+ def test_comp_image_hcompress_image_stack(self):
1274
+ """
1275
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/171
1276
+
1277
+ Tests that data containing more than two dimensions can be
1278
+ compressed with HCOMPRESS_1 so long as the user-supplied tile size can
1279
+ be flattened to two dimensions.
1280
+ """
1281
+
1282
+ cube = np.arange(300, dtype=np.float32).reshape(3, 10, 10)
1283
+ hdu = fits.CompImageHDU(data=cube, name='SCI',
1284
+ compression_type='HCOMPRESS_1',
1285
+ quantize_level=16, tile_size=[5, 5, 1])
1286
+ hdu.writeto(self.temp('test.fits'))
1287
+
1288
+ with fits.open(self.temp('test.fits')) as hdul:
1289
+ # HCOMPRESSed images are allowed to deviate from the original by
1290
+ # about 1/quantize_level of the RMS in each tile.
1291
+ assert np.abs(hdul['SCI'].data - cube).max() < 1./15.
1292
+
1293
+ def test_subtractive_dither_seed(self):
1294
+ """
1295
+ Regression test for https://github.com/spacetelescope/PyFITS/issues/32
1296
+
1297
+ Ensure that when floating point data is compressed with the
1298
+ SUBTRACTIVE_DITHER_1 quantization method that the correct ZDITHER0 seed
1299
+ is added to the header, and that the data can be correctly
1300
+ decompressed.
1301
+ """
1302
+
1303
+ array = np.arange(100.0).reshape(10, 10)
1304
+ csum = (array[0].view('uint8').sum() % 10000) + 1
1305
+ hdu = fits.CompImageHDU(data=array,
1306
+ quantize_method=SUBTRACTIVE_DITHER_1,
1307
+ dither_seed=DITHER_SEED_CHECKSUM)
1308
+ hdu.writeto(self.temp('test.fits'))
1309
+
1310
+ with fits.open(self.temp('test.fits')) as hdul:
1311
+ assert isinstance(hdul[1], fits.CompImageHDU)
1312
+ assert 'ZQUANTIZ' in hdul[1]._header
1313
+ assert hdul[1]._header['ZQUANTIZ'] == 'SUBTRACTIVE_DITHER_1'
1314
+ assert 'ZDITHER0' in hdul[1]._header
1315
+ assert hdul[1]._header['ZDITHER0'] == csum
1316
+ assert np.all(hdul[1].data == array)
1317
+
1318
+ def test_disable_image_compression(self):
1319
+ with catch_warnings():
1320
+ # No warnings should be displayed in this case
1321
+ warnings.simplefilter('error')
1322
+ with fits.open(self.data('comp.fits'),
1323
+ disable_image_compression=True) as hdul:
1324
+ # The compressed image HDU should show up as a BinTableHDU, but
1325
+ # *not* a CompImageHDU
1326
+ assert isinstance(hdul[1], fits.BinTableHDU)
1327
+ assert not isinstance(hdul[1], fits.CompImageHDU)
1328
+
1329
+ with fits.open(self.data('comp.fits')) as hdul:
1330
+ assert isinstance(hdul[1], fits.CompImageHDU)
1331
+
1332
+ def test_open_comp_image_in_update_mode(self):
1333
+ """
1334
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/167
1335
+
1336
+ Similar to test_open_scaled_in_update_mode(), but specifically for
1337
+ compressed images.
1338
+ """
1339
+
1340
+ # Copy the original file before making any possible changes to it
1341
+ self.copy_file('comp.fits')
1342
+ mtime = os.stat(self.temp('comp.fits')).st_mtime
1343
+
1344
+ time.sleep(1)
1345
+
1346
+ fits.open(self.temp('comp.fits'), mode='update').close()
1347
+
1348
+ # Ensure that no changes were made to the file merely by immediately
1349
+ # opening and closing it.
1350
+ assert mtime == os.stat(self.temp('comp.fits')).st_mtime
1351
+
1352
+ def test_open_scaled_in_update_mode_compressed(self):
1353
+ """
1354
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/88 2
1355
+
1356
+ Identical to test_open_scaled_in_update_mode() but with a compressed
1357
+ version of the scaled image.
1358
+ """
1359
+
1360
+ # Copy+compress the original file before making any possible changes to
1361
+ # it
1362
+ with fits.open(self.data('scale.fits'),
1363
+ do_not_scale_image_data=True) as hdul:
1364
+ chdu = fits.CompImageHDU(data=hdul[0].data,
1365
+ header=hdul[0].header)
1366
+ chdu.writeto(self.temp('scale.fits'))
1367
+ mtime = os.stat(self.temp('scale.fits')).st_mtime
1368
+
1369
+ time.sleep(1)
1370
+
1371
+ fits.open(self.temp('scale.fits'), mode='update').close()
1372
+
1373
+ # Ensure that no changes were made to the file merely by immediately
1374
+ # opening and closing it.
1375
+ assert mtime == os.stat(self.temp('scale.fits')).st_mtime
1376
+
1377
+ # Insert a slight delay to ensure the mtime does change when the file
1378
+ # is changed
1379
+ time.sleep(1)
1380
+
1381
+ hdul = fits.open(self.temp('scale.fits'), 'update')
1382
+ hdul[1].data
1383
+ hdul.close()
1384
+
1385
+ # Now the file should be updated with the rescaled data
1386
+ assert mtime != os.stat(self.temp('scale.fits')).st_mtime
1387
+ hdul = fits.open(self.temp('scale.fits'), mode='update')
1388
+ assert hdul[1].data.dtype == np.dtype('float32')
1389
+ assert hdul[1].header['BITPIX'] == -32
1390
+ assert 'BZERO' not in hdul[1].header
1391
+ assert 'BSCALE' not in hdul[1].header
1392
+
1393
+ # Try reshaping the data, then closing and reopening the file; let's
1394
+ # see if all the changes are preseved properly
1395
+ hdul[1].data.shape = (42, 10)
1396
+ hdul.close()
1397
+
1398
+ hdul = fits.open(self.temp('scale.fits'))
1399
+ assert hdul[1].shape == (42, 10)
1400
+ assert hdul[1].data.dtype == np.dtype('float32')
1401
+ assert hdul[1].header['BITPIX'] == -32
1402
+ assert 'BZERO' not in hdul[1].header
1403
+ assert 'BSCALE' not in hdul[1].header
1404
+ hdul.close()
1405
+
1406
+ def test_write_comp_hdu_direct_from_existing(self):
1407
+ with fits.open(self.data('comp.fits')) as hdul:
1408
+ hdul[1].writeto(self.temp('test.fits'))
1409
+
1410
+ with fits.open(self.data('comp.fits')) as hdul1:
1411
+ with fits.open(self.temp('test.fits')) as hdul2:
1412
+ assert np.all(hdul1[1].data == hdul2[1].data)
1413
+ assert comparerecords(hdul1[1].compressed_data,
1414
+ hdul2[1].compressed_data)
1415
+
1416
+ def test_rewriting_large_scaled_image_compressed(self):
1417
+ """
1418
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/88 1
1419
+
1420
+ Identical to test_rewriting_large_scaled_image() but with a compressed
1421
+ image.
1422
+ """
1423
+
1424
+ with fits.open(self.data('fixed-1890.fits'),
1425
+ do_not_scale_image_data=True) as hdul:
1426
+ chdu = fits.CompImageHDU(data=hdul[0].data,
1427
+ header=hdul[0].header)
1428
+ chdu.writeto(self.temp('fixed-1890-z.fits'))
1429
+
1430
+ hdul = fits.open(self.temp('fixed-1890-z.fits'))
1431
+ orig_data = hdul[1].data
1432
+ with ignore_warnings():
1433
+ hdul.writeto(self.temp('test_new.fits'), overwrite=True)
1434
+ hdul.close()
1435
+ hdul = fits.open(self.temp('test_new.fits'))
1436
+ assert (hdul[1].data == orig_data).all()
1437
+ hdul.close()
1438
+
1439
+ # Just as before, but this time don't touch hdul[0].data before writing
1440
+ # back out--this is the case that failed in
1441
+ # https://aeon.stsci.edu/ssb/trac/pyfits/ticket/84
1442
+ hdul = fits.open(self.temp('fixed-1890-z.fits'))
1443
+ with ignore_warnings():
1444
+ hdul.writeto(self.temp('test_new.fits'), overwrite=True)
1445
+ hdul.close()
1446
+ hdul = fits.open(self.temp('test_new.fits'))
1447
+ assert (hdul[1].data == orig_data).all()
1448
+ hdul.close()
1449
+
1450
+ # Test opening/closing/reopening a scaled file in update mode
1451
+ hdul = fits.open(self.temp('fixed-1890-z.fits'),
1452
+ do_not_scale_image_data=True)
1453
+ hdul.writeto(self.temp('test_new.fits'), overwrite=True,
1454
+ output_verify='silentfix')
1455
+ hdul.close()
1456
+ hdul = fits.open(self.temp('test_new.fits'))
1457
+ orig_data = hdul[1].data
1458
+ hdul.close()
1459
+ hdul = fits.open(self.temp('test_new.fits'), mode='update')
1460
+ hdul.close()
1461
+ hdul = fits.open(self.temp('test_new.fits'))
1462
+ assert (hdul[1].data == orig_data).all()
1463
+ hdul = fits.open(self.temp('test_new.fits'))
1464
+ hdul.close()
1465
+
1466
+ def test_scale_back_compressed(self):
1467
+ """
1468
+ Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/88 3
1469
+
1470
+ Identical to test_scale_back() but uses a compressed image.
1471
+ """
1472
+
1473
+ # Create a compressed version of the scaled image
1474
+ with fits.open(self.data('scale.fits'),
1475
+ do_not_scale_image_data=True) as hdul:
1476
+ chdu = fits.CompImageHDU(data=hdul[0].data,
1477
+ header=hdul[0].header)
1478
+ chdu.writeto(self.temp('scale.fits'))
1479
+
1480
+ with fits.open(self.temp('scale.fits'), mode='update',
1481
+ scale_back=True) as hdul:
1482
+ orig_bitpix = hdul[1].header['BITPIX']
1483
+ orig_bzero = hdul[1].header['BZERO']
1484
+ orig_bscale = hdul[1].header['BSCALE']
1485
+ orig_data = hdul[1].data.copy()
1486
+ hdul[1].data[0] = 0
1487
+
1488
+ with fits.open(self.temp('scale.fits'),
1489
+ do_not_scale_image_data=True) as hdul:
1490
+ assert hdul[1].header['BITPIX'] == orig_bitpix
1491
+ assert hdul[1].header['BZERO'] == orig_bzero
1492
+ assert hdul[1].header['BSCALE'] == orig_bscale
1493
+
1494
+ zero_point = int(math.floor(-orig_bzero / orig_bscale))
1495
+ assert (hdul[1].data[0] == zero_point).all()
1496
+
1497
+ with fits.open(self.temp('scale.fits')) as hdul:
1498
+ assert (hdul[1].data[1:] == orig_data[1:]).all()
1499
+ # Extra test to ensure that after everything the data is still the
1500
+ # same as in the original uncompressed version of the image
1501
+ with fits.open(self.data('scale.fits')) as hdul2:
1502
+ # Recall we made the same modification to the data in hdul
1503
+ # above
1504
+ hdul2[0].data[0] = 0
1505
+ assert (hdul[1].data == hdul2[0].data).all()
1506
+
1507
+ def test_lossless_gzip_compression(self):
1508
+ """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/198"""
1509
+
1510
+ noise = np.random.normal(size=(1000, 1000))
1511
+
1512
+ chdu1 = fits.CompImageHDU(data=noise, compression_type='GZIP_1')
1513
+ # First make a test image with lossy compression and make sure it
1514
+ # wasn't compressed perfectly. This shouldn't happen ever, but just to
1515
+ # make sure the test non-trivial.
1516
+ chdu1.writeto(self.temp('test.fits'))
1517
+
1518
+ with fits.open(self.temp('test.fits')) as h:
1519
+ assert np.abs(noise - h[1].data).max() > 0.0
1520
+
1521
+ del h
1522
+
1523
+ chdu2 = fits.CompImageHDU(data=noise, compression_type='GZIP_1',
1524
+ quantize_level=0.0) # No quantization
1525
+ with ignore_warnings():
1526
+ chdu2.writeto(self.temp('test.fits'), overwrite=True)
1527
+
1528
+ with fits.open(self.temp('test.fits')) as h:
1529
+ assert (noise == h[1].data).all()
1530
+
1531
+ def test_compression_column_tforms(self):
1532
+ """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/199"""
1533
+
1534
+ # Some interestingly tiled data so that some of it is quantized and
1535
+ # some of it ends up just getting gzip-compressed
1536
+ data2 = ((np.arange(1, 8, dtype=np.float32) * 10)[:, np.newaxis] +
1537
+ np.arange(1, 7))
1538
+ np.random.seed(1337)
1539
+ data1 = np.random.uniform(size=(6 * 4, 7 * 4))
1540
+ data1[:data2.shape[0], :data2.shape[1]] = data2
1541
+ chdu = fits.CompImageHDU(data1, compression_type='RICE_1',
1542
+ tile_size=(6, 7))
1543
+ chdu.writeto(self.temp('test.fits'))
1544
+
1545
+ with fits.open(self.temp('test.fits'),
1546
+ disable_image_compression=True) as h:
1547
+ assert re.match(r'^1PB\(\d+\)$', h[1].header['TFORM1'])
1548
+ assert re.match(r'^1PB\(\d+\)$', h[1].header['TFORM2'])
1549
+
1550
+ def test_compression_update_header(self):
1551
+ """Regression test for
1552
+ https://github.com/spacetelescope/PyFITS/issues/23
1553
+ """
1554
+
1555
+ self.copy_file('comp.fits')
1556
+ with fits.open(self.temp('comp.fits'), mode='update') as hdul:
1557
+ assert isinstance(hdul[1], fits.CompImageHDU)
1558
+ hdul[1].header['test1'] = 'test'
1559
+ hdul[1]._header['test2'] = 'test2'
1560
+
1561
+ with fits.open(self.temp('comp.fits')) as hdul:
1562
+ assert 'test1' in hdul[1].header
1563
+ assert hdul[1].header['test1'] == 'test'
1564
+ assert 'test2' in hdul[1].header
1565
+ assert hdul[1].header['test2'] == 'test2'
1566
+
1567
+ # Test update via index now:
1568
+ with fits.open(self.temp('comp.fits'), mode='update') as hdul:
1569
+ hdr = hdul[1].header
1570
+ hdr[hdr.index('TEST1')] = 'foo'
1571
+
1572
+ with fits.open(self.temp('comp.fits')) as hdul:
1573
+ assert hdul[1].header['TEST1'] == 'foo'
1574
+
1575
+ # Test slice updates
1576
+ with fits.open(self.temp('comp.fits'), mode='update') as hdul:
1577
+ hdul[1].header['TEST*'] = 'qux'
1578
+
1579
+ with fits.open(self.temp('comp.fits')) as hdul:
1580
+ assert list(hdul[1].header['TEST*'].values()) == ['qux', 'qux']
1581
+
1582
+ with fits.open(self.temp('comp.fits'), mode='update') as hdul:
1583
+ hdr = hdul[1].header
1584
+ idx = hdr.index('TEST1')
1585
+ hdr[idx:idx + 2] = 'bar'
1586
+
1587
+ with fits.open(self.temp('comp.fits')) as hdul:
1588
+ assert list(hdul[1].header['TEST*'].values()) == ['bar', 'bar']
1589
+
1590
+ # Test updating a specific COMMENT card duplicate
1591
+ with fits.open(self.temp('comp.fits'), mode='update') as hdul:
1592
+ hdul[1].header[('COMMENT', 1)] = 'I am fire. I am death!'
1593
+
1594
+ with fits.open(self.temp('comp.fits')) as hdul:
1595
+ assert hdul[1].header['COMMENT'][1] == 'I am fire. I am death!'
1596
+ assert hdul[1]._header['COMMENT'][1] == 'I am fire. I am death!'
1597
+
1598
+ # Test deleting by keyword and by slice
1599
+ with fits.open(self.temp('comp.fits'), mode='update') as hdul:
1600
+ hdr = hdul[1].header
1601
+ del hdr['COMMENT']
1602
+ idx = hdr.index('TEST1')
1603
+ del hdr[idx:idx + 2]
1604
+
1605
+ with fits.open(self.temp('comp.fits')) as hdul:
1606
+ assert 'COMMENT' not in hdul[1].header
1607
+ assert 'COMMENT' not in hdul[1]._header
1608
+ assert 'TEST1' not in hdul[1].header
1609
+ assert 'TEST1' not in hdul[1]._header
1610
+ assert 'TEST2' not in hdul[1].header
1611
+ assert 'TEST2' not in hdul[1]._header
1612
+
1613
+ def test_compression_update_header_with_reserved(self):
1614
+ """
1615
+ Ensure that setting reserved keywords related to the table data
1616
+ structure on CompImageHDU image headers fails.
1617
+ """
1618
+
1619
+ def test_set_keyword(hdr, keyword, value):
1620
+ with catch_warnings() as w:
1621
+ hdr[keyword] = value
1622
+ assert len(w) == 1
1623
+ assert str(w[0].message).startswith(
1624
+ "Keyword {!r} is reserved".format(keyword))
1625
+ assert keyword not in hdr
1626
+
1627
+ with fits.open(self.data('comp.fits')) as hdul:
1628
+ hdr = hdul[1].header
1629
+ test_set_keyword(hdr, 'TFIELDS', 8)
1630
+ test_set_keyword(hdr, 'TTYPE1', 'Foo')
1631
+ test_set_keyword(hdr, 'ZCMPTYPE', 'ASDF')
1632
+ test_set_keyword(hdr, 'ZVAL1', 'Foo')
1633
+
1634
+ def test_compression_header_append(self):
1635
+ with fits.open(self.data('comp.fits')) as hdul:
1636
+ imghdr = hdul[1].header
1637
+ tblhdr = hdul[1]._header
1638
+ with catch_warnings() as w:
1639
+ imghdr.append('TFIELDS')
1640
+ assert len(w) == 1
1641
+ assert 'TFIELDS' not in imghdr
1642
+
1643
+ imghdr.append(('FOO', 'bar', 'qux'), end=True)
1644
+ assert 'FOO' in imghdr
1645
+ assert imghdr[-1] == 'bar'
1646
+ assert 'FOO' in tblhdr
1647
+ assert tblhdr[-1] == 'bar'
1648
+
1649
+ imghdr.append(('CHECKSUM', 'abcd1234'))
1650
+ assert 'CHECKSUM' in imghdr
1651
+ assert imghdr['CHECKSUM'] == 'abcd1234'
1652
+ assert 'CHECKSUM' not in tblhdr
1653
+ assert 'ZHECKSUM' in tblhdr
1654
+ assert tblhdr['ZHECKSUM'] == 'abcd1234'
1655
+
1656
+ def test_compression_header_append2(self):
1657
+ """
1658
+ Regresion test for issue https://github.com/astropy/astropy/issues/5827
1659
+ """
1660
+ with fits.open(self.data('comp.fits')) as hdul:
1661
+ header = hdul[1].header
1662
+ while (len(header) < 1000):
1663
+ header.append() # pad with grow room
1664
+
1665
+ # Append stats to header:
1666
+ header.append(("Q1_OSAVG", 1, "[adu] quadrant 1 overscan mean"))
1667
+ header.append(("Q1_OSSTD", 1, "[adu] quadrant 1 overscan stddev"))
1668
+ header.append(("Q1_OSMED", 1, "[adu] quadrant 1 overscan median"))
1669
+
1670
+ def test_compression_header_insert(self):
1671
+ with fits.open(self.data('comp.fits')) as hdul:
1672
+ imghdr = hdul[1].header
1673
+ tblhdr = hdul[1]._header
1674
+ # First try inserting a restricted keyword
1675
+ with catch_warnings() as w:
1676
+ imghdr.insert(1000, 'TFIELDS')
1677
+ assert len(w) == 1
1678
+ assert 'TFIELDS' not in imghdr
1679
+ assert tblhdr.count('TFIELDS') == 1
1680
+
1681
+ # First try keyword-relative insert
1682
+ imghdr.insert('TELESCOP', ('OBSERVER', 'Phil Plait'))
1683
+ assert 'OBSERVER' in imghdr
1684
+ assert imghdr.index('OBSERVER') == imghdr.index('TELESCOP') - 1
1685
+ assert 'OBSERVER' in tblhdr
1686
+ assert tblhdr.index('OBSERVER') == tblhdr.index('TELESCOP') - 1
1687
+
1688
+ # Next let's see if an index-relative insert winds up being
1689
+ # sensible
1690
+ idx = imghdr.index('OBSERVER')
1691
+ imghdr.insert('OBSERVER', ('FOO',))
1692
+ assert 'FOO' in imghdr
1693
+ assert imghdr.index('FOO') == idx
1694
+ assert 'FOO' in tblhdr
1695
+ assert tblhdr.index('FOO') == tblhdr.index('OBSERVER') - 1
1696
+
1697
+ def test_compression_header_set_before_after(self):
1698
+ with fits.open(self.data('comp.fits')) as hdul:
1699
+ imghdr = hdul[1].header
1700
+ tblhdr = hdul[1]._header
1701
+
1702
+ with catch_warnings() as w:
1703
+ imghdr.set('ZBITPIX', 77, 'asdf', after='XTENSION')
1704
+ assert len(w) == 1
1705
+ assert 'ZBITPIX' not in imghdr
1706
+ assert tblhdr.count('ZBITPIX') == 1
1707
+ assert tblhdr['ZBITPIX'] != 77
1708
+
1709
+ # Move GCOUNT before PCOUNT (not that there's any reason you'd
1710
+ # *want* to do that, but it's just a test...)
1711
+ imghdr.set('GCOUNT', 99, before='PCOUNT')
1712
+ assert imghdr.index('GCOUNT') == imghdr.index('PCOUNT') - 1
1713
+ assert imghdr['GCOUNT'] == 99
1714
+ assert tblhdr.index('ZGCOUNT') == tblhdr.index('ZPCOUNT') - 1
1715
+ assert tblhdr['ZGCOUNT'] == 99
1716
+ assert tblhdr.index('PCOUNT') == 5
1717
+ assert tblhdr.index('GCOUNT') == 6
1718
+ assert tblhdr['GCOUNT'] == 1
1719
+
1720
+ imghdr.set('GCOUNT', 2, after='PCOUNT')
1721
+ assert imghdr.index('GCOUNT') == imghdr.index('PCOUNT') + 1
1722
+ assert imghdr['GCOUNT'] == 2
1723
+ assert tblhdr.index('ZGCOUNT') == tblhdr.index('ZPCOUNT') + 1
1724
+ assert tblhdr['ZGCOUNT'] == 2
1725
+ assert tblhdr.index('PCOUNT') == 5
1726
+ assert tblhdr.index('GCOUNT') == 6
1727
+ assert tblhdr['GCOUNT'] == 1
1728
+
1729
+ def test_compression_header_append_commentary(self):
1730
+ """
1731
+ Regression test for https://github.com/astropy/astropy/issues/2363
1732
+ """
1733
+
1734
+ hdu = fits.CompImageHDU(np.array([0], dtype=np.int32))
1735
+ hdu.header['COMMENT'] = 'hello world'
1736
+ assert hdu.header['COMMENT'] == ['hello world']
1737
+ hdu.writeto(self.temp('test.fits'))
1738
+
1739
+ with fits.open(self.temp('test.fits')) as hdul:
1740
+ assert hdul[1].header['COMMENT'] == ['hello world']
1741
+
1742
+ def test_compression_with_gzip_column(self):
1743
+ """
1744
+ Regression test for https://github.com/spacetelescope/PyFITS/issues/71
1745
+ """
1746
+
1747
+ arr = np.zeros((2, 7000), dtype='float32')
1748
+
1749
+ # The first row (which will be the first compressed tile) has a very
1750
+ # wide range of values that will be difficult to quantize, and should
1751
+ # result in use of a GZIP_COMPRESSED_DATA column
1752
+ arr[0] = np.linspace(0, 1, 7000)
1753
+ arr[1] = np.random.normal(size=7000)
1754
+
1755
+ hdu = fits.CompImageHDU(data=arr)
1756
+ hdu.writeto(self.temp('test.fits'))
1757
+
1758
+ with fits.open(self.temp('test.fits')) as hdul:
1759
+ comp_hdu = hdul[1]
1760
+
1761
+ # GZIP-compressed tile should compare exactly
1762
+ assert np.all(comp_hdu.data[0] == arr[0])
1763
+ # The second tile uses lossy compression and may be somewhat off,
1764
+ # so we don't bother comparing it exactly
1765
+
1766
+ def test_duplicate_compression_header_keywords(self):
1767
+ """
1768
+ Regression test for https://github.com/astropy/astropy/issues/2750
1769
+
1770
+ Tests that the fake header (for the compressed image) can still be read
1771
+ even if the real header contained a duplicate ZTENSION keyword (the
1772
+ issue applies to any keyword specific to the compression convention,
1773
+ however).
1774
+ """
1775
+
1776
+ arr = np.arange(100, dtype=np.int32)
1777
+ hdu = fits.CompImageHDU(data=arr)
1778
+
1779
+ header = hdu._header
1780
+ # append the duplicate keyword
1781
+ hdu._header.append(('ZTENSION', 'IMAGE'))
1782
+ hdu.writeto(self.temp('test.fits'))
1783
+
1784
+ with fits.open(self.temp('test.fits')) as hdul:
1785
+ assert header == hdul[1]._header
1786
+ # There's no good reason to have a duplicate keyword, but
1787
+ # technically it isn't invalid either :/
1788
+ assert hdul[1]._header.count('ZTENSION') == 2
1789
+
1790
+ def test_scale_bzero_with_compressed_int_data(self):
1791
+ """
1792
+ Regression test for https://github.com/astropy/astropy/issues/4600
1793
+ and https://github.com/astropy/astropy/issues/4588
1794
+
1795
+ Identical to test_scale_bzero_with_int_data() but uses a compressed
1796
+ image.
1797
+ """
1798
+
1799
+ a = np.arange(100, 200, dtype=np.int16)
1800
+
1801
+ hdu1 = fits.CompImageHDU(data=a.copy())
1802
+ hdu2 = fits.CompImageHDU(data=a.copy())
1803
+ # Previously the following line would throw a TypeError,
1804
+ # now it should be identical to the integer bzero case
1805
+ hdu1.scale('int16', bzero=99.0)
1806
+ hdu2.scale('int16', bzero=99)
1807
+ assert np.allclose(hdu1.data, hdu2.data)
1808
+
1809
+ def test_scale_back_compressed_uint_assignment(self):
1810
+ """
1811
+ Extend fix for #4600 to assignment to data
1812
+
1813
+ Identical to test_scale_back_uint_assignment() but uses a compressed
1814
+ image.
1815
+
1816
+ Suggested by:
1817
+ https://github.com/astropy/astropy/pull/4602#issuecomment-208713748
1818
+ """
1819
+
1820
+ a = np.arange(100, 200, dtype=np.uint16)
1821
+ fits.CompImageHDU(a).writeto(self.temp('test.fits'))
1822
+ with fits.open(self.temp('test.fits'), mode="update",
1823
+ scale_back=True) as hdul:
1824
+ hdul[1].data[:] = 0
1825
+ assert np.allclose(hdul[1].data, 0)
1826
+
1827
+ def test_compressed_header_missing_znaxis(self):
1828
+ a = np.arange(100, 200, dtype=np.uint16)
1829
+ comp_hdu = fits.CompImageHDU(a)
1830
+ comp_hdu._header.pop('ZNAXIS')
1831
+ with pytest.raises(KeyError):
1832
+ comp_hdu.compressed_data
1833
+ comp_hdu = fits.CompImageHDU(a)
1834
+ comp_hdu._header.pop('ZBITPIX')
1835
+ with pytest.raises(KeyError):
1836
+ comp_hdu.compressed_data
1837
+
1838
+ @pytest.mark.parametrize(
1839
+ ('keyword', 'dtype', 'expected'),
1840
+ [('BSCALE', np.uint8, np.float32), ('BSCALE', np.int16, np.float32),
1841
+ ('BSCALE', np.int32, np.float64), ('BZERO', np.uint8, np.float32),
1842
+ ('BZERO', np.int16, np.float32), ('BZERO', np.int32, np.float64)])
1843
+ def test_compressed_scaled_float(self, keyword, dtype, expected):
1844
+ """
1845
+ If BSCALE,BZERO is set to floating point values, the image
1846
+ should be floating-point.
1847
+
1848
+ https://github.com/astropy/astropy/pull/6492
1849
+
1850
+ Parameters
1851
+ ----------
1852
+ keyword : `str`
1853
+ Keyword to set to a floating-point value to trigger
1854
+ floating-point pixels.
1855
+ dtype : `numpy.dtype`
1856
+ Type of original array.
1857
+ expected : `numpy.dtype`
1858
+ Expected type of uncompressed array.
1859
+ """
1860
+ value = 1.23345 # A floating-point value
1861
+ hdu = fits.CompImageHDU(np.arange(0, 10, dtype=dtype))
1862
+ hdu.header[keyword] = value
1863
+ hdu.writeto(self.temp('test.fits'))
1864
+ del hdu
1865
+ with fits.open(self.temp('test.fits')) as hdu:
1866
+ assert hdu[1].header[keyword] == value
1867
+ assert hdu[1].data.dtype == expected
1868
+
1869
+
1870
+ def test_comphdu_bscale(tmpdir):
1871
+ """
1872
+ Regression test for a bug that caused extensions that used BZERO and BSCALE
1873
+ that got turned into CompImageHDU to end up with BZERO/BSCALE before the
1874
+ TFIELDS.
1875
+ """
1876
+
1877
+ filename1 = tmpdir.join('3hdus.fits').strpath
1878
+ filename2 = tmpdir.join('3hdus_comp.fits').strpath
1879
+
1880
+ x = np.random.random((100, 100))*100
1881
+
1882
+ x0 = fits.PrimaryHDU()
1883
+ x1 = fits.ImageHDU(np.array(x-50, dtype=int), uint=True)
1884
+ x1.header['BZERO'] = 20331
1885
+ x1.header['BSCALE'] = 2.3
1886
+ hdus = fits.HDUList([x0, x1])
1887
+ hdus.writeto(filename1)
1888
+
1889
+ # fitsverify (based on cfitsio) should fail on this file, only seeing the
1890
+ # first HDU.
1891
+ with fits.open(filename1) as hdus:
1892
+ hdus[1] = fits.CompImageHDU(data=hdus[1].data.astype(np.uint32),
1893
+ header=hdus[1].header)
1894
+ hdus.writeto(filename2)
1895
+
1896
+ # open again and verify
1897
+ with fits.open(filename2) as hdus:
1898
+ hdus[1].verify('exception')
1899
+
1900
+
1901
+ def test_scale_implicit_casting():
1902
+
1903
+ # Regression test for an issue that occurred because Numpy now does not
1904
+ # allow implicit type casting during inplace operations.
1905
+
1906
+ hdu = fits.ImageHDU(np.array([1], dtype=np.int32))
1907
+ hdu.scale(bzero=1.3)
1908
+
1909
+
1910
+ def test_bzero_implicit_casting_compressed():
1911
+
1912
+ # Regression test for an issue that occurred because Numpy now does not
1913
+ # allow implicit type casting during inplace operations. Astropy is
1914
+ # actually not able to produce a file that triggers the failure - the
1915
+ # issue occurs when using unsigned integer types in the FITS file, in which
1916
+ # case BZERO should be 32768. But if the keyword is stored as 32768.0, then
1917
+ # it was possible to trigger the implicit casting error.
1918
+
1919
+ filename = os.path.join(os.path.dirname(__file__),
1920
+ 'data', 'compressed_float_bzero.fits')
1921
+
1922
+ with fits.open(filename) as hdul:
1923
+ hdu = hdul[1]
1924
+ hdu.data
1925
+
1926
+
1927
+ def test_bzero_mishandled_info(tmpdir):
1928
+ # Regression test for #5507:
1929
+ # Calling HDUList.info() on a dataset which applies a zeropoint
1930
+ # from BZERO but which astropy.io.fits does not think it needs
1931
+ # to resize to a new dtype results in an AttributeError.
1932
+ filename = tmpdir.join('floatimg_with_bzero.fits').strpath
1933
+ hdu = fits.ImageHDU(np.zeros((10, 10)))
1934
+ hdu.header['BZERO'] = 10
1935
+ hdu.writeto(filename, overwrite=True)
1936
+ with fits.open(filename) as hdul:
1937
+ hdul.info()
1938
+
1939
+
1940
+ def test_image_write_readonly(tmpdir):
1941
+
1942
+ # Regression test to make sure that we can write out read-only arrays (#5512)
1943
+
1944
+ x = np.array([1, 2, 3])
1945
+ x.setflags(write=False)
1946
+ ghdu = fits.ImageHDU(data=x)
1947
+ ghdu.add_datasum()
1948
+
1949
+ filename = tmpdir.join('test.fits').strpath
1950
+
1951
+ ghdu.writeto(filename)
1952
+
1953
+ with fits.open(filename) as hdulist:
1954
+ assert_equal(hdulist[1].data, [1, 2, 3])
1955
+
1956
+ # Same for compressed HDU
1957
+ x = np.array([1.0, 2.0, 3.0])
1958
+ x.setflags(write=False)
1959
+ ghdu = fits.CompImageHDU(data=x)
1960
+ # add_datasum does not work for CompImageHDU
1961
+ # ghdu.add_datasum()
1962
+
1963
+ filename = tmpdir.join('test2.fits').strpath
1964
+
1965
+ ghdu.writeto(filename)
1966
+
1967
+ with fits.open(filename) as hdulist:
1968
+ assert_equal(hdulist[1].data, [1.0, 2.0, 3.0])
testbed/astropy__astropy/astropy/io/fits/tests/test_nonstandard.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import numpy as np
4
+
5
+ from astropy.io import fits
6
+ from . import FitsTestCase
7
+
8
+
9
+ class TestNonstandardHdus(FitsTestCase):
10
+ def test_create_fitshdu(self):
11
+ """
12
+ A round trip test of creating a FitsHDU, adding a FITS file to it,
13
+ writing the FitsHDU out as part of a new FITS file, and then reading
14
+ it and recovering the original FITS file.
15
+ """
16
+
17
+ self._test_create_fitshdu(compression=False)
18
+
19
+ def test_create_fitshdu_with_compression(self):
20
+ """Same as test_create_fitshdu but with gzip compression enabled."""
21
+
22
+ self._test_create_fitshdu(compression=True)
23
+
24
+ def test_create_fitshdu_from_filename(self):
25
+ """Regression test on `FitsHDU.fromfile`"""
26
+
27
+ # Build up a simple test FITS file
28
+ a = np.arange(100)
29
+ phdu = fits.PrimaryHDU(data=a)
30
+ phdu.header['TEST1'] = 'A'
31
+ phdu.header['TEST2'] = 'B'
32
+ imghdu = fits.ImageHDU(data=a + 1)
33
+ phdu.header['TEST3'] = 'C'
34
+ phdu.header['TEST4'] = 'D'
35
+
36
+ hdul = fits.HDUList([phdu, imghdu])
37
+ hdul.writeto(self.temp('test.fits'))
38
+
39
+ fitshdu = fits.FitsHDU.fromfile(self.temp('test.fits'))
40
+ hdul2 = fitshdu.hdulist
41
+
42
+ assert len(hdul2) == 2
43
+ assert fits.FITSDiff(hdul, hdul2).identical
44
+
45
+ def _test_create_fitshdu(self, compression=False):
46
+ hdul_orig = fits.open(self.data('test0.fits'),
47
+ do_not_scale_image_data=True)
48
+
49
+ fitshdu = fits.FitsHDU.fromhdulist(hdul_orig, compress=compression)
50
+ # Just to be meta, let's append to the same hdulist that the fitshdu
51
+ # encapuslates
52
+ hdul_orig.append(fitshdu)
53
+ hdul_orig.writeto(self.temp('tmp.fits'), overwrite=True)
54
+ del hdul_orig[-1]
55
+
56
+ hdul = fits.open(self.temp('tmp.fits'))
57
+ assert isinstance(hdul[-1], fits.FitsHDU)
58
+
59
+ wrapped = hdul[-1].hdulist
60
+ assert isinstance(wrapped, fits.HDUList)
61
+
62
+ assert hdul_orig.info(output=False) == wrapped.info(output=False)
63
+ assert (hdul[1].data == wrapped[1].data).all()
64
+ assert (hdul[2].data == wrapped[2].data).all()
65
+ assert (hdul[3].data == wrapped[3].data).all()
66
+ assert (hdul[4].data == wrapped[4].data).all()
67
+
68
+ hdul_orig.close()
69
+ hdul.close()
testbed/astropy__astropy/astropy/io/fits/tests/test_structured.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see PYFITS.rst
2
+
3
+ import sys
4
+
5
+ import numpy as np
6
+
7
+ from astropy.io import fits
8
+ from . import FitsTestCase
9
+
10
+
11
+ def compare_arrays(arr1in, arr2in, verbose=False):
12
+ """
13
+ Compare the values field-by-field in two sets of numpy arrays or
14
+ recarrays.
15
+ """
16
+
17
+ arr1 = arr1in.view(np.ndarray)
18
+ arr2 = arr2in.view(np.ndarray)
19
+
20
+ nfail = 0
21
+ for n2 in arr2.dtype.names:
22
+ n1 = n2
23
+ if n1 not in arr1.dtype.names:
24
+ n1 = n1.lower()
25
+ if n1 not in arr1.dtype.names:
26
+ n1 = n1.upper()
27
+ if n1 not in arr1.dtype.names:
28
+ raise ValueError('field name {} not found in array 1'.format(n2))
29
+
30
+ if verbose:
31
+ sys.stdout.write(" testing field: '{}'\n".format(n2))
32
+ sys.stdout.write(' shape...........')
33
+ if arr2[n2].shape != arr1[n1].shape:
34
+ nfail += 1
35
+ if verbose:
36
+ sys.stdout.write('shapes differ\n')
37
+ else:
38
+ if verbose:
39
+ sys.stdout.write('OK\n')
40
+ sys.stdout.write(' elements........')
41
+ w, = np.where(arr1[n1].ravel() != arr2[n2].ravel())
42
+ if w.size > 0:
43
+ nfail += 1
44
+ if verbose:
45
+ sys.stdout.write(
46
+ '\n {} elements in field {} differ\n'.format(
47
+ w.size, n2))
48
+ else:
49
+ if verbose:
50
+ sys.stdout.write('OK\n')
51
+
52
+ if nfail == 0:
53
+ if verbose:
54
+ sys.stdout.write('All tests passed\n')
55
+ return True
56
+ else:
57
+ if verbose:
58
+ sys.stdout.write('{} differences found\n'.format(nfail))
59
+ return False
60
+
61
+
62
+ def get_test_data(verbose=False):
63
+ st = np.zeros(3, [('f1', 'i4'), ('f2', 'S6'), ('f3', '>2f8')])
64
+
65
+ np.random.seed(35)
66
+ st['f1'] = [1, 3, 5]
67
+ st['f2'] = ['hello', 'world', 'byebye']
68
+ st['f3'] = np.random.random(st['f3'].shape)
69
+
70
+ return st
71
+
72
+
73
+ class TestStructured(FitsTestCase):
74
+ def test_structured(self):
75
+ fname = self.data('stddata.fits')
76
+
77
+ data1, h1 = fits.getdata(fname, ext=1, header=True)
78
+ data2, h2 = fits.getdata(fname, ext=2, header=True)
79
+
80
+ st = get_test_data()
81
+
82
+ outfile = self.temp('test.fits')
83
+ fits.writeto(outfile, data1, overwrite=True)
84
+ fits.append(outfile, data2)
85
+
86
+ fits.append(outfile, st)
87
+ assert st.dtype.isnative
88
+ assert np.all(st['f1'] == [1, 3, 5])
89
+
90
+ data1check, h1check = fits.getdata(outfile, ext=1, header=True)
91
+ data2check, h2check = fits.getdata(outfile, ext=2, header=True)
92
+ stcheck, sthcheck = fits.getdata(outfile, ext=3, header=True)
93
+
94
+ assert compare_arrays(data1, data1check, verbose=True)
95
+ assert compare_arrays(data2, data2check, verbose=True)
96
+ assert compare_arrays(st, stcheck, verbose=True)
97
+
98
+ # try reading with view
99
+ dataviewcheck, hviewcheck = fits.getdata(outfile, ext=2, header=True,
100
+ view=np.ndarray)
101
+ assert compare_arrays(data2, dataviewcheck, verbose=True)
testbed/astropy__astropy/astropy/io/fits/tests/test_table.py ADDED
The diff for this file is too large to render. See raw diff