Input GEIS files "input" will be read and a HDUList object will
       be returned.

       The user can use the writeto method to write the HDUList object to
       a FITS file.
552016
def readgeis(input):

    

    global dat
    cardLen = fits.Card.length

    # input file(s) must be of the form *.??h and *.??d
    if input[-1] != 'h' or input[-4] != '.':
        raise "Illegal input GEIS file name %s" % input

    data_file = input[:-1]+'d'

    _os = sys.platform
    if _os[:5] == 'linux' or _os[:5] == 'win32' or _os[:5] == 'sunos' or _os[:3] == 'osf' or _os[:6] == 'darwin':
        bytes_per_line = cardLen+1
    else:
        raise "Platform %s is not supported (yet)." % _os

    geis_fmt = {'REAL':'f', 'INTEGER':'i', 'LOGICAL':'i','CHARACTER':'S'}
    end_card = 'END'+' '* (cardLen-3)

    # open input file
    im = open(input)

    # Generate the primary HDU
    cards = []
    while 1:
        line = im.read(bytes_per_line)[:cardLen]
        line = line[:8].upper() + line[8:]
        if line == end_card:
            break
        cards.append(fits.Card.fromstring(line))

    phdr = fits.Header(cards)
    im.close()

    _naxis0 = phdr.get('NAXIS', 0)
    _naxis = [phdr['NAXIS'+str(j)] for j in range(1, _naxis0+1)]
    _naxis.insert(0, _naxis0)
    _bitpix = phdr['BITPIX']
    _psize = phdr['PSIZE']
    if phdr['DATATYPE'][:4] == 'REAL':
        _bitpix = -_bitpix
    if _naxis0 > 0:
        size = reduce(lambda x,y:x*y, _naxis[1:])
        data_size = abs(_bitpix) * size // 8
    else:
        data_size = 0
    group_size = data_size + _psize // 8

    # decode the group parameter definitions,
    # group parameters will become extension header
    groups = phdr['GROUPS']
    gcount = phdr['GCOUNT']
    pcount = phdr['PCOUNT']

    formats = []
    bools = []
    floats = []
    _range = range(1, pcount+1)
    key = [phdr['PTYPE'+str(j)] for j in _range]
    comm = [phdr.cards['PTYPE'+str(j)].comment for j in _range]

    # delete group parameter definition header keywords
    _list = ['PTYPE'+str(j) for j in _range] + \
            ['PDTYPE'+str(j) for j in _range] + \
            ['PSIZE'+str(j) for j in _range] + \
            ['DATATYPE', 'PSIZE', 'GCOUNT', 'PCOUNT', 'BSCALE', 'BZERO']

    # Construct record array formats for the group parameters
    # as interpreted from the Primary header file
    for i in range(1, pcount+1):
        ptype = key[i-1]
        pdtype = phdr['PDTYPE'+str(i)]
        star = pdtype.find('*')
        _type = pdtype[:star]
        _bytes = pdtype[star+1:]

        # collect boolean keywords since they need special attention later

        if _type == 'LOGICAL':
            bools.append(i)
        if pdtype == 'REAL*4':
            floats.append(i)

        fmt = geis_fmt[_type] + _bytes
        formats.append((ptype,fmt))

    _shape = _naxis[1:]
    _shape.reverse()
    _code = fits.BITPIX2DTYPE[_bitpix]
    _bscale = phdr.get('BSCALE', 1)
    _bzero = phdr.get('BZERO', 0)
    if phdr['DATATYPE'][:10] == 'UNSIGNED*2':
        _uint16 = 1
        _bzero = 32768
    else:
        _uint16 = 0

    # delete from the end, so it will not conflict with previous delete
    for i in range(len(phdr)-1, -1, -1):
        if phdr.cards[i].keyword in _list:
            del phdr[i]

    # clean up other primary header keywords
    phdr['SIMPLE'] = True
    phdr['BITPIX'] = 16
    phdr['GROUPS'] = False
    _after = 'NAXIS'
    if _naxis0 > 0:
        _after += str(_naxis0)
    phdr.set('EXTEND', value=True, comment="FITS dataset may contain extensions", after=_after)
    phdr.set('NEXTEND', value=gcount, comment="Number of standard extensions")

    hdulist = fits.HDUList([fits.PrimaryHDU(header=phdr, data=None)])

    # Use copy-on-write for all data types since byteswap may be needed
    # in some platforms.
    f1 = open(data_file, mode='rb')
    dat = f1.read()
