Exemplo n.º 1
0
def do_reprojection(filename,input_sys,output_sys,size=None,center=None,outfile=None,list_o_files=False,hdu=0):
    system_lookup= {"GALACTIC":"galactic","J2000":"equatorial"}
    filename_lookup = {"GALACTIC":"GAL","J2000":"EQ"}

    if list_o_files:
        filename = filename[0]
    d,h = pyfits.getdata(filename,hdu,header=True)
    if not size:
        size = get_size(h)
        
    #Center coords always in J2000
    if not center:
        x,y = get_center_position(h,input_sys,"J2000")
    else:
        x,y = ac.convertCoords(input_sys,"J2000",center[0],center[1],2000.)
    pix_size = get_pixel_size(h)
    #print(x,y)
    print(pix_size)
    coord_string = str(x)+" "+str(y)
    #print(coord_string)
    #Note that older versions on Montage do not work because of normal split
    #dividing the coordinates. Fix is to use shlex.split instead.
    montage.mHdr(coord_string,size,"Test.hdr",system=system_lookup[output_sys],pix_size=pix_size*3600)
    #print(yo)
    montage.mSubimage(filename,"Test.fits",x,y,size*2,hdu=hdu)
    if not outfile: #Try a reasonable guess for output file
        outfile = filename.replace(".fits","_"+filename_lookup[output_sys]+".fits")
    montage.mProject("Test.fits",outfile,"Test.hdr")
Exemplo n.º 2
0
def do_reprojection(filename,
                    input_sys,
                    output_sys,
                    size=None,
                    center=None,
                    outfile=None,
                    list_o_files=False,
                    hdu=0):
    system_lookup = {"GALACTIC": "galactic", "J2000": "equatorial"}
    filename_lookup = {"GALACTIC": "GAL", "J2000": "EQ"}

    if list_o_files:
        filename = filename[0]
    d, h = pyfits.getdata(filename, hdu, header=True)
    if not size:
        size = get_size(h)

    #Center coords always in J2000
    if not center:
        x, y = get_center_position(h, input_sys, "J2000")
    else:
        x, y = ac.convertCoords(input_sys, "J2000", center[0], center[1],
                                2000.)
    pix_size = get_pixel_size(h)
    #print(x,y)
    print(pix_size)
    coord_string = str(x) + " " + str(y)
    #print(coord_string)
    #Note that older versions on Montage do not work because of normal split
    #dividing the coordinates. Fix is to use shlex.split instead.
    montage.mHdr(coord_string,
                 size,
                 "Test.hdr",
                 system=system_lookup[output_sys],
                 pix_size=pix_size * 3600)
    #print(yo)
    montage.mSubimage(filename, "Test.fits", x, y, size * 2, hdu=hdu)
    if not outfile:  #Try a reasonable guess for output file
        outfile = filename.replace(".fits",
                                   "_" + filename_lookup[output_sys] + ".fits")
    montage.mProject("Test.fits", outfile, "Test.hdr")
