Builds and returns a FITs HDU with the energy values

    extname   : The HDU extension name
355512
def make_energies_hdu(energy_vals, extname="ENERGIES"):
    
    cols = [fits.Column("Energy", "D", unit='MeV', array=energy_vals)]
    hdu = fits.BinTableHDU.from_columns(cols, name=extname)
    return hdu
257578
def movnam_hdu(self, extname, hdutype=ANY_HDU, extver=0):
        
        extname = mks(extname)
        hdu = self._FITS.movnam_hdu(hdutype, extname, extver)
        return hdu
354492
def create_mef(filename=None):
    
    import pyfits, time

    if not filename:
        ### here I know what filename is to start with.
        import tempfile
        filename=tempfile.mktemp(suffix='.fits')
    else:
        import string, re
        ### filenames gotta be a string and no lead/trailing space
        filename=string.strip(str(filename))
        ### require that the filename ends in .fits
        suffix=re.match(r'^.*.fits$',filename)
        if not suffix:
            filename = filename+'.fits'

    ### create an HDU list
    temp = pyfits.HDUList()

    ### create a primary HDU
    prihdu = pyfits.PrimaryHDU()

    ### build the header
    h=prihdu.header
    h.update('EXTEND',pyfits.TRUE,after='NAXIS')
    h.update('NEXTEND',0,after='EXTEND')
    h.add_comment('MEF created at CADC')
    h.add_comment('Created using '+__name__+' '+__Version__)
    h.add_comment('Extensions may not be in CCD order')
    #h.update('cfh12k',__Version__,comment='split2mef software at CADC')
    h.add_comment('Use the EXTNAME keyword')
    h.add_history('Primary HDU created on '+time.asctime())

    ### stick the HDU onto the HDU list and write to file
    temp.append(prihdu)
    temp.writeto(filename)
    temp.close()

    return(filename)
433606
def _get_ext_namespaces(config):
    '''
    
    '''
    namespaces = {}
    if not config:
        return namespaces

    for ns in config:
        constraint_version = tuple(config[ns].get('py-version', []))
        if not constraint_version:
            raise salt.exceptions.SaltSystemExit("An alternative version is configured, but not defined "
                                                 "to what Python's major/minor version it should be constrained.")
        else:
            namespaces[ns] = constraint_version

    return namespaces
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)
1190207
def format_energy_results(energy):
    """"""
    if not energy:
        return {}
    result = {}
    cpuenergy = Decimal(0)
    for pkg, domains in energy.items():
        for domain, value in domains.items():
            if domain == DOMAIN_PACKAGE:
                cpuenergy += value
                result['cpuenergy-pkg{}'.format(pkg)] = value
            else:
                result['cpuenergy-pkg{}-{}'.format(pkg, domain)] = value
    result['cpuenergy'] = cpuenergy
    result = collections.OrderedDict(sorted(result.items()))
    return result
500742
def fromfits(infilename, hdu = 0, verbose = True):
    
    
    pixelarray, hdr = pyfits.getdata(infilename, hdu, header=True)
    pixelarray = np.asarray(pixelarray).transpose()
    
    pixelarrayshape = pixelarray.shape
    if verbose :
        print "FITS import shape : (%i, %i)" % (pixelarrayshape[0], pixelarrayshape[1])
        print "FITS file BITPIX : %s" % (hdr["BITPIX"])
        print "Internal array type :", pixelarray.dtype.name
    
    return pixelarray, hdr
1334889
def buildNewRootname(filename, extn=None, extlist=None):
    

    # Search known suffixes to replace ('_crj.fits',...)
    _extlist = copy.deepcopy(EXTLIST)
    # Also, add a default where '_dth.fits' replaces
    # whatever extension was there ('.fits','.c1h',...)
    #_extlist.append('.')
    # Also append any user-specified extensions...
    if extlist:
        _extlist += extlist

    if isinstance(filename, fits.HDUList):
        try:
            filename = filename.filename()
        except:
            raise ValueError("Can't determine the filename of an waivered HDUList object.")
    for suffix in _extlist:
        _indx = filename.find(suffix)
        if _indx > 0: break

    if _indx < 0:
         # default to entire rootname
        _indx = len(filename)

    if extn is None:
        extn = ''

    return filename[:_indx] + extn