#    dat = memmap(data_file, mode='c')
    hdulist.mmobject = dat

    errormsg = ""

    loc = 0
    for k in range(gcount):
        ext_dat = numpy.fromstring(dat[loc:loc+data_size], dtype=_code)
        ext_dat = ext_dat.reshape(_shape)
        if _uint16:
            ext_dat += _bzero
        # Check to see whether there are any NaN's or infs which might indicate
        # a byte-swapping problem, such as being written out on little-endian
        #   and being read in on big-endian or vice-versa.
        if _code.find('float') >= 0 and \
            (numpy.any(numpy.isnan(ext_dat)) or numpy.any(numpy.isinf(ext_dat))):
            errormsg += "===================================\n"
            errormsg += "= WARNING:                        =\n"
            errormsg += "=  Input image:                   =\n"
            errormsg += input+"[%d]\n"%(k+1)
            errormsg += "=  had floating point data values =\n"
            errormsg += "=  of NaN and/or Inf.             =\n"
            errormsg += "===================================\n"
        elif _code.find('int') >= 0:
            # Check INT data for max values
            ext_dat_frac,ext_dat_exp = numpy.frexp(ext_dat)
            if ext_dat_exp.max() == int(_bitpix) - 1:
                # Potential problems with byteswapping
                errormsg += "===================================\n"
                errormsg += "= WARNING:                        =\n"
                errormsg += "=  Input image:                   =\n"
                errormsg += input+"[%d]\n"%(k+1)
                errormsg += "=  had integer data values        =\n"
                errormsg += "=  with maximum bitvalues.        =\n"
                errormsg += "===================================\n"

        ext_hdu = fits.ImageHDU(data=ext_dat)

        rec = numpy.fromstring(dat[loc+data_size:loc+group_size], dtype=formats)

        loc += group_size

        # Create separate PyFITS Card objects for each entry in 'rec'
        for i in range(1, pcount+1):
            #val = rec.field(i-1)[0]
            val = rec[0][i-1]
            if val.dtype.kind == 'S':
                val = val.decode('ascii')

            if i in bools:
                if val:
                    val = True
                else:
                    val = False

            if i in floats:
                # use fromstring, format in Card is deprecated in pyfits 0.9
                _str = '%-8s= %20.7G / %s' % (key[i-1], val, comm[i-1])
                _card = fits.Card.fromstring(_str)
            else:
                _card = fits.Card(keyword=key[i-1], value=val, comment=comm[i-1])

            ext_hdu.header.append(_card)

        # deal with bscale/bzero
        if (_bscale != 1 or _bzero != 0):
            ext_hdu.header['BSCALE'] = _bscale
            ext_hdu.header['BZERO'] = _bzero

        hdulist.append(ext_hdu)

    if errormsg != "":
        errormsg += "===================================\n"
        errormsg += "=  This file may have been        =\n"
        errormsg += "=  written out on a platform      =\n"
        errormsg += "=  with a different byte-order.   =\n"
        errormsg += "=                                 =\n"
        errormsg += "=  Please verify that the values  =\n"
        errormsg += "=  are correct or apply the       =\n"
        errormsg += "=  '.byteswap()' method.          =\n"
        errormsg += "===================================\n"
        print(errormsg)

    f1.close()
    stsci(hdulist)
    return hdulist
