How to use the fitsio.read function in fitsio

To help you get started, we’ve selected a few fitsio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rmjarvis / Piff / tests / test_optics.py View on Github external
def test_pupil_im(pupil_plane_im='input/DECam_pupil_128.fits'):
    import galsim
    # make sure we can load up a pupil image
    model = piff.Optical(diam=4.274419, lam=500., r0=0.1, pupil_plane_im=pupil_plane_im)
    test_optical(model)
    # make sure we really loaded it
    pupil_plane_im = galsim.Image(fitsio.read(pupil_plane_im))
    model_pupil_plane_im = model.optical_psf_kwargs['pupil_plane_im']
    np.testing.assert_array_equal(pupil_plane_im.array, model_pupil_plane_im.array)

    # test passing a different optical template that includes diam
    piff.optical_model.optical_templates['test'] = {'diam': 2, 'lam':500, 'r0':0.1}
    model = piff.Optical(pupil_plane_im=pupil_plane_im, template='test')
    model_pupil_plane_im = model.optical_psf_kwargs['pupil_plane_im']
    np.testing.assert_array_equal(pupil_plane_im.array, model_pupil_plane_im.array)
github rmjarvis / TreeCorr / tests / test_nk.py View on Github external
print('true_xi = ',true_xi)
    print('nk.xi = ',nk.xi)
    np.testing.assert_allclose(nk.xi, true_xi, rtol=1.e-4, atol=1.e-8)

    try:
        import fitsio
    except ImportError:
        print('Skipping FITS tests, since fitsio is not installed')
        return

    # Check that running via the corr2 script works correctly.
    config = treecorr.config.read_config('configs/nk_direct.yaml')
    cat1.write(config['file_name'])
    cat2.write(config['file_name2'])
    treecorr.corr2(config)
    data = fitsio.read(config['nk_file_name'])
    np.testing.assert_allclose(data['r_nom'], nk.rnom)
    np.testing.assert_allclose(data['npairs'], nk.npairs)
    np.testing.assert_allclose(data['weight'], nk.weight)
    np.testing.assert_allclose(data['kappa'], nk.xi, rtol=1.e-3)

    # Invalid with only one file_name
    del config['file_name2']
    with assert_raises(TypeError):
        treecorr.corr2(config)
    config['file_name2'] = 'data/nk_direct_cat2.fits'
    # Invalid to request compoensated if no rand_file
    config['nk_statistic'] = 'compensated'
    with assert_raises(TypeError):
        treecorr.corr2(config)

    # Repeat with binslop = 0, since the code flow is different from brute=True
github rmjarvis / TreeCorr / tests / test_kg.py View on Github external
print('kg.xi = ',kg.xi)
    np.testing.assert_allclose(kg.xi, true_xi.real, rtol=1.e-4, atol=1.e-8)
    np.testing.assert_allclose(kg.xi_im, true_xi.imag, rtol=1.e-4, atol=1.e-8)

    try:
        import fitsio
    except ImportError:
        print('Skipping FITS tests, since fitsio is not installed')
        return

    # Check that running via the corr2 script works correctly.
    config = treecorr.config.read_config('configs/kg_direct_spherical.yaml')
    cat1.write(config['file_name'])
    cat2.write(config['file_name2'])
    treecorr.corr2(config)
    data = fitsio.read(config['kg_file_name'])
    np.testing.assert_allclose(data['r_nom'], kg.rnom)
    np.testing.assert_allclose(data['npairs'], kg.npairs)
    np.testing.assert_allclose(data['weight'], kg.weight)
    np.testing.assert_allclose(data['kgamT'], kg.xi, rtol=1.e-3)
    np.testing.assert_allclose(data['kgamX'], kg.xi_im, rtol=1.e-3)

    # Repeat with binslop = 0
    # And don't do any top-level recursion so we actually test not going to the leaves.
    kg = treecorr.KGCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins,
                                sep_units='deg', bin_slop=0, max_top=0)
    kg.process(cat1, cat2)
    np.testing.assert_array_equal(kg.npairs, true_npairs)
    np.testing.assert_allclose(kg.weight, true_weight, rtol=1.e-5, atol=1.e-8)
    np.testing.assert_allclose(kg.xi, true_xi.real, rtol=1.e-3, atol=1.e-3)
    np.testing.assert_allclose(kg.xi_im, true_xi.imag, rtol=1.e-3, atol=1.e-3)
github dstndstn / tractor / check-coadd.py View on Github external
#           vmin=0, vmax=1)
            #plt.axis(ax)
            #plt.title('WISE mask')
            #ps.savefig()

            plt.clf()
            plt.imshow(comask > 0, interpolation='nearest', origin='lower',
                       vmin=0, vmax=1)
            plt.title('Coadd mask')
            ps.savefig()


    for frame in []: #'05579a167']:
        for band in [1]:
            imgfn = '%s-w%i-int-1b.fits' % (frame, band)
            img = fitsio.read(imgfn)
            maskfn = '%s-w%i-msk-1b.fits.gz' % (frame, band)
            mask = fitsio.read(maskfn)
            comaskfn = 'coadd-mask-%s-%s-w%i-1b.fits' % (coadd, frame, band)
            comask = fitsio.read(comaskfn)

            plo,phi = [np.percentile(img, p) for p in [25,98]]
            ima = dict(interpolation='nearest', origin='lower',
                       vmin=plo, vmax=phi)
            ax = [200,700,200,700]
            plt.clf()
            plt.imshow(img, **ima)
            plt.axis(ax)
            plt.title('Image %s W%i' % (frame,band))
            ps.savefig()

            plt.clf()
