def fits2fits(infile, outfile, verbose=False, fix_idr=False): """ Returns: error string, or None on success. """ if fix_idr: from astrometry.util.fix_sdss_idr import fix_sdss_idr # Read input file. fitsin = pyfits.open(infile) # Print out info about input file. if verbose: fitsin.info() for i, hdu in enumerate(fitsin): if fix_idr: hdu = fitsin[i] = fix_sdss_idr(hdu) # verify() fails when a keywords contains invalid characters, # so go through the primary header and fix them by converting invalid # characters to '_' hdr = hdu.header logging.info('Header has %i cards' % len(hdr)) # allowed characters (FITS standard section 5.1.2.1) pat = re.compile(r'[^A-Z0-9_\-]') for k in hdr.keys(): # new keyword: knew = pat.sub('_', k) if k != knew: logging.debug('Replacing illegal keyword %s by %s' % (k, knew)) # add the new header card # it seems pyfits is not clever enough to notice this... if len(knew) > 8: knew = 'HIERARCH ' + knew hdr.update(knew, cards[k].value, cards[k].comment, after=k) # remove the old one. del hdr[k] # Fix input header hdu.verify('fix') # UGH! Work around stupid pyfits handling of scaled data... # (it fails to round-trip scaled data correctly!) bzero = hdr.get('BZERO', None) bscale = hdr.get('BSCALE', None) if (bzero is not None and bscale is not None and (bzero != 0. or bscale != 1.)): logging.debug('Scaling to bzero=%g, bscale=%g' % (bzero, bscale)) hdu.scale('int16', '', bscale, bzero) # Describe output file we're about to write... if verbose: print 'Outputting:' fitsin.info() try: pyfits_writeto(fitsin, outfile, output_verify='warn') except pyfits.VerifyError, ve: return ('Verification of output file failed: your FITS file is probably too broken to automatically fix.' + ' Error message is:' + str(ve))
def removelines(infile, outfile, xcol='X', ycol='Y', cut=None, **kwargs): if cut is None: cut = 100 p = pyfits.open(infile) xy = p[1].data hdr = p[1].header if xy is None: print 'removelines.py: Input file contains no sources.' pyfits_writeto(p, outfile) return 0 x = xy.field(xcol) y = xy.field(ycol) if len(x) == 0: print 'removelines.py: Your FITS file contains 0 sources (rows)' pyfits_writeto(p, outfile) return 0 ix = hist_remove_lines(x, 1, 0.5, logcut=-cut) iy = hist_remove_lines(y, 1, 0.5, logcut=-cut) I = ix * iy xc = x[I] yc = y[I] print 'removelines.py: Removed %i sources' % (len(x) - len(xc)) p[1].header.add_history('This xylist was filtered by the "removelines.py" program') p[1].header.add_history('to remove horizontal and vertical lines of sources') p[1].header.update('REMLINEN', len(x) - len(xc), 'Number of sources removed by "removelines.py"') p[1].data = p[1].data[I] pyfits_writeto(p, outfile) return 0