How to use the fitsio.write 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_simple.py View on Github external
g1 = 0.23
    g2 = -0.17
    psf = galsim.Gaussian(sigma=sigma).shear(g1=g1, g2=g2)
    for x,y in zip(x_list, y_list):
        bounds = galsim.BoundsI(int(x-31), int(x+32), int(y-31), int(y+32))
        psf.drawImage(image[bounds], center=galsim.PositionD(x,y), method='no_pixel')
    image.addNoise(galsim.GaussianNoise(rng=galsim.BaseDeviate(1234), sigma=1e-6))
    image_file = os.path.join('output','test_load_images_im.fits')
    image.write(image_file)

    dtype = [ ('x','f8'), ('y','f8') ]
    data = np.empty(len(x_list), dtype=dtype)
    data['x'] = x_list
    data['y'] = y_list
    cat_file = os.path.join('output','test_load_images_cat.fits')
    fitsio.write(cat_file, data, clobber=True)

    # Make star data
    config = { 'image_file_name' : image_file,
               'cat_file_name': cat_file }
    orig_stars, wcs, pointing = piff.Input.process(config, logger)

    # Fit these with a simple Mean, Gaussian
    model = piff.Gaussian()
    interp = piff.Mean()
    psf = piff.SimplePSF(model, interp)
    psf.fit(orig_stars, wcs, pointing, logger=logger)
    psf_file = os.path.join('output','test_load_images_psf.fits')
    psf.write(psf_file, logger)

    # Read this file back in.  It has the star data, but the images are blank.
    psf2 = piff.read(psf_file, logger)
github dstndstn / tractor / projects / inference / testblob2.py View on Github external
targetwcs.add_to_header(hdr)

            newpsf = GaussianMixturePSF(psf.mog.amp, newmean, newvar)
            newpsf.toFitsHeader(hdr, 'PSF_')
            
            # First time, overwrite existing file.  Later, append
            clobber = not band in written
            written.add(band)

            if band == 'r':
                rimgs.append(img)
            
            fn = stamp_pattern % band
            print('writing', fn)
            fitsio.write(fn, img.astype(np.float32), clobber=clobber, header=hdr)
            fitsio.write(fn, iv.astype(np.float32))
            if clobber:
                outfns.append(fn)

        if band == 'r':
            N = len(rimgs)
            ncols = int(np.ceil(np.sqrt(float(N))))
            nrows = int(np.ceil(float(N) / ncols))
            plt.clf()
            for k,img in enumerate(rimgs):
                plt.subplot(nrows, ncols, k+1)
                dimshow(img, vmin=-0.1, vmax=1., ticks=False)
            plt.savefig('stamps-%.4f-%.4f.png' % (ra, dec))
                
    return outfns
github rmjarvis / Piff / tests / test_input.py View on Github external
cat_file_name = os.path.join('input', 'test_input_cat_00.fits')
    data = fitsio.read(cat_file_name)
    print('flag = ',data['flag'])
    new_flag = np.empty((len(data), 50), dtype=bool)
    for bit in range(50):
        new_flag[:,bit] = data['flag'] & 2**bit != 0
    print('new_flag = ',new_flag)
    # Write out the catalog to a file
    print('dtype = ',new_flag.dtype)
    dtype = [ ('x','f8'), ('y','f8'), ('flag', bool, 50) ]
    new_data = np.empty(len(data), dtype=dtype)
    new_data['x'] = data['x']
    new_data['y'] = data['y']
    new_data['flag'] = new_flag
    new_cat_file_name = os.path.join('input','test_input_boolarray.fits')
    fitsio.write(new_cat_file_name, new_data, clobber=True)

    # Specifiable columns are: x, y, flag, use, sky, gain.  (We'll do flag, use below.)
    config = {
                'dir' : 'input',
                'image_file_name' : 'test_input_image_00.fits',
                'cat_file_name' : 'test_input_boolarray.fits',
                'x_col' : 'x',
                'y_col' : 'y',
                'flag_col' : 'flag',
                'skip_flag' : '$2**1 + 2**2 + 2**39'
             }
    input = piff.InputFiles(config, logger=logger)
    assert input.nimages == 1
    _, _, image_pos, _, _, _ = input.getRawImageData(0)
    print('len = ',len(image_pos))
    assert len(image_pos) == 80