866084
def cl_input(fname, unpack=True, anonpipe=True):
    
    try:
        manager = _get_storage_manager(fname)
    except ValueError:
        return fname

    return manager.cl_input(fname, unpack, anonpipe)
1111582
def as_hdu(self):
        ""
        from astropy.io import fits

        # transfer header, preserving ordering
        ahdr = self.get_header()
        header = fits.Header(ahdr.items())
        data = self.get_mddata()

        hdu = fits.PrimaryHDU(data=data, header=header)
        return hdu
251280
def build_data_input(cls, name='input'):
        
        return cls(name, PortDirection.INPUT, type=PortType.DATA)
1056983
def load_inputs(self):
        """"""
        for f in self.args.files:
            if os.path.isfile(f):
                fparts = str(f).split('.')
                if fparts[-1] == 'gz':
                    if self.args.unzip:
                        fullpath = os.path.abspath(str(f))
                        self.input_files.append(fullpath)
                    else:
                        return 0
                elif fparts[-1] == 'bz2' or fparts[-1] == 'zip':
                    return 0
                else:
                    fullpath = os.path.abspath(str(f))
                    self.input_files.append(fullpath)
            else:
                print('File '+ f + ' not found')
                return 1
523590
def gather_info_hdu(self, hdulist):
        """"""
        values = {}
        values['n_ext'] = len(hdulist)
        extnames = [hdu.header.get('extname', '') for hdu in hdulist[1:]]
        values['name_ext'] = ['PRIMARY'] + extnames

        fits_extractor = self.extractor_map['fits']
        for key in self.meta_dinfo_headers:
            values[key] = fits_extractor.extract(key, hdulist)

        return values
1056987
def stsci2(hdulist, filename):
    """"""

    # Write output file name to the primary header
    instrument = hdulist[0].header.get('INSTRUME', '')
    if instrument in ("WFPC2", "FOC"):
        hdulist[0].header['FILENAME'] = filename
708082
def overwrite_fits(hdulist, filename):
    

    assert isinstance(hdulist, (fits.HDUList, fits.PrimaryHDU))
    temp_name = None
    flag_delete_temp = False
    if os.path.isfile(filename):
        # PyFITS does not overwrite file
        temp_name = a99.rename_to_temp(filename)
    try:
        hdulist.writeto(filename, output_verify='warn')
        flag_delete_temp = temp_name is not None
    except:
        # Writing failed, reverts renaming
        os.rename(temp_name, filename)
        raise

    if flag_delete_temp:
        os.unlink(temp_name)
1064628
def _reader_factory(name, filetype, descr):
    """"""
    def basic_reader(filename, last = None, first = 0):
        """Common "template" to all read functions."""
        hdl = Sndfile(filename, 'r')
        try:
            if not hdl.format.file_format == filetype:
                raise ValueError, "%s is not a %s file (is %s)" \
                      % (filename, filetype, hdl.format.file_format)

            fs = hdl.samplerate
            enc = hdl.encoding
            # Set the pointer to start position
            nf  = hdl.seek(first, 1)
            if not nf == first:
                raise IOError("Error while seeking at starting position")

            if last is None:
                nframes = hdl.nframes - first
                data    = hdl.read_frames(nframes)
            else:
                data    = hdl.read_frames(last)
        finally:
            hdl.close()

        return data, fs, enc
    doc = \
    """Simple reader for %(format)s audio files.

    Parameters
    ----------
    filename : str
        Name of the file to read
    last : int
        Last frame to read. If None, this is equal to the number of frames in
        the file.
    first : int
        First frame to read. If 0, means starting from the beginning of the
        file.

    Returns
    -------
    data : array
        the read data (one column per channel)
    fs : int
        the sampling rate
    enc : str
        the encoding of the file, such as 'pcm16', 'float32', etc...

    Notes
    -----
    For total control over options, such as output's dtype, etc...,
    you should use Sndfile class instances instead""" % {'format': str(descr)}
    basic_reader.__doc__    = doc
    basic_reader.__name__   = name
    return basic_reader