Exemplo n.º 3
0
    def do_cutout(self, undone_cutout):
        """Make a cutout"""
        success = True
        version = 2
        print("Making a cut-out for: " + undone_cutout)
        cutsize = 0.08

        #print(self.filenames)

        if undone_cutout.startswith("I"):
            #Spitzer/GLIMPSE
            channel = undone_cutout[2]
            mosaic = "self.glimpse_mosaic_" + channel
            try:
                reproject_map.do_reprojection(
                    eval(mosaic),
                    "GALACTIC",
                    "GALACTIC",
                    size=cutsize,
                    center=(self.apos, self.bpos),
                    outfile=self.filenames[undone_cutout])
            except montage.status.MontageError:
                #    success=False
                #    print()
                return (False)
            os.remove(self.filenames[undone_cutout].replace(
                '.fits', '_area.fits'))
        elif undone_cutout.startswith("M"):
            #Spitzer/MIPSGAL
            try:
                #reproject_map.do_reprojection(self.mips_mosaic,"J2000","GALACTIC",size=cutsize,center=(self.apos_ra,self.bpos_dec),
                #                            outfile=self.filenames[undone_cutout])
                reproject_map.do_reprojection(
                    self.mips_mosaic,
                    "J2000",
                    "GALACTIC",
                    size=cutsize,
                    center=(self.apos_ra, self.bpos_dec),
                    outfile=self.filenames[undone_cutout])
            except:
                print("Failed to reproject MIPS!!!")
                return (False)
            os.remove(self.filenames[undone_cutout].replace(
                '.fits', '_area.fits'))
            d, h = pyfits.getdata(self.filenames[undone_cutout], header=True)
            d[np.where(d != d)] = 2000.0
            pyfits.writeto(self.filenames[undone_cutout], d, h, clobber=True)
        elif undone_cutout.startswith("T"):
            #2MASS
            coord_string = str(self.ra) + "," + str(self.dec)
            headname = self.filenames[undone_cutout].replace(".fits", ".hdr")
            montage.mHdr(coord_string, cutsize, headname, system="galactic")
            band = undone_cutout[2]  #This gets correct filter from name
            print("2MASS " + band + " " + self.filenames[undone_cutout] + " " +
                  headname)
            montage.mExec("2MASS",
                          band,
                          output_image=self.filenames[undone_cutout],
                          region_header=headname)
            os.remove(headname)

        elif undone_cutout.startswith("R"):
            maptype = undone_cutout[3:]
            print("Actually doing reproject")
            print(undone_cutout)
            print(maptype)
            mosaic1 = "self.RH_mos_" + maptype + "_try1"
            mosaic2 = "self.RH_mos_" + maptype + "_try2"

            try:
                reproject_map.do_reprojection(
                    eval(mosaic1),
                    "J2000",
                    "GALACTIC",
                    size=cutsize,
                    center=(self.apos_ra, self.bpos_dec),
                    outfile=self.filenames[undone_cutout])
            except:
                reproject_map.do_reprojection(
                    eval(mosaic2),
                    "J2000",
                    "GALACTIC",
                    size=cutsize,
                    center=(self.apos_ra, self.bpos_dec),
                    outfile=self.filenames[undone_cutout])
            os.remove(self.filenames[undone_cutout].replace(
                '.fits', '_area.fits'))

        elif undone_cutout.startswith("A"):
            #ATLASGAL does NOT use existing mosaics.
            #Instead, we fetch from Magpis
            print("Doing Atlasgal")
            image = Magpis.get_images(coordinates.Galactic(float(self.glon),
                                                           float(self.glat),
                                                           unit=(u.deg,
                                                                 u.deg)),
                                      image_size=cutsize * u.deg,
                                      survey='atlasgal')
            print(image)
            fits.writeto(self.filenames[undone_cutout],
                         image[0].data,
                         image[0].header,
                         clobber=True)

        elif undone_cutout.startswith("H"):
            #Herschel HiGal
            print("Trying to make a cut-out")
            channel = undone_cutout[1:4]
            try:
                os.mkdir("temp")
                mosaic = "self.H" + channel + "c_try1_file1"
                file1 = self.filenames[undone_cutout].replace(
                    "cutouts", "temp").replace(".fits", "1.fits")
                reproject_map.do_reprojection(eval(mosaic),
                                              "J2000",
                                              "GALACTIC",
                                              size=cutsize,
                                              center=(self.apos_ra,
                                                      self.bpos_dec),
                                              outfile=file1,
                                              list_o_files=True,
                                              hdu=1)
                mosaic = "self.H" + channel + "c_try1_file2"
                file2 = self.filenames[undone_cutout].replace(
                    "cutouts", "temp").replace(".fits", "2.fits")
                reproject_map.do_reprojection(eval(mosaic),
                                              "J2000",
                                              "GALACTIC",
                                              size=cutsize,
                                              center=(self.apos_ra,
                                                      self.bpos_dec),
                                              outfile=file2,
                                              list_o_files=True,
                                              hdu=1)
                #Now we assume these files are the exact same size and projection
                dd1, hh1 = pyfits.getdata(file1, header=True)
                dd2, hh2 = pyfits.getdata(file2, header=True)
                try:
                    dd = np.average(np.dstack((dd1, dd2)), axis=2)
                except ValueError:
                    dd = dd1  #Remove this hack!!
                pyfits.writeto(self.filenames[undone_cutout],
                               dd,
                               hh1,
                               clobber=True)
            except (montage.status.MontageError, IndexError):
                print("Failure!!")
                try:
                    mosaic = "self.H" + channel + "c_try2_file1"
                    file1 = self.filenames[undone_cutout].replace(
                        "cutouts", "temp").replace(".fits", "1.fits")
                    reproject_map.do_reprojection(eval(mosaic),
                                                  "J2000",
                                                  "GALACTIC",
                                                  size=cutsize,
                                                  center=(self.apos_ra,
                                                          self.bpos_dec),
                                                  outfile=file1,
                                                  list_o_files=True,
                                                  hdu=1)
                    mosaic = "self.H" + channel + "c_try2_file2"
                    file2 = self.filenames[undone_cutout].replace(
                        "cutouts", "temp").replace(".fits", "2.fits")
                    reproject_map.do_reprojection(eval(mosaic),
                                                  "J2000",
                                                  "GALACTIC",
                                                  size=cutsize,
                                                  center=(self.apos_ra,
                                                          self.bpos_dec),
                                                  outfile=file2,
                                                  list_o_files=True,
                                                  hdu=1)
                    #Now we assume these files are the exact same size and projection
                    dd1, hh1 = pyfits.getdata(file1, header=True)
                    dd2, hh2 = pyfits.getdata(file2, header=True)
                    try:
                        dd = np.average(np.dstack((dd1, dd2)), axis=2)
                    except ValueError:
                        dd = dd1  #Remove this hack!!
                    pyfits.writeto(self.filenames[undone_cutout],
                                   dd,
                                   hh1,
                                   clobber=True)
                except montage.status.MontageError:
                    success = False
            finally:
                try:
                    shutil.rmtree("temp")
                except OSError:
                    pass

            #try to reproject try 1 500
            #If this fails, try 2
            #Then coadd/median combine the re_projected images

        #Look-up source mosaic / get 2MASS image / get multiple files
        #Lead character in cutout can tell us the basics
        #Extract using montage
        #Do any necessary post-processing.
        #MIPS fix NANs to 2000
        #Herschel rationalize header?
        #Save to the appropriate place
        print("Saving to: " + self.filenames[undone_cutout])
        if success:
            self.report_success(undone_cutout, version)
