Esempio n. 1
0
def trim(args):
    # Define region to be trimmed
    y0, y1, x0, x1 = args.region

    # args.output should be a list of output names. If they do not exist, the outputs should be the same as the
    # inputs with whatever suffix, if any, the user gave
    if not args.output:
        args.output = [utilities.add_suffix_prefix(im_name, suffix=args.suffix) for im_name in args.input]

    # Do the actual trimming. We will do it first into a temporary file, then copy it into args.output. This is just
    # in case the output and input filenames are the same, or if the output exists. IRAF will not overwrite!
    for im_name, new_name in zip(args.input, args.output):
        basename = os.path.splitext(os.path.basename(im_name))[0]
        _, temp_output = tempfile.mkstemp(prefix=basename, suffix=".fits")
        os.unlink(temp_output )
        with utilities.tmp_mute():
            imcopy(im_name + "[{0}:{1}, {2}:{3}]".format(x0, x1, y0, y1), temp_output)
            shutil.move(temp_output, new_name)

            # If a mask exists, trim exactly equally
            if args.mask_key:
                maskname = fits.getheader(im_name)[args.mask_key]
                with fits.open(maskname, 'readonly') as mask_im:
                    mask_im[0].data = mask_im[0].data[y0:y1+1, x0:x1+1]
                    mask_output = utilities.replace_extension(new_name, ".fits.msk")
                    fits.writeto(mask_output, mask_im[0].data, mask_im[0].header, clobber=True)
                utilities.header_update_keyword(new_name, "MASK", os.path.abspath(mask_output),
                                                comment="Name of mask image. ")

    return args.output
Esempio n. 2
0
def include_wcs(args):
    # Copy input names into output names
    output_names = args.input[:]
    for ii, im_name in enumerate(args.input):
        # If it is a domeflat, skyflat or bias image, calculating the astrometry makes little sense
        im = astroim.Astroim(im_name)
        if im.target.objtype in ["bias", "domeflat", "skyflat", "flat"]:
            continue

        # Prepare my output file  for the resulting image
        if args.suffix:
            new_file = utilities.add_suffix_prefix(im_name, suffix=args.suffix)
        elif args.overwrite:
            new_file = im_name

        # Copy input image into a temporary file, so that we can modify it freely, for example, remove cosmics
        # or filter it (to be done).
        basename = get_basename(im_name)
        _, input_image = tempfile.mkstemp(prefix=basename, suffix=".fits")
        shutil.copy2(im_name, input_image)

        # Remove cosmics
        if args.cosmics:
            perform_cosmic_removal(input_image)

        # The output of the WCS process of astrometry.net will go to a .new file, the coordinates to a .coor
        output_wcs = utilities.replace_extension(input_image, ".new")
        solved_file = utilities.replace_extension(input_image, ".solved")
        corrfile = utilities.replace_extension(input_image, ".cor")

        # Try first with the defaults of astrometry
        arguments_def = ["solve-field", "--no-plots", "--no-fits2fits", "--dir", "/tmp", "--overwrite",
                      "--new-fits", output_wcs, "--corr", corrfile, "--cpulimit", "1", input_image]
        try:  # Try to add the RA, DEC, Radius options to constrain the search
            ra, dec = im.primary_header.get(im.primary_header.RAk, im.primary_header.DECk)
            ra, dec = utilities.sex2deg(ra, dec)
            arguments = arguments_def + ["--ra", str(ra), "--dec", str(dec), "--radius", str(args.radius),
                                      "--cpulimit", "20"]
        except:
            arguments = arguments_def
        print "Trying to find WCS with astrometry standard keywords. "
        with utilities.tmp_mute():
            subprocess.call(arguments)

        # Now we will try using sextractor
        build_default_sex(args)
        # To avoid having too much residual crap in the folder, the output of astrometry will go to tmp (--dir /tmp).
        arguments0 = ["solve-field", "--no-plots", "--no-fits2fits", "--use-sextractor", "--dir", "/tmp",
                      "--x-column", "X_IMAGE", "--y-column", "Y_IMAGE", "--sort-column", "MAG_AUTO",
                      "--sort-ascending", "--sextractor-config", os.path.join(repipy_path, "default.sex"),
                      "--overwrite", "--new-fits", output_wcs, "--corr", corrfile, input_image]
        arguments0 += args.extras

        try:  # Try to add the RA, DEC, Radius options to constrain the search
            ra, dec = im.primary_header.get(im.primary_header.RAk, im.primary_header.DECk)
            ra, dec = utilities.sex2deg(ra, dec)
            arguments = arguments0 + ["--ra", str(ra), "--dec", str(dec), "--radius", str(args.radius),
                                      "--cpulimit", "20"]
        except:
            arguments = arguments0

        # Run astrometry, in case of not solving it on the first attempt, try fitting freely (no RA, DEC used)
        if not os.path.exists(solved_file):
            subprocess.call(arguments)

        if not os.path.exists(solved_file):
            subprocess.call(arguments0)


        # Only if we have a solution
        if os.path.exists(solved_file):
            # copy the input file into the new file if they are not the same
            if os.path.abspath(im_name) != os.path.abspath(new_file):
                shutil.copy2(im_name, new_file)

            # get WCS from the resulting file, only the part added by astrometry.net
            with fits.open(output_wcs) as file_wcs:
                hdr_wcs = file_wcs[0].header
                ind = hdr_wcs.values().index('Original key: "END"')  # new part added by astrometry
                hdr_wcs = hdr_wcs[ind:]

            # Add that header to the original one of the image
            with fits.open(new_file, 'update') as new_im:
                new_im[0].header += hdr_wcs
                new_im.flush()

            # Build a catalogue of RA, DEC for the stars found
            with fits.open(corrfile) as table:
                cat_radec = utilities.replace_extension(new_file, "radec")
                with open(cat_radec, "w") as f:
                    for ra, dec in zip(table[1].data["field_ra"], table[1].data["field_dec"]):
                        f.write(str(ra) + " " + str(dec) + "\n")
            output_names[ii] = new_file

            # If --remove_original is True
            if args.remove_orig and not args.overwrite:
                os.unlink(im_name)

    return output_names