856628
def write(self, outfile):
        """"""

        hdu_pri = fits.PrimaryHDU()

        hdu_exp = self._create_exp_hdu(self.data)
        hdu_exp.name = 'EXPOSURE'
        hdu_exp_wt = self._create_exp_hdu(self._data_wt)
        hdu_exp_wt.name = 'WEIGHTED_EXPOSURE'

        cols = [Column(name='CTHETA_MIN', dtype='f4',
                       data=self.costh_edges[:-1][::-1]),
                Column(name='CTHETA_MAX',  dtype='f4',
                       data=self.costh_edges[1:][::-1]), ]
        hdu_bnds = fits.table_to_hdu(Table(cols))
        hdu_bnds.name = 'CTHETABOUNDS'

        hdu_gti = fits.table_to_hdu(self._tab_gti)
        hdu_gti.name = 'GTI'

        hdus = [hdu_pri, hdu_exp, hdu_exp_wt,
                hdu_bnds, hdu_gti]

        for hdu in hdus:
            hdu.header['TSTART'] = self.tstart
            hdu.header['TSTOP'] = self.tstop

        with fits.HDUList(hdus) as hdulist:
            hdulist.writeto(outfile, clobber=True)
967761
def write_moc_fits_hdu(moc):
    

    # Ensure data are normalized.
    moc.normalize()

    # Determine whether a 32 or 64 bit column is required.
    if moc.order < 14:
        moc_type = np.int32
        col_type = 'J'
    else:
        moc_type = np.int64
        col_type = 'K'

    # Convert to the NUNIQ value which guarantees that one of the
    # top two bits is set so that the order of the value can be
    # determined.
    nuniq = []
    for (order, cells) in moc:
        uniq_prefix = 4 * (4 ** order)
        for npix in cells:
            nuniq.append(npix + uniq_prefix)

    # Prepare the data, and sort into numerical order.
    nuniq = np.array(nuniq, dtype=moc_type)
    nuniq.sort()

    # Create the FITS file.
    col = fits.Column(name='UNIQ', format=col_type, array=nuniq)

    cols = fits.ColDefs([col])
    rec = fits.FITS_rec.from_columns(cols)
    tbhdu = fits.BinTableHDU(rec)

    # Mandatory Keywords.
    tbhdu.header['PIXTYPE'] = 'HEALPIX'
    tbhdu.header['ORDERING'] = 'NUNIQ'
    tbhdu.header['COORDSYS'] = 'C'
    tbhdu.header['MOCORDER'] = moc.order
    tbhdu.header.comments['PIXTYPE'] = 'HEALPix magic code'
    tbhdu.header.comments['ORDERING'] = 'NUNIQ coding method'
    tbhdu.header.comments['COORDSYS'] = 'ICRS reference frame'
    tbhdu.header.comments['MOCORDER'] = 'MOC resolution (best order)'

    # Optional Keywords.
    tbhdu.header['MOCTOOL'] = 'PyMOC ' + version
    tbhdu.header.comments['MOCTOOL'] = 'Name of MOC generator'
    if moc.type is not None:
        tbhdu.header['MOCTYPE'] = moc.type
        tbhdu.header.comments['MOCTYPE'] = 'Source type (IMAGE or CATALOG)'
    if moc.id is not None:
        tbhdu.header['MOCID'] = moc.id
        tbhdu.header.comments['MOCID'] = 'Identifier of the collection'
    if moc.origin is not None:
        tbhdu.header['ORIGIN'] = moc.origin
        tbhdu.header.comments['ORIGIN'] = 'MOC origin'
    tbhdu.header['DATE'] = datetime.utcnow().replace(
        microsecond=0).isoformat()
    tbhdu.header.comments['DATE'] = 'MOC creation date'
    if moc.name is not None:
        tbhdu.header['EXTNAME'] = moc.name
        tbhdu.header.comments['EXTNAME'] = 'MOC name'

    return tbhdu