github erykoff / fgcm / fgcm / fgcmComputeStepUnits.py View on Github external
(self.fgcmPars.parAlphaLoc +
                                                           self.fgcmPars.nCampaignNights)]
        tempCat['lnPwvIntercept'][0][:] = self.fgcmPars.stepUnits[self.fgcmPars.parLnPwvInterceptLoc:
                                                                      (self.fgcmPars.parLnPwvInterceptLoc +
                                                                       self.fgcmPars.nCampaignNights)]
        tempCat['lnPwvSlope'][0][:] = self.fgcmPars.stepUnits[self.fgcmPars.parLnPwvSlopeLoc:
                                                                  (self.fgcmPars.parLnPwvSlopeLoc +
                                                                   self.fgcmPars.nCampaignNights)]
        tempCat['lnPwvQuadratic'][0][:] = self.fgcmPars.stepUnits[self.fgcmPars.parLnPwvQuadraticLoc:
                                                                  (self.fgcmPars.parLnPwvQuadraticLoc +
                                                                   self.fgcmPars.nCampaignNights)]
        tempCat['qeSysIntercept'][0][:] = self.fgcmPars.stepUnits[self.fgcmPars.parQESysInterceptLoc:
                                                                      (self.fgcmPars.parQESysInterceptLoc +
                                                                       self.fgcmPars.nWashIntervals)]

        fitsio.write('%s_stepUnits.fits' % (self.outfileBaseWithCycle), tempCat, clobber=True)

        self.fgcmLog.info('Step size computation took %.2f seconds.' %
                          (time.time() - startTime))
github DarkEnergySurvey / ugali / ugali / utils / healpix.py View on Github external
names = list(data.keys())
    else:
        names = data.dtype.names

    if 'PIXEL' not in names:
        msg = "'PIXEL' column not found."
        raise ValueError(msg)

    hdr = header_odict(nside=nside,coord=coord,nest=nest)
    fitshdr = fitsio.FITSHDR(list(hdr.values()))
    if header is not None:
        for k,v in header.items():
            fitshdr.add_record({'name':k,'value':v})

    logger.info("Writing %s"%filename)
    fitsio.write(filename,data,extname='PIX_DATA',header=fitshdr,clobber=True)
github dstndstn / tractor / unwise-coadd.py View on Github external
WISE.sky1[ii] = mm.sky
        WISE.sky2[ii] = mm.dsky
        WISE.zeropoint[ii] = mm.zp
        WISE.npixoverlap[ii] = mm.ncopix
        WISE.npixpatched[ii] = mm.npatched
        WISE.npixrchi[ii] = mm.nrchipix
        WISE.weight[ii] = mm.w

        ofn = WISE.intfn[ii].replace('-int', '')
        ofn = os.path.join(maskdir, 'unwise-mask-' + ti.coadd_id + '-'
                           + os.path.basename(ofn) + '.gz')
        w,h = WISE.imagew[ii],WISE.imageh[ii]
        fullmask = np.zeros((h,w), mm.omask.dtype)
        x0,x1,y0,y1 = WISE.imextent[ii,:]
        fullmask[y0:y1+1, x0:x1+1] = mm.omask
        fitsio.write(ofn, fullmask, clobber=True)
        print 'Wrote mask', (i+1), 'of', len(masks), ':', ofn

    WISE.delete_column('wcs')

    # downcast datatypes, and work around fitsio's issues with
    # "bool" columns
    for c,t in [('included', np.uint8),
                ('use', np.uint8),
                ('moon_masked', np.uint8),
                ('imagew', np.int16),
                ('imageh', np.int16),
                ('coextent', np.int16),
                ('imextent', np.int16),
                ]:
        WISE.set(c, WISE.get(c).astype(t))