Exemplo n.º 4
0
    def do_cutout(self,undone_cutout):
        """Make a cutout"""
        success = True
        version = 2
        print("Making a cut-out for: "+undone_cutout)
        cutsize = 0.08

        #print(self.filenames)

        if undone_cutout.startswith("I"):
            #Spitzer/GLIMPSE
            channel = undone_cutout[2]
            mosaic = "self.glimpse_mosaic_"+channel
            try:
                reproject_map.do_reprojection(eval(mosaic),"GALACTIC","GALACTIC",size=cutsize,center=(self.apos,self.bpos),
                                                outfile=self.filenames[undone_cutout])
            except montage.status.MontageError:
            #    success=False
            #    print()
                return(False)
            os.remove(self.filenames[undone_cutout].replace('.fits','_area.fits'))
        elif undone_cutout.startswith("M"):
            #Spitzer/MIPSGAL
            try:
                #reproject_map.do_reprojection(self.mips_mosaic,"J2000","GALACTIC",size=cutsize,center=(self.apos_ra,self.bpos_dec),
                #                            outfile=self.filenames[undone_cutout])
                reproject_map.do_reprojection(self.mips_mosaic,"J2000","GALACTIC",size=cutsize,center=(self.apos_ra,self.bpos_dec),
                                            outfile=self.filenames[undone_cutout])
            except:
                print("Failed to reproject MIPS!!!")
                return(False)
            os.remove(self.filenames[undone_cutout].replace('.fits','_area.fits'))
            d,h = pyfits.getdata(self.filenames[undone_cutout],header=True)
            d[np.where(d!=d)] = 2000.0
            pyfits.writeto(self.filenames[undone_cutout],d,h,clobber=True)
        elif undone_cutout.startswith("T"):
            #2MASS
            coord_string = str(self.ra)+","+str(self.dec)
            headname = self.filenames[undone_cutout].replace(".fits",".hdr")
            montage.mHdr(coord_string,cutsize,headname,system="galactic")
            band = undone_cutout[2] #This gets correct filter from name
            print("2MASS "+band+" "+self.filenames[undone_cutout]+" "+headname)
            montage.mExec("2MASS",band,output_image=self.filenames[undone_cutout],region_header=headname)
            os.remove(headname)
            
        elif undone_cutout.startswith("R"):
            maptype = undone_cutout[3:]
            print("Actually doing reproject")
            print(undone_cutout)
            print(maptype)
            mosaic1 = "self.RH_mos_"+maptype+"_try1"
            mosaic2 = "self.RH_mos_"+maptype+"_try2"
            
            try:
                reproject_map.do_reprojection(eval(mosaic1),"J2000","GALACTIC",size=cutsize,center=(self.apos_ra,self.bpos_dec),
                                            outfile=self.filenames[undone_cutout])
            except:
                reproject_map.do_reprojection(eval(mosaic2),"J2000","GALACTIC",size=cutsize,center=(self.apos_ra,self.bpos_dec),
                                                outfile=self.filenames[undone_cutout])
            os.remove(self.filenames[undone_cutout].replace('.fits','_area.fits'))
            
        elif undone_cutout.startswith("A"):
            #ATLASGAL does NOT use existing mosaics.
            #Instead, we fetch from Magpis
            print("Doing Atlasgal")
            image = Magpis.get_images(coordinates.Galactic(float(self.glon), float(self.glat),
                    unit=(u.deg,u.deg)), image_size=cutsize*u.deg, survey='atlasgal')
            print(image)
            fits.writeto(self.filenames[undone_cutout],
                         image[0].data,image[0].header,clobber=True)
                
            
        elif undone_cutout.startswith("H"):
            #Herschel HiGal
            print("Trying to make a cut-out")
            channel = undone_cutout[1:4]
            try:
                os.mkdir("temp")
                mosaic = "self.H"+channel+"c_try1_file1"
                file1 = self.filenames[undone_cutout].replace("cutouts","temp").replace(".fits","1.fits")
                reproject_map.do_reprojection(eval(mosaic),"J2000","GALACTIC",size=cutsize,center=(self.apos_ra,self.bpos_dec),
                                                outfile=file1,list_o_files=True,hdu=1)
                mosaic = "self.H"+channel+"c_try1_file2"
                file2 = self.filenames[undone_cutout].replace("cutouts","temp").replace(".fits","2.fits")
                reproject_map.do_reprojection(eval(mosaic),"J2000","GALACTIC",size=cutsize,center=(self.apos_ra,self.bpos_dec),
                                                outfile=file2,list_o_files=True,hdu=1)
                #Now we assume these files are the exact same size and projection
                dd1,hh1 = pyfits.getdata(file1,header=True)
                dd2,hh2 = pyfits.getdata(file2,header=True)
                try:
                    dd = np.average(np.dstack((dd1,dd2)),axis=2)
                except ValueError:
                    dd = dd1 #Remove this hack!!
                pyfits.writeto(self.filenames[undone_cutout],dd,hh1,clobber=True)
            except (montage.status.MontageError, IndexError):
                print("Failure!!")
                try:
                    mosaic = "self.H"+channel+"c_try2_file1"
                    file1 = self.filenames[undone_cutout].replace("cutouts","temp").replace(".fits","1.fits")
                    reproject_map.do_reprojection(eval(mosaic),"J2000","GALACTIC",size=cutsize,center=(self.apos_ra,self.bpos_dec),
                                                    outfile=file1,list_o_files=True,hdu=1)
                    mosaic = "self.H"+channel+"c_try2_file2"
                    file2 = self.filenames[undone_cutout].replace("cutouts","temp").replace(".fits","2.fits")
                    reproject_map.do_reprojection(eval(mosaic),"J2000","GALACTIC",size=cutsize,center=(self.apos_ra,self.bpos_dec),
                                                    outfile=file2,list_o_files=True,hdu=1)
                    #Now we assume these files are the exact same size and projection
                    dd1,hh1 = pyfits.getdata(file1,header=True)
                    dd2,hh2 = pyfits.getdata(file2,header=True)
                    try:
                        dd = np.average(np.dstack((dd1,dd2)),axis=2)
                    except ValueError:
                        dd = dd1 #Remove this hack!!
                    pyfits.writeto(self.filenames[undone_cutout],dd,hh1,clobber=True)
                except montage.status.MontageError:
                    success = False
            finally:
                try:
                    shutil.rmtree("temp")
                except OSError:
                    pass
            
            #try to reproject try 1 500 
            #If this fails, try 2
            #Then coadd/median combine the re_projected images
            
        #Look-up source mosaic / get 2MASS image / get multiple files
            #Lead character in cutout can tell us the basics
        #Extract using montage
        #Do any necessary post-processing.
            #MIPS fix NANs to 2000
            #Herschel rationalize header?
        #Save to the appropriate place
        print("Saving to: "+self.filenames[undone_cutout])
        if success:
            self.report_success(undone_cutout,version)