901202
def write(file,hdu,order=None,format=None):
    """"""


    if order or format:
        warnings.warn('Use of <order> and <format> depricated',DeprecationWarning)

    ## if the order of the columns isn't constrained just use the keys in what ever order
    data='data'
    if not order:
        if not hdu.has_key('order'):
            hdu['order']=hdu[data].keys()
    else:
        hdu['order']=order
	
    if not format:
        if not hdu.has_key('format'):
            hdu['format']={}
        for o in hdu['order']:
            if not hdu['format'].has_key(o):
	       hdu['format'][o]='%10s'
    else:
        hdu['format']=format
	
    f=open(file,'w')
    kline='## '
    vline='#  '
    header='header'
    num=0
    for keyword in hdu[header]:
        kline+='%10s ' % (keyword, )
        vline+='%10s ' % str(hdu[header][keyword])
        num+=1
        if not ( num % 6 ) :
            num=0
            f.write(kline+'\n')
            f.write(vline+'\n')
            kline='## '
            vline='#  '
    if num > 0:
        f.write(kline+'\n')
        f.write(vline+'\n')

    f.write('## ')
    for column in hdu['order']:
        f.write(' %10s' % (column))
    f.write('\n')
    dlen=len(hdu[data][hdu['order'][0]])
    for i in range(dlen):
        f.write('   ')
        for column in hdu['order']:
            f.write(hdu['format'][column] % (hdu[data][column][i]))
            f.write(' ')
        f.write('\n')
    f.close()
    return
698550
private Input processGA4GHInput(String input) throws IOException, GeneralSecurityException, URISyntaxException {
    GA4GHUrl url = new GA4GHUrl(input);
    SAMFilePump pump;
    if (usingGrpc) {
      factoryGrpc.configure(url.getRootUrl(), 
        new Settings(clientSecretsFilename, apiKey, noLocalServer));
      pump = new ReadIteratorToSAMFilePump<
          com.google.genomics.v1.Read,
          com.google.genomics.v1.ReadGroupSet, 
          com.google.genomics.v1.Reference>(
              factoryGrpc
                .get(url.getRootUrl())
                .getReads(url));
    } else {
      factoryRest.configure(url.getRootUrl(), 
          new Settings(clientSecretsFilename, apiKey, noLocalServer));
        pump = new ReadIteratorToSAMFilePump<
            com.google.api.services.genomics.model.Read,
            com.google.api.services.genomics.model.ReadGroupSet, 
            com.google.api.services.genomics.model.Reference>(
                factoryRest
                  .get(url.getRootUrl())
                  .getReads(url)); 
    }
    return new Input(input, STDIN_FILE_NAME, pump);
  }
1152823
def getHeader(filename, handle=None):
    

    _fname, _extn = parseFilename(filename)
    # Allow the user to provide an already opened PyFITS object
    # to derive the header from...
    #
    if not handle:
        # Open image whether it is FITS or GEIS
        _fimg = openImage(_fname, mode='readonly')
    else:
        # Use what the user provides, after insuring
        # that it is a proper PyFITS object.
        if isinstance(handle, fits.HDUList):
            _fimg = handle
        else:
            raise ValueError('Handle must be a %r object!' % fits.HDUList)

    _hdr = _fimg['PRIMARY'].header.copy()

    # if the data is not in the primary array delete NAXIS
    # so that the correct value is read from the extension header
    if _hdr['NAXIS'] == 0:
        del _hdr['NAXIS']

    if not (_extn is None or (_extn.isdigit() and int(_extn) == 0)):
        # Append correct extension/chip/group header to PRIMARY...
        #for _card in getExtn(_fimg,_extn).header.ascard:
            #_hdr.ascard.append(_card)
        for _card in getExtn(_fimg, _extn).header.cards:
            _hdr.append(_card)
    if not handle:
        # Close file handle now...
        _fimg.close()
        del _fimg

    return _hdr