github dstndstn / tractor / projects / desi / common.py View on Github external
# Remap the "blobs" image so that empty regions are = -1 and the blob values
    # correspond to their indices in the "blobsrcs" list.
    if len(blobmap):
        maxblob = max(blobmap.keys())
    else:
        maxblob = 0
    maxblob = max(maxblob, blobs.max())
    bm = np.zeros(maxblob + 1, int)
    for k,v in blobmap.items():
        bm[k] = v
    bm[0] = -1

    # DEBUG
    if plots:
        fitsio.write('blobs-before-%s.fits' % name, blobs, clobber=True)

    # Remap blob numbers
    blobs = bm[blobs]

    if plots:
        fitsio.write('blobs-after-%s.fits' % name, blobs, clobber=True)

    if plots:
        plt.clf()
        dimshow(blobs > -1, vmin=0, vmax=1)
        ax = plt.axis()
        for i,bs in enumerate(blobslices):
            sy,sx = bs
            by0,by1 = sy.start, sy.stop
            bx0,bx1 = sx.start, sx.stop
            plt.plot([bx0, bx0, bx1, bx1, bx0], [by0, by1, by1, by0, by0], 'r-')
github dstndstn / astrometry.net / python / resample / resample.py View on Github external
t1 = time.clock() - t0
        print 'C resampling took', t1

    t0 = time.clock()
    Yo2,Xo2,Yi2,Xi2,ims2 = resample_with_wcs(cowcs, wcs, [pix], 3, cinterp=False, table=False)
    t2 = time.clock() - t0
    print 'py resampling took', t2
    
    out = np.zeros((H,W))
    out[Yo,Xo] = ims[0]
    fitsio.write('resampled-c.fits', out, clobber=True)
    cout = out
    
    out = np.zeros((H,W))
    out[Yo,Xo] = ims2[0]
    fitsio.write('resampled-py.fits', out, clobber=True)
    pyout = out

    plt.clf()
    plt.imshow(cout, interpolation='nearest', origin='lower')
    plt.colorbar()
    plt.savefig('c.png')
    plt.clf()
    plt.imshow(pyout, interpolation='nearest', origin='lower')
    plt.colorbar()
    plt.savefig('py.png')

    plt.clf()
    plt.imshow(cout - pyout, interpolation='nearest', origin='lower')
    plt.colorbar()
    plt.savefig('diff.png')
github dstndstn / tractor / wise-coverage.py View on Github external
for i,lst in enumerate(M):
                if lst is None:
                    continue
                if arrs[-1][i] == -1:
                    continue
                wcs.set(*[a[i] for a in arrs])
                if i % 10000 == 0:
                    print 'WCS', i, ':', len(lst), 'matched'
                for j in lst:
                    if wcs.is_inside(ra[j], dec[j]):
                        counts[band-1][j] += 1
            print 'Added a total of', counts[band-1].sum() - n0
                        
    for i,c in enumerate(counts):
        fn = 'coverage-hp-w%i.fits' % (i+1)
        fitsio.write(fn, c, clobber=True)
        print 'Wrote', fn
github DarkEnergySurvey / ugali / ugali / analysis / search.py View on Github external
def writeCandidates(self,filename=None):
        if filename is None: filename = self.candfile

        threshold = self.config['search']['cand_threshold']
        select  = (self.assocs['CUT']==0)
        select &= (self.assocs['TS']>threshold)
        #select &= (self.assocs['ASSOC2']=='')

        self.candidates = self.assocs[select]
        logger.info("Writing %s..."%filename)
        fitsio.write(filename,self.candidates,clobber=True)