Exemplo n.º 5
0
    def rotcrop_cube(x1, y1, x2, y2, cubename, outname, xwidth=25, ywidth=25,
            in_system='galactic',  out_system='equatorial', clobber=True, 
            newheader=None, xcen=None, ycen=None):
        """
        Crop a data cube and then rotate it with montage

        """

        cubefile = pyfits.open(cubename)

        if xcen is None and ycen is None:
            pos1 = coords.Position([x1,y1],system=in_system)
            pos2 = coords.Position([x2,y2],system=in_system)

            if cubefile[0].header.get('CTYPE1')[:2] == 'RA':
                x1,y1 = pos1.j2000()
                x2,y2 = pos2.j2000()
                coord_system = 'celestial'
            elif  cubefile[0].header.get('CTYPE1')[:4] == 'GLON':
                x1,y1 = pos1.galactic()
                x2,y2 = pos2.galactic()
                coord_system = 'galactic'

            xcen = (x1+x2)/2.0
            ycen = (y1+y2)/2.0
            print xcen,ycen,xwidth,ywidth,coord_system
        else:
            coord_system = in_system

        sc = subcube(cubefile[0].data, xcen, xwidth, ycen, ywidth, 
                widthunits='pixels', units="wcs", header=cubefile[0].header,
                return_HDU=True)
        # note: there should be no security risk here because pyfits' writeto
        # will not overwrite by default
        tempcube = tempfile.mktemp(suffix='.fits')
        sc.writeto(tempcube)
        
        pa = posang.posang(x1,y1,x2,y2,system=coord_system) - 90

        if newheader is None:
            newheader = sc.header.copy()
            cd11 = newheader.get('CDELT1') if newheader.get('CDELT1') else newheader.get('CD1_1')
            cd22 = newheader.get('CDELT2') if newheader.get('CDELT2') else newheader.get('CD2_2')
            cd12 = newheader.get('CD1_2') if newheader.get('CD1_2') else 0.0
            cd21 = newheader.get('CD2_1') if newheader.get('CD2_1') else 0.0
            cdelt = numpy.sqrt(cd11**2+cd12**2)

            tempheader = tempfile.mktemp(suffix='.hdr')
            ycensign = "+" if numpy.sign(ycen) >= 0 else "-"
            montage.mHdr("%s %1s%s" % (xcen, ycensign, numpy.abs(ycen)), xwidth*cdelt,
                    tempheader, system=out_system, height=ywidth*cdelt,
                    pix_size=cdelt*3600.0, rotation=pa)
            os.system("sed -i bck '/END/d' %s" % (tempheader))
            newheader2 = pyfits.Header()
            newheader2.fromTxtFile(tempheader)
            #newheader2.fromtextfile(tempheader)
            for key in ('CRPIX3','CRVAL3','CDELT3','CD3_3','CUNIT3','WCSTYPE3','CTYPE3'):
                if newheader.get(key):
                    newheader2.update(key,newheader.get(key))
            if newheader.get('CD3_3') and newheader2.get('CDELT3') is None:
                newheader2.update('CDELT3',newheader.get('CD3_3'))
            newheader2.toTxtFile(tempheader,clobber=True)
            #if newheader2.get('CDELT3') is None:
            #    raise Exception("No CD3_3 or CDELT3 in header.")
        else:
            if isinstance(newheader,str):
                newheader2 = pyfits.Header()
                newheader2.fromTxtFile(newheader)
            tempheader = tempfile.mktemp(suffix='.hdr')
            newheader2.toTxtFile(tempheader,clobber=True)


        montage.wrappers.reproject_cube(tempcube,outname,header=tempheader,clobber=clobber)
        #print "\n",outname
        #os.system('imhead %s | grep CDELT' % outname)

        # AWFUL hack because montage removes CDELT3
        tempcube = pyfits.open(outname)
        tempcube.header = newheader2
        #if tempcube.header.get('CDELT3') is None:
        #    raise Exception("No CD3_3 or CDELT3 in header.")
        #print tempcube.header.get('CDELT3')
        tempcube.writeto(outname,clobber=True)
        #print tempcube.get('CDELT3')
        #print "\n",outname
        #os.system('imhead %s | grep CDELT' % outname)

        #print "\nnewheader2"
        #print newheader2.ascard
        #print
        
        return