163024
def make_hdu(self, data, **kwargs):
        
        shape = data.shape
        extname = kwargs.get('extname', self.conv.extname)

        if shape[-1] != self._npix:
            raise Exception(
                "Size of data array does not match number of pixels")
        cols = []

        if self._ipix is not None:
            cols.append(fits.Column(self.conv.idxstring, "J", array=self._ipix))

        if self.conv.convname == 'FGST_SRCMAP_SPARSE':
            nonzero = data.nonzero()
            nfilled = len(nonzero[0])
            if len(shape) == 1:
                cols.append(fits.Column("PIX", "J", array=nonzero[0].astype(int)))
                cols.append(fits.Column("VALUE", "E", array=data.flat[nonzero].astype(float).reshape(nfilled)))
            elif len(shape) == 2:
                keys = self._npix * nonzero[0] + nonzero[1]
                cols.append(fits.Column("PIX", "J", array=nonzero[1].reshape(nfilled)))
                cols.append(fits.Column("CHANNEL", "I", array=nonzero[0].reshape(nfilled)))
                cols.append(fits.Column("VALUE", "E",
                                        array=data.flat[keys].astype(float).reshape(nfilled)))
            else:
                raise Exception("HPX.write_fits only handles 1D and 2D maps")

        else:
            if len(shape) == 1:
                cols.append(fits.Column(self.conv.colname(
                    indx=self.conv.firstcol), "E", array=data.astype(float)))
            elif len(shape) == 2:
                for i in range(shape[0]):
                    cols.append(fits.Column(self.conv.colname(
                        indx=i + self.conv.firstcol), "E", array=data[i].astype(float)))
            else:
                raise Exception("HPX.write_fits only handles 1D and 2D maps")

        header = self.make_header()
        hdu = fits.BinTableHDU.from_columns(cols, header=header, name=extname)

        return hdu
331028
def get_file_type(filename):
    
    txt_extensions = [".txt", ".dat", ".csv"]
    hdf_extensions = [".hdf", ".h5", ".bkup", ".checkpoint"]
    for ext in hdf_extensions:
        if filename.endswith(ext):
            with _h5py.File(filename, 'r') as fp:
                filetype = fp.attrs['filetype']
            return filetypes[filetype]
    for ext in txt_extensions:
        if filename.endswith(ext):
            return InferenceTXTFile
    raise TypeError("Extension is not supported.")
179920
def read_spectral_data(hdu):
    
    ebins = read_energy_bounds(hdu)
    fluxes = np.ndarray((len(ebins)))
    try:
        fluxes[0:-1] = hdu.data.field("E_MIN_FL")
        fluxes[-1] = hdu.data.field("E_MAX_FL")[-1]
        npreds = hdu.data.field("NPRED")
    except:
        fluxes = np.ones((len(ebins)))
        npreds = np.ones((len(ebins)))
    return ebins, fluxes, npreds
1274033
def create_from_hdu(cls, hdu, ebins=None):
        
        convname = HPX.identify_HPX_convention(hdu.header)
        conv = HPX_FITS_CONVENTIONS[convname]
        try:
            pixels = hdu.data[conv.idxstring]
        except KeyError:
            pixels = None
        return cls.create_from_header(hdu.header, ebins, pixels)
23051
def count_sci_extensions(filename):
    
    num_sci = 0
    extname = 'SCI'

    hdu_list = fileutil.openImage(filename, memmap=False)

    for extn in hdu_list:
        if 'extname' in extn.header and extn.header['extname'] == extname:
            num_sci += 1

    if num_sci == 0:
        extname = 'PRIMARY'
        num_sci = 1

    hdu_list.close()

    return num_sci,extname
1247479
def _get_dtype_and_shape(self):
        
        npy_dtype = self._get_image_numpy_dtype()

        if self._info['ndims'] != 0:
            shape = self._info['dims']
        else:
            raise IOError("no image present in HDU")

        return npy_dtype, shape
1031205
def read_energy_bounds(hdu):
    
    nebins = len(hdu.data)
    ebin_edges = np.ndarray((nebins + 1))
    try:
        ebin_edges[0:-1] = np.log10(hdu.data.field("E_MIN")) - 3.
        ebin_edges[-1] = np.log10(hdu.data.field("E_MAX")[-1]) - 3.
    except KeyError:
        ebin_edges[0:-1] = np.log10(hdu.data.field("energy_MIN"))
        ebin_edges[-1] = np.log10(hdu.data.field("energy_MAX")[-1])
    return ebin_edges
859637
def build_extension_item(name: str, parameters: List[ExtensionParameter]) -> str:
    
    return "; ".join(
        [name]
        + [
            # Quoted strings aren't necessary because values are always tokens.
            name if value is None else f"{name}={value}"
            for name, value in parameters
        ]
    )
52090
def show_extension(self, ext_alias, **_params):
        """"""
        return self.get(self.extension_path % ext_alias, params=_params)