class Column(NotifierMixin):
    """
    Class which contains the definition of one column, e.g.  ``ttype``,
    ``tform``, etc. and the array containing values for the column.
    """

    def __init__(self, name=None, format=None, unit=None, null=None,
                 bscale=None, bzero=None, disp=None, start=None, dim=None,
                 array=None, ascii=None):
        """
        Construct a `Column` by specifying attributes.  All attributes
        except ``format`` can be optional; see :ref:`column_creation` and
        :ref:`creating_ascii_table` for more information regarding
        ``TFORM`` keyword.

        Parameters
        ----------
        name : str, optional
            column name, corresponding to ``TTYPE`` keyword

        format : str
            column format, corresponding to ``TFORM`` keyword

        unit : str, optional
            column unit, corresponding to ``TUNIT`` keyword

        null : str, optional
            null value, corresponding to ``TNULL`` keyword

        bscale : int-like, optional
            bscale value, corresponding to ``TSCAL`` keyword

        bzero : int-like, optional
            bzero value, corresponding to ``TZERO`` keyword

        disp : str, optional
            display format, corresponding to ``TDISP`` keyword

        start : int, optional
            column starting position (ASCII table only), corresponding
            to ``TBCOL`` keyword

        dim : str, optional
            column dimension corresponding to ``TDIM`` keyword

        array : iterable, optional
            a `list`, `numpy.ndarray` (or other iterable that can be used to
            initialize an ndarray) providing initial data for this column.
            The array will be automatically converted, if possible, to the data
            format of the column.  In the case were non-trivial ``bscale``
            and/or ``bzero`` arguments are given, the values in the array must
            be the *physical* values--that is, the values of column as if the
            scaling has already been applied (the array stored on the column
            object will then be converted back to its storage values).

        ascii : bool, optional
            set `True` if this describes a column for an ASCII table; this
            may be required to disambiguate the column format
        """

        if format is None:
            raise ValueError('Must specify format to construct Column.')

        # any of the input argument (except array) can be a Card or just
        # a number/string
        kwargs = {'ascii': ascii}
        for attr in KEYWORD_ATTRIBUTES:
            value = locals()[attr]  # get the argument's value

            if isinstance(value, Card):
                value = value.value

            kwargs[attr] = value

        valid_kwargs, invalid_kwargs = self._verify_keywords(**kwargs)

        if invalid_kwargs:
            msg = ['The following keyword arguments to Column were invalid:']

            for val in invalid_kwargs.values():
                msg.append(indent(val[1]))

            raise VerifyError('\n'.join(msg))

        for attr in KEYWORD_ATTRIBUTES:
            setattr(self, attr, valid_kwargs.get(attr))

        # TODO: For PyFITS 3.3 try to eliminate the following two special cases
        # for recformat and dim:
        # This is not actually stored as an attribute on columns for some
        # reason
        recformat = valid_kwargs['recformat']

        # The 'dim' keyword's original value is stored in self.dim, while
        # *only* the tuple form is stored in self._dims.
        self._dims = self.dim
        self.dim = dim

        # Awful hack to use for now to keep track of whether the column holds
        # pseudo-unsigned int data
        self._pseudo_unsigned_ints = False

        # if the column data is not ndarray, make it to be one, i.e.
        # input arrays can be just list or tuple, not required to be ndarray
        # does not include Object array because there is no guarantee
        # the elements in the object array are consistent.
        if not isinstance(array,
                          (np.ndarray, chararray.chararray, Delayed)):
            try:  # try to convert to a ndarray first
                if array is not None:
                    array = np.array(array)
            except:
                try:  # then try to convert it to a strings array
                    itemsize = int(recformat[1:])
                    array = chararray.array(array, itemsize=itemsize)
                except ValueError:
                    # then try variable length array
                    # Note: This includes _FormatQ by inheritance
                    if isinstance(recformat, _FormatP):
                        array = _VLF(array, dtype=recformat.dtype)
                    else:
                        raise ValueError('Data is inconsistent with the '
                                         'format `%s`.' % format)

        array = self._convert_to_valid_data_type(array)

        # We have required (through documentation) that arrays passed in to
        # this constructor are already in their physical values, so we make
        # note of that here
        if isinstance(array, np.ndarray):
            self._physical_values = True
        else:
            self._physical_values = False

        self._parent_fits_rec = None
        self.array = array

    def __repr__(self):
        text = ''
        for attr in KEYWORD_ATTRIBUTES:
            value = getattr(self, attr)
            if value is not None:
                text += attr + ' = ' + repr(value) + '; '
        return text[:-2]

    def __eq__(self, other):
        """
        Two columns are equal if their name and format are the same.  Other
        attributes aren't taken into account at this time.
        """

        # According to the FITS standard column names must be case-insensitive
        a = (self.name.lower(), self.format)
        b = (other.name.lower(), other.format)
        return a == b

    def __hash__(self):
        """
        Like __eq__, the hash of a column should be based on the unique column
        name and format, and be case-insensitive with respect to the column
        name.
        """

        return hash((self.name.lower(), self.format))

    @property
    def array(self):
        """
        The Numpy `~numpy.ndarray` associated with this `Column`.

        If the column was instantiated with an array passed to the ``array``
        argument, this will return that array.  However, if the column is
        later added to a table, such as via `BinTableHDU.from_columns` as
        is typically the case, this attribute will be updated to reference
        the associated field in the table, which may no longer be the same
        array.
        """

        # Ideally the .array attribute never would have existed in the first
        # place, or would have been internal-only.  This is a legacy of the
        # older design from PyFITS that needs to have continued support, for
        # now.

        # One of the main problems with this design was that it created a
        # reference cycle.  When the .array attribute was updated after
        # creating a FITS_rec from the column (as explained in the docstring) a
        # reference cycle was created.  This is because the code in BinTableHDU
        # (and a few other places) does essentially the following:
        #
        # data._coldefs = columns  # The ColDefs object holding this Column
        # for col in columns:
        #     col.array = data.field(col.name)
        #
        # This way each columns .array attribute now points to the field in the
        # table data.  It's actually a pretty confusing interface (since it
        # replaces the array originally pointed to by .array), but it's the way
        # things have been for a long, long time.
        #
        # However, this results, in *many* cases, in a reference cycle.
        # Because the array returned by data.field(col.name), while sometimes
        # an array that owns its own data, is usually like a slice of the
        # original data.  It has the original FITS_rec as the array .base.
        # This results in the following reference cycle (for the n-th column):
        #
        #    data -> data._coldefs -> data._coldefs[n] ->
        #     data._coldefs[n].array -> data._coldefs[n].array.base -> data
        #
        # Because ndarray objects do not handled by Python's garbage collector
        # the reference cycle cannot be broken.  Therefore the FITS_rec's
        # refcount never goes to zero, its __del__ is never called, and its
        # memory is never freed.  This didn't occur in *all* cases, but it did
        # occur in many cases.
        #
        # To get around this, Column.array is no longer a simple attribute
        # like it was previously.  Now each Column has a ._parent_fits_rec
        # attribute which is a weakref to a FITS_rec object.  Code that
        # previously assigned each col.array to field in a FITS_rec (as in
        # the example a few paragraphs above) is still used, however now
        # array.setter checks if a reference cycle will be created.  And if
        # so, instead of saving directly to the Column's __dict__, it creates
        # the ._prent_fits_rec weakref, and all lookups of the column's .array
        # go through that instead.
        #
        # This alone does not fully solve the problem.  Because
        # _parent_fits_rec is a weakref, if the user ever holds a reference to
        # the Column, but deletes all references to the underlying FITS_rec,
        # the .array attribute would suddenly start returning None instead of
        # the array data.  This problem is resolved on FITS_rec's end.  See the
        # note in the FITS_rec._coldefs property for the rest of the story.

        # If the Columns's array is not a reference to an existing FITS_rec,
        # then it is just stored in self.__dict__; otherwise check the
        # _parent_fits_rec reference if it 's still available.
        if 'array' in self.__dict__:
            return self.__dict__['array']
        elif self._parent_fits_rec is not None:
            parent = self._parent_fits_rec()
            if parent is not None:
                return parent[self.name]
        else:
            return None

    @array.setter
    def array(self, array):
        # The following looks over the bases of the given array to check if it
        # has a ._coldefs attribute (i.e. is a FITS_rec) and that that _coldefs
        # contains this Column itself, and would create a reference cycle if we
        # stored the array directly in self.__dict__.
        # In this case it instead sets up the _parent_fits_rec weakref to the
        # underlying FITS_rec, so that array.getter can return arrays through
        # self._parent_fits_rec().field(self.name), rather than storing a
        # hard reference to the field like it used to.
        base = array
        while True:
            if (hasattr(base, '_coldefs') and
                    isinstance(base._coldefs, ColDefs)):
                for col in base._coldefs:
                    if col is self and self._parent_fits_rec is None:
                        self._parent_fits_rec = weakref.ref(base)

                        # Just in case the user already set .array to their own
                        # array.
                        if 'array' in self.__dict__:
                            del self.__dict__['array']
                        return

            if getattr(base, 'base', None) is not None:
                base = base.base
            else:
                break

        self.__dict__['array'] = array

    @array.deleter
    def array(self):
        try:
            del self.__dict__['array']
        except KeyError:
            pass

        self._parent_fits_rec = None

    @ColumnAttribute('TTYPE')
    def name(col, name):
        if name is None:
            # Allow None to indicate deleting the name, or to just indicate an
            # unspecified name (when creating a new Column).
            return

        # Check that the name meets the recommended standard--other column
        # names are *allowed*, but will be discouraged
        if isinstance(name, string_types) and not TTYPE_RE.match(name):
            warnings.warn(
                'It is strongly recommended that column names contain only '
                'upper and lower-case ASCII letters, digits, or underscores '
                'for maximum compatibility with other software '
                '(got {0!r}).'.format(name), VerifyWarning)

        # This ensures that the new name can fit into a single FITS card
        # without any special extension like CONTINUE cards or the like.
        assert (isinstance(name, string_types) and
                len(str(Card('TTYPE', name))) == CARD_LENGTH), \
                    ('Column name must be a string able to fit in a single '
                     'FITS card--typically this means a maximum of 68 '
                     'characters, though it may be fewer if the string '
                     'contains special characters like quotes.')

    format = ColumnAttribute('TFORM')
    unit = ColumnAttribute('TUNIT')
    null = ColumnAttribute('TNULL')
    bscale = ColumnAttribute('TSCAL')
    bzero = ColumnAttribute('TZERO')
    disp = ColumnAttribute('TDISP')
    start = ColumnAttribute('TBCOL')
    dim = ColumnAttribute('TDIM')

    @lazyproperty
    def ascii(self):
        """Whether this `Column` represents an column in an ASCII table."""

        return isinstance(self.format, _AsciiColumnFormat)

    @lazyproperty
    def dtype(self):
        return self.format.dtype

    def copy(self):
        """
        Return a copy of this `Column`.
        """
        tmp = Column(format='I')  # just use a throw-away format
        tmp.__dict__ = self.__dict__.copy()
        return tmp

    if sys.version_info < (2, 7):
        # This is only needed on Python 2.6, where it appears deepcopy has
        # problems with weakrefs, and especially weak-keyed dicts.
        def __deepcopy__(self, memo=None):
            tmp = object.__new__(self.__class__)
            tmp_dict = dict(self.__dict__)
            array = self.array
            listeners = None
            if array is not None:
                tmp_dict['array'] = array.copy()
            tmp_dict['_parent_fits_rec'] = None

            if '_listeners' in tmp_dict:
                listners = tmp_dict['_listeners']
                del tmp_dict['_listeners']

            tmp.__dict__ = copy.deepcopy(tmp_dict, memo=memo)

            if listeners is not None:
                tmp.__dict__['_listeners'] = listeners
            return tmp

    @staticmethod
    def _convert_format(format, cls):
        """The format argument to this class's initializer may come in many
        forms.  This uses the given column format class ``cls`` to convert
        to a format of that type.

        TODO: There should be an abc base class for column format classes
        """

        # Short circuit in case we're already a _BaseColumnFormat--there is at
        # least one case in which this can happen
        if isinstance(format, _BaseColumnFormat):
            return format, format.recformat

        if format in NUMPY2FITS:
            with ignored(VerifyError):
                # legit recarray format?
                recformat = format
                format = cls.from_recformat(format)

        try:
            # legit FITS format?
            format = cls(format)
            recformat = format.recformat
        except VerifyError:
            raise VerifyError('Illegal format `%s`.' % format)

        return format, recformat

    @classmethod
    def _verify_keywords(cls, name=None, format=None, unit=None, null=None,
                         bscale=None, bzero=None, disp=None, start=None,
                         dim=None, ascii=None):
        """
        Given the keyword arguments used to initialize a Column, specifically
        those that typically read from a FITS header (so excluding array),
        verify that each keyword has a valid value.

        Returns a 2-tuple of dicts.  The first maps valid keywords to their
        values.  The second maps invalid keywords to a 2-tuple of their value,
        and a message explaining why they were found invalid.
        """

        valid = {}
        invalid = {}

        format, recformat = cls._determine_formats(format, start, dim, ascii)
        valid.update(format=format, recformat=recformat)

        # Currently we don't have any validation for name, unit, bscale, or
        # bzero so include those by default
        # TODO: Add validation for these keywords, obviously
        for k, v in [('name', name), ('unit', unit), ('bscale', bscale),
                     ('bzero', bzero)]:
            if v is not None and v != '':
                valid[k] = v

        # Validate null option
        # Note: Enough code exists that thinks empty strings are sensible
        # inputs for these options that we need to treat '' as None
        if null is not None and null != '':
            msg = None
            if isinstance(format, _AsciiColumnFormat):
                null = str(null)
                if len(null) > format.width:
                    msg = (
                        "ASCII table null option (TNULLn) is longer than "
                        "the column's character width and will be truncated "
                        "(got %r)." % null)
            else:
                if not _is_int(null):
                    # Make this an exception instead of a warning, since any
                    # non-int value is meaningless
                    msg = (
                        'Column null option (TNULLn) must be an integer for '
                        'binary table columns (got %r).  The invalid value '
                        'will be ignored for the purpose of formatting '
                        'the data in this column.' % null)

                tnull_formats = ('B', 'I', 'J', 'K')

                if not (format.format in tnull_formats or
                        (format.format in ('P', 'Q') and
                         format.p_format in tnull_formats)):
                    # TODO: We should also check that TNULLn's integer value
                    # is in the range allowed by the column's format
                    msg = (
                        'Column null option (TNULLn) is invalid for binary '
                        'table columns of type %r (got %r).  The invalid '
                        'value will be ignored for the purpose of formatting '
                        'the data in this column.' % (format, null))

            if msg is None:
                valid['null'] = null
            else:
                invalid['null'] = (null, msg)

        # Validate the disp option
        # TODO: Add full parsing and validation of TDISPn keywords
        if disp is not None and disp != '':
            msg = None
            if not isinstance(disp, string_types):
                msg = (
                    'Column disp option (TDISPn) must be a string (got %r).'
                    'The invalid value will be ignored for the purpose of '
                    'formatting the data in this column.' % disp)

            if (isinstance(format, _AsciiColumnFormat) and
                    disp[0].upper() == 'L'):
                # disp is at least one character long and has the 'L' format
                # which is not recognized for ASCII tables
                msg = (
                    "Column disp option (TDISPn) may not use the 'L' format "
                    "with ASCII table columns.  The invalid value will be "
                    "ignored for the purpose of formatting the data in this "
                    "column.")

            if msg is None:
                valid['disp'] = disp
            else:
                invalid['disp'] = (disp, msg)

        # Validate the start option
        if start is not None and start != '':
            msg = None
            if not isinstance(format, _AsciiColumnFormat):
                # The 'start' option only applies to ASCII columns
                msg = (
                    'Column start option (TBCOLn) is not allowed for binary '
                    'table columns (got %r).  The invalid keyword will be '
                    'ignored for the purpose of formatting the data in this '
                    'column.'% start)
            try:
                start = int(start)
            except (TypeError, ValueError):
                pass

            if not _is_int(start) and start < 1:
                msg = (
                    'Column start option (TBCOLn) must be a positive integer '
                    '(got %r).  The invalid value will be ignored for the '
                    'purpose of formatting the data in this column.' % start)

            if msg is None:
                valid['start'] = start
            else:
                invalid['start'] = (start, msg)

        # Process TDIMn options
        # ASCII table columns can't have a TDIMn keyword associated with it;
        # for now we just issue a warning and ignore it.
        # TODO: This should be checked by the FITS verification code
        if dim is not None and dim != '':
            msg = None
            dims_tuple = tuple()
            # NOTE: If valid, the dim keyword's value in the the valid dict is
            # a tuple, not the original string; if invalid just the original
            # string is returned
            if isinstance(format, _AsciiColumnFormat):
                msg = (
                    'Column dim option (TDIMn) is not allowed for ASCII table '
                    'columns (got %r).  The invalid keyword will be ignored '
                    'for the purpose of formatting this column.' % dim)

            elif isinstance(dim, string_types):
                dims_tuple = _parse_tdim(dim)
            elif isinstance(dim, tuple):
                dims_tuple = dim
            else:
                msg = (
                    "`dim` argument must be a string containing a valid value "
                    "for the TDIMn header keyword associated with this column, "
                    "or a tuple containing the C-order dimensions for the "
                    "column.  The invalid value will be ignored for the purpose "
                    "of formatting this column.")

            if dims_tuple:
                if reduce(operator.mul, dims_tuple) > format.repeat:
                    msg = (
                        "The repeat count of the column format %r for column %r "
                        "is fewer than the number of elements per the TDIM "
                        "argument %r.  The invalid TDIMn value will be ignored "
                        "for the purpose of formatting this column." %
                        (name, format, dim))

            if msg is None:
                valid['dim'] = dims_tuple
            else:
                invalid['dim'] = (dim, msg)

        return valid, invalid

    @classmethod
    def _determine_formats(cls, format, start, dim, ascii):
        """
        Given a format string and whether or not the Column is for an
        ASCII table (ascii=None means unspecified, but lean toward binary table
        where ambiguous) create an appropriate _BaseColumnFormat instance for
        the column's format, and determine the appropriate recarray format.

        The values of the start and dim keyword arguments are also useful, as
        the former is only valid for ASCII tables and the latter only for
        BINARY tables.
        """

        # If the given format string is unambiguously a Numpy dtype or one of
        # the Numpy record format type specifiers supported by PyFITS then that
        # should take priority--otherwise assume it is a FITS format
        if isinstance(format, np.dtype):
            format, _, _ = _dtype_to_recformat(format)

        # check format
        if ascii is None and not isinstance(format, _BaseColumnFormat):
            # We're just give a string which could be either a Numpy format
            # code, or a format for a binary column array *or* a format for an
            # ASCII column array--there may be many ambiguities here.  Try our
            # best to guess what the user intended.
            format, recformat = cls._guess_format(format, start, dim)
        elif not ascii and not isinstance(format, _BaseColumnFormat):
            format, recformat = cls._convert_format(format, _ColumnFormat)
        elif ascii and not isinstance(format, _AsciiColumnFormat):
            format, recformat = cls._convert_format(format,
                                                    _AsciiColumnFormat)
        else:
            # The format is already acceptable and unambiguous
            recformat = format.recformat

        return format, recformat

    @classmethod
    def _guess_format(cls, format, start, dim):
        if start and dim:
            # This is impossible; this can't be a valid FITS column
            raise ValueError(
                'Columns cannot have both a start (TCOLn) and dim '
                '(TDIMn) option, since the former is only applies to '
                'ASCII tables, and the latter is only valid for binary '
                'tables.')
        elif start:
            # Only ASCII table columns can have a 'start' option
            guess_format = _AsciiColumnFormat
        elif dim:
            # Only binary tables can have a dim option
            guess_format = _ColumnFormat
        else:
            # If the format is *technically* a valid binary column format
            # (i.e. it has a valid format code followed by arbitrary
            # "optional" codes), but it is also strictly a valid ASCII
            # table format, then assume an ASCII table column was being
            # requested (the more likely case, after all).
            with ignored(VerifyError):
                format = _AsciiColumnFormat(format, strict=True)

            # A safe guess which reflects the existing behavior of previous
            # PyFITS versions
            guess_format = _ColumnFormat

        try:
            format, recformat = cls._convert_format(format, guess_format)
        except VerifyError:
            # For whatever reason our guess was wrong (for example if we got
            # just 'F' that's not a valid binary format, but it an ASCII format
            # code albeit with the width/precision omitted
            guess_format = (_AsciiColumnFormat
                            if guess_format is _ColumnFormat
                            else _ColumnFormat)
            # If this fails too we're out of options--it is truly an invalid
            # format, or at least not supported
            format, recformat = cls._convert_format(format, guess_format)

        return format, recformat

    def _convert_to_valid_data_type(self, array):
        # Convert the format to a type we understand
        if isinstance(array, Delayed):
            return array
        elif array is None:
            return array
        else:
            format = self.format
            dims = self._dims

            if dims:
                shape = dims[:-1] if 'A' in format else dims
                shape = (len(array),) + shape
                array = array.reshape(shape)

            if 'P' in format or 'Q' in format:
                return array
            elif 'A' in format:
                if array.dtype.char in 'SU':
                    if dims:
                        # The 'last' dimension (first in the order given
                        # in the TDIMn keyword itself) is the number of
                        # characters in each string
                        fsize = dims[-1]
                    else:
                        fsize = np.dtype(format.recformat).itemsize
                    return chararray.array(array, itemsize=fsize)
                else:
                    return _convert_array(array, np.dtype(format.recformat))
            elif 'L' in format:
                # boolean needs to be scaled back to storage values ('T', 'F')
                if array.dtype == np.dtype('bool'):
                    return np.where(array == False, ord('F'), ord('T'))
                else:
                    return np.where(array == 0, ord('F'), ord('T'))
            elif 'X' in format:
                return _convert_array(array, np.dtype('uint8'))
            else:
                # Preserve byte order of the original array for now; see #77
                numpy_format = array.dtype.byteorder + format.recformat

                # Handle arrays passed in as unsigned ints as pseudo-unsigned
                # int arrays; blatantly tacked in here for now--we need columns
                # to have explicit knowledge of whether they treated as
                # pseudo-unsigned
                bzeros = {2: np.uint16(2**15), 4: np.uint32(2**31),
                          8: np.uint64(2**63)}
                if (array.dtype.kind == 'u' and
                        array.dtype.itemsize in bzeros and
                        self.bscale in (1, None, '') and
                        self.bzero == bzeros[array.dtype.itemsize]):
                    # Basically the array is uint, has scale == 1.0, and the
                    # bzero is the appropriate value for a pseudo-unsigned
                    # integer of the input dtype, then go ahead and assume that
                    # uint is assumed
                    numpy_format = numpy_format.replace('i', 'u')
                    self._pseudo_unsigned_ints = True

                # The .base here means we're dropping the shape information,
                # which is only used to format recarray fields, and is not
                # useful for converting input arrays to the correct data type
                dtype = np.dtype(numpy_format).base

                return _convert_array(array, dtype) class ColDefs(NotifierMixin):
    """
    Column definitions class.

    It has attributes corresponding to the `Column` attributes
    (e.g. `ColDefs` has the attribute ``names`` while `Column`
    has ``name``). Each attribute in `ColDefs` is a list of
    corresponding attribute values from all `Column` objects.
    """

    _padding_byte = '\x00'
    _col_format_cls = _ColumnFormat

    def __new__(cls, input, tbtype=None, ascii=False):
        if tbtype is not None:
            warnings.warn(
                'The ``tbtype`` argument to `ColDefs` is deprecated as of '
                'PyFITS 3.3; instead the appropriate table type should be '
                'inferred from the formats of the supplied columns.  Use the '
                '``ascii=True`` argument to ensure that ASCII table columns '
                'are used.')
        else:
            tbtype = 'BinTableHDU'  # The old default

        # Backwards-compat support
        # TODO: Remove once the tbtype argument is removed entirely
        if tbtype == 'BinTableHDU':
            klass = cls
        elif tbtype == 'TableHDU':
            klass = _AsciiColDefs
        else:
            raise ValueError('Invalid table type: %s.' % tbtype)

        if (hasattr(input, '_columns_type') and
                issubclass(input._columns_type, ColDefs)):
            klass = input._columns_type
        elif (hasattr(input, '_col_format_cls') and
                issubclass(input._col_format_cls, _AsciiColumnFormat)):
            klass = _AsciiColDefs

        if ascii:  # force ASCII if this has been explicitly requested
            klass = _AsciiColDefs

        return object.__new__(klass)

    def __getnewargs__(self):
        return (self._arrays,)

    def __init__(self, input, tbtype=None, ascii=False):
        """
        Parameters
        ----------

        input : sequence of `Column`, `ColDefs`, other
            An existing table HDU, an existing `ColDefs`, or any multi-field
            Numpy array or `numpy.recarray`.

        **(Deprecated)** tbtype : str, optional
            which table HDU, ``"BinTableHDU"`` (default) or
            ``"TableHDU"`` (text table).
            Now ColDefs for a normal (binary) table by default, but converted
            automatically to ASCII table ColDefs in the appropriate contexts
            (namely, when creating an ASCII table).

        ascii : bool
        """

        from pyfits.hdu.table import _TableBaseHDU
        from pyfits.fitsrec import FITS_rec

        if isinstance(input, ColDefs):
            self._init_from_coldefs(input)
        elif (isinstance(input, FITS_rec) and hasattr(input, '_coldefs') and
                input._coldefs):
            # If given a FITS_rec object we can directly copy its columns, but
            # only if its columns have already been defined, otherwise this
            # will loop back in on itself and blow up
            self._init_from_coldefs(input._coldefs)
        elif isinstance(input, np.ndarray) and input.dtype.fields is not None:
            # Construct columns from the fields of a record array
            self._init_from_array(input)
        elif isiterable(input):
            # if the input is a list of Columns
            self._init_from_sequence(input)
        elif isinstance(input, _TableBaseHDU):
            # Construct columns from fields in an HDU header
            self._init_from_table(input)
        else:
            raise TypeError('Input to ColDefs must be a table HDU, a list '
                            'of Columns, or a record/field array.')

        # Listen for changes on all columns
        for col in self.columns:
            col._add_listener(self)

    def _init_from_coldefs(self, coldefs):
        """Initialize from an existing ColDefs object (just copy the
        columns and convert their formats if necessary).
        """

        self.columns = [self._copy_column(col) for col in coldefs]

    def _init_from_sequence(self, columns):
        for idx, col in enumerate(columns):
            if not isinstance(col, Column):
                raise TypeError(
                    'Element %d in the ColDefs input is not a Column.' % idx)

        self._init_from_coldefs(columns)

    def _init_from_array(self, array):
        self.columns = []
        for idx in range(len(array.dtype)):
            cname = array.dtype.names[idx]
            ftype = array.dtype.fields[cname][0]
            format = self._col_format_cls.from_recformat(ftype)

            # Determine the appropriate dimensions for items in the column
            # (typically just 1D)
            dim = array.dtype[idx].shape[::-1]
            if dim and (len(dim) > 1 or 'A' in format):
                if 'A' in format:
                    # n x m string arrays must include the max string
                    # length in their dimensions (e.g. l x n x m)
                    dim = (array.dtype[idx].base.itemsize,) + dim
                dim = repr(dim).replace(' ', '')
            else:
                dim = None

            # Check for unsigned ints.
            bzero = None
            if 'I' in format and ftype == np.dtype('uint16'):
                bzero = np.uint16(2**15)
            elif 'J' in format and ftype == np.dtype('uint32'):
                bzero = np.uint32(2**31)
            elif 'K' in format and ftype == np.dtype('uint64'):
                bzero = np.uint64(2**63)

            c = Column(name=cname, format=format,
                       array=array.view(np.ndarray)[cname], bzero=bzero,
                       dim=dim)
            self.columns.append(c)

    def _init_from_table(self, table):
        hdr = table._header
        nfields = hdr['TFIELDS']

        # go through header keywords to pick out column definition keywords
        # definition dictionaries for each field
        col_keywords = [{} for i in range(nfields)]
        for keyword, value in iteritems(hdr):
            key = TDEF_RE.match(keyword)
            try:
                keyword = key.group('label')
            except:
                continue  # skip if there is no match
            if keyword in KEYWORD_NAMES:
                col = int(key.group('num'))
                if col <= nfields and col > 0:
                    attr = KEYWORD_TO_ATTRIBUTE[keyword]
                    if attr == 'format':
                        # Go ahead and convert the format value to the
                        # appropriate ColumnFormat container now
                        value = self._col_format_cls(value)
                    col_keywords[col - 1][attr] = value

        # Verify the column keywords and display any warnings if necessary;
        # we only want to pass on the valid keywords
        for idx, kwargs in enumerate(col_keywords):
            valid_kwargs, invalid_kwargs = Column._verify_keywords(**kwargs)
            for val in invalid_kwargs.values():
                warnings.warn(
                    'Invalid keyword for column %d: %s' % (idx + 1, val[1]),
                    VerifyWarning)
            # Special cases for recformat and dim
            # TODO: Try to eliminate the need for these special cases
            del valid_kwargs['recformat']
            if 'dim' in valid_kwargs:
                valid_kwargs['dim'] = kwargs['dim']
            col_keywords[idx] = valid_kwargs

        # data reading will be delayed
        for col in range(nfields):
            col_keywords[col]['array'] = Delayed(table, col)

        # now build the columns
        self.columns = [Column(**attrs) for attrs in col_keywords]

        # Add the table HDU is a listener to changes to the columns
        # (either changes to individual columns, or changes to the set of
        # columns (add/remove/etc.))
        self._add_listener(table)

    def __copy__(self):
        return self.__class__(self)

    def __deepcopy__(self, memo):
        return self.__class__([copy.deepcopy(c, memo) for c in self.columns])

    def _copy_column(self, column):
        """Utility function used currently only by _init_from_coldefs
        to help convert columns from binary format to ASCII format or vice
        versa if necessary (otherwise performs a straight copy).
        """

        if isinstance(column.format, self._col_format_cls):
            # This column has a FITS format compatible with this column
            # definitions class (that is ascii or binary)
            return column.copy()

        new_column = column.copy()

        # Try to use the Numpy recformat as the equivalency between the
        # two formats; if that conversion can't be made then these
        # columns can't be transferred
        # TODO: Catch exceptions here and raise an explicit error about
        # column format conversion
        new_column.format = self._col_format_cls.from_column_format(
                column.format)

        # Handle a few special cases of column format options that are not
        # compatible between ASCII an binary tables
        # TODO: This is sort of hacked in right now; we really need
        # separate classes for ASCII and Binary table Columns, and they
        # should handle formatting issues like these
        if not isinstance(new_column.format, _AsciiColumnFormat):
            # the column is a binary table column...
            new_column.start = None
            if new_column.null is not None:
                # We can't just "guess" a value to represent null
                # values in the new column, so just disable this for
                # now; users may modify it later
                new_column.null = None
        else:
            # the column is an ASCII table column...
            if new_column.null is not None:
                new_column.null = DEFAULT_ASCII_TNULL
            if (new_column.disp is not None and
                    new_column.disp.upper().startswith('L')):
                # ASCII columns may not use the logical data display format;
                # for now just drop the TDISPn option for this column as we
                # don't have a systematic conversion of boolean data to ASCII
                # tables yet
                new_column.disp = None

        return new_column

    def __getattr__(self, name):
        """
        Automatically returns the values for the given keyword attribute for
        all `Column`s in this list.

        Implements for example self.units, self.formats, etc.
        """

        cname = name[:-1]
        if cname in KEYWORD_ATTRIBUTES and name[-1] == 's':
            attr = []
            for col in self:
                val = getattr(col, cname)
                if val is not None:
                    attr.append(val)
                else:
                    attr.append('')
            return attr
        raise AttributeError(name)

    @lazyproperty
    def dtype(self):
        # Note: This previously returned a dtype that just used the raw field
        # widths based on the format's repeat count, and did not incorporate
        # field *shapes* as provided by TDIMn keywords.
        # Now this incorporates TDIMn from the start, which makes *this* method
        # a little more complicated, but simplifies code elsewhere (for example
        # fields will have the correct shapes even in the raw recarray).
        fields = []
        offsets = [0]

        for name, format_, dim in zip(self.names, self.formats, self._dims):
            dt = format_.dtype

            if len(offsets) < len(self.formats):
                # Note: the size of the *original* format_ may be greater than
                # one would expect from the number of elements determined by
                # dim.  The FITS format allows this--the rest of the field is
                # filled with undefined values.
                offsets.append(offsets[-1] + dt.itemsize)

            if dim:
                if format_.format == 'A':
                    dt = np.dtype((dt.char + str(dim[-1]), dim[:-1]))
                else:
                    dt = np.dtype((dt.base, dim))

            fields.append((name, dt))

        return nh.realign_dtype(np.dtype(fields), offsets)

    @lazyproperty
    def _arrays(self):
        return [col.array for col in self.columns]

    @lazyproperty
    def _recformats(self):
        return [fmt.recformat for fmt in self.formats]

    @lazyproperty
    def _dims(self):
        """Returns the values of the TDIMn keywords parsed into tuples."""

        return [col._dims for col in self.columns]

    def __getitem__(self, key):
        if isinstance(key, string_types):
            key = _get_index(self.names, key)

        x = self.columns[key]
        if _is_int(key):
            return x
        else:
            return ColDefs(x)

    def __len__(self):
        return len(self.columns)

    def __repr__(self):
        rep = 'ColDefs('
        if hasattr(self, 'columns') and self.columns:
            # The hasattr check is mostly just useful in debugging sessions
            # where self.columns may not be defined yet
            rep += '\n    '
            rep += '\n    '.join([repr(c) for c in self.columns])
            rep += '\n'
        rep += ')'
        return rep

    def __add__(self, other, option='left'):
        if isinstance(other, Column):
            b = [other]
        elif isinstance(other, ColDefs):
            b = list(other.columns)
        else:
            raise TypeError('Wrong type of input.')
        if option == 'left':
            tmp = list(self.columns) + b
        else:
            tmp = b + list(self.columns)
        return ColDefs(tmp)

    def __radd__(self, other):
        return self.__add__(other, 'right')

    def __sub__(self, other):
        if not isinstance(other, (list, tuple)):
            other = [other]
        _other = [_get_index(self.names, key) for key in other]
        indx = range(len(self))
        for x in _other:
            indx.remove(x)
        tmp = [self[i] for i in indx]
        return ColDefs(tmp)

    def _update_column_attribute_changed(self, column, attr, old_value,
                                         new_value):
        """
        Handle column attribute changed notifications from columns that are
        members of this `ColDefs`.

        `ColDefs` itself does not currently do anything with this, and just
        bubbles the notification up to any listening table HDUs that may need
        to update their headers, etc.  However, this also informs the table of
        the numerical index of the column that changed.
        """

        idx = 0
        for idx, col in enumerate(self.columns):
            if col is column:
                break

        self._notify('column_attribute_changed', column, idx, attr, old_value,
                     new_value)

    def add_col(self, column):
        """
        Append one `Column` to the column definition.

        .. warning::

            *New in pyfits 2.3*: This function appends the new column
            to the `ColDefs` object in place.  Prior to pyfits 2.3,
            this function returned a new `ColDefs` with the new column
            at the end.
        """

        assert isinstance(column, Column)

        self._arrays.append(column.array)
        # Obliterate caches of certain things
        del self.dtype
        del self._recformats
        del self._dims

        self.columns.append(column)

        # Listen for changes on the new column
        column._add_listener(self)

        # If this ColDefs is being tracked by a Table, inform the
        # table that its data is now invalid.
        self._notify('column_added', self, column)
        return self

    def del_col(self, col_name):
        """
        Delete (the definition of) one `Column`.

        col_name : str or int
            The column's name or index
        """

        indx = _get_index(self.names, col_name)
        col = self.columns[indx]

        del self._arrays[indx]
        # Obliterate caches of certain things
        del self.dtype
        del self._recformats
        del self._dims

        del self.columns[indx]

        col._remove_listener(self)

        # If this ColDefs is being tracked by a table HDU, inform the HDU (or
        # any other listeners) that the column has been removed
        # Just send a reference to self, and the index of the column that was
        # removed
        self._notify('column_removed', self, indx)
        return self

    def change_attrib(self, col_name, attrib, new_value):
        """
        Change an attribute (in the ``KEYWORD_ATTRIBUTES`` list) of a `Column`.

        Parameters
        ----------
        col_name : str or int
            The column name or index to change

        attrib : str
            The attribute name

        new_value : object
            The new value for the attribute
        """

        setattr(self[col_name], attrib, new_value)

    def change_name(self, col_name, new_name):
        """
        Change a `Column`'s name.

        Parameters
        ----------
        col_name : str
            The current name of the column

        new_name : str
            The new name of the column
        """

        if new_name != col_name and new_name in self.names:
            raise ValueError('New name %s already exists.' % new_name)
        else:
            self.change_attrib(col_name, 'name', new_name)

    def change_unit(self, col_name, new_unit):
        """
        Change a `Column`'s unit.

        Parameters
        ----------
        col_name : str or int
            The column name or index

        new_unit : str
            The new unit for the column
        """

        self.change_attrib(col_name, 'unit', new_unit)

    def info(self, attrib='all', output=None):
        """
        Get attribute(s) information of the column definition.

        Parameters
        ----------
        attrib : str
            Can be one or more of the attributes listed in
            ``pyfits.column.KEYWORD_ATTRIBUTES``.  The default is ``"all"``
            which will print out all attributes.  It forgives plurals and
            blanks.  If there are two or more attribute names, they must be
            separated by comma(s).

        output : file, optional
            File-like object to output to.  Outputs to stdout by default.
            If `False`, returns the attributes as a `dict` instead.

        Notes
        -----
        This function doesn't return anything by default; it just prints to
        stdout.
        """

        if output is None:
            output = sys.stdout

        if attrib.strip().lower() in ['all', '']:
            lst = KEYWORD_ATTRIBUTES
        else:
            lst = attrib.split(',')
            for idx in range(len(lst)):
                lst[idx] = lst[idx].strip().lower()
                if lst[idx][-1] == 's':
                    lst[idx] = list[idx][:-1]

        ret = {}

        for attr in lst:
            if output:
                if attr not in KEYWORD_ATTRIBUTES:
                    output.write("'%s' is not an attribute of the column "
                                 "definitions.\n" % attr)
                    continue
                output.write("%s:\n" % attr)
                output.write('    %s\n' % getattr(self, attr + 's'))
            else:
                ret[attr] = getattr(self, attr + 's')

        if not output:
            return ret FITS2NUMPY = {'L': 'i1', 'B': 'u1', 'I': 'i2', 'J': 'i4', 'K': 'i8', 'E': 'f4',
              'D': 'f8', 'C': 'c8', 'M': 'c16', 'A': 'a'} class FITS_rec(np.recarray):
    """
    FITS record array class.

    `FITS_rec` is the data part of a table HDU's data part.  This is a layer
    over the `~numpy.recarray`, so we can deal with scaled columns.

    It inherits all of the standard methods from `numpy.ndarray`.
    """

    _record_type = FITS_record

    def __new__(subtype, input):
        """
        Construct a FITS record array from a recarray.
        """

        # input should be a record array
        if input.dtype.subdtype is None:
            self = np.recarray.__new__(subtype, input.shape, input.dtype,
                                       buf=input.data)
        else:
            self = np.recarray.__new__(subtype, input.shape, input.dtype,
                                       buf=input.data, strides=input.strides)

        self._init()
        if self.dtype.fields:
            self._nfields = len(self.dtype.fields)

        return self

    def __setstate__(self, state):
        meta = state[-1]
        column_state = state[-2]
        state = state[:-2]

        super(FITS_rec, self).__setstate__(state)

        self._col_weakrefs = WeakSet()

        for attr, value in zip(meta, column_state):
            setattr(self, attr, value)

    def __reduce__(self):
        """
        Return a 3-tuple for pickling a FITS_rec. Use the super-class
        functionality but then add in a tuple of FITS_rec-specific
        values that get used in __setstate__.
        """
        super_class = np.ndarray
        reconst_func, reconst_func_args, state = super_class.__reduce__(self)

        # Define FITS_rec-specific attrs that get added to state
        column_state = []
        meta = []

        if '_coldefs' in self.__dict__:
            meta.append('_coldefs')
            column_state.append(self._coldefs.__deepcopy__(None))

        for attr in set(dir(self))-set(dir(self.__class__)):
            # _coldefs can be Delayed, and file objects cannot be
            # picked, it needs to be deepcopied first
            if attr == '_col_weakrefs':
                continue
            else:
                column_state.append(getattr(self, attr))
            meta.append(attr)

        state = state + (column_state, meta)

        return reconst_func, reconst_func_args, state

    def __array_finalize__(self, obj):
        if obj is None:
            return

        if isinstance(obj, FITS_rec) and obj.dtype == self.dtype:
            self._converted = obj._converted
            self._heapoffset = obj._heapoffset
            self._heapsize = obj._heapsize
            self._col_weakrefs = obj._col_weakrefs
            self._coldefs = obj._coldefs
            self._nfields = obj._nfields
            self._gap = obj._gap
            self._uint = obj._uint
        elif self.dtype.fields is not None:
            # This will allow regular ndarrays with fields, rather than
            # just other FITS_rec objects
            self._nfields = len(self.dtype.fields)
            self._converted = {}

            self._heapoffset = getattr(obj, '_heapoffset', 0)
            self._heapsize = getattr(obj, '_heapsize', 0)

            self._gap = getattr(obj, '_gap', 0)
            self._uint = getattr(obj, '_uint', False)
            self._col_weakrefs = WeakSet()
            self._coldefs = ColDefs(self)

            # Work around chicken-egg problem.  Column.array relies on the
            # _coldefs attribute to set up ref back to parent FITS_rec; however
            # in the above line the self._coldefs has not been assigned yet so
            # this fails.  This patches that up...
            for col in self._coldefs:
                del col.array
                col._parent_fits_rec = weakref.ref(self)
        else:
            self._init()

    def _init(self):
        """Initializes internal attributes specific to FITS-isms."""

        self._nfields = 0
        self._converted = {}
        self._heapoffset = 0
        self._heapsize = 0
        self._col_weakrefs = WeakSet()
        self._coldefs = None
        self._gap = 0
        self._uint = False

    @classmethod
    def from_columns(cls, columns, nrows=0, fill=False):
        """
        Given a `ColDefs` object of unknown origin, initialize a new `FITS_rec`
        object.

        .. note::

            This was originally part of the `new_table` function in the table
            module but was moved into a class method since most of its
            functionality always had more to do with initializing a `FITS_rec`
            object than anything else, and much of it also overlapped with
            ``FITS_rec._scale_back``.

        Parameters
        ----------
        columns : sequence of `Column` or a `ColDefs`
            The columns from which to create the table data.  If these
            columns have data arrays attached that data may be used in
            initializing the new table.  Otherwise the input columns
            will be used as a template for a new table with the requested
            number of rows.

        nrows : int
            Number of rows in the new table.  If the input columns have data
            associated with them, the size of the largest input column is used.
            Otherwise the default is 0.

        fill : bool
            If `True`, will fill all cells with zeros or blanks.  If
            `False`, copy the data from input, undefined cells will still
            be filled with zeros/blanks.
        """

        if not isinstance(columns, ColDefs):
            columns = ColDefs(columns)

        # read the delayed data
        for column in columns:
            arr = column.array
            if isinstance(arr, Delayed):
                if arr.hdu.data is None:
                    column.array = None
                else:
                    column.array = _get_recarray_field(arr.hdu.data,
                                                       arr.field)
        # Reset columns._arrays (which we may want to just do away with
        # altogether
        del columns._arrays

        # use the largest column shape as the shape of the record
        if nrows == 0:
            for arr in columns._arrays:
                if arr is not None:
                    dim = arr.shape[0]
                else:
                    dim = 0
                if dim > nrows:
                    nrows = dim

        raw_data = np.empty(columns.dtype.itemsize * nrows, dtype=np.uint8)
        raw_data.fill(ord(columns._padding_byte))
        data = np.recarray(nrows, dtype=columns.dtype, buf=raw_data).view(cls)

        # Make sure the data is a listener for changes to the columns
        columns._add_listener(data)

        # Previously this assignment was made from hdu.columns, but that's a
        # bug since if a _TableBaseHDU has a FITS_rec in its .data attribute
        # the _TableBaseHDU.columns property is actually returned from
        # .data._coldefs, so this assignment was circular!  Don't make that
        # mistake again.
        # All of this is an artifact of the fragility of the FITS_rec class,
        # and that it can't just be initialized by columns...
        data._coldefs = columns

        # If fill is True we don't copy anything from the column arrays.  We're
        # just using them as a template, and returning a table filled with
        # zeros/blanks
        if fill:
            return data

        # Otherwise we have to fill the recarray with data from the input
        # columns
        for idx, column in enumerate(columns):
            # For each column in the ColDef object, determine the number of
            # rows in that column.  This will be either the number of rows in
            # the ndarray associated with the column, or the number of rows
            # given in the call to this function, which ever is smaller.  If
            # the input FILL argument is true, the number of rows is set to
            # zero so that no data is copied from the original input data.
            arr = column.array

            if arr is None:
                array_size = 0
            else:
                array_size = len(arr)

            n = min(array_size, nrows)

            # TODO: At least *some* of this logic is mostly redundant with the
            # _convert_foo methods in this class; see if we can eliminate some
            # of that duplication.

            if not n:
                # The input column had an empty array, so just use the fill
                # value
                continue

            field = _get_recarray_field(data, idx)
            name = column.name
            fitsformat = column.format
            recformat = fitsformat.recformat

            outarr = field[:n]
            inarr = arr[:n]

            if isinstance(recformat, _FormatX):
                # Data is a bit array
                if inarr.shape[-1] == recformat.repeat:
                    _wrapx(inarr, outarr, recformat.repeat)
                    continue
            elif isinstance(recformat, _FormatP):
                data._cache_field(name, _makep(inarr, field, recformat,
                                               nrows=nrows))
                continue
            # TODO: Find a better way of determining that the column is meant
            # to be FITS L formatted
            elif recformat[-2:] == FITS2NUMPY['L'] and inarr.dtype == bool:
                # column is boolean
                # The raw data field should be filled with either 'T' or 'F'
                # (not 0).  Use 'F' as a default
                field[:] = ord('F')
                # Also save the original boolean array in data._converted so
                # that it doesn't have to be re-converted
                converted = np.zeros(field.shape, dtype=bool)
                converted[:n] = inarr
                data._cache_field(name, converted)
                # TODO: Maybe this step isn't necessary at all if _scale_back
                # will handle it?
                inarr = np.where(inarr == False, ord('F'), ord('T'))
            elif (columns[idx]._physical_values and
                    columns[idx]._pseudo_unsigned_ints):
                # Temporary hack...
                bzero = column.bzero
                converted = np.zeros(field.shape, dtype=inarr.dtype)
                converted[:n] = inarr
                data._cache_field(name, converted)
                if n < nrows:
                    # Pre-scale rows below the input data
                    field[n:] = -bzero

                inarr = inarr - bzero
            elif isinstance(columns, _AsciiColDefs):
                # Regardless whether the format is character or numeric, if the
                # input array contains characters then it's already in the raw
                # format for ASCII tables
                if fitsformat._pseudo_logical:
                    # Hack to support converting from 8-bit T/F characters
                    # Normally the column array is a chararray of 1 character
                    # strings, but we need to view it as a normal ndarray of
                    # 8-bit ints to fill it with ASCII codes for 'T' and 'F'
                    outarr = field.view(np.uint8, np.ndarray)[:n]
                elif arr.dtype.kind not in ('S', 'U'):
                    # Set up views of numeric columns with the appropriate
                    # numeric dtype
                    # Fill with the appropriate blanks for the column format
                    data._cache_field(name, np.zeros(nrows, dtype=arr.dtype))
                    outarr = data._converted[name][:n]

                outarr[:] = inarr
                continue

            if inarr.shape != outarr.shape:
                if (inarr.dtype.kind == outarr.dtype.kind and
                        inarr.dtype.kind in ('U', 'S') and
                        inarr.dtype != outarr.dtype):

                    inarr_rowsize = inarr[0].size
                    inarr = inarr.flatten().view(outarr.dtype)

                # This is a special case to handle input arrays with
                # non-trivial TDIMn.
                # By design each row of the outarray is 1-D, while each row of
                # the input array may be n-D
                if outarr.ndim > 1:
                    # The normal case where the first dimension is the rows
                    inarr_rowsize = inarr[0].size
                    inarr = inarr.reshape((n, inarr_rowsize))
                    outarr[:, :inarr_rowsize] = inarr
                else:
                    # Special case for strings where the out array only has one
                    # dimension (the second dimension is rolled up into the
                    # strings
                    outarr[:n] = inarr.ravel()
            else:
                outarr[:] = inarr

        # Now replace the original column array references with the new
        # fields
        # This is required to prevent the issue reported in
        # https://github.com/spacetelescope/PyFITS/issues/99
        for idx in range(len(columns)):
            columns._arrays[idx] = data.field(idx)

        return data

    def __repr__(self):
        # Force use of the normal ndarray repr (rather than the new
        # one added for recarray in Numpy 1.10) for backwards compat
        return np.ndarray.__repr__(self)

    def __getitem__(self, key):
        if self._coldefs is None:
            return super(FITS_rec, self).__getitem__(key)

        if isinstance(key, string_types):
            return self.field(key)
        elif isinstance(key, (slice, np.ndarray, tuple, list)):
            # Have to view as a recarray then back as a FITS_rec, otherwise the
            # circular reference fix/hack in FITS_rec.field() won't preserve
            # the slice
            subtype = type(self)
            out = self.view(np.recarray).__getitem__(key).view(subtype)
            out._coldefs = ColDefs(self._coldefs)
            arrays = []
            out._converted = {}
            for idx, name in enumerate(self._coldefs.names):
                #
                # Store the new arrays for the _coldefs object
                #
                arrays.append(self._coldefs._arrays[idx][key])

                # Ensure that the sliced FITS_rec will view the same scaled
                # columns as the original; this is one of the few cases where
                # it is not necessary to use _cache_field()
                if name in self._converted:
                    dummy = self._converted[name]
                    field = np.ndarray.__getitem__(dummy, key)
                    out._converted[name] = field

            out._coldefs._arrays = arrays
            return out

        # if not a slice, do this because Record has no __getstate__.
        # also more efficient.
        else:
            if isinstance(key, int) and key >= len(self):
                raise IndexError("Index out of bounds")

            newrecord = self._record_type(self, key)
            return newrecord

    def __setitem__(self, key, value):
        if self._coldefs is None:
            return super(FITS_rec, self).__setitem__(key, value)

        if isinstance(key, string_types):
            self[key][:] = value
            return

        if isinstance(key, slice):
            end = min(len(self), key.stop or len(self))
            end = max(0, end)
            start = max(0, key.start or 0)
            end = min(end, start + len(value))

            for idx in range(start, end):
                self.__setitem__(idx, value[idx - start])
            return

        if isinstance(value, FITS_record):
            for idx in range(self._nfields):
                self.field(self.names[idx])[key] = value.field(self.names[idx])
        elif isinstance(value, (tuple, list, np.void)):
            if self._nfields == len(value):
                for idx in range(self._nfields):
                    self.field(idx)[key] = value[idx]
            else:
                raise ValueError('Input tuple or list required to have %s '
                                 'elements.' % self._nfields)
        else:
            raise TypeError('Assignment requires a FITS_record, tuple, or '
                            'list as input.')

    def __getslice__(self, start, end):
        return self[slice(start, end)]

    def __setslice__(self, start, end, value):
        self[slice(start, end)] = value

    def copy(self, order='C'):
        """
        The Numpy documentation lies; `numpy.ndarray.copy` is not equivalent to
        `numpy.copy`.  Differences include that it re-views the copied array as
        self's ndarray subclass, as though it were taking a slice; this means
        ``__array_finalize__`` is called and the copy shares all the array
        attributes (including ``._converted``!).  So we need to make a deep
        copy of all those attributes so that the two arrays truly do not share
        any data.
        """

        new = super(FITS_rec, self).copy(order=order)
        new_dict = dict(self.__dict__)
        del new_dict['_col_weakrefs']
        new.__dict__ = copy.deepcopy(new_dict)

        # Re-fill _col_weakrefs
        new.__dict__['_col_weakrefs'] = WeakSet()
        new._coldefs = new._coldefs
        return new

    @property
    def columns(self):
        """
        A user-visible accessor for the coldefs.

        See https://aeon.stsci.edu/ssb/trac/pyfits/ticket/44
        """

        return self._coldefs

    @property
    def _coldefs(self):
        # This used to be a normal internal attribute, but it was changed to a
        # property as a quick and transparent way to work around the reference
        # leak bug fixed in https://github.com/astropy/astropy/pull/4539
        #
        # See the long comment in the Column.array property for more details
        # on this.  But in short, FITS_rec now has a ._col_weakrefs attribute
        # which is a WeakSet of weakrefs to each Column in _coldefs.
        #
        # So whenever ._coldefs is set we also add each Column in the ColDefs
        # to the weakrefs set.  This is an easy way to find out if a Column has
        # any references to it external to the FITS_rec (i.e. a user assigned a
        # column to a variable).  If the column is still in _col_weakrefs then
        # there are other references to it external to this FITS_rec.  We use
        # that information in __del__ to save off copies of the array data
        # for those columns to their Column.array property before our memory
        # is freed.
        return self.__dict__.get('_coldefs')

    @_coldefs.setter
    def _coldefs(self, cols):
        self.__dict__['_coldefs'] = cols
        if isinstance(cols, ColDefs):
            for col in cols.columns:
                self._col_weakrefs.add(col)

    @_coldefs.deleter
    def _coldefs(self):
        try:
            del self.__dict__['_coldefs']
        except KeyError as exc:
            raise AttributeError(exc.args[0])

    def __del__(self):
        try:
            del self._coldefs
        except AttributeError:
            pass
        else:
            if self.dtype.fields is not None:
                for col in self._col_weakrefs:
                    if isinstance(col.array, np.ndarray):
                        col.array = col.array.copy()

    @property
    def names(self):
        """List of column names."""

        if hasattr(self, '_coldefs') and self._coldefs is not None:
            return self._coldefs.names
        elif self.dtype.fields:
            return list(self.dtype.names)
        else:
            return None

    @property
    def formats(self):
        """List of column FITS foramts."""

        if hasattr(self, '_coldefs') and self._coldefs is not None:
            return self._coldefs.formats

        return None

    @property
    def _raw_itemsize(self):
        """
        Returns the size of row items that would be written to the raw FITS
        file, taking into account the possibility of unicode columns being
        compactified.

        Currently for internal use only.
        """

        if _has_unicode_fields(self):
            total_itemsize = 0
            for field in self.dtype.fields.values():
                itemsize = field[0].itemsize
                if field[0].kind == 'U':
                    itemsize = itemsize // 4
                total_itemsize += itemsize
            return total_itemsize
        else:
            # Just return the normal itemsize
            return self.itemsize

    def field(self, key):
        """
        A view of a `Column`'s data as an array.
        """

        # NOTE: The *column* index may not be the same as the field index in
        # the recarray, if the column is a phantom column
        column = self.columns[key]
        name = column.name
        format = column.format

        if format.dtype.itemsize == 0:
            warnings.warn(
                'Field %r has a repeat count of 0 in its format code, '
                'indicating an empty field.' % key)
            return np.array([], dtype=format.dtype)

        # If field's base is a FITS_rec, we can run into trouble because it
        # contains a reference to the ._coldefs object of the original data;
        # this can lead to a circular reference; see ticket #49
        base = self
        while (isinstance(base, FITS_rec) and
                isinstance(base.base, np.recarray)):
            base = base.base
        # base could still be a FITS_rec in some cases, so take care to
        # use rec.recarray.field to avoid a potential infinite
        # recursion
        field = _get_recarray_field(base, name)

        if name not in self._converted:
            recformat = format.recformat
            # TODO: If we're now passing the column to these subroutines, do we
            # really need to pass them the recformat?
            if isinstance(recformat, _FormatP):
                # for P format
                converted = self._convert_p(column, field, recformat)
            else:
                # Handle all other column data types which are fixed-width
                # fields
                converted = self._convert_other(column, field, recformat)

            # Note: Never assign values directly into the self._converted dict;
            # always go through self._cache_field; this way self._converted is
            # only used to store arrays that are not already direct views of
            # our own data.
            self._cache_field(name, converted)
            return converted

        return self._converted[name]

    def _cache_field(self, name, field):
        """
        Do not store fields in _converted if one of its bases is self,
        or if it has a common base with self.

        This results in a reference cycle that cannot be broken since
        ndarrays do not participate in cyclic garbage collection.
        """

        base = field
        while True:
            self_base = self
            while True:
                if self_base is base:
                    return

                if getattr(self_base, 'base', None) is not None:
                    self_base = self_base.base
                else:
                    break

            if getattr(base, 'base', None) is not None:
                base = base.base
            else:
                break

        self._converted[name] = field

    def _update_column_attribute_changed(self, column, idx, attr, old_value,
                                         new_value):
        """
        Update how the data is formatted depending on changes to column
        attributes initiated by the user through the `Column` interface.

        Dispatches column attribute change notifications to individual methods
        for each attribute ``_update_column_<attr>``
        """

        method_name = '_update_column_{0}'.format(attr)
        if hasattr(self, method_name):
            # Right now this is so we can be lazy and not implement updaters
            # for every attribute yet--some we may not need at all, TBD
            getattr(self, method_name)(column, idx, old_value, new_value)

    def _update_column_name(self, column, idx, old_name, name):
        """Update the dtype field names when a column name is changed."""

        dtype = self.dtype
        # Updating the names on the dtype should suffice
        dtype.names = dtype.names[:idx] + (name,) + dtype.names[idx + 1:]

    def _convert_x(self, field, recformat):
        """Convert a raw table column to a bit array as specified by the
        FITS X format.
        """

        dummy = np.zeros(self.shape + (recformat.repeat,), dtype=np.bool_)
        _unwrapx(field, dummy, recformat.repeat)
        return dummy

    def _convert_p(self, column, field, recformat):
        """Convert a raw table column of FITS P or Q format descriptors
        to a VLA column with the array data returned from the heap.
        """

        dummy = _VLF([None] * len(self), dtype=recformat.dtype)
        raw_data = self._get_raw_data()

        if raw_data is None:
            raise IOError(
                "Could not find heap data for the %r variable-length "
                "array column." % column.name)

        for idx in range(len(self)):
            offset = field[idx, 1] + self._heapoffset
            count = field[idx, 0]

            if recformat.dtype == 'a':
                dt = np.dtype(recformat.dtype + str(1))
                arr_len = count * dt.itemsize
                da = raw_data[offset:offset + arr_len].view(dt)
                da = np.char.array(da.view(dtype=dt), itemsize=count)
                dummy[idx] = decode_ascii(da)
            else:
                dt = np.dtype(recformat.dtype)
                arr_len = count * dt.itemsize
                dummy[idx] = raw_data[offset:offset + arr_len].view(dt)
                dummy[idx].dtype = dummy[idx].dtype.newbyteorder('>')
                # Each array in the field may now require additional
                # scaling depending on the other scaling parameters
                # TODO: The same scaling parameters apply to every
                # array in the column so this is currently very slow; we
                # really only need to check once whether any scaling will
                # be necessary and skip this step if not
                # TODO: Test that this works for X format; I don't think
                # that it does--the recformat variable only applies to the P
                # format not the X format
                dummy[idx] = self._convert_other(column, dummy[idx],
                                                 recformat)

        return dummy

    def _convert_ascii(self, column, field):
        """
        Special handling for ASCII table columns to convert columns containing
        numeric types to actual numeric arrays from the string representation.
        """

        format = column.format
        recformat = ASCII2NUMPY[format[0]]
        # if the string = TNULL, return ASCIITNULL
        nullval = str(column.null).strip().encode('ascii')
        if len(nullval) > format.width:
            nullval = nullval[:format.width]

        dummy = np.char.ljust(field, format.width)
        dummy = np.char.replace(dummy, encode_ascii('D'), encode_ascii('E'))
        null_fill = encode_ascii(str(ASCIITNULL).rjust(format.width))
        dummy = np.where(np.char.strip(dummy) == nullval, null_fill, dummy)

        try:
            dummy = np.array(dummy, dtype=recformat)
        except ValueError as exc:
            indx = self._coldefs.names.index(column.name)
            raise ValueError(
                '%s; the header may be missing the necessary TNULL%d '
                'keyword or the table contains invalid data' %
                (exc, indx + 1))

        return dummy

    def _convert_other(self, column, field, recformat):
        """Perform conversions on any other fixed-width column data types.

        This may not perform any conversion at all if it's not necessary, in
        which case the original column array is returned.
        """

        if isinstance(recformat, _FormatX):
            # special handling for the X format
            return self._convert_x(field, recformat)

        (_str, _bool, _number, _scale, _zero, bscale, bzero, dim) = \
            self._get_scale_factors(column)

        indx = self._coldefs.names.index(column.name)

        # ASCII table, convert strings to numbers
        # TODO:
        # For now, check that these are ASCII columns by checking the coldefs
        # type; in the future all columns (for binary tables, ASCII tables, or
        # otherwise) should "know" what type they are already and how to handle
        # converting their data from FITS format to native format and vice
        # versa...
        if not _str and isinstance(self._coldefs, _AsciiColDefs):
            field = self._convert_ascii(column, field)

        # Test that the dimensions given in dim are sensible; otherwise
        # display a warning and ignore them
        if dim:
            # See if the dimensions already match, if not, make sure the
            # number items will fit in the specified dimensions
            if field.ndim > 1:
                actual_shape = field.shape[1:]
                if _str:
                    actual_shape = actual_shape + (field.itemsize,)
            else:
                actual_shape = field.shape[0]

            if dim == actual_shape:
                # The array already has the correct dimensions, so we
                # ignore dim and don't convert
                dim = None
            else:
                nitems = reduce(operator.mul, dim)
                if _str:
                    actual_nitems = field.itemsize
                elif len(field.shape) == 1:  # No repeat count in TFORMn, equivalent to 1
                    actual_nitems = 1
                else:
                    actual_nitems = field.shape[1]
                if nitems > actual_nitems:
                    warnings.warn(
                        'TDIM%d value %s does not fit with the size of '
                        'the array items (%d).  TDIM%d will be ignored.'
                        % (indx + 1, self._coldefs.dims[indx],
                           actual_nitems, indx + 1))
                    dim = None

        # further conversion for both ASCII and binary tables
        # For now we've made columns responsible for *knowing* whether their
        # data has been scaled, but we make the FITS_rec class responsible for
        # actually doing the scaling
        # TODO: This also needs to be fixed in the effort to make Columns
        # responsible for scaling their arrays to/from FITS native values
        if not column.ascii and column.format.p_format:
            format_code = column.format.p_format
        else:
            # TODO: Rather than having this if/else it might be nice if the
            # ColumnFormat class had an attribute guaranteed to give the format
            # of actual values in a column regardless of whether the true
            # format is something like P or Q
            format_code = column.format.format

        if (_number and (_scale or _zero) and not column._physical_values):
            # This is to handle pseudo unsigned ints in table columns
            # TODO: For now this only really works correctly for binary tables
            # Should it work for ASCII tables as well?
            if self._uint:
                if bzero == 2**15 and format_code == 'I':
                    field = np.array(field, dtype=np.uint16)
                elif bzero == 2**31 and format_code == 'J':
                    field = np.array(field, dtype=np.uint32)
                elif bzero == 2**63 and format_code == 'K':
                    field = np.array(field, dtype=np.uint64)
                    bzero64 = np.uint64(2 ** 63)
                else:
                    field = np.array(field, dtype=np.float64)
            else:
                field = np.array(field, dtype=np.float64)

            if _scale:
                np.multiply(field, bscale, field)
            if _zero:
                if self._uint and format_code == 'K':
                    # There is a chance of overflow, so be careful
                    test_overflow = field.copy()
                    try:
                        test_overflow += bzero64
                    except OverflowError:
                        warnings.warn(
                            "Overflow detected while applying TZERO{0:d}. "
                            "Returning unscaled data.".format(indx + 1))
                    else:
                        field = test_overflow
                else:
                    field += bzero
        elif _bool and field.dtype != bool:
            field = np.equal(field, ord('T'))
        elif _str:
            with ignored(UnicodeDecodeError):
                field = decode_ascii(field)

        if dim:
            # Apply the new field item dimensions
            nitems = reduce(operator.mul, dim)
            if field.ndim > 1:
                field = field[:, :nitems]
            if _str:
                fmt = field.dtype.char
                dtype = ('|%s%d' % (fmt, dim[-1]), dim[:-1])
                field.dtype = dtype
            else:
                field.shape = (field.shape[0],) + dim

        return field

    def _get_heap_data(self):
        """
        Returns a pointer into the table's raw data to its heap (if present).

        This is returned as a numpy byte array.
        """

        if self._heapsize:
            raw_data = self._get_raw_data().view(np.ubyte)
            heap_end = self._heapoffset + self._heapsize
            return raw_data[self._heapoffset:heap_end]
        else:
            return np.array([], dtype=np.ubyte)

    def _get_raw_data(self):
        """
        Returns the base array of self that "raw data array" that is the
        array in the format that it was first read from a file before it was
        sliced or viewed as a different type in any way.

        This is determined by walking through the bases until finding one that
        has at least the same number of bytes as self, plus the heapsize.  This
        may be the immediate .base but is not always.  This is used primarily
        for variable-length array support which needs to be able to find the
        heap (the raw data *may* be larger than nbytes + heapsize if it
        contains a gap or padding).

        May return ``None`` if no array resembling the "raw data" according to
        the stated criteria can be found.
        """

        raw_data_bytes = self.nbytes + self._heapsize
        base = self
        while hasattr(base, 'base') and base.base is not None:
            base = base.base
            if hasattr(base, 'nbytes') and base.nbytes >= raw_data_bytes:
                return base

    def _get_scale_factors(self, column):
        """Get all the scaling flags and factors for one column."""

        # TODO: Maybe this should be a method/property on Column?  Or maybe
        # it's not really needed at all...
        _str = column.format.format == 'A'
        _bool = column.format.format == 'L'

        _number = not (_bool or _str)
        bscale = column.bscale
        bzero = column.bzero

        _scale = bscale not in ('', None, 1)
        _zero = bzero not in ('', None, 0)

        # ensure bscale/bzero are numbers
        if not _scale:
            bscale = 1
        if not _zero:
            bzero = 0

        # column._dims gives a tuple, rather than column.dim which returns the
        # original string format code from the FITS header...
        dim = column._dims

        return (_str, _bool, _number, _scale, _zero, bscale, bzero, dim)

    def _scale_back(self, update_heap_pointers=True):
        """
        Update the parent array, using the (latest) scaled array.

        If ``update_heap_pointers`` is `False`, this will leave all the heap
        pointers in P/Q columns as they are verbatim--it only makes sense to do
        this if there is already data on the heap and it can be guaranteed that
        that data has not been modified, and there is not new data to add to
        the heap.  Currently this is only used as an optimization for
        CompImageHDU that does its own handling of the heap.
        """

        # Running total for the new heap size
        heapsize = 0

        for indx, name in enumerate(self.dtype.names):
            column = self._coldefs[indx]
            recformat = column.format.recformat
            raw_field = _get_recarray_field(self, indx)

            # add the location offset of the heap area for each
            # variable length column
            if isinstance(recformat, _FormatP):
                # Irritatingly, this can return a different dtype than just
                # doing np.dtype(recformat.dtype); but this returns the results
                # that we want.  For example if recformat.dtype is 'a' we want
                # an array of characters.
                dtype = np.array([], dtype=recformat.dtype).dtype

                if update_heap_pointers and name in self._converted:
                    # The VLA has potentially been updated, so we need to
                    # update the array descriptors
                    raw_field[:] = 0  # reset
                    npts = [len(arr) for arr in self._converted[name]]

                    raw_field[:len(npts), 0] = npts
                    raw_field[1:, 1] = (np.add.accumulate(raw_field[:-1, 0]) *
                                        dtype.itemsize)
                    raw_field[:, 1][:] += heapsize

                heapsize += raw_field[:, 0].sum() * dtype.itemsize
                # Even if this VLA has not been read or updated, we need to
                # include the size of its constituent arrays in the heap size
                # total

            if isinstance(recformat, _FormatX) and name in self._converted:
                _wrapx(self._converted[name], raw_field, recformat.repeat)
                continue

            _str, _bool, _number, _scale, _zero, bscale, bzero, _ = \
                self._get_scale_factors(column)

            field = self._converted.get(name, raw_field)

            # conversion for both ASCII and binary tables
            if _number or _str:
                if _number and (_scale or _zero) and column._physical_values:
                    dummy = field.copy()
                    if _zero:
                        dummy -= bzero
                    if _scale:
                        dummy /= bscale
                    # This will set the raw values in the recarray back to
                    # their non-physical storage values, so the column should
                    # be mark is not scaled
                    column._physical_values = False
                elif _str or isinstance(self._coldefs, _AsciiColDefs):
                    dummy = field
                else:
                    continue

                # ASCII table, convert numbers to strings
                if isinstance(self._coldefs, _AsciiColDefs):
                    self._scale_back_ascii(indx, dummy, raw_field)
                # binary table string column
                elif isinstance(raw_field, chararray.chararray):
                    self._scale_back_strings(indx, dummy, raw_field)
                # all other binary table columns
                else:
                    if len(raw_field) and isinstance(raw_field[0],
                                                     np.integer):
                        dummy = np.around(dummy)

                    if raw_field.shape == dummy.shape:
                        raw_field[:] = dummy
                    else:
                        # Reshaping the data is necessary in cases where the
                        # TDIMn keyword was used to shape a column's entries
                        # into arrays
                        raw_field[:] = dummy.ravel().view(raw_field.dtype)

                del dummy

            # ASCII table does not have Boolean type
            elif _bool and name in self._converted:
                choices = (np.array([ord('F')], dtype=np.int8)[0],
                           np.array([ord('T')], dtype=np.int8)[0])
                raw_field[:] = np.choose(field, choices)

        # Store the updated heapsize
        self._heapsize = heapsize

    def _scale_back_strings(self, col_idx, input_field, output_field):
        # There are a few possibilities this has to be able to handle properly
        # The input_field, which comes from the _converted column is of dtype
        # 'Sn' (where n in string length) on Python 2--this is maintain the
        # existing user expectation of not being returned Python 2-style
        # unicode strings.  One Python 3 the array in _converted is of dtype
        # 'Un' so that elements read out of the array are normal Python 3 str
        # objects (i.e. unicode strings)
        #
        # At the other end the *output_field* may also be of type 'S' or of
        # type 'U'.  It will *usually* be of type 'S' (regardless of Python
        # version) because when reading an existing FITS table the raw data is
        # just ASCII strings, and represented in Numpy as an S array.
        # However, when a user creates a new table from scratch, they *might*
        # pass in a column containing unicode strings (dtype 'U'), especially
        # on Python 3 where this will be the default.  Therefore the
        # output_field of the raw array is actually a unicode array.  But we
        # still want to make sure the data is encodable as ASCII.  Later when
        # we write out the array we use, in the dtype 'U' case, a different
        # write routine that writes row by row and encodes any 'U' columns to
        # ASCII.

        # If the output_field is non-ASCII we will worry about ASCII encoding
        # later when writing; otherwise we can do it right here
        if input_field.dtype.kind == 'U' and output_field.dtype.kind == 'S':
            try:
                _ascii_encode(input_field, out=output_field)
            except _UnicodeArrayEncodeError as exc:
                raise ValueError(
                    "Could not save column '{0}': Contains characters that "
                    "cannot be encoded as ASCII as required by FITS, starting "
                    "at the index {1!r} of the column, and the index {2} of "
                    "the string at that location.".format(
                        self._coldefs.names[col_idx],
                        exc.index[0] if len(exc.index) == 1 else exc.index,
                        exc.start))
        else:
            # Otherwise go ahead and do a direct copy into--if both are type
            # 'U' we'll handle encoding later
            input_field = input_field.flatten().view(output_field.dtype)
            output_field.flat[:] = input_field

        # Ensure that blanks at the end of each string are
        # converted to nulls instead of spaces, see Trac #15
        # and #111
        _rstrip_inplace(output_field)


    def _scale_back_ascii(self, col_idx, input_field, output_field):
        """
        Convert internal array values back to ASCII table representation.

        The ``input_field`` is the internal representation of the values, and
        the ``output_field`` is the character array representing the ASCII
        output that will be written.
        """

        starts = self._coldefs.starts[:]
        spans = self._coldefs.spans
        format = self._coldefs.formats[col_idx]

        # The the index of the "end" column of the record, beyond
        # which we can't write
        end = super(FITS_rec, self).field(-1).itemsize
        starts.append(end + starts[-1])

        if col_idx > 0:
            lead = starts[col_idx] - starts[col_idx - 1] - spans[col_idx - 1]
        else:
            lead = 0

        if lead < 0:
            warnings.warn('Column %r starting point overlaps the previous '
                          'column.' % (col_idx + 1))

        trail = starts[col_idx + 1] - starts[col_idx] - spans[col_idx]

        if trail < 0:
            warnings.warn('Column %r ending point overlaps the next '
                          'column.' % (col_idx + 1))

        # TODO: It would be nice if these string column formatting
        # details were left to a specialized class, as is the case
        # with FormatX and FormatP
        if 'A' in format:
            _pc = '%-'
        else:
            _pc = '%'

        fmt = ''.join([_pc, format[1:], ASCII2STR[format[0]],
                       (' ' * trail)])

        # Even if the format precision is 0, we should output a decimal point
        # as long as there is space to do so--not including a decimal point in
        # a float value is discouraged by the FITS Standard
        trailing_decimal = (format.precision == 0 and
                            format.format in ('F', 'E', 'D'))

        # not using numarray.strings's num2char because the
        # result is not allowed to expand (as C/Python does).
        for jdx, value in enumerate(input_field):
            value = fmt % value
            if len(value) > starts[col_idx + 1] - starts[col_idx]:
                raise ValueError(
                    "Value %r does not fit into the output's itemsize of "
                    "%s." % (value, spans[col_idx]))

            if trailing_decimal and value[0] == ' ':
                # We have some extra space in the field for the trailing
                # decimal point
                value = value[1:] + '.'

            output_field[jdx] = value

        # Replace exponent separator in floating point numbers
        if 'D' in format:
            output_field.replace(encode_ascii('E'), encode_ascii('D')) class FITS_record(object):
    """
    FITS record class.

    `FITS_record` is used to access records of the `FITS_rec` object.
    This will allow us to deal with scaled columns.  It also handles
    conversion/scaling of columns in ASCII tables.  The `FITS_record`
    class expects a `FITS_rec` object as input.
    """

    def __init__(self, input, row=0, start=None, end=None, step=None,
                 base=None):
        """
        Parameters
        ----------
        input : array
           The array to wrap.

        row : int, optional
           The starting logical row of the array.

        start : int, optional
           The starting column in the row associated with this object.
           Used for subsetting the columns of the `FITS_rec` object.

        end : int, optional
           The ending column in the row associated with this object.
           Used for subsetting the columns of the `FITS_rec` object.
        """

        self.array = input
        self.row = row
        if base:
            width = len(base)
        else:
            width = self.array._nfields

        s = slice(start, end, step).indices(width)
        self.start, self.end, self.step = s
        self.base = base

    def __getitem__(self, key):
        if isinstance(key, string_types):
            indx = _get_index(self.array.names, key)

            if indx < self.start or indx > self.end - 1:
                raise KeyError("Key '%s' does not exist." % key)
        elif isinstance(key, slice):
            return type(self)(self.array, self.row, key.start, key.stop,
                              key.step, self)
        else:
            indx = self._get_index(key)

            if indx > self.array._nfields - 1:
                raise IndexError('Index out of bounds')

        return self.array.field(indx)[self.row]

    def __setitem__(self, key, value):
        if isinstance(key, string_types):
            indx = _get_index(self.array._coldefs.names, key)

            if indx < self.start or indx > self.end - 1:
                raise KeyError("Key '%s' does not exist." % key)
        elif isinstance(key, slice):
            for indx in xrange(slice.start, slice.stop, slice.step):
                indx = self._get_indx(indx)
                self.array.field(indx)[self.row] = value
        else:
            indx = self._get_index(key)
            if indx > self.array._nfields - 1:
                raise IndexError('Index out of bounds')

        self.array.field(indx)[self.row] = value

    def __getslice__(self, start, end):
        return self[slice(start, end)]

    def __len__(self):
        return len(xrange(self.start, self.end, self.step))

    def __repr__(self):
        """
        Display a single row.
        """

        outlist = []
        for idx in xrange(len(self)):
            outlist.append(repr(self[idx]))
        return '(%s)' % ', '.join(outlist)

    def field(self, field):
        """
        Get the field data of the record.
        """

        return self.__getitem__(field)

    def setfield(self, field, value):
        """
        Set the field data of the record.
        """

        self.__setitem__(field, value)

    @lazyproperty
    def _bases(self):
        bases = [weakref.proxy(self)]
        base = self.base
        while base:
            bases.append(base)
            base = base.base
        return bases

    def _get_index(self, indx):
        indices = np.ogrid[:self.array._nfields]
        for base in reversed(self._bases):
            if base.step < 1:
                s = slice(base.start, None, base.step)
            else:
                s = slice(base.start, base.end, base.step)
            indices = indices[s]
        return indices[indx] class lazyproperty(object):
    """
    Works similarly to property(), but computes the value only once.

    Adapted from the recipe at
    http://code.activestate.com/recipes/363602-lazy-property-evaluation
    """

    def __init__(self, fget, fset=None, fdel=None, doc=None):
        self._fget = fget
        self._fset = fset
        self._fdel = fdel
        if doc is None:
            self.__doc__ = fget.__doc__
        else:
            self.__doc__ = doc
        self._key = self._fget.__name__

    def __get__(self, obj, owner=None):
        if obj is None:
            return self
        try:
            return obj.__dict__[self._key]
        except KeyError:
            val = self._fget(obj)
            obj.__dict__[self._key] = val
            return val

    def __set__(self, obj, val):
        obj_dict = obj.__dict__
        if self._fset:
            ret = self._fset(obj, val)
            if ret is not None and obj_dict.get(self._key) is ret:
                # By returning the value set the setter signals that it took
                # over setting the value in obj.__dict__; this mechanism allows
                # it to override the input value
                return
        obj_dict[self._key] = val

    def __delete__(self, obj):
        if self._fdel:
            self._fdel(obj)
        if self._key in obj.__dict__:
            del obj.__dict__[self._key]

    def getter(self, fget):
        return self.__ter(fget, 0)

    def setter(self, fset):
        return self.__ter(fset, 1)

    def deleter(self, fdel):
        return self.__ter(fdel, 2)

    def __ter(self, f, arg):
        args = [self._fget, self._fset, self._fdel, self.__doc__]
        args[arg] = f
        cls_ns = sys._getframe(1).f_locals
        for k, v in iteritems(cls_ns):
            if v is self:
                property_name = k
                break

        cls_ns[property_name] = lazyproperty(*args)

        return cls_ns[property_name] def _is_int(val):
    return isinstance(val, integer_types + (np.integer,)) def _is_pseudo_unsigned(dtype):
    return dtype.kind == 'u' and dtype.itemsize >= 2 def _unsigned_zero(dtype):
    """
    Given a numpy dtype, finds its "zero" point, which is exactly in the
    middle of its range.
    """

    assert dtype.kind == 'u'
    return 1 << (dtype.itemsize * 8 - 1) DTYPE2BITPIX = {'uint8': 8, 'int16': 16, 'uint16': 16, 'int32': 32,
                'uint32': 32, 'int64': 64, 'uint64': 64, 'float32': -32,
                'float64': -64} class PrimaryHDU(_ImageBaseHDU):
    """
    FITS primary HDU class.
    """

    _default_name = 'PRIMARY'

    def __init__(self, data=None, header=None, do_not_scale_image_data=False,
                 ignore_blank=False,
                 uint=True, scale_back=None):
        """
        Construct a primary HDU.

        Parameters
        ----------
        data : array or DELAYED, optional
            The data in the HDU.

        header : Header instance, optional
            The header to be used (as a template).  If ``header`` is `None`, a
            minimal header will be provided.

        do_not_scale_image_data : bool, optional
            If `True`, image data is not scaled using BSCALE/BZERO values
            when read. (default: False)

        ignore_blank : bool, optional
            If `True`, the BLANK header keyword will be ignored if present.
            Otherwise, pixels equal to this value will be replaced with
            NaNs. (default: False)

        uint : bool, optional
            Interpret signed integer data where ``BZERO`` is the
            central value and ``BSCALE == 1`` as unsigned integer
            data.  For example, ``int16`` data with ``BZERO = 32768``
            and ``BSCALE = 1`` would be treated as ``uint16`` data.
            (default: True)

        scale_back : bool, optional
            If `True`, when saving changes to a file that contained scaled
            image data, restore the data to the original type and reapply the
            original BSCALE/BZERO values.  This could lead to loss of accuracy
            if scaling back to integer values after performing floating point
            operations on the data.  Pseudo-unsigned integers are automatically
            rescaled unless scale_back is explicitly set to `False`.
            (default: None)
        """

        super(PrimaryHDU, self).__init__(
            data=data, header=header,
            do_not_scale_image_data=do_not_scale_image_data, uint=uint,
            ignore_blank=ignore_blank,
            scale_back=scale_back)

        # insert the keywords EXTEND
        if header is None:
            dim = self._header['NAXIS']
            if dim == 0:
                dim = ''
            self._header.set('EXTEND', True, after='NAXIS' + str(dim))

    @classmethod
    def match_header(cls, header):
        card = header.cards[0]
        return (card.keyword == 'SIMPLE' and
                ('GROUPS' not in header or header['GROUPS'] != True) and
                card.value == True)

    def update_header(self):
        super(PrimaryHDU, self).update_header()

        # Update the position of the EXTEND keyword if it already exists
        if 'EXTEND' in self._header:
            if len(self._axes):
                after = 'NAXIS' + str(len(self._axes))
            else:
                after = 'NAXIS'
            self._header.set('EXTEND', after=after)

    def _verify(self, option='warn'):
        errs = super(PrimaryHDU, self)._verify(option=option)

        # Verify location and value of mandatory keywords.
        # The EXTEND keyword is only mandatory if the HDU has extensions; this
        # condition is checked by the HDUList object.  However, if we already
        # have an EXTEND keyword check that its position is correct
        if 'EXTEND' in self._header:
            naxis = self._header.get('NAXIS', 0)
            self.req_cards('EXTEND', naxis + 3, lambda v: isinstance(v, bool),
                           True, option, errs)
        return errs class _TableLikeHDU(_ValidHDU):
    """
    A class for HDUs that have table-like data.  This is used for both
    Binary/ASCII tables as well as Random Access Group HDUs (which are
    otherwise too dissimilar for tables to use _TableBaseHDU directly).
    """

    _data_type = FITS_rec
    _columns_type = ColDefs

    # TODO: Temporary flag representing whether uints are enabled; remove this
    # after restructuring to support uints by default on a per-column basis
    _uint = False

    @classmethod
    def match_header(cls, header):
        """
        This is an abstract HDU type for HDUs that contain table-like data.
        This is even more abstract than _TableBaseHDU which is specifically for
        the standard ASCII and Binary Table types.
        """

        raise NotImplementedError

    @classmethod
    def from_columns(cls, columns, header=None, nrows=0, fill=False,
                     **kwargs):
        """
        Given either a `ColDefs` object, a sequence of `Column` objects,
        or another table HDU or table data (a `FITS_rec` or multi-field
        `numpy.ndarray` or `numpy.recarray` object, return a new table HDU of
        the class this method was called on using the column definition from
        the input.

        This is an alternative to the now deprecated `new_table` function,
        and otherwise accepts the same arguments.  See also
        `FITS_rec.from_columns`.

        Parameters
        ----------
        columns : sequence of `Column`, `ColDefs`, or other
            The columns from which to create the table data, or an object with
            a column-like structure from which a `ColDefs` can be instantiated.
            This includes an existing `BinTableHDU` or `TableHDU`, or a
            `numpy.recarray` to give some examples.

            If these columns have data arrays attached that data may be used in
            initializing the new table.  Otherwise the input columns will be
            used as a template for a new table with the requested number of
            rows.

        header : `Header`
            An optional `Header` object to instantiate the new HDU yet.  Header
            keywords specifically related to defining the table structure (such
            as the "TXXXn" keywords like TTYPEn) will be overridden by the
            supplied column definitions, but all other informational and data
            model-specific keywords are kept.

        nrows : int
            Number of rows in the new table.  If the input columns have data
            associated with them, the size of the largest input column is used.
            Otherwise the default is 0.

        fill : bool
            If `True`, will fill all cells with zeros or blanks.  If `False`,
            copy the data from input, undefined cells will still be filled with
            zeros/blanks.

        Notes
        -----

        Any additional keyword arguments accepted by the HDU class's
        ``__init__`` may also be passed in as keyword arguments.
        """

        coldefs = cls._columns_type(columns)
        data = FITS_rec.from_columns(coldefs, nrows=nrows, fill=fill)
        hdu = cls(data=data, header=header, **kwargs)
        coldefs._add_listener(hdu)
        return hdu

    @lazyproperty
    def columns(self):
        """
        The :class:`ColDefs` objects describing the columns in this table.
        """

        # The base class doesn't make any assumptions about where the column
        # definitions come from, so just return an empty ColDefs
        return ColDefs([])

    @property
    def _nrows(self):
        """
        Table-like HDUs must provide an attribute that specifies the number of
        rows in the HDU's table.

        For now this is an internal-only attribute.
        """

        raise NotImplementedError

    def _get_tbdata(self):
        """Get the table data from an input HDU object."""

        columns = self.columns

        # TODO: Details related to variable length arrays need to be dealt with
        # specifically in the BinTableHDU class, since they're a detail
        # specific to FITS binary tables
        if (any(type(r) in (_FormatP, _FormatQ)
                for r in columns._recformats) and
                self._data_size is not None and
                self._data_size > self._theap):
            # We have a heap; include it in the raw_data
            raw_data = self._get_raw_data(self._data_size, np.uint8,
                                          self._data_offset)
            data = raw_data[:self._theap].view(dtype=columns.dtype,
                                               type=np.rec.recarray)
        else:
            raw_data = self._get_raw_data(self._nrows, columns.dtype,
                                          self._data_offset)
            if raw_data is None:
                # This can happen when a brand new table HDU is being created
                # and no data has been assigned to the columns, which case just
                # return an empty array
                raw_data = np.array([], dtype=columns.dtype)

            data = raw_data.view(np.rec.recarray)

        self._init_tbdata(data)
        data = data.view(self._data_type)
        columns._add_listener(data)
        return data

    def _init_tbdata(self, data):
        columns = self.columns

        data.dtype = data.dtype.newbyteorder('>')

        # hack to enable pseudo-uint support
        data._uint = self._uint

        # pass datLoc, for P format
        data._heapoffset = self._theap
        data._heapsize = self._header['PCOUNT']
        tbsize = self._header['NAXIS1'] * self._header['NAXIS2']
        data._gap = self._theap - tbsize

        # pass the attributes
        for idx, col in enumerate(columns):
            # get the data for each column object from the rec.recarray
            col.array = data.field(idx)

        # delete the _arrays attribute so that it is recreated to point to the
        # new data placed in the column object above
        del columns._arrays

    def _update_column_added(self, columns, column):
        """
        Update the data upon addition of a new column through the `ColDefs`
        interface.
        """

        # TODO: It's not clear that this actually works--it probably does not.
        # This is what the code used to do before introduction of the
        # notifier interface, but I don't believe it actually worked (there are
        # several bug reports related to this...)
        if self._data_loaded:
            del self.data

    def _update_column_removed(self, columns, col_idx):
        """
        Update the data upon removal of a column through the `ColDefs`
        interface.
        """

        # For now this doesn't do anything fancy--it just deletes the data
        # attribute so that it is forced to be recreated again.  It doesn't
        # change anything on the existing data recarray (this is also how this
        # worked before introducing the notifier interface)
        if self._data_loaded:
            del self.data