Exemplo n.º 6
0
    def rotcrop_cube(x1, y1, x2, y2, cubename, outname, xwidth=25, ywidth=25,
                     in_system='galactic',  out_system='equatorial',
                     clobber=True, newheader=None, xcen=None, ycen=None):
        """
        Crop a data cube and then rotate it with montage

        """

        cubefile = fits.open(cubename)

        if xcen is None and ycen is None:
            pos1 = coords.Position([x1,y1],system=in_system)
            pos2 = coords.Position([x2,y2],system=in_system)

            if cubefile[0].header.get('CTYPE1')[:2] == 'RA':
                x1,y1 = pos1.j2000()
                x2,y2 = pos2.j2000()
                coord_system = 'celestial'
            elif  cubefile[0].header.get('CTYPE1')[:4] == 'GLON':
                x1,y1 = pos1.galactic()
                x2,y2 = pos2.galactic()
                coord_system = 'galactic'

            xcen = (x1+x2)/2.0
            ycen = (y1+y2)/2.0
            print xcen,ycen,xwidth,ywidth,coord_system
        else:
            coord_system = in_system

        sc = subcube(cubefile[0].data, xcen, xwidth, ycen, ywidth, 
                widthunits='pixels', units="wcs", header=cubefile[0].header,
                return_HDU=True)
        # note: there should be no security risk here because fits' writeto
        # will not overwrite by default
        tempcube = tempfile.mktemp(suffix='.fits')
        sc.writeto(tempcube)
        
        pa = posang.posang(x1,y1,x2,y2,system=coord_system) - 90

        if newheader is None:
            newheader = sc.header.copy()
            cd11 = newheader.get('CDELT1') if newheader.get('CDELT1') else newheader.get('CD1_1')
            cd22 = newheader.get('CDELT2') if newheader.get('CDELT2') else newheader.get('CD2_2')
            cd12 = newheader.get('CD1_2') if newheader.get('CD1_2') else 0.0
            cd21 = newheader.get('CD2_1') if newheader.get('CD2_1') else 0.0
            cdelt = numpy.sqrt(cd11**2+cd12**2)

            tempheader = tempfile.mktemp(suffix='.hdr')
            ycensign = "+" if numpy.sign(ycen) >= 0 else "-"
            montage.mHdr("%s %1s%s" % (xcen, ycensign, numpy.abs(ycen)), xwidth*cdelt,
                    tempheader, system=out_system, height=ywidth*cdelt,
                    pix_size=cdelt*3600.0, rotation=pa)
            os.system("sed -i bck '/END/d' %s" % (tempheader))
            newheader2 = fits.Header()
            newheader2.fromTxtFile(tempheader)
            #newheader2.fromtextfile(tempheader)
            for key in ('CRPIX3','CRVAL3','CDELT3','CD3_3','CUNIT3','WCSTYPE3','CTYPE3'):
                if newheader.get(key):
                    newheader2[key] = newheader.get(key)
            if newheader.get('CD3_3') and newheader2.get('CDELT3') is None:
                newheader2['CDELT3'] = newheader.get('CD3_3')
            newheader2.toTxtFile(tempheader,clobber=True)
            #if newheader2.get('CDELT3') is None:
            #    raise Exception("No CD3_3 or CDELT3 in header.")
        else:
            if isinstance(newheader,str):
                newheader2 = fits.Header()
                newheader2.fromTxtFile(newheader)
            tempheader = tempfile.mktemp(suffix='.hdr')
            newheader2.toTxtFile(tempheader,clobber=True)


        montage.wrappers.reproject_cube(tempcube,outname,header=tempheader,clobber=clobber)
        #print "\n",outname
        #os.system('imhead %s | grep CDELT' % outname)

        # AWFUL hack because montage removes CDELT3
        tempcube = fits.open(outname)
        tempcube.header = newheader2
        #if tempcube.header.get('CDELT3') is None:
        #    raise Exception("No CD3_3 or CDELT3 in header.")
        #print tempcube.header.get('CDELT3')
        tempcube.writeto(outname,clobber=True)
        #print tempcube.get('CDELT3')
        #print "\n",outname
        #os.system('imhead %s | grep CDELT' % outname)

        
        return
