def make_rgb_cube(files, output, north=False, system=None, equinox=None): ''' Make an RGB data cube from a list of three FITS images. This method can read in three FITS files with different projections/sizes/resolutions and uses Montage to reproject them all to the same projection. Two files are produced by this function. The first is a three-dimensional FITS cube with a filename give by `output`, where the third dimension contains the different channels. The second is a two-dimensional FITS image with a filename given by `output` with a `_2d` suffix. This file contains the mean of the different channels, and is required as input to FITSFigure if show_rgb is subsequently used to show a color image generated from the FITS cube (to provide the correct WCS information to FITSFigure). Parameters ---------- files : tuple or list A list of the filenames of three FITS filename to reproject. The order is red, green, blue. output : str The filename of the output RGB FITS cube. north : bool, optional By default, the FITS header generated by Montage represents the best fit to the images, often resulting in a slight rotation. If you want north to be straight up in your final mosaic, you should use this option. system : str, optional Specifies the system for the header (default is EQUJ). Possible values are: EQUJ EQUB ECLJ ECLB GAL SGAL equinox : str, optional If a coordinate system is specified, the equinox can also be given in the form YYYY. Default is J2000. ''' # Check whether the Python montage module is installed. The Python module # checks itself whether the Montage command-line tools are available, and # if they are not then importing the Python module will fail. try: import montage_wrapper as montage except ImportError: raise Exception("Both the Montage command-line tools and the" " montage-wrapper Python module are required" " for this function") # Check that input files exist for f in files: if not os.path.exists(f): raise Exception("File does not exist : " + f) # Create work directory work_dir = tempfile.mkdtemp() raw_dir = '%s/raw' % work_dir final_dir = '%s/final' % work_dir images_raw_tbl = '%s/images_raw.tbl' % work_dir header_hdr = '%s/header.hdr' % work_dir # Create raw and final directory in work directory os.mkdir(raw_dir) os.mkdir(final_dir) # Create symbolic links to input files for i, f in enumerate(files): os.symlink(os.path.abspath(f), '%s/image_%i.fits' % (raw_dir, i)) # List files and create optimal header montage.mImgtbl(raw_dir, images_raw_tbl, corners=True) montage.mMakeHdr(images_raw_tbl, header_hdr, north_aligned=north, system=system, equinox=equinox) # Read header in with astropy.io.fits header = fits.Header.fromtextfile(header_hdr) # Find image dimensions nx = int(header['NAXIS1']) ny = int(header['NAXIS2']) # Generate emtpy datacube image_cube = np.zeros((len(files), ny, nx), dtype=np.float32) # Loop through files for i in range(len(files)): # Reproject channel to optimal header montage.reproject('%s/image_%i.fits' % (raw_dir, i), '%s/image_%i.fits' % (final_dir, i), header=header_hdr, exact_size=True, bitpix=-32) # Read in and add to datacube image_cube[i, :, :] = fits.getdata('%s/image_%i.fits' % (final_dir, i)) # Write out final cube fits.writeto(output, image_cube, header, clobber=True) # Write out collapsed version of cube fits.writeto(output.replace('.fits', '_2d.fits'), \ np.mean(image_cube, axis=0), header, clobber=True) # Remove work directory shutil.rmtree(work_dir)
def mosaic(input_files, mosaic_file, work_dir, ext=0, background_match=False, cdelt=None, density=False, equinox=None, header=None, level_only=False, north_aligned=False, postprocess=None, preprocess=None, system=None, weights_file=None): """Make a mosiac. High-level wrapper around several Montage operations similar to `montage_wrapper.mosaic`. The main differences are 1) added support for preprocessing the input images before reprojection and postprocessing the final image after mosaicking, 2) options for using images in total flux units instead of flux density (as assumed by Montage), 3) more of the `montage_wrapper.mMakeHdr` keywords available for header creation, and 4) the `whole` keyword for `montage_wrapper.mProjExec` is automatically set to True when `background_match` is True. The latter is important since backround matching behaves unreliably otherwise. Parameters ---------- input_files : list or string List of paths to the input images. This may also be the path to a directory containing all input images, in which case `input_files` will automatically be set to a list of all files in the directory ending with ".fits". mosaic_file : str Path to the output mosaic file. The final mosaic always has the same units as the `input_files` images. work_dir : str Path to the working directory for all intermediate files produced by Montage. The directory has the following structure:: work_dir/ input/ Contains either symlinks to `input_files` or new files depending on the `preprocess` and `density` keywords. Assuming the `density` keyword has been set correctly, these images will always be in flux density units. reprojected/ The reprojected images. differences/ Difference calculations for background matching (only if `background_match` is True). corrected/ Background-matched images (only if `background_match` is True). output/ The intermediate mosiac used to produce the final mosaic file, depending on the `density` and `postprocess` keywords. background_match : bool, optional If True, match the background levels of the reprojected images before mosaicking. Automatically sets ``whole = True`` in `montage_wrapper.mProjExec`. Default is False. cdelt : float, optional See `header` and `montage_wrapper.mMakeHdr`. Default is None. density : bool, optional If True, the input images are in flux density units (i.e., signal per unit pixel area). If False (default), the input images are assumed to be in units of total flux, and are automatically scaled to flux density before reprojection. equinox : str, optional See `header` and `montage_wrapper.mMakeHdr`. Default is None. header : str, optional Path to the template header file describing the output mosaic. Default is None, in which case a template header is created automatically using `montage_wrapper.mMakeHdr` and the `cdelt`, `equinox`, `north_aligned`, and `system` keyword arguments. level_only : bool, optional See `montage_wrapper.mBgModel`. Ignored if `background_match` is False. Default is False. north_aligned : bool, optional See `header` and `montage_wrapper.mMakeHdr`. Default is None. postprocess, preprocess : function, optional Functions for processing the raw input images before the input density images are created (`preprocess`) and after the final mosaic is created (`postprocess`). The function arguments should be the image data array and the image header (`astropy.io.fits.Header`), and the return values should be the same. Default is None. system : str, optional See `header` and `montage_wrapper.mMakeHdr`. Default is None. weights_file : str, optional Path to output pixel weights file. Pixel weights are derived from the final mosaic area file. Weights are normalized to 1, and represent coverage of the mosaic area by the input images. Unlike Montage area files, regions where the input images overlap are not considered. Default is None. Returns ------- None """ # Get list of files if input_files is a directory name if isinstance(input_files, basestring): dirname = os.path.dirname(input_files) input_files = [os.path.join(dirname, basename) for basename in os.listdir(dirname) if os.path.splitext(basename)[1] == '.fits'] # Create working directory try: os.makedirs(work_dir) except OSError: shutil.rmtree(work_dir) os.makedirs(work_dir) # Create input directory, populate it, and get image metadata input_dir = os.path.join(work_dir, 'input') os.mkdir(input_dir) if preprocess or not density or ext>0: # Create new input files for input_file in input_files: data, hdr = astropy.io.fits.getdata(input_file, header=True, ext=ext) if preprocess: data, hdr = preprocess(data, hdr) if not density: # Convert total flux into flux density dx, dy = wcs.calc_pixscale(hdr, ref='crpix').arcsec pixarea = dx * dy # arcsec2 data /= pixarea # Write basename = os.path.basename(input_file) basename = '_density'.join(os.path.splitext(basename)) new_input_file = os.path.join(input_dir, basename) hdu = astropy.io.fits.PrimaryHDU(data=data, header=hdr) hdu.writeto(new_input_file, output_verify='ignore') else: # Symlink existing files for input_file in input_files: basename = os.path.basename(input_file) new_input_file = os.path.join(input_dir, basename) os.symlink(input_file, new_input_file) input_table = os.path.join(input_dir, 'input.tbl') montage.mImgtbl(input_dir, input_table, corners=True) # Template header if header is None: template_header = os.path.join(work_dir, 'template.hdr') montage.mMakeHdr(input_table, template_header, cdelt=cdelt, equinox=equinox, north_aligned=north_aligned, system=system) else: template_header = header # Create reprojection directory, reproject, and get image metadata proj_dir = os.path.join(work_dir, 'reprojected') os.makedirs(proj_dir) whole = True if background_match else False stats_table = os.path.join(proj_dir, 'mProjExec_stats.log') montage.mProjExec(input_table, template_header, proj_dir, stats_table, raw_dir=input_dir, whole=whole) reprojected_table = os.path.join(proj_dir, 'reprojected.tbl') montage.mImgtbl(proj_dir, reprojected_table, corners=True) # Background matching if background_match: diff_dir = os.path.join(work_dir, 'differences') os.makedirs(diff_dir) # Find overlaps diffs_table = os.path.join(diff_dir, 'differences.tbl') montage.mOverlaps(reprojected_table, diffs_table) # Calculate differences between overlapping images montage.mDiffExec(diffs_table, template_header, diff_dir, proj_dir=proj_dir) # Find best-fit plane coefficients fits_table = os.path.join(diff_dir, 'fits.tbl') montage.mFitExec(diffs_table, fits_table, diff_dir) # Calculate corrections corr_dir = os.path.join(work_dir, 'corrected') os.makedirs(corr_dir) corrections_table = os.path.join(corr_dir, 'corrections.tbl') montage.mBgModel(reprojected_table, fits_table, corrections_table, level_only=level_only) # Apply corrections montage.mBgExec(reprojected_table, corrections_table, corr_dir, proj_dir=proj_dir) img_dir = corr_dir else: img_dir = proj_dir # Make mosaic output_dir = os.path.join(work_dir, 'output') os.makedirs(output_dir) out_image = os.path.join(output_dir, 'mosaic.fits') montage.mAdd(reprojected_table, template_header, out_image, img_dir=img_dir, exact=True) # Pixel areas and weights if weights_file or not density: area_file = '_area'.join(os.path.splitext(out_image)) area, hdr = astropy.io.fits.getdata(area_file, header=True) # steradians area *= (180/np.pi*3600)**2 # arcsec2 dx, dy = wcs.calc_pixscale(hdr, ref='crpix').arcsec pixarea = dx * dy # arcsec2 area = np.clip(area, 0, pixarea) # Don't care about overlaps if weights_file: weights = area / pixarea # Normalize to 1 hdu = astropy.io.fits.PrimaryHDU(weights, header=hdr) try: hdu.writeto(weights_file) except IOError: os.remove(weights_file) hdu.writeto(weights_file) # Write final mosaic dirname = os.path.dirname(mosaic_file) try: os.makedirs(dirname) except OSError: pass if postprocess or not density: # Create new file data, hdr = astropy.io.fits.getdata(out_image, header=True) if not density: # Convert flux density into total flux data *= pixarea if postprocess: data, hdr = postprocess(data, hdr) # Write hdu = astropy.io.fits.PrimaryHDU(data, header=hdr) try: hdu.writeto(mosaic_file) except IOError: os.remove(mosaic_file) hdu.writeto(mosaic_file) else: # Move existing file os.rename(out_image, mosaic_file) return
def _montage_test(): # create density images input_dir = os.path.dirname(density_files[0]) # image metadata meta1_file = os.path.join(input_dir, 'meta1.tbl') montage.mImgtbl(input_dir, meta1_file, corners=True) # make header #lon, lat = [], [] #for density_file in density_files: # data, hdr = astropy.io.fits.getdata(density_file, header=True) # wcs = astropy.wcs.WCS(hdr) # x1, y1 = 0.5, 0.5 # y2, x2 = data.shape # x2, y2 = x2 + 0.5, y2 + 0.5 # x, y = [x1, x2, x2, x1], [y1, y1, y2, y2] # ln, lt = wcs.wcs_pix2world(x, y, 1) # lon += list(ln) # lat += list(lt) #lon1, lon2 = np.min(lon), np.max(lon) #lat1, lat2 = np.min(lat), np.max(lat) hdr_file = os.path.join(os.path.dirname(input_dir), 'test.hdr') montage.mMakeHdr(meta1_file, hdr_file) # reproject proj_dir = os.path.dirname(proj_files[0]) safe_mkdir(proj_dir) stats_file = os.path.join(proj_dir, 'stats.tbl') montage.mProjExec(meta1_file, hdr_file, proj_dir, stats_file, raw_dir=input_dir, exact=True) # image metadata meta2_file = os.path.join(proj_dir, 'meta2.tbl') montage.mImgtbl(proj_dir, meta2_file, corners=True) # Background modeling diff_dir = os.path.join(os.path.dirname(proj_dir), 'difference') safe_mkdir(diff_dir) diff_file = os.path.join(diff_dir, 'diffs.tbl') montage.mOverlaps(meta2_file, diff_file) montage.mDiffExec(diff_file, hdr_file, diff_dir, proj_dir) fits_file = os.path.join(diff_dir, 'fits.tbl') montage.mFitExec(diff_file, fits_file, diff_dir) # Background matching corr_dir = os.path.join(os.path.dirname(proj_dir), 'correct') safe_mkdir(corr_dir) corr_file = os.path.join(corr_dir, 'corrections.tbl') montage.mBgModel(meta2_file, fits_file, corr_file, level_only=False) montage.mBgExec(meta2_file, corr_file, corr_dir, proj_dir=proj_dir) # Native mosaic projadd_file = config.path('{:s}.reproject.add'.format(kind)) projadd_dir, filename = os.path.split(projadd_file) filename, ext = os.path.splitext(filename) filename = '{0:s}_native{1:s}'.format(filename, ext) projaddnative_file = os.path.join(projadd_dir, filename) safe_mkdir(projadd_dir) montage.mAdd(meta2_file, hdr_file, projaddnative_file, img_dir=corr_dir, exact=True) # Reproject to final header header_file = config.path('{:s}.hdr'.format(kind)) montage.mProject(projaddnative_file, projadd_file, header_file) # Postprocess data, hdr = astropy.io.fits.getdata(projaddnative_file, header=True) x1, x2 = 900, 1900 y1, y2 = 3000, 4500 val = np.mean(data[y1:y2,x1:x2]) data, hdr = astropy.io.fits.getdata(projadd_file, header=True) data = data - val areaadd_file = config.path('{:s}.area.add'.format(kind)) area = astropy.io.fits.getdata(areaadd_file) * (180/np.pi*3600)**2 # arcsec2 data = data * area add_file = config.path('{:s}.add'.format(kind)) dirname = os.path.dirname(add_file) safe_mkdir(dirname) if os.path.exists(add_file): os.remove(add_file) hdu = astropy.io.fits.PrimaryHDU(data, header=hdr) hdu.writeto(add_file)
def mosaic_band(self,band,ra,dec,margin,radius,pgc,survey,remove_bkgrd=False): ''' Input: source info param Create a mosaic fit file for the specified band. Return: String filename of resulting mosaic ''' print ("------------------mosaic_band----------------------") print ("Now mosaic_band on {}".format(pgc)) output = open("../rc3_galaxies_outside_{}_footprint".format(survey.name),'a') # 'a' for append #'w') unclean = open("../rc3_galaxies_unclean_{}".format(survey.name),"a") filename = str(ra)+str(dec) if (DEBUG) : print ("Querying data that lies inside margin") print (ra,dec,margin) result = survey.data_server.surveyFieldConverter(float(ra),float(dec),float(margin)) clean_result = survey.data_server.surveyFieldConverter(float(ra),float(dec),float(margin),True) clean = True if(DEBUG):print ("result: "+str(result)) if(DEBUG):print ("clean_result: "+str(clean_result)) if (len(result)!=len(clean_result)and band=='u'): # Only print this once in the u band. # Assume that if it is unclean in u band (ex. cosmic ray, bright star..etc) then it must be unclean in the other bands too. print ("Data contain unclean images") clean=False unclean.write("{} {} {} {} \n".format(self.rc3_ra,self.rc3_dec,self.rc3_radius,self.pgc)) if (len(result)==0): if (DEBUG): print ('The given ra, dec of this galaxy does not lie in the survey footprint. Onto the next galaxy!')#Exit Program.' output.write("{} {} {} {} \n".format(str(ra),str(dec),str(radius),str(pgc))) return -1 #special value reserved for not in survey footprint galaxies else : if (DEBUG): print ( "Complete Query. These data lies within margin: ") print (result) os.mkdir(band) os.chdir(band) os.mkdir ("rawdir") os.mkdir ("projdir") if (remove_bkgrd): os.mkdir ("diffdir") os.mkdir ("corrdir") # os.mkdir("final") if (DEBUG): print ("Retrieving data from server for "+ band +"band") os.chdir("rawdir") out="" # Raw Imaging Data naming for i in result : if (survey.data_server.name=='Gator'): survey.data_server.getData(band,ra,dec,margin,survey) out = i # 2MASS designation print out elif (survey.data_server.name=='SkyServer'): survey.data_server.getData(band,str(i[0]), str(i[1]),str(i[2])) # run-camcol-field out = "frame-"+str(band)+"-"+str(i[0]).zfill(6)+"-"+str(i[1])+"-"+str(i[2]).zfill(4) elif (survey.data_server.name=='DSSServer'): survey.data_server.getData(band,ra,dec,margin) # Patch for when we can not pass in th pgc number in getData of dssServer class, we rename the file here to conform with RC3's filename expectation for the imaging data raw_data = glob.glob("raw_*.fits") print (raw_data) for i in raw_data: os.rename(i,"DSS_{}_{}.fits".format(band, self.pgc)) out = "raw_{}_{}".format(band,self.pgc) print ("dss_out: "+out) else: raise TypeError("Missing implementation for data retrieval") os.chdir("../") if (DEBUG) : print("Creating mosaic for "+band+" band.") outfile_r = "{}_{}_{}r.fits".format(survey.name,band,self.pgc) outfile = "{}_{}_{}.fits".format(survey.name,band,self.pgc) if (len(result)==1): #With header info, len of processed result list is 1 if there is only 1 field lying in the margin, simply do mSubImage without mosaicing print ("Only one field in region of interest") os.chdir("rawdir") if (DEBUG):print ("m:{}".format(margin)) try: if (DEBUG):print ("2m:{}".format(2*margin)) if (DEBUG):print ([outfile_r,outfile,ra,dec,2*margin]) montage.mSubimage(outfile,outfile,ra,dec,2*margin) # mSubImage takes xsize which should be twice the margin (margin measures center to edge of image) except(montage.status.MontageError): print ("montage_wrapper.status.MontageError: mSubimage: Region outside image.") try :#give it one last chance if (DEBUG):print ("lastchancem:{}".format(margin)) montage.mSubimage(out+".fits",outfile,ra,dec,margin) except(montage.status.MontageError): print("Doesn't work after trying half the margin, just keep the raw FITS file") if (DEBUG):print (out+".fits") if (DEBUG):print (outfile) shutil.move(out+".fits","../..") os.chdir("../../") os.rename(out+".fits",outfile) os.system("rm -r {}".format(survey.best_band)) return outfile if (DEBUG):print (os.getcwd()) os.chdir("../../") #Get out of directory for that galaxy and move on os.system("rm -r {}".format(survey.best_band)) if (DEBUG):print(os.getcwd()) failed_msubimage = open ("failed_msubimage","a") failed_msubimage.write("{} {} {} {} \n".format(str(ra),str(dec),str(radius),str(pgc))) return -1 # masking with special value reserved for not in survey footprint galaxies hdulist = pyfits.open(outfile) if (os.path.exists("../../"+outfile)): os.system("rm ../../"+outfile) shutil.move(outfile,"../..") os.chdir("../..") else: imgtbl="images-rawdir.tbl" hdr="template.hdr" montage.mImgtbl("rawdir",imgtbl) # montage.mHdr(str(ra)+" "+str(dec),margin,out+".hdr") montage.mMakeHdr(imgtbl,hdr) if (DEBUG): print ("Reprojecting images") # os.chdir("rawdir") if (DEBUG):print(os.getcwd()) montage.mProjExec(imgtbl,hdr,"projdir", "stats.tbl",raw_dir="rawdir")#, mpi=enable_mpi,debug=True) if os.listdir("projdir") == []: print "Projection Failed. No projected images produced. Skip to the next galaxy" os.chdir("../") #Get out of directory for that galaxy and move on os.system("rm -r {}".format(survey.best_band)) failed_projection = open ("failed_projection","a") failed_projection.write("{} {} {} {} \n".format(str(ra),str(dec),str(radius),str(pgc))) return -1 # masking with special value reserved for not in survey footprint galaxies if (remove_bkgrd): if (DEBUG): print "Calling the bash script containing Montage routines to rectify the background" if os.getcwd()[-4:-2]==str(pgc): os.system("bash ../../mosaic.sh") else: os.system("bash ../mosaic.sh") print "mSubimage" montage.mSubimage("mosaic.fits" ,"mosaic.fits",ra,dec,2*margin) # mSubImage takes xsize which should be twice the margin (margin measures center to edge of image) shutil.move("mosaic.fits","../{}".format(outfile_r))#if change to :-11 then move out of u,g,r,i,z directory, may be more convenient for mJPEG if (DEBUG) : print ("Completed Mosaic for " + band) else: montage.mImgtbl("projdir","pimages.tbl") os.chdir("projdir") montage.mAdd("../pimages.tbl","../"+hdr,"{}_{}.fits".format(survey.name,out))#, mpi=enable_mpi) montage.mSubimage("{}_{}.fits".format(survey.name,out),outfile_r,ra,dec,2*margin) # mSubImage takes xsize which should be twice the margin (margin measures center to edge of image) shutil.move(outfile_r,"../../{}".format(outfile_r) )#if change to :-11 then move out of u,g,r,i,z directory, may be more convenient for mJPEG if (DEBUG) : print ("Completed Mosaic for " + band) os.chdir("..") os.chdir("../") hdulist = pyfits.open(outfile_r) hdulist[0].header['RA']=float(ra) hdulist[0].header['DEC']=float(dec) hdulist[0].header['RADIUS']=radius if (DEBUG):print ("Finished mosaic_band on {}".format(pgc)) hdulist[0].header['PGC']=pgc hdulist[0].header['NED']=("http://ned.ipac.caltech.edu/cgi-bin/objsearch?objname="+ str(hdulist[0].header['PGC'])+"&extend=no&hconst=73&omegam=0.27&omegav=0.73&corr_z=1&out_csys=Equatorial&out_equinox=J2000.0&obj_sort=RA+or+Longitude&of=pre_text&zv_breaker=30000.0&list_limit=5&img_stamp=YES") hdulist[0].header['CLEAN']=clean hdulist[0].header['MARGIN']=margin if (os.path.exists(outfile)): os.system("rm "+ outfile) hdulist.writeto(outfile) if (os.path.exists(outfile_r)): os.system("rm "+outfile_r) os.system("rm -r {}".format(band)) return outfile