Ejemplo n.º 1
0
    def __init__(self):
        """
        Donut class constructor.
        """
        SExtractor.__init__(self)

        # Basic sextractor configuration for donut detection
        self.config['PIXEL_SCALE'] = 0.55
        self.config['BACK_TYPE'] = "AUTO"
        self.config['SATUR_LEVEL'] = 60000
        self.config['DETECT_MINAREA'] = 200
        self.config['DETECT_THRESH'] = 10.0
        self.config['VERBOSE_TYPE'] = "QUIET"
        self.config['PARAMETERS_LIST'] = ["NUMBER",'X_IMAGE', 'Y_IMAGE',
                                         "XWIN_IMAGE", "YWIN_IMAGE",
                                         "FLUX_BEST", "FWHM_IMAGE",
                                         "FLAGS"]

        self._useMPI = True
        self._mpithreads = 8
        self.setCFP(0.*units.meter)
        self.setPixScale(0.*units.mm)

        self.sign_x = +1.
        self.sign_y = +1.
        self.sign_u = +1.
        self.sign_v = +1.
Ejemplo n.º 2
0
    def solveField(fullfilename, findstarmethod="astrometry.net"):
        """
        @param: fullfilename entire path to image
        @type: str

        @param: findstarmethod (astrometry.net, sex)
        @type: str

        Does astrometry to image=fullfilename
        Uses either astrometry.net or sex(tractor) as its star finder
        """

        pathname, filename = os.path.split(fullfilename)
        pathname = pathname + "/"
        basefilename, file_xtn = os.path.splitext(filename)
        # *** enforce .fits extension
        if file_xtn != ".fits":
            raise ValueError("File extension must be .fits it was = %s\n" % file_xtn)

        # *** check whether the file exists or not
        if os.path.exists(fullfilename) == False:
            raise IOError("You selected image %s  It does not exist\n" % fullfilename)

        # version 0.23 changed behavior of --overwrite
        # I need to specify an output filename with -o
        outfilename = basefilename + "-out"

        image = Image.fromFile(fullfilename)
        try:
            ra = image["CRVAL1"]  # expects to see this in image
        except:
            raise AstrometryNetException("Need CRVAL1 and CRVAL2 and CD1_1 on header")
        try:
            dec = image["CRVAL2"]
        except:
            raise AstrometryNetException("Need CRVAL1 and CRVAL2 and CD1_1 on header")
        width = image["NAXIS1"]
        height = image["NAXIS2"]
        radius = 10.0 * abs(image["CD1_1"]) * width

        wcs_filename = pathname + outfilename + ".wcs"

        if findstarmethod == "astrometry.net":
            line = "solve-field %s --no-plots --overwrite -o %s --ra %f --dec %f --radius %f" % (
                fullfilename, outfilename, ra, dec, radius)
        elif findstarmethod == "sex":
            sexoutfilename = pathname + outfilename + ".xyls"
            line = "solve-field %s --no-plots --overwrite -o %s --x-column X_IMAGE --y-column Y_IMAGE " \
                   "--sort-column MAG_ISO --sort-ascending --width %d --height %d --ra %f --dec %f --radius %f" % (
                       sexoutfilename, outfilename, width, height, ra, dec, radius)

            sex = SExtractor()
            sex.config['BACK_TYPE'] = "AUTO"
            sex.config['DETECT_THRESH'] = 3.0
            sex.config['DETECT_MINAREA'] = 18.0
            sex.config['VERBOSE_TYPE'] = "QUIET"
            sex.config['CATALOG_TYPE'] = "FITS_1.0"
            sex.config['CATALOG_NAME'] = sexoutfilename
            sex.config['PARAMETERS_LIST'] = ["X_IMAGE", "Y_IMAGE", "MAG_ISO"]
            sex.run(fullfilename)

        else:
            log.error("Unknown option used in astrometry.net")

        # when there is a solution astrometry.net creates a file with .solved
        # added as extension.
        is_solved = pathname + outfilename + ".solved"
        # if it is already there, make sure to delete it
        if os.path.exists(is_solved):
            os.remove(is_solved)
        log.debug("SOLVE %s" % line)
        # *** it would be nice to add a test here to check
        # whether astrometrynet is running OK, if not raise a new exception
        # like AstrometryNetInstallProblem
        log.debug('Starting solve-field...')
        t0 = time.time()
        solve = Popen(line.split())  # ,env=os.environ)
        solve.wait()
        log.debug('Solve field finished. Took %3.2f sec' % (time.time() - t0))
        # if solution failed, there will be no file .solved
        if (os.path.exists(is_solved) == False):
            raise NoSolutionAstrometryNetException(
                "Astrometry.net could not find a solution for image: %s %s" % (fullfilename, is_solved))

        return wcs_filename