Exemplo n.º 7
0
    def rotcrop_cube(
        x1,
        y1,
        x2,
        y2,
        cubename,
        outname,
        xwidth=25,
        ywidth=25,
        in_system="galactic",
        out_system="equatorial",
        clobber=True,
    ):
        """
        Crop a data cube and then rotate it with montage

        """

        cubefile = pyfits.open(cubename)

        if not coordsOK:
            raise ImportError("cubes.py requires coords for rotcrop_cube")
        pos1 = coords.Position([x1, y1], system=in_system)
        pos2 = coords.Position([x2, y2], system=in_system)

        if cubefile[0].header.get("CTYPE1")[:2] == "RA":
            x1, y1 = pos1.j2000()
            x2, y2 = pos2.j2000()
            coord_system = "celestial"
        elif cubefile[0].header.get("CTYPE1")[:2] == "GLON":
            x1, y1 = pos1.galactic()
            x2, y2 = pos2.galactic()
            coord_system = "galactic"

        xcen = (x1 + x2) / 2.0
        ycen = (y1 + y2) / 2.0

        sc = subcube(
            cubefile[0].data,
            xcen,
            xwidth,
            ycen,
            ywidth,
            widthunits="pixels",
            units="wcs",
            header=cubefile[0].header,
            return_HDU=True,
        )
        # note: there should be no security risk here because pyfits' writeto
        # will not overwrite by default
        tempcube = tempfile.mktemp(suffix=".fits")
        sc.writeto(tempcube)

        pa = posang.posang(x1, y1, x2, y2, system=coord_system) - 90

        newheader = sc.header.copy()
        cd11 = newheader.get("CDELT1") if newheader.get("CDELT1") else newheader.get("CD1_1")
        cd22 = newheader.get("CDELT2") if newheader.get("CDELT2") else newheader.get("CD2_2")
        cd12 = newheader.get("CD1_2") if newheader.get("CD1_2") else 0.0
        cd21 = newheader.get("CD2_1") if newheader.get("CD2_1") else 0.0
        cdelt = numpy.sqrt(cd11 ** 2 + cd12 ** 2)

        tempheader = tempfile.mktemp(suffix=".hdr")
        ycensign = "+" if numpy.sign(ycen) >= 0 else "-"
        montage.mHdr(
            "%s %1s%s" % (xcen, ycensign, numpy.abs(ycen)),
            xwidth * cdelt,
            tempheader,
            system=out_system,
            height=ywidth * cdelt,
            pix_size=cdelt * 3600.0,
            rotation=pa,
        )
        os.system("sed -i bck '/END/d' %s" % (tempheader))
        newheader2 = pyfits.Header()
        newheader2.fromTxtFile(tempheader)
        for key in ("CRPIX3", "CRVAL3", "CDELT3", "CD3_3", "CUNIT3", "WCSTYPE3", "CTYPE3"):
            if newheader.get(key):
                newheader2.update(key, newheader.get(key))
        if newheader.get("CD3_3") and newheader2.get("CDELT3") is None:
            newheader2.update("CDELT3", newheader.get("CD3_3"))
        newheader2.toTxtFile(tempheader, clobber=True)
        # if newheader2.get('CDELT3') is None:
        #    raise Exception("No CD3_3 or CDELT3 in header.")

        montage.wrappers.reproject_cube(tempcube, outname, header=tempheader, clobber=clobber)
        # print "\n",outname
        # os.system('imhead %s | grep CDELT' % outname)

        # AWFUL hack because montage removes CDELT3
        tempcube = pyfits.open(outname)
        tempcube.header = newheader2
        # if tempcube.header.get('CDELT3') is None:
        #    raise Exception("No CD3_3 or CDELT3 in header.")
        # print tempcube.header.get('CDELT3')
        tempcube.writeto(outname, clobber=True)
        # print tempcube.get('CDELT3')
        # print "\n",outname
        # os.system('imhead %s | grep CDELT' % outname)

        # print "\nnewheader2"
        # print newheader2.ascard
        # print

        return