223663
def main():
    
    usage = "usage: %(prog)s [options] "
    description = "Merge a set of Fermi-LAT files."

    parser = argparse.ArgumentParser(usage=usage, description=description)

    parser.add_argument('-o', '--output', default=None, type=str,
                        help='Output file.')
    parser.add_argument('--clobber', default=False, action='store_true',
                        help='Overwrite output file.')
    parser.add_argument('--hdu', default=None, type=str,
                        help='HDU name.')
    parser.add_argument('--gzip', action='store_true',
                        help='Compress output file')
    parser.add_argument('--rm', action='store_true',
                        help='Remove input files.')
    parser.add_argument('files', nargs='+', default=None,
                        help='List of input files.')

    args = parser.parse_args()

    hpx_map = merge_utils.stack_energy_planes_hpx(args.files, hdu=args.hdu)

    if args.output:
        hpx_map.hpx.write_fits(hpx_map.counts, args.output,
                               extname=args.hdu, clobber=args.clobber)

        if args.gzip:
            os.system('gzip -9 %s' % args.output)

        if args.rm:
            for farg in args.files:
                flist = glob.glob(farg)
                for ffound in flist:
                    os.path.unlink(ffound)
9604
def fromfits(infile, hdu = 0, verbose = True):
    
    
    pixelarray, hdr = ft.getdata(infile, hdu, header=True)
    pixelarray = np.asarray(pixelarray).transpose()
    #print pixelarray
    
    pixelarrayshape = pixelarray.shape
    if verbose :
        print "Input shape : (%i, %i)" % (pixelarrayshape[0], pixelarrayshape[1])
        print "Input file BITPIX : %s" % (hdr["BITPIX"])
    pixelarrayshape = np.asarray(pixelarrayshape)
    if verbose :
        print "Internal array type :", pixelarray.dtype.name
    
    return f2nimage(pixelarray, verbose = verbose)
932771
def geis2mef(sciname, convert_dq=True):
    
    clobber = True
    mode = 'update'
    memmap = True
    # Input was specified as a GEIS image, but no FITS copy
    # exists.  Read it in with 'readgeis' and make a copy
    # then open the FITS copy...
    try:
        # Open as a GEIS image for reading only
        fimg = readgeis.readgeis(sciname)
    except Exception:
        raise IOError("Could not open GEIS input: %s" % sciname)

    #check for the existence of a data quality file
    _dqname = fileutil.buildNewRootname(sciname, extn='.c1h')
    dqexists = os.path.exists(_dqname)
    if dqexists:
        try:
            dqfile = readgeis.readgeis(_dqname)
            dqfitsname = fileutil.buildFITSName(_dqname)
        except Exception:
            print("Could not read data quality file %s" % _dqname)

    # Check to see if user wanted to update GEIS header.
    # or write out a multi-extension FITS file and return a handle to it
    # User wants to make a FITS copy and update it
    # using the filename they have provided
    fitsname = fileutil.buildFITSName(sciname)

    # Write out GEIS image as multi-extension FITS.
    fexists = os.path.exists(fitsname)
    if (fexists and clobber) or not fexists:
            print('Writing out GEIS as MEF to ', fitsname)
            if ASTROPY_VER_GE13:
                fimg.writeto(fitsname, overwrite=clobber)
            else:
                fimg.writeto(fitsname, clobber=clobber)
            if dqexists:
                print('Writing out GEIS as MEF to ', dqfitsname)
                if ASTROPY_VER_GE13:
                    dqfile.writeto(dqfitsname, overwrite=clobber)
                else:
                    dqfile.writeto(dqfitsname, clobber=clobber)
    # Now close input GEIS image, and open writable
    # handle to output FITS image instead...
    fimg.close()
    del fimg
    fimg = fits.open(fitsname, mode=mode, memmap=memmap)

    return fimg