github afeinstein20 / eleanor / make_postcards.py View on Github external
def make_postcards(fns, outdir, width=104, height=148, wstep=None, hstep=None):
    # Make sure that the output directory exists
    os.makedirs(outdir, exist_ok=True)

    # We'll assume that the filenames can be sorted like this (it is true for
    # the ETE-6 test data
    fns = list(sorted(fns))
    total_ffis = len(fns)
    # Save the middle header as the primary header
    middle_fn = fns[total_ffis//2]
    data, primary_header = fitsio.read(middle_fn, 1, header=True)

    # Add the eleanor info to the header
    primary_header.add_record("COMMENT   ***********************")
    primary_header.add_record("COMMENT   *    eleanor INFO     *")
    primary_header.add_record("COMMENT   ***********************")
    primary_header.add_record(
        dict(name='AUTHOR', value='Adina D. Feinstein'))
    primary_header.add_record(
        dict(name='VERSION', value=__version__))
    primary_header.add_record(
        dict(name='GITHUB',
             value='https://github.com/afeinstein20/eleanor'))
    primary_header.add_record(
        dict(name='CREATED', value=strftime('%Y-%m-%d'),
             comment='eleanor file creation date (YYY-MM-DD)'))
github DarkEnergySurvey / ugali / ugali / utils / fileio.py View on Github external
def load_file(kwargs):
    """ Load a FITS file with kwargs. 

    Parameters:
    kwargs : keyword arguments passed to fitsio.read
    Returns:
    ndarray : fits catalog data
    """
    logger.debug("Loading %s..."%kwargs['filename'])
    return fitsio.read(**kwargs)
github DarkEnergySurvey / ugali / ugali / utils / fileio.py View on Github external
for col in data.dtype.names:
        if col not in names:
            msg = "Inserting column: %s"%col
            logger.info(msg)
            fits[ext].insert_column(col,data[col],colnum=colnum)
        else:
            msg = "Found column %s"%col
            logger.warning(msg)
            fits[ext].write_column(col,data[col])
        if colnum is not None: colnum += 1

    fits.close()

    # It's already too late since the file has been written...
    if test is not None:
        new = fitsio.read(filename,ext=ext,columns=[test])
        if np.any(new != orig):
            msg = "Input and output do not match!"
            raise Exception(msg)
github DarkEnergySurvey / ugali / ugali / preprocess / maglims.py View on Github external
"""
    Check if set of ra,dec combinations are in footprint.
    Careful, input files must be in celestial coordinates.
    
    filename : Either healpix map or mangle polygon file
    ra,dec   : Celestial coordinates

    Returns:
    inside   : boolean array of coordinates in footprint
    """
        
    try:
        if isinstance(footprint,str) and os.path.exists(footprint):
            filename = footprint
            #footprint = healpy.read_map(filename,verbose=False)
            footprint = fitsio.read(filename)['I'].ravel()
        nside = healpy.npix2nside(len(footprint))
        pix = ang2pix(nside,ra,dec)
        inside = (footprint[pix] > 0)
    except IOError:
        logger.warning("Failed to load healpix footprint; trying to use mangle...")
        inside = inMangle(filename,ra,dec)
    return inside
github dstndstn / tractor / sequels.py View on Github external
print 'Coadd tile', tile.coadd_id
        print 'Band', band
        wband = 'w%i' % band

        imfn = os.path.join(thisdir, 'unwise-%s-w%i-img-m.fits'    % (tile.coadd_id, band))
        ivfn = os.path.join(thisdir, 'unwise-%s-w%i-invvar-m.fits' % (tile.coadd_id, band))
        ppfn = os.path.join(thisdir, 'unwise-%s-w%i-std-m.fits'    % (tile.coadd_id, band))
        nifn = os.path.join(thisdir, 'unwise-%s-w%i-n-m.fits'      % (tile.coadd_id, band))

        print 'Reading', imfn
        wcs = Tan(imfn)
        r0,r1,d0,d1 = wcs.radec_bounds()
        print 'RA,Dec bounds:', r0,r1,d0,d1
        ra,dec = wcs.radec_center()
        print 'Center:', ra,dec
        img = fitsio.read(imfn)
        print 'Reading', ivfn
        iv = fitsio.read(ivfn)
        print 'Reading', ppfn
        pp = fitsio.read(ppfn)
        print 'Reading', nifn
        nims = fitsio.read(nifn)

        sig1 = 1./np.sqrt(np.median(iv))
        minsig = getattr(opt, 'minsig%i' % band)
        minsb = sig1 * minsig
        print 'Sigma1:', sig1, 'minsig', minsig, 'minsb', minsb

        # Load the average PSF model (generated by wise_psf.py)
        P = fits_table('wise-psf-avg.fits', hdu=band)
        psf = GaussianMixturePSF(P.amp, P.mean, P.var)
github erykoff / fgcm / fgcm / fgcmParameters.py View on Github external
Config variables
        ----------------
        exposureFile: string
           File with exposure information
        inParameterFile: string
           File with input parameters (from previous cycle)
        """

        import fitsio

        expInfoFile = fgcmConfig.exposureFile
        inParFile = fgcmConfig.inParameterFile

        expInfo = fitsio.read(expInfoFile, ext=1)
        inParInfo = fitsio.read(inParFile, ext='PARINFO')
        inParams = fitsio.read(inParFile, ext='PARAMS')
        inSuperStar = fitsio.read(inParFile, ext='SUPER')

        return cls(fgcmConfig, expInfo=expInfo,
                   inParInfo=inParInfo, inParams=inParams, inSuperStar=inSuperStar)