import sys
import numpy as np
from ..column import Column, ColDefs, FITS2NUMPY
from ..fitsrec import FITS_rec, FITS_record
from ..util import lazyproperty, _is_int, _is_pseudo_unsigned, _unsigned_zero
from .base import DTYPE2BITPIX
from .image import PrimaryHDU
from .table import _TableLikeHDU
            # representation of the data
            return self._header.get('GCOUNT', 0)
        else:
            return len(self.data)

    @lazyproperty
    def _theap(self):
        # Only really a lazyproperty for symmetry with _TableBaseHDU
        return 0

    @property
    def size(self):
        """
        Returns the size (in bytes) of the HDU's data part.
        """

        size = 0
        naxis = self._header.get('NAXIS', 0)

        # for random group image, NAXIS1 should be 0, so we skip NAXIS1.
        if naxis > 1:
            size = 1
            for idx in range(1, naxis):
                size = size * self._header['NAXIS' + str(idx + 1)]
            bitpix = self._header['BITPIX']
            gcount = self._header.get('GCOUNT', 1)
            pcount = self._header.get('PCOUNT', 0)
            size = abs(bitpix) * gcount * (pcount + size) // 8
        return size

    def update_header(self):
        old_naxis = self._header.get('NAXIS', 0)

        if self._data_loaded:
            if isinstance(self.data, GroupData):
                self._axes = list(self.data.data.shape)[1:]
                self._axes.reverse()
                self._axes = [0] + self._axes
                field0 = self.data.dtype.names[0]
                field0_code = self.data.dtype.fields[field0][0].name
            elif self.data is None:
                self._axes = [0]
                field0_code = 'uint8'  # For lack of a better default
            else:
                raise ValueError('incorrect array type')

            self._header['BITPIX'] = DTYPE2BITPIX[field0_code]

        self._header['NAXIS'] = len(self._axes)

        # add NAXISi if it does not exist
        for idx, axis in enumerate(self._axes):
            if (idx == 0):
                after = 'NAXIS'
            else:
                after = 'NAXIS' + str(idx)

            self._header.set('NAXIS' + str(idx + 1), axis, after=after)

        # delete extra NAXISi's
        for idx in range(len(self._axes) + 1, old_naxis + 1):
            try:
                del self._header['NAXIS' + str(idx)]
            except KeyError:
                pass

        if self._has_data and isinstance(self.data, GroupData):
            self._header.set('GROUPS', True,
                             after='NAXIS' + str(len(self._axes)))
            self._header.set('PCOUNT', len(self.data.parnames), after='GROUPS')
            self._header.set('GCOUNT', len(self.data), after='PCOUNT')

            column = self.data._coldefs[self._data_field]
            scale, zero = self.data._get_scale_factors(column)[3:5]
            if scale:
                self._header.set('BSCALE', column.bscale)
            if zero:
                self._header.set('BZERO', column.bzero)

            for idx, name in enumerate(self.data.parnames):
                self._header.set('PTYPE' + str(idx + 1), name)
                column = self.data._coldefs[idx]
                scale, zero = self.data._get_scale_factors(column)[3:5]
                if scale:
                    self._header.set('PSCAL' + str(idx + 1), column.bscale)
                if zero:
                    self._header.set('PZERO' + str(idx + 1), column.bzero)

        # Update the position of the EXTEND keyword if it already exists
        if 'EXTEND' in self._header:
            if len(self._axes):
                after = 'NAXIS' + str(len(self._axes))
            else:
                after = 'NAXIS'
            self._header.set('EXTEND', after=after)

    def _writedata_internal(self, fileobj):
        """
        Basically copy/pasted from `_ImageBaseHDU._writedata_internal()`, but
        we have to get the data's byte order a different way...

        TODO: Might be nice to store some indication of the data's byte order
        as an attribute or function so that we don't have to do this.
        """

        size = 0

        if self.data is not None:
            self.data._scale_back()

            # Based on the system type, determine the byteorders that
            # would need to be swapped to get to big-endian output
            if sys.byteorder == 'little':
                swap_types = ('<', '=')
            else:
                swap_types = ('<',)
            # deal with unsigned integer 16, 32 and 64 data
            if _is_pseudo_unsigned(self.data.dtype):
                # Convert the unsigned array to signed
                output = np.array(

                    self.data - _unsigned_zero(self.data.dtype),