Ejemplo n.º 3
0
    def extract(self, params={}, saveCatalog=False, saveConfig=False):

        sex = SExtractor()

        # default params
        sex.config['PIXEL_SCALE'] = 0.45
        sex.config['BACK_TYPE'] = "AUTO"
        sex.config['SATUR_LEVEL'] = 60000
        sex.config['DETECT_THRESH'] = 3.0
        sex.config['VERBOSE_TYPE'] = "QUIET"
        sex.config['PARAMETERS_LIST'] = [
            "NUMBER", "XWIN_IMAGE", "YWIN_IMAGE", "FLUX_BEST", "FWHM_IMAGE",
            "FLAGS"
        ]

        # update values from user params
        sex.config.update(params)

        # ok, here we go!
        try:
            sex.run(self._filename, clean=False)
            result = sex.catalog()
            return result
        finally:
            if saveCatalog:
                shutil.move(sex.config['CATALOG_NAME'], saveCatalog)
            if saveConfig:
                shutil.move(sex.config['CONFIG_FILE'], saveConfig)

            sex.clean(config=True, catalog=True, check=True)
Ejemplo n.º 4
0
    def extract(self, params={}, saveCatalog=False, saveConfig=False):

        sex = SExtractor()

        # default params
        sex.config['PIXEL_SCALE'] = 0.45
        sex.config['BACK_TYPE'] = "AUTO"
        sex.config['SATUR_LEVEL'] = 60000
        sex.config['DETECT_THRESH'] = 3.0
        sex.config['VERBOSE_TYPE'] = "QUIET"
        sex.config['PARAMETERS_LIST'] = ["NUMBER",
                                         "XWIN_IMAGE", "YWIN_IMAGE",
                                         "FLUX_BEST", "FWHM_IMAGE",
                                         "FLAGS"]

        # update values from user params
        sex.config.update(params)

        # ok, here we go!
        try:
            sex.run(self._filename, clean=False)
            result = sex.catalog()
            return result
        finally:
            if saveCatalog:
                shutil.move(sex.config['CATALOG_NAME'], saveCatalog)
            if saveConfig:
                shutil.move(sex.config['CONFIG_FILE'], saveConfig)

            sex.clean(config=True, catalog=True, check=True)
Ejemplo n.º 5
0
    def solveField(fullfilename, findstarmethod="astrometry.net"):
        """
        @param: fullfilename entire path to image
        @type: str

        @param: findstarmethod (astrometry.net, sex)
        @type: str

        Does astrometry to image=fullfilename
        Uses either astrometry.net or sex(tractor) as its star finder
        """

        pathname, filename = os.path.split(fullfilename)
        pathname = pathname + "/"
        basefilename, file_xtn = os.path.splitext(filename)
        # *** enforce .fits extension
        if (file_xtn != ".fits"):
            raise ValueError(
                "File extension must be .fits it was = %s\n" % file_xtn)

        # *** check whether the file exists or not
        if (os.path.exists(fullfilename) == False):
            raise IOError(
                "You selected image %s  It does not exist\n" % fullfilename)

        # version 0.23 changed behavior of --overwrite
        # I need to specify an output filename with -o
        outfilename = basefilename + "-out"

        image = Image.fromFile(fullfilename)
        try:
            ra = image["CRVAL1"]    # expects to see this in image
        except:
            raise AstrometryNetException(
                "Need CRVAL1 and CRVAL2 and CD1_1 on header")
        try:
            dec = image["CRVAL2"]
        except:
            raise AstrometryNetException(
                "Need CRVAL1 and CRVAL2 and CD1_1 on header")
        width = image["NAXIS1"]
        height = image["NAXIS2"]
        radius = 5.0 * abs(image["CD1_1"]) * width

        if findstarmethod == "astrometry.net":
            line = "solve-field %s -d 10,20,30,40,50,60,70,80,90,100 --overwrite -o %s --ra %f --dec %f --radius %f" % (
                fullfilename, outfilename, ra, dec, radius)
        elif findstarmethod == "sex":
            sexoutfilename = pathname + outfilename + ".xyls"
            line = "solve-field %s  -d 10,20,30,40,50,60,70,80,90,100 --overwrite -o %s --x-column X_IMAGE --y-column Y_IMAGE --sort-column MAG_ISO --sort-ascending --width %d --height %d --ra %f --dec %f --radius %f" % (
                sexoutfilename, outfilename, width, height, ra, dec, radius)
            # line = "solve-field %s --overwrite -o %s --x-column X_IMAGE --y-column Y_IMAGE --sort-column MAG_ISO --sort-ascending --width %d --height %d"  %(sexoutfilename, outfilename,width, height)
            # could use --guess-scale for unreliable mounts:
            # line = "solve-field %s --overwrite -o %s --x-column X_IMAGE --y-column Y_IMAGE --sort-column MAG_ISO --sort-ascending --width %d --height %d --guess-scale"  %(sexoutfilename, outfilename, width, height)

            sex = SExtractor()
            sex.config['BACK_TYPE'] = "AUTO"
            sex.config['DETECT_THRESH'] = 3.0
            sex.config['DETECT_MINAREA'] = 18.0
            sex.config['VERBOSE_TYPE'] = "QUIET"
            sex.config['CATALOG_TYPE'] = "FITS_1.0"
            #sex.config['CATALOG_TYPE'] = "ASCII"
            sex.config['CATALOG_NAME'] = sexoutfilename
            sex.config['PARAMETERS_LIST'] = ["X_IMAGE", "Y_IMAGE", "MAG_ISO"]
            sex.run(fullfilename)

        else:
            log.error("Unknown option used in astrometry.net")

        # when there is a solution astrometry.net creates a file with .solved
        # added as extension.
        is_solved = pathname + outfilename + ".solved"
        # if it is already there, make sure to delete it
        if (os.path.exists(is_solved)):
            os.remove(is_solved)
        print "SOLVE", line
        # *** it would be nice to add a test here to check
        # whether astrometrynet is running OK, if not raise a new exception
        # like AstrometryNetInstallProblem
        solve = Popen(line.split())  # ,env=os.environ)
        solve.wait()
        # if solution failed, there will be no file .solved
        if (os.path.exists(is_solved) == False):
            raise NoSolutionAstrometryNetException(
                "Astrometry.net could not find a solution for image: %s %s" % (fullfilename, is_solved))

        # wcs_imgname will be the old fits file with the new header
        # wcs_solution is the solve-field solution file
        wcs_imgname = pathname + outfilename + "-wcs" + ".fits"
        wcs_solution = pathname + outfilename + ".wcs"
        shutil.copyfile(wcs_solution, wcs_solution + ".fits")
        if (os.path.exists(wcs_imgname) == True):
            iraf.imdelete(wcs_imgname)

        # create a separate image with new header
        iraf.artdata()
        iraf.imcopy(fullfilename, wcs_imgname)
        iraf.hedit(wcs_imgname, "CD1_1,CD1_2,CD2_1,CD2_2,CRPIX1,CRPIX2,CRVAL1,CRVAL2,RA,DEC,ALT,AZ",
                   add="no", addonly="no", delete="yes",
                   verify="no", show="no", update="yes")
        iraf.mkheader(images=wcs_imgname, headers=wcs_solution + ".fits",
                      append="yes", verbose="no", mode="al")
        return(wcs_imgname)
Ejemplo n.º 6
0
def main(argv):

    from optparse import OptionParser

    parser = OptionParser()

    parser.add_option('-i',
                      '--image',
                      help='Fit image file with donuts to measure.',
                      type='string')
    parser.add_option(
        '-p',
        '--parameters',
        help='Base donut json parameters. Position will be overwritten.',
        type='string')
    parser.add_option('--mpithreads',
                      help='Number of threads to start mpi with (default 4)',
                      type='int',
                      default=4)
    parser.add_option('--display',
                      help='Display image and load catalog on ds9?',
                      action='store_true',
                      default=False)
    parser.add_option('--overwrite',
                      help='Run in overwrite mode?',
                      action='store_true',
                      default=False)

    opt, args = parser.parse_args(argv)

    # Run sextractor on image to get catalog list
    sex = SExtractor()

    # default params
    sex.config['PIXEL_SCALE'] = 0.55
    sex.config['BACK_TYPE'] = "AUTO"
    sex.config['SATUR_LEVEL'] = 60000
    sex.config['DETECT_MINAREA'] = 200
    sex.config['DETECT_THRESH'] = 10.0
    sex.config['VERBOSE_TYPE'] = "QUIET"
    sex.config['PARAMETERS_LIST'] = [
        "NUMBER", 'X_IMAGE', 'Y_IMAGE', "XWIN_IMAGE", "YWIN_IMAGE",
        "FLUX_BEST", "FWHM_IMAGE", "FLAGS"
    ]

    # ok, here we go!

    log.info('Running sextractor')
    sex.run(opt.image, clean=False)

    if opt.display:
        log.info('Displaying image in ds9')

    # Now calculate zernike coef

    outname = os.path.basename(opt.image).split('-')[1].replace(
        '.fits', '_zern.npy')

    cmd = 'mpirun -np %i python ~/Develop/donut/script/donut -i %s -p %s -c %s -o %s' % (
        opt.mpithreads, opt.image, opt.parameters, sex.config['CATALOG_NAME'],
        outname)

    if not os.path.exists(outname) and not opt.overwrite:
        log.info('Running donut with %i cores' % opt.mpithreads)
        log.debug(cmd)
        p = subprocess.Popen(cmd,
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        p.wait()
    else:
        log.warning(
            'File %s exists. Run with --overwrite to force reprocess.' %
            outname)

    log.info('Mapping hexapod position')

    zerpar = [
        os.path.basename(__file__), '-f', outname, '--max', '100', '--niter',
        '3', '-i', opt.image
    ]

    zernmap.main(zerpar)

    return 0
Ejemplo n.º 7
0
    def solveField(fullfilename, findstarmethod="astrometry.net"):
        """
        @param: fullfilename entire path to image
        @type: str

        @param: findstarmethod (astrometry.net, sex) 
        @type: str

        Does astrometry to image=fullfilename
        Uses either astrometry.net or sex(tractor) as its star finder

        """

        pathname, filename = os.path.split(fullfilename)
        pathname = pathname + "/"
        basefilename,file_xtn = os.path.splitext(filename)
        # *** enforce .fits extension
        if (file_xtn != ".fits"):
            raise ValueError("File extension must be .fits it was = %s\n" %file_xtn)

        # *** check whether the file exists or not
        if ( os.path.exists(fullfilename) == False ):
            raise IOError("You selected image %s  It does not exist\n" %fullfilename)

        # version 0.23 changed behavior of --overwrite
        # I need to specify an output filename with -o
        outfilename = basefilename + "-out"

        image = Image.fromFile(fullfilename)
        try:
            ra = image["CRVAL1"]    # expects to see this in image
        except:
            raise AstrometryNetException("Need CRVAL1 and CRVAL2 and CD1_1 on header")
        try:
            dec = image["CRVAL2"]
        except:
            raise AstrometryNetException("Need CRVAL1 and CRVAL2 and CD1_1 on header")
        width = image["NAXIS1"]
        height = image["NAXIS2"] 
        radius = 5.0 * abs(image["CD1_1"]) * width

        if findstarmethod == "astrometry.net":
            #line = "solve-field --guess-scale %s --overwrite -o %s" %(fullfilename, outfilename)
            line = "solve-field %s --overwrite -o %s --ra %f --dec %f --radius %f"  %(fullfilename, outfilename, ra, dec, radius)
            print line


        elif findstarmethod == "sex":
            sexoutfilename = pathname + outfilename + ".xyls"
            line = "solve-field %s --overwrite -o %s --x-column X_IMAGE --y-column Y_IMAGE --sort-column MAG_ISO --sort-ascending --width %d --height %d --ra %f --dec %f --radius %f"  %(sexoutfilename, outfilename, width, height, ra, dec, radius)
            print "Sextractor command line %s" %line
            # using --guess-scale
            # line = "solve-field %s --overwrite -o %s --x-column X_IMAGE --y-column Y_IMAGE --sort-column MAG_ISO --sort-ascending --width %d --height %d --guess-scale"  %(sexoutfilename, outfilename, width, height)

            sex = SExtractor()
            sex.config['BACK_TYPE']   = "AUTO"
            sex.config['DETECT_THRESH'] = 3.0
            sex.config['DETECT_MINAREA'] = 18.0
            sex.config['VERBOSE_TYPE'] = "QUIET"
            sex.config['CATALOG_TYPE'] = "FITS_1.0"
            #sex.config['CATALOG_TYPE'] = "ASCII"
            sex.config['CATALOG_NAME'] = sexoutfilename
            sex.config['PARAMETERS_LIST'] = ["X_IMAGE","Y_IMAGE","MAG_ISO"]
            sex.run(fullfilename)

        else:
            log.error("Unknown option used in astrometry.net")

        # when there is a solution astrometry.net creates a file with .solved
        # added as extension.  
        is_solved = pathname + outfilename + ".solved"
        # if it is already there, make sure to delete it 
        if ( os.path.exists(is_solved)):
            os.remove(is_solved)
        solve = Popen(line.split()) # ,env=os.environ)
        solve.wait()
        # if solution failed, there will be no file .solved
        if ( os.path.exists(is_solved) == False ):
            raise NoSolutionAstrometryNetException("Astrometry.net could not find a solution for image: %s %s" %(fullfilename, is_solved))

        # wcs_imgname will be the old fits file with the new header
        # wcs_solution is the solve-field solution file
        wcs_imgname = pathname + outfilename + "-wcs" + ".fits"
        wcs_solution = pathname + outfilename + ".wcs"
        shutil.copyfile(wcs_solution,wcs_solution+".fits")
        if ( os.path.exists(wcs_imgname) == True ):
            iraf.imdelete(wcs_imgname)

        # create a separate image with new header
        iraf.artdata()
        iraf.imcopy(fullfilename,wcs_imgname)
        iraf.mkheader(images=wcs_imgname,headers=wcs_solution+".fits",
                      append="no",verbose="no",mode="al")
        return(wcs_imgname)