phat_alone/ 40755 1332 567 0 6503632730 12104 5ustar hallast_hyeephat_alone/README100644 1332 567 762 6503633003 13040 0ustar hallast_hyee PHAT -- Pat Hall's Add-on Tasks v 2.10 980317 First & only release for IRAF V2.10. This is my compilation of personal miscellaneous add-on IRAF tasks and their help files, including some tasks for defringing and coadding optical CCD data. This is the standalone version which does not require PHIIRS. To install, enter the proper pathnames in "phip.cl" and "phip.hd", load the softools IRAF package, and type "mkhelpdb root.hd helpdb.mip", deleting the old helpdb.mip if necessary. phat_alone/doc/ 40755 1332 567 0 6503630454 12652 5ustar hallast_hyeephat_alone/doc/biasfix.hlp100644 1332 567 2634 6174726426 15117 0ustar hallast_hyee.help biasfix Jul95 phat .ih NAME biasfix -- fix the 1200x800 CCD's bias discontinuities. .ih USAGE biasfix imname toprow .ih PARAMETERS .ls imname Name of image .le .ls toprow Top row of bottom section .le .ls numrows Number of rows to use for computing statistics .le .ls leftcol Leftmost column to use for statistics .le .ls rightcol Rightmost column to use for statistics .le .ih DESCRIPTION This script deals with the problem of the ~3 ADU discontinuities in the bias level shown by the 1200x800 CCD when binning. The location of the discontinuity is roughly dependent on the exposure time but will wander slightly and occasionally will jump by over 100 pixels. Fortunately the problem seems to be removable (to first order) using the overscan region. .sp 1) Examine each image to identify the TOP row of the BOTTOM bias section, if there is a jump in the bias level at all. .sp 2) Copy the images to a safe location, since the biasfix (and ccdproc) operations are done "in place". .sp 3) Run this routine, which computes the mean of 2 blocks of pixels, one each just below and just above the discontinuity, calculates the difference, and adds that # constant into the entire bottom half of the image. .sp 4) Do the first pass through "ccdproc". The overscan correction in this pass (polynomial-fitting) can proceed normally. .sp 21/04/93 created by Brian McLeod .ih SEE ALSO fixbias .endhelp phat_alone/doc/bindata.hlp100644 1332 567 2253 6174726430 15064 0ustar hallast_hyee.help bindata Jul95 phat .ih NAME bindata.cl -- bin data and plot histograms of it .ih USAGE bindata histype cumulative autoscale binwidth firstfile firstcol .ih PARAMETERS .ls histype Histogram type (normal|percent|sumpercent) .le .ls cumulative Cumulative histogram? .le .ls autoscale Automatically determine start & end bin values? .le .ls binwidth Bin width .le .ls firstfile File containing first variable .le .ls firstcol Column containing first variable (default=1) .le .ls secondfile File containing second variable .le .ls secondcol Column containing second variable (default=1) .le .ls z1 Starting value for bins .le .ls z2 Ending value for bins .le .ls outfile List out histogram to this filename .le .ls include Include z2 in top bin? .le .ih DESCRIPTION This task reads in data from one or two input files (call the data values 1 and 2 respectively), bins them as specified, and outputs one of three histogram types: .sp 1. normal plots 1 (cumulative: sum1) .sp 2. percent plots 1/2 (cumulative: (sum1)/(sum2) .sp 3. sumpercent plots 1/(1+2) (cumulative: (sum1)/(sum(1+2))) .ih BUGS Currently there is a limit of 1000 bins. .endhelp phat_alone/doc/bscount.hlp100644 1332 567 2727 6174726432 15147 0ustar hallast_hyee.help bscount date phat .ih NAME bscount -- estimate Bahcall & Soneira star counts for given (l,b) .ih USAGE bscount long lat mag filter option xtinct .ih PARAMETERS .ls long Galactic longitude (l) of field .le .ls lat Galactic latitude (b) of field .le .ls mag Apparent magnitude at which to calculate counts .le .ls filter Filter in which to calculate counts (B or V) .le .ls option Differential or integral counts? .le .ls xtinct Extinction (obscuration), in magnitudes .le .ls verbose Verbose output? (mag, counts, l, b, xtinct, filter, option)) .le .ih DESCRIPTION This task estimates the integral or differential star counts at the given B or V magnitude and Galactic coordinates, using Equations B1 and B2 in Appendix B of Bahcall & Soneira 1980 (ApJS 44, 73). (Although B&S80 only consider b>=20 degrees, the program works for all b; however, accuracy for |b|<20 cannot be assured, and b<0 values are calculated simply by assuming symmetry around the Galactic plane. The output values are either (stars mag-1 deg-2) for differential counts, or (stars deg-2) for integral counts. The average absolute error between this task's approximation and a full integration of their model is quoted by them as 15%. You can estimate the error for a particular field by comparing this tasks' output to the rigorously calculated values for certain coordinates tabulated in Tables 5 and 6 of B&S80 and interpolating between the fields. .ih BUGS Written by Pat Hall. .endhelp phat_alone/doc/checkfringe.hlp100644 1332 567 1220 6174726434 15727 0ustar hallast_hyee.help checkfringe Jul95 phat .ih NAME checkfringe -- interactively adjust defringing .ih USAGE checkfringe fiximage fringe outname .ih PARAMETERS .ls fiximage Name of (original) image to be defringed .le .ls fringe Fringe image to scale and subtract .le .ls outname Name of defringed image to create .le .ls fit Boolean prompt: Adjust parameters and refit image? .le .ls scale Scaling to use on fringe image .le .ls z Number of image to save .le DESCRIPTION This task scales and subtracts a fringe image from a data image and allows the user to interactively adjust the defringing until it is satisfactory. .ih SEE ALSO defringe .endhelp phat_alone/doc/cubeexam.hlp100644 1332 567 2406 6174726436 15261 0ustar hallast_hyee.help cubeexam Jul95 phat .ih NAME cubeexam -- apply imexam to one band of a 3-D image cube .ih USAGE cubeexam image band .ih PARAMETERS .ls cube Image cube to be examined .le .ls band Specific band of cube to be examined .le .ih DESCRIPTION From adass.iraf.applications: .sp Q: I have stacked a series of 2D images into a cube (e.g. a single image from the cube is tt0066[1:12,1:12,4000]). I can display such individual images OK but commands like imexam or fitpsf always seem to take only the first image in the cube, i.e. tt0066[*,*,1]. The only workaround I've found is to copy out the band: .sp cl> imcopy tt0066[*,*,4000] junk cl> imexam junk .sp What is wrong and is there a better workaround? .sp .sp A: What you report, that IMEXAMINE ignores any image section, is a property of this task. This has to do with wanting to always use the parent image coordinates and not the image section coordinates; I won't go into the technical reasons why. It does this by removing any image section. There are better ways to do this now and IMEXAM should probably changed. In the meantime, the usage of cubeexam would then be: .sp cl> cubeexam tt00066 7 .sp to work on band 7. A temporary image will automatically be created and then deleted upon exiting. .endhelp phat_alone/doc/defringe.hlp100644 1332 567 3002 6174726441 15240 0ustar hallast_hyee.help defringe Jul95 phat .ih NAME defringe -- do sky illumination correction & remove fringing from images .ih USAGE defringe rootname imagelist logfile defstring biasimage .ih PARAMETERS .ls rootname Rootname for output images and image list .le .ls imagelist List of images to process (do not use an `@') .le .ls logfile Name of log file .le .ls defstring String to be appended to output images .le .ls biasimage Zero level calibration image for ccdproc .le .ls dofringe Boolean: Do fringe removal step? .le .ls gain Gain of CCD (for ccdclip in imcombine) .le .ls rdnoise Read noise of CCD (for ccdclip in imcombine) .le .ls forcescale Boolean: Force recalculation of image scales? .le .ls goon Boolean prompt: Continue with task using displayed sky+fringe image? .le .ih DESCRIPTION This task creates a sky+fringe image from a list of data images. The image can optionally be used to perform illumination correction and defringing steps. Before the subtraction is attempted, the sky+fringe image is displayed. If object residuals are present, you may wish to stop, create object masks, and rerun the task. You can use makeobjmask on the non-defringed images to create object masks for them directly, or you can use shiftnadd on the non-defringed images, run mkobjmask on the skysubbed output, insert the object mask names into the non-defringed image headers, and then rerun this task so that the objects are masked out during the creation of the sky+fringe image. .ih SEE ALSO checkfringe .endhelp phat_alone/doc/optcoadd.hlp100644 1332 567 32163 6503630210 15264 0ustar hallast_hyee.help optcoadd Jul96 phat .ih NAME optcoadd -- produce coadded image, exposure map, and sky-subtracted image .ih USAGE optcoadd comblist outimage expmap normmap shiftlist scaling zeroing weighting magfac stack logfile .ih PARAMETERS .ls comblist List of images to combine .le .ls outimage Name of output coadded image .le .ls expmap Name of output exposure map image, which gives the weighted AVERAGE exposure time for each pixel in the coadded image. .le .ls normmap Name of output normalization map image, which can be used with `sigmanorm' to create a constant-rms version of the output coadded image. .le .ls shiftlist File with image shifts. These should be INTEGERS (for best results, take the exact shifts and round them off (file `prefix.roundoff.suffix' from shiftnadd) rather than truncate them) UNLESS parameter magfac>1, in which case they should be the exact image shifts (file `prefix.shiftexact.suffix' from shiftnadd). .le .ls scaling Imcombine scaling factors (none|@file|!|etc.). If scaling=@filename and "filename" does not exist, default scalings will be calculated that correct for extinction relative to a specified airmass. These scaling factors will then be combined with additional scaling factors (that correct for nonphotometric conditions, etc.) if desired. The final scaling factors can then optionally be inserted into the image headers and multiplied into the images prior to imcombining. .le .ls zeroing Imcombine zero-level offsets (@file|none|mode|!|etc.). If zeroing=@filename and "filename" does not exist, the iterative median of all images will be found, the average found, and "filename" created and filled with zero offsets for each image calculated as "average - iterative median". Note that the offsets found this way cannot be used within imcombine with weighted coadding, as some of the offsets will be negative. Set prescale=yes to get around this problem. .le .ls weighting Imcombine weights (none|@file|!|mode|etc.). If weighting=@filename and "filename" does not exist, the iterative variances of all images will be found (after pre-scaling) and combined with the exposure times (from the header keyword given by `expname') to produce the optimum weights=exptime/variance, which will then be listed in the newly created file "filename". .le .ls magfac Magnification factor for subpixel shifting (min=1, max=10). NOTE that this parameter should be set to the appropriate value even if the block-replication has been done with `irrotate' prior to starting this task. This ensures that e.g. the zero-level offsets will be properly recalculated if need be. .le .ls stack Boolean: Combine images by stacking & projecting? .le .ls logfile Name of log file .le .sp .ls normname Header keyword for normalization factor. This should be either the exposure time or mean value of the image, if the image rms is proportional to the square root of either of those, or the variance (rms**2) of the image. If given the value "" (null string) the variance will be found and inserted into the image header with keyword VARIANCE. .le .ls newmask=no Boolean: override bad pixel masks listed in image headers? .le .ls badmask Bad pixel mask to use instead .le .ls shiftsubpix=no Boolean: Do image shifts account for subpixel shifting? .le .ls prescale=no Boolean: Scale images before, not during, imcombine? .le .ls unscale=yes Boolean: Undo scaling factors when done? .le .ls extcoeff Extinction coefficient for default scalings .le .ls airzero Airmass to scale images to? (INDEF=minimum airmass of all images in comblist) .le .ls scalecombine=no Boolean: Combine default & additional scalings? .le .ls scalecomname @filename or !keyword for additional scalings .le .ls putscale Boolean: Insert scaling factors into image headers? .le .ls wordscale="SCALEFAC" Scaling factor header keyword .le .ls defscale=no Boolean: Do scales include default airmass scaling? .le .ls prezero=no Boolean: Do zero offseting before, not during, imcombine? .le .ls unzero=yes Boolean: Undo zero offsets when done? .le .ls putzero=no Boolean: Insert zero offsets into image headers? .le .ls wordzero="ZEROVAL" Zero offset header keyword .le .ls putweight=no Boolean: Insert weights into image headers? .le .ls wordweight="WEIGHT" Weighting factor header keyword .le .ls stackimage Name of stacked image .le .ls unstack Boolean: delete stacked image when done? .le .ls scalesubpix=no Boolean: Do zero offsets account for subpixel shifting? .le .ls expname="EXPTIME" Header keyword for exposure time .le .ls maskedstat=no Boolean: Use `maskstat' with iterstat option, instead of just `iterstat', when finding default zero offsets and weights? The difference between the two is almost always insignificant, and maskstat is slower. .le .ls statfile="" File to for image statistics from iterstat or maskstat. This file will be created if it doesn't exist, to save time in later iterations of task. If it already exists, the statistics will be read in from it rather than recalculated. .le .ls stdpars=yes Boolean: Use standard imcombine parameters for coadd? These parameters are combine=average, rej=ccdclip, zeros given by `zeroing' (default = mode), scales given by `scaling' (default = none), weight given by `weighting' (default = none), expname=expname, lsig=hsig=5., nkeep=1., mclip+. NOTE that the GAIN and READNOISE parameters are still taken from imcoaddpars if stdpars=yes, as are the SIGSCALE, MASKTYPE, and MASKVAL parameters. .le .ls makeavg=no Boolean: Make pure coadd (comb=average,rej=none)? Note that otherwise the parameters are the same as when stdpars=yes. .le .ls flip=no Boolean: Flip image L-R after coadd? .le .ls cleanup=yes Boolean: Clean up blkrep'd images after use? .le .ls tpl=no Boolean: Account for throughput correction in normalization map? .le .ls optcoaddpars Parameter set for imcombine operation used in coadding. GAIN and READNOISE parameters are located here. See help page for imcombine for description. The files "phat$optcoadd8x12.par" and "phat$optcoadd2kx2k.par" contain default params for the SO 800x1200 and 2048x2048 CCDs, respectively. .le .ih DESCRIPTION This tasks coadds the input images using the specified integer-pixel offsets, producing a coadded image, a sky-subtracted coadded image, an exposure map, and an *.imshifts file listing images & offsets used by the photcheck and masklet tasks. The parameters for imcombine can be specified directly in the "imcoaddpars" parameter set, or default parameters "stdpars" or "makeavg" can be used. NOTE that even in those cases, the GAIN, READNOISE, SIGSCALE, MASKTYPE, and MASKVAL parameters are still taken from imcoaddpars. .sp The following steps are performed, in this order: .sp .nf 1. Calculate default (multiplicative) scaling factors that correct for extinction relative to a specified airmass if desired, combine these scaling factors with additional scaling factors (that correct for nonphotometric conditions, etc.) if desired, insert scaling factors into image headers if desired, and multiply the images by the scaling factors before imcombine, if desired. 2. Calculate (additive) zero level offsets using iterative (and masked, if desired) means, if desired, and insert into image headers if desired. 3. Determine default weights (=exptime/variance, where the variance is the square of the iterative (and optionally masked) rms of the image) and put into file if desired, and/or insert weights into image headers if desired. 4. Block replicate images and calculate subpixel shifts if desired, adjusting zero offsets as necessary. 5. Implement (additive) zero level offsets before imcombine if desired. 6. Coadd as requested, stacking if necessary. Will not overwrite an output image. 7. Set output image airmass to average of input image airmasses if default airmass scaling was not used, otherwise set it to the specified airmass to which all images were normalized. 8. Do sky subtraction by subtracting off iterative mean. 9. Create exposure maps & coadd them into a coadded-image exposure map, if the latter doesn't already exist. 10. Divide image by the weighted exposure time at each pixel, to get constant exposure time across the image. 11. Normalize image to the maximum total exposure time that went into it. 12. Flip image left-right if desired. 13. Undo pre-imcombine zero offsets if desired. 14. Undo pre-imcombine scalings if desired. 15. Create normalization maps & coadd them into a coadded-image normalization map, if the latter doesn't already exist. 16. Create the *.imshifts file, listing images & offsets, used by tasks "photcheck" to check the photometric stability of the data and "masklet" to produce individual image object masks from the coadded-image object mask. .fi .sp The default imcombine parameters (stdpars+) usually work quite well with prezero+ and prescale+, although nkeep=-2 is preferable if images of widely varying seeing are being coadded to avoid clipping the wings of bright objects. If you do experiment with different imcombine parameters, the task `photcomp' is a useful task for quickly and easily comparing the photometric differences between two images on the same coordinate system (i.e. the same set of images coadded two different ways). .sp .sp EXPOSURE MAPS .sp An exposure map of the weighted exposure time at each pixel is generated by imcombining the individual exposure map images in the same way as the actual images, except with scale=zero=none. This is used to scale the output image from imcombine to constant global exposure time. It is suggested that if weighting is used, the weights be calculated outside of imcombine, and inserted into a file. This allows for an accurate weighted exposure map to be generated in all cases, and for the weighted exposure time to be correctly calculated if stacking is done. .sp .sp NORMALIZATION MAPS .sp A normalization map is also generated. This can be used with sigmanorm to normalize the output image to constant rms. Each input image has rms=sigma_i (including effects of throughput correction, which however vary between pixels) and weight=weight_i, so each output pixel has sigma_out given by .sp .nf sigma_out^2 = sum_i(sigma_i^2 * weight_i^2)/(sum_i(weight_i))^2 .fi .sp where sum_i denotes a sum over all i images which contribute to the pixel. The normalization map is the inverse of the right-hand-side of this equation, normalized to a maximum of one. Thus when the square root of the normalization map is multiplied by the image, all pixels have equal sigma_out (RMS noise). In the case of roughly equal weights and negligible read noise, this is essentially the same as using the exposure map to do the normalization. .sp The parameter `normname' is the header keyword which contains the parameter to use in creating the normalization map. In the example above, the parameter was the variance of each image, which is the best value to use for the normname parameter. In the case of roughly equal weights and negligible read noise, the exposure time of each image (or mean, if poisson statistics have been preserved) can be used. .sp Using the exposure time is fine for a quick estimate or first pass; if normname="" the normalization factors will be calculated and inserted into the image headers as keyword VARIANCE, if this has not already been done. Note that the variances must include any scaling done before imcombining, but NOT any throughput correction. This is because the throughput correction image is taken into account explicitly (a different tpl_i for each pixel is divided into sigma_i in the equation above) while the variance is assumed constant across the image (one value of sigma_i for each image). .sp .sp This task calls tasks addcomment, iterstat, fileroot, filecalc, and stsdas.toolbox.imgtools.imcalc. .ih EXAMPLES .ih TIME REQUIREMENTS .ih BUGS 1. There is a known bug (IRAF buglog #244) in imcombine (all versions prior to V2.11) possibly applicable to the default parameters (combine=average, reject=ccdclip, and mclip=yes) for this task: .sp When combine=average, reject=(sigclip, avsigclip, ccdclip, or pclip), and mclip=yes (the value of mclip does not matter for pclip) the average will be incorrect if the number of low pixels rejected is greater than the number of unrejected pixels. For example if 3 low pixels are rejected and only 2 pixels remain then the final average will be incorrect for that pixel. There is no workaround other than to avoid this combination of parameters. .sp .sp 2. Only one bad pixel mask is allowed when stack=yes (this is a shortcoming of imcombine). If the first image in the list has an individual bad pixel mask (e.g. due to holes in the sky-subtracted image), that bad pixel mask will be used for the stacked image. This can be avoided by using newmask=yes, but the individual bad pixel masks can only be implemented in this case by multiplying the images by their individual bad pixel masks before running the task. .sp .sp 3. Weighted coadding cannot be used with the default zero level offsets, since some of those are negative. Workaround is to set prezero=yes. .ih SEE ALSO optcoaddirtf, irrotate, masklet, mkobjmask, photcomp, photcheck, shiftnadd .endhelp phat_alone/doc/fixbias.hlp100644 1332 567 454 6174726446 15077 0ustar hallast_hyee.help fixbias Jul95 phat .ih NAME fixbias -- script to implement biasfix .ih USAGE cl < fixbias.cl .ih PARAMETERS .ls none .le .ih DESCRIPTION This script displays an image, copies it, unmodified, to image//orig, does biasfix on it, and then displays the fixed version. .ih SEE ALSO biasfix .endhelp phat_alone/doc/optcoaddirtf.hlp100644 1332 567 32442 6503630455 16164 0ustar hallast_hyee.help optcoadd Jul96 phat .ih NAME optcoadd -- produce coadded image, exposure map, and sky-subtracted image .ih USAGE optcoadd comblist outimage expmap normmap shiftlist scaling zeroing weighting magfac stack logfile .ih PARAMETERS .ls comblist List of images to combine .le .ls outimage Name of output coadded image .le .ls expmap Name of output exposure map image, which gives the weighted AVERAGE exposure time for each pixel in the coadded image. .le .ls normmap Name of output normalization map image, which can be used with `sigmanorm' to create a constant-rms version of the output coadded image. .le .ls shiftlist File with image shifts. These should be INTEGERS (for best results, take the exact shifts and round them off (file `prefix.roundoff.suffix' from shiftnadd) rather than truncate them) UNLESS parameter magfac>1, in which case they should be the exact image shifts (file `prefix.shiftexact.suffix' from shiftnadd). .le .ls scaling Imcombine scaling factors (none|@file|!|etc.). If scaling=@filename and "filename" does not exist, default scalings will be calculated that correct for extinction relative to a specified airmass. These scaling factors will then be combined with additional scaling factors (that correct for nonphotometric conditions, etc.) if desired. The final scaling factors can then optionally be inserted into the image headers and multiplied into the images prior to imcombining. .le .ls zeroing Imcombine zero-level offsets (@file|none|mode|!|etc.). If zeroing=@filename and "filename" does not exist, the iterative median of all images will be found, the average found, and "filename" created and filled with zero offsets for each image calculated as "average - iterative median". Note that the offsets found this way cannot be used within imcombine with weighted coadding, as some of the offsets will be negative. Set prescale=yes to get around this problem. .le .ls weighting Imcombine weights (none|@file|!|mode|etc.). If weighting=@filename and "filename" does not exist, the iterative variances of all images will be found (after pre-scaling) and combined with the exposure times (from the header keyword given by `expname') to produce the optimum weights=exptime/variance, which will then be listed in the newly created file "filename". .le .ls magfac Magnification factor for subpixel shifting (min=1, max=10). NOTE that this parameter should be set to the appropriate value even if the block-replication has been done with `irrotate' prior to starting this task. This ensures that e.g. the zero-level offsets will be properly recalculated if need be. .le .ls stack Boolean: Combine images by stacking & projecting? .le .ls logfile Name of log file .le .sp .ls normname Header keyword for normalization factor. This should be either the exposure time or mean value of the image, if the image rms is proportional to the square root of either of those, or the variance (rms**2) of the image. If given the value "" (null string) the variance will be found and inserted into the image header with keyword VARIANCE. .le .ls newmask=no Boolean: override bad pixel masks listed in image headers? .le .ls badmask Bad pixel mask to use instead .le .ls shiftsubpix=no Boolean: Do image shifts account for subpixel shifting? .le .ls prescale=no Boolean: Scale images before, not during, imcombine? .le .ls unscale=yes Boolean: Undo scaling factors when done? .le .ls extcoeff Extinction coefficient for default scalings .le .ls airzero Airmass to scale images to? (INDEF=minimum airmass of all images in comblist) .le .ls scalecombine=no Boolean: Combine default & additional scalings? .le .ls scalecomname @filename or !keyword for additional scalings .le .ls putscale Boolean: Insert scaling factors into image headers? .le .ls wordscale="SCALEFAC" Scaling factor header keyword .le .ls defscale=no Boolean: Do scales include default airmass scaling? .le .ls prezero=no Boolean: Do zero offseting before, not during, imcombine? .le .ls unzero=yes Boolean: Undo zero offsets when done? .le .ls putzero=no Boolean: Insert zero offsets into image headers? .le .ls wordzero="ZEROVAL" Zero offset header keyword .le .ls putweight=no Boolean: Insert weights into image headers? .le .ls wordweight="WEIGHT" Weighting factor header keyword .le .ls stackimage Name of stacked image .le .ls unstack Boolean: delete stacked image when done? .le .ls scalesubpix=no Boolean: Do zero offsets account for subpixel shifting? .le .ls expname="EXPTIME" Header keyword for exposure time .le .ls maskedstat=no Boolean: Use `maskstat' with iterstat option, instead of just `iterstat', when finding default zero offsets and weights? The difference between the two is almost always insignificant, and maskstat is slower. .le .ls statfile="" File to for image statistics from iterstat or maskstat. This file will be created if it doesn't exist, to save time in later iterations of task. If it already exists, the statistics will be read in from it rather than recalculated. .le .ls stdpars=yes Boolean: Use standard imcombine parameters for coadd? These parameters are combine=average, rej=ccdclip, zeros given by `zeroing' (default = mode), scales given by `scaling' (default = none), weight given by `weighting' (default = none), expname=expname, lsig=hsig=5., nkeep=1., mclip+. NOTE that the GAIN and READNOISE parameters are still taken from imcoaddpars if stdpars=yes, as are the SIGSCALE, MASKTYPE, and MASKVAL parameters. .le .ls makeavg=no Boolean: Make pure coadd (comb=average,rej=none)? Note that otherwise the parameters are the same as when stdpars=yes. .le .ls flip=no Boolean: Flip image L-R after coadd? .le .ls cleanup=yes Boolean: Clean up blkrep'd images after use? .le .ls tpl=no Boolean: Account for throughput correction in normalization map? .le .ls optcoaddpars Parameter set for imcombine operation used in coadding. GAIN and READNOISE parameters are located here. See help page for imcombine for description. The files "phat$optcoadd8x12.par" and "phat$optcoadd2kx2k.par" contain default params for the SO 800x1200 and 2048x2048 CCDs, respectively. .le .ih DESCRIPTION IRTF version -- calls perl scripts "irtfcoadd_?.p" and "irtfshift_?.p". You will need to edit the source code and insert the proper pathnames for these scripts before running. .sp This task coadds the input images using the specified integer-pixel offsets, producing a coadded image, a sky-subtracted coadded image, an exposure map, and an *.imshifts file listing images & offsets used by the photcheck and masklet tasks. The parameters for imcombine can be specified directly in the "imcoaddpars" parameter set, or default parameters "stdpars" or "makeavg" can be used. NOTE that even in those cases, the GAIN, READNOISE, SIGSCALE, MASKTYPE, and MASKVAL parameters are still taken from imcoaddpars. .sp The following steps are performed, in this order: .sp .nf 1. Calculate default (multiplicative) scaling factors that correct for extinction relative to a specified airmass if desired, combine these scaling factors with additional scaling factors (that correct for nonphotometric conditions, etc.) if desired, insert scaling factors into image headers if desired, and multiply the images by the scaling factors before imcombine, if desired. 2. Calculate (additive) zero level offsets using iterative (and masked, if desired) means, if desired, and insert into image headers if desired. 3. Determine default weights (=exptime/variance, where the variance is the square of the iterative (and optionally masked) rms of the image) and put into file if desired, and/or insert weights into image headers if desired. 4. Block replicate images and calculate subpixel shifts if desired, adjusting zero offsets as necessary. 5. Implement (additive) zero level offsets before imcombine if desired. 6. Coadd as requested, stacking if necessary. Will not overwrite an output image. 7. Set output image airmass to average of input image airmasses if default airmass scaling was not used, otherwise set it to the specified airmass to which all images were normalized. 8. Do sky subtraction by subtracting off iterative mean. 9. Create exposure maps & coadd them into a coadded-image exposure map, if the latter doesn't already exist. 10. Divide image by the weighted exposure time at each pixel, to get constant exposure time across the image. 11. Normalize image to the maximum total exposure time that went into it. 12. Flip image left-right if desired. 13. Undo pre-imcombine zero offsets if desired. 14. Undo pre-imcombine scalings if desired. 15. Create normalization maps & coadd them into a coadded-image normalization map, if the latter doesn't already exist. 16. Create the *.imshifts file, listing images & offsets, used by tasks "photcheck" to check the photometric stability of the data and "masklet" to produce individual image object masks from the coadded-image object mask. .fi .sp The default imcombine parameters (stdpars+) usually work quite well with prezero+ and prescale+, although nkeep=-2 is preferable if images of widely varying seeing are being coadded to avoid clipping the wings of bright objects. If you do experiment with different imcombine parameters, the task `photcomp' is a useful task for quickly and easily comparing the photometric differences between two images on the same coordinate system (i.e. the same set of images coadded two different ways). .sp .sp EXPOSURE MAPS .sp An exposure map of the weighted exposure time at each pixel is generated by imcombining the individual exposure map images in the same way as the actual images, except with scale=zero=none. This is used to scale the output image from imcombine to constant global exposure time. It is suggested that if weighting is used, the weights be calculated outside of imcombine, and inserted into a file. This allows for an accurate weighted exposure map to be generated in all cases, and for the weighted exposure time to be correctly calculated if stacking is done. .sp .sp NORMALIZATION MAPS .sp A normalization map is also generated. This can be used with sigmanorm to normalize the output image to constant rms. Each input image has rms=sigma_i (including effects of throughput correction, which however vary between pixels) and weight=weight_i, so each output pixel has sigma_out given by .sp .nf sigma_out^2 = sum_i(sigma_i^2 * weight_i^2)/(sum_i(weight_i))^2 .fi .sp where sum_i denotes a sum over all i images which contribute to the pixel. The normalization map is the inverse of the right-hand-side of this equation, normalized to a maximum of one. Thus when the square root of the normalization map is multiplied by the image, all pixels have equal sigma_out (RMS noise). In the case of roughly equal weights and negligible read noise, this is essentially the same as using the exposure map to do the normalization. .sp The parameter `normname' is the header keyword which contains the parameter to use in creating the normalization map. In the example above, the parameter was the variance of each image, which is the best value to use for the normname parameter. In the case of roughly equal weights and negligible read noise, the exposure time of each image (or mean, if poisson statistics have been preserved) can be used. .sp Using the exposure time is fine for a quick estimate or first pass; if normname="" the normalization factors will be calculated and inserted into the image headers as keyword VARIANCE, if this has not already been done. Note that the variances must include any scaling done before imcombining, but NOT any throughput correction. This is because the throughput correction image is taken into account explicitly (a different tpl_i for each pixel is divided into sigma_i in the equation above) while the variance is assumed constant across the image (one value of sigma_i for each image). .sp .sp This task calls tasks addcomment, iterstat, fileroot, filecalc, and stsdas.toolbox.imgtools.imcalc. .ih EXAMPLES .ih TIME REQUIREMENTS .ih BUGS 1. There is a known bug (IRAF buglog #244) in imcombine (all versions prior to V2.11) possibly applicable to the default parameters (combine=average, reject=ccdclip, and mclip=yes) for this task: .sp When combine=average, reject=(sigclip, avsigclip, ccdclip, or pclip), and mclip=yes (the value of mclip does not matter for pclip) the average will be incorrect if the number of low pixels rejected is greater than the number of unrejected pixels. For example if 3 low pixels are rejected and only 2 pixels remain then the final average will be incorrect for that pixel. There is no workaround other than to avoid this combination of parameters. .sp .sp 2. Only one bad pixel mask is allowed when stack=yes (this is a shortcoming of imcombine). If the first image in the list has an individual bad pixel mask (e.g. due to holes in the sky-subtracted image), that bad pixel mask will be used for the stacked image. This can be avoided by using newmask=yes, but the individual bad pixel masks can only be implemented in this case by multiplying the images by their individual bad pixel masks before running the task. .sp .sp 3. Weighted coadding cannot be used with the default zero level offsets, since some of those are negative. Workaround is to set prezero=yes. .ih SEE ALSO optcoadd, irrotate, masklet, mkobjmask, photcomp, photcheck, shiftnadd .endhelp phat_alone/doc/offlist.hlp100644 1332 567 1755 6174726471 15143 0ustar hallast_hyee.help offlist Jul95 phat .ih NAME offlist -- find the offsets on the sky between two lists of objects .ih USAGE offlist list1 list2 outlist limit .ih PARAMETERS .ih list1 First list of coordinates .ih list2 Second list of coordinates .ih outlist Output file name .ih limit Maximum separation to save, in arcminutes .ih all Boolean: List all objects closer than "limit" to each object? .ih DESCRIPTION This task finds the offsets on the sky between objects in two lists. The input lists should have the format: .sp 1. RA of object .sp 2. Dec of object .sp 3. ID# of object .sp The output has nine columns: .sp 1. ID # of first object .sp 2. RA of first object .sp 3. Dec of first object .sp 4. ID # of second object .sp 5. RA of second object .sp 6. Dec of second object .sp 7. Distance between objects, in arcmin, ... .sp 8. @ (at sign) .sp 9. ...position angle (measured E from N) .ih BUGS It would be nice to implement several different output display options. .ih SEE ALSO .endhelp phat_alone/doc/offset.hlp100644 1332 567 1402 6174726473 14752 0ustar hallast_hyee.help offset Jul95 phat .ih NAME offset -- find the offset on the sky between two objects .ih USAGE offset num1 ir1 id1 num2 ir2 id2 .ih PARAMETERS .ls num1 ID number of first object .le .ls ir1 RA coordinate of first object .le .ls id1 Dec coordinate of first object .le .ls num2 ID number of second object .le .ls ir2 RA coordinate of second object .le .ls id2 Dec coordinate of second object .le .ls outfile Output file name .le .ih DESCRIPTION This task takes the ID numbers and coordinates of two objects and computes the actual offset on the sky between them, in arsec both E-W and N-S, as well as the distance between them in arcminutes. Optionally these values can be output to a file instead of STDOUT. .ih SEE ALSO offlist .endhelp phat_alone/doc/patpostproc.hlp100644 1332 567 633 6174726500 16016 0ustar hallast_hyee.help patpostproc Jul95 phat .ih NAME patpostproc -- get stats for and display a new CCD image .ih USAGE patpostproc oldlist newlist .ih PARAMETERS .ls image Image to get statistics for and to display .le .ls frame Frame in which to display image .le .ih DESCRIPTION This task is meant to be used immediately after a new image is acquired by the CCD. It displays the image and its statistics. .endhelp phat_alone/doc/shiftnadd.hlp100644 1332 567 5734 6174726530 15436 0ustar hallast_hyee.help shiftnadd Jul95 phat .ih NAME shiftnadd -- find offsets for a set of CCD images and coadd them .ih USAGE shiftnadd flatlist refimage prefix outstring fracshift coaddname expmap .ih PARAMETERS .ls flatlist List of images for which to find offsets .le .ls refimage Name of (flattened) reference image .le .ls prefix Prefix string for output files .le .ls outstring Suffix string for output files .le .ls fracshift Boolean: Create fractional-pixel-offset images? (yes|no) .le .ls coaddname Name for output coadded image .le .ls expmap Name of output exposure map image .le .ls shiftlist List of output, offset images .le .ls combdata Boolean: Combine shifts with earlier dataset? (yes|no) .le .ls expname Header keyword for exposure time .le .ls xref Reference object x coordinate (nearest integer) .le .ls yref Reference object y coordinate (nearest integer) .le .ls xshiftold Reference image x shift in earlier dataset .le .ls yshiftold Reference image y shift in earlier dataset .le .ls radius=5. Aperture photometry radius for imexamine .le .ls buffer=10. Aperture photometry sky buffer for imexamine .le .ls width=10. Aperture photometry sky annulus width for imexamine .le .ls bs=9. Centering box size for final shift calculation .le .ls doshift Boolean: Do offset measuring step? .le .ls stdpars Boolean: Use std imcombine parameters for coadd? .le .ls makeavg Boolean: Make pure coadd (comb=average,rej=none)? .le .ls addpars Parameter set: imcombine parameters .le .ih DESCRIPTION This tasks allows measurement of image offsets and coadding using those offsets. Procedure: .sp 1. Choose one image (which all images overlap) to be the reference image. .sp 2. imexam the reference image & get the coordinates (using 'r' or 'a') of ALL REFERENCE OBJECTS that are to be used. .sp 3. imexam all the images and get the coordinates (using 'r' or 'a' and 'n' to go to the next image) of ONLY THE BRIGHTEST or "BEST" reference object in each. .sp 4. You are asked for the X and Y coordinates of this "BEST" reference object. the coords file is printed to jog your memory. .sp 5. lintran is used to calculate the coarse shifts from just the "BEST" object .sp 6. The coarse shifts are used as input to imcentroid, which finds the final offsets using ALL reference objects available. The imcentroid parameters (e.g. boxsize) can be adjusted if deemed necessary. .sp Output: .sp prefix.refcoords.outstring registration objects' reference image coords .sp prefix.allcoords.outstring registration objects' coordinates in all images .sp prefix.coarse.outstring coarse shifts .sp prefix.shiftnadd.outstring final shifts, imcombine log, & misc. other info .sp prefix.shiftfrac.outstring fractional part of final shifts .sp prefix.shiftint.outstring integer part of final shifts .sp prefix.roundoff.outstring final shifts rounded off to integer shifts .sp coaddname.imh coadded image .ih SEE ALSO optcoadd .endhelp phat_alone/doc/strrev.hlp100644 1332 567 431 6174726533 14767 0ustar hallast_hyee.help strrev Jul95 phat .ih NAME strrev -- parse a string into its reverse .ih USAGE strrev forward .ih PARAMETERS .ls forward Input string .le .ls reverse Output reversed string .le .ih DESCRIPTION This task takes a string and reverses it character by character. .endhelp phat_alone/doc/swap.hlp100644 1332 567 377 6174726536 14430 0ustar hallast_hyee.help swap Jul95 phat .ih NAME swap -- swap the contents of two files .ih USAGE swap file1 file2 .ih PARAMETERS .ls file1 Name of first file .le .ls file2 Name of second file .le .ih DESCRIPTION This task swaps the contents of two files. .endhelp phat_alone/doc/undel.hlp100644 1332 567 544 6174726542 14556 0ustar hallast_hyee.help undel Jul95 phat .ih NAME undel -- unprotect and delete a file(s) in one fell swoop .ih USAGE undel file1 .ih PARAMETERS .ls file1 Name of file(s) to unprotect and delete .le .ls verify Boolean: verify deletion? .le .ih DESCRIPTION This task removes the protection from a file or files and deletes them. .ih SEE ALSO protect, delete .endhelp phat_alone/doc/imswap.hlp100644 1332 567 565 6367434206 14747 0ustar hallast_hyee.help imswap Feb97 phat .ih NAME imswap -- swap two images .ih USAGE imswap img1 img2 .ih PARAMETERS .ls img1 Name of first image .le .ls img2 Name of second image .le .ih DESCRIPTION This task swaps two images. The first image is renamed to a temporary image, the second is renamed to the first image, and then the first image is renamed to the second. .endhelp phat_alone/doc/patcopy.hlp100644 1332 567 1065 6316401251 15126 0ustar hallast_hyee.help patcopy Jul95 phat .ih NAME patcopy -- copy a list of filenames to another list .ih USAGE patcopy oldlist newlist .ih PARAMETERS .ls oldlist List of original file names ("@" is optional) .le .ls newlist List of copied file names ("@" is optional) .le .ls verb Boolean: Print names of files as they are copied? .le .ih DESCRIPTION This task copies the files listed in "oldlist" to those listed in "newlist". If the lists do not contain the same numbers of files, the task exits with an error message and no copying. .ih SEE ALSO patrename .endhelp phat_alone/doc/patrename.hlp100644 1332 567 1077 6316401266 15434 0ustar hallast_hyee.help patrename Jul95 phat .ih NAME patrename -- rename a list of filenames to another list .ih USAGE patrename oldlist newlist .ih PARAMETERS .ls oldlist List of original file names ("@" is optional) .le .ls newlist List of renamed file names ("@" is optional) .le .ls verb Boolean: Print names of files as they are renamed? .le .ih DESCRIPTION This task renames the files listed in "oldlist" to those listed in "newlist". If the lists do not contain the same numbers of files, the task exits with an error message and no renaming. .ih SEE ALSO patcopy .endhelp phat_alone/doc/iteravg.hlp100644 1332 567 3056 6352646727 15135 0ustar hallast_hyee.help iteravg Jun97 phat .ih NAME average -- compute the average and standard deviation with iterative rejection .ih USAGE average option .ih PARAMETERS .ls option Chosen from "add", "subtract" or "new_sample", in which case the numbers averaged are those in STDIN. If no argument is given on the command line, "new_sample" is assumed. .le .wp .ls maxiter Maximum number of iterations for rejection .le .ls nsigrej Number of sigma from mean beyond which to reject points .le .ih DESCRIPTION Task \fIiteravg\fR computes the average and standard deviation of a list of numbers. Numeric input is read from STDIN with one number per line. The mean, sigma and number of points are calculated, and limits of mean +/- nsigrej * sigma calculated, and the mean, sigma, and number of points recalculated until maxiter iterations have been performed or the number of points did not change during the last integration, whereupon the mean, sigma, and number of points are written to the standard output. The rest of this description is taken from the \fIaverage\fR help page and has not been tested, but probably doesn't work. By default, the sample is taken to be the set of numbers in the standard input when \fIiteravg\fR is run. Additional points can be added to or deleted from the sample by rerunning \fIiteravg\fR with \fBoption\fR equal to one of the following: .nf add -- add points to the sample, recalculate mean and sigma sub -- subtract points from the sample .fi The sample is reinitialized by setting \fBoption\fR = "new_sample". .ih SEE ALSO average, lintran, iterstat phat_alone/doc/mkrgb.hlp100644 1332 567 5333 6362724123 14562 0ustar hallast_hyee.help mkrgb Jul97 phat .ih NAME mkrgb -- make Sun rgb rasterfiles from IRAF images .ih USAGE swap red green blue neg pos rgb .ih PARAMETERS .ls red, green, blue Name of images to drive red, green, blue color guns .le .ls neg = 0 Number of sigma for minimum intensity in faint-object rasterfile .le .ls pos = 8 Number of sigma for maximum intensity in faint-object rasterfile .le .ls rgb Root name for output Sun rasterfiles .le .sp .ls magred, maggreen, magblue Maximum mag/sqarcsec for red, green, blue images in common-magnitude-scale rasterfile. .le .ls pixfact Conversion of mag/sqarcsec to mag/pixel: =2.5*log10((pixels/arcsec)**2. .le .ls gogreen = no Independent green-gun image? (As opposed to sum of red & blue images.) .le .ls orient = yes Preserve orientation of IRAF images? (Left to themselves, the rasterfiles would be flipped up-down relative to the IRAF images.) .le .ls log = no Use logarithmic intensity mapping? .le .ls logfile Logfile of rgbsun commands; null string=no logging .le .ih DESCRIPTION This task uses "rgbsun" in the "color" package to make two Sun rgb rasterfiles from 3 IRAF images (if you have only two images, add them together and use that as the green image). Images must be 2-D, all the same size, and have approximately zero mean (mean << sigma). The task requires that header keywords ITERSIG and ZEROPT be present in the images (ITERSIG can be put there by running "iterstat addheader+" or "maskstat iterstat+ addheader+"). Note that ZEROPT should be a POSITIVE number -- it has the opposite sign from that typically used in photometric solutions. .sp The first rasterfile "rgb_faint" uses ITERSIG to scale the min & max intensity so as to emphasize the faintest objects possible in each image. The second rasterfile "rgb_scale" uses ZEROPT to set the max intensity to a fixed surface brightness in units of mag/arcsec converted to mag/pixel: max_cts=10**(-0.4*(magX+pixfact-zeropt)) where magX is magred, maggreen, or magblue. This allows direct comparison of "rgb_scale" files from different fields, since they have the same color scheme. Xview can be used to display the rasterfiles and to save them as PostScript. .sp The appearance of color images varies between monitors, between printers, and between monitors and printers. The default parameters chosen here should be used as a starting point. Generally I find that using log-mapping looks ok on screen, but NOT on printers, and that the default "rgb_faint" images look good on screen AND on paper, but the "rgb_scale" images look good only on screen. .ih BUGS Conceivably the task could be changed to do mask/iterstat addh- on each image, pulling out the mean and sigma, so that zero mean is not required. .endhelp phat_alone/doc/complete.hlp100644 1332 567 16574 6367445256 15335 0ustar hallast_hyee.help complete Jul97 phat .ih NAME complete -- calculate completeness corrections for mosaiced image .ih USAGE complete image1 image2 image3 untrim1 untrim2 untrim3 mask sum color21 color31 mlim1 spacing nbins nobjs nrepeat pixscale .ih PARAMETERS .ls image1 K (1st filter) image & catalog root name .le .ls image2 r (2nd filter) image & catalog root name (optional) .le .ls image3 Other filter image & catalog root name (optional) .le .ls untrim1 K (1st filter) area as f(m_lim) image name .le .ls untrim2 r (2nd filter) area as f(m_lim) image name (optional) .le .ls untrim3 Other filter area as f(m_lim) image name (optional) .le .ls mask Mask image from which to find x,y limits .le .ls sum Root name of comparison summed image .le .ls color21=0 Typical r-K (2nd - 1st filter) galaxy color (optional) .le .ls color31=0 Typical (3rd - 1st filter) galaxy color (optional) .le .ls mlim1=0 Magnitude of faintest bin in K (1st filter) .le .ls spacing Magnitude bin spacing (should evenly divide color21,31) .le .ls nbins Number of magnitude (flux) bins to create .le .ls nobjs Number of objects to simultaneously add to images .le .ls nrepeat Number of times to add nobjs to image at each flux bin .le .ls pixscale Scale of images in arcsec/pixel .le .sp .ls disimages Display temporary cleaned and altered images? .le .ls log_file (Optional) name of verbose log file .le .ls border=5 Size in pixels of FOCAS catalog border region (min=1) .le .ls cleanfactor=1 Area to increase FOCAS isophotes for cleaning (min=1) .le .ls firstseed=1. Starting seed integer for ARTDATA object positions .le .ls psf="moffat" Type of PSF for ARTDATA (gaussian|moffat|image|textfile) .le .ih DESCRIPTION This task is designed specifically to calculate the completeness corrections and useful areas as a function of magnitude for mosaiced images with variable sky sigma. It is assumed that object detection was performed on a summed image of all filters; this can be circumvented by specifying images in only one filter. This tasks REQUIRES existing image1.cat, image2.cat, image3.cat, & sum.cat, and also REQUIRES the following header keywords in the input images: rlambda, ebv, gain, rdnoise, fwhmpix, & zeropt. The output files are comparea_image? and complete_image? where ?=1,2,3 as appropriate. The magnitudes given are for the CENTERS of the magnitude bins, and the completeness values should be DIVIDED into the observed N(m) to get the true N(m). This task CANNOT BE RUN IN BATCH MODE due to a focas.mfilter/ffilter problem. The comparea_image? output will be ERRONEOUS unless the magnitude limits input to the task bracket all limiting magnitudes which exist in the image(s). Here is a fairly accurate overview of the task. Pardon the latex formatting. We assume that completeness is a function of signal-to-noise only, ignoring its dependence on surface brightness. In each filter, we calculate the fraction $f$ of simulated objects recovered by FOCAS as a function of counts in the normalized image. We know the area $A(\Delta m)$ of the image as a function of $\Delta m$=$m_{real}$$-$$m_{norm}$, where $m_{real}$ is the real magnitude of an object and $m_{norm}$$=$z.p.$-$2.5$\times$log10(counts) is the magnitude measured on the normalized constant-RMS image. Thus we calculate the completeness by summing over the fractional area at each $\Delta m$ multiplied by the fraction $f$ of recovered simulated objects with counts on the normalized image corresponding to that real magnitude: \begin{equation} C(m_{real})=\sum_{\Delta m} {{A(\Delta m)}\over{A_{tot}}} f(m_{real} - \Delta m) {{A(\Delta m)}\over{A_{tot}}} f(m_{real} - \Delta m) \end{equation} We also accounted for galactic extinction $A_{\lambda}$ in each filter of each field so that the final completeness values $C(m_{final})$=$C(m_{real}-A_{\lambda})$ were for identical values of $m_{final}$ in each field. The exact procedure followed in adding simulated objects to the images of each field was as follows. We took the normalized images from all filters which went into the summed image. For counts values separated by a factor of 1.585 (0\fm5) down to $\sim$0\fm5 below the 3$\sigma$ limit, we used FOCAS {\sc clean} to remove from the normalized images objects with fewer total counts than this in the \ks\ filter. We summed these cleaned image(s) and ran FOCAS on the sum to create a comparison catalog. We then added unresolved objects 30 at a time to the cleaned images in each filter simultaneously using the PSF of each image, an average color of $r-K_s$=4 and $J-K_s$=1.5 for the objects, and a random magnitude offset within the magnitude bin. We summed these altered images and reran FOCAS. Simulated objects should thus be recovered unless they merged with an object brighter than themselves in \ks\ and were not split by FOCAS. (Strictly speaking, this step should be repeated for each filter, each time removing objects brighter than the simulated objects {\it in that filter}.) This procedure yields the completeness in all filters simultaneously, albeit at different magnitudes as given by the average galaxy colors used. We repeated this procedure 34 times in each counts bin, each time including different randomly generated Poisson noise appropriate to the object's counts and the image gain. We repeated the entire procedure for each field, taking into account each field's galactic extinction. Here is a fairly accurate flow chart of the task. .nf #--for each field # --get x,y limits for that field and filter # --get g.e. for each filter # --choose each filter's fluxes so m_final (= m_real-g.e.) # = e.g. 20.25, 20.75, thus in the deepest part of the image where # m_norm1=m_real1, m_norm1 = e.g. 20.25+ge1, 20.75+ge1, ... # m_norm2=m_real2, m_norm2 = e.g. 20.25+ge2, 20.75+ge2, ... # --find scalings for individual-filter images # **for each mag bin: each mag bin represents a different mag in each filter # (m1=m1, m2=m1+color21, m3=m1+color31), but should really repeat for # each filter since the crowding is different to each filter's limit # (i.e. mk .le .ls goodvalue Good pixel value in mask .le .ls lower Initial lower limit for data range .le .ls upper Initial upper limit for data range .le .ls verbose Verbose output? .le .ls iterstat Use iterstat instead of imstat for statistics calculation? .le .ls addheader Add iterstat output to image headers? .le .ls printit Print iterstat output? .le .ih DESCRIPTION maskstat takes the input image(s) and sets the bad pixels as given by the input mask(s) to a flag value which is subsequently ignored. The statistics of the remaining pixels in the image(s) are calculated normally using either imstat or iterstat. .sp If a list of images and only one mask is given, that mask is used for all images. If the masks are to be taken from the image headers, they are first output to a temporary list. Then, and in the case where lists of both images and masks are given, the numbers of each are checked to make sure they are identical, and if so, the images and masks are paired up and the statistics calculated. It would be kind of neat if only one image and a list of masks gave you the statistics of the image computed using all the different masks, but the task simply exits if that is the case. .ih EXAMPLES .ih TIME REQUIREMENTS .ih BUGS .ih SEE ALSO iterstat .endhelp phat_alone/doc/minv.hlp100644 1332 567 625 6503624114 14404 0ustar hallast_hyee.help minv Feb95 phiirs .ih NAME minv -- invert a mask of ones and zeros .ih USAGE minv infile outfile .ih PARAMETERS .ls infile Input mask image .le .ls outfile Output inverted mask image .le .ih DESCRIPTION This task takes a mask composed solely of 0's and 1's and inverts it; i.e. all the 0's are set to 1 and all the 1's to 0. .ih EXAMPLES .ih TIME REQUIREMENTS .ih BUGS .ih SEE ALSO .endhelp phat_alone/doc/mkobjmask.hlp100644 1332 567 3204 6503624115 15426 0ustar hallast_hyee.help mkobjmask Feb95 phiirs .ih NAME mkobjmask -- create object mask from coadded image and exposure map .ih USAGE mkobjmask image expname .ih PARAMETERS .ls image Name of image for making mask .le .ls expname Name of exposure map for normalization .le .ls suffix="objmask" Suffix of output object mask .le .ls prefix="norm" Prefix for temporary normalized image .le .ls nsmooth=3 Size of filter for boxcar smoothing. .le .ls subsample=1 Block averaging factor before median filtering .le .ls filtsize=15 Median filter size for local sky evaluation .le .ls ngrow=1 Width of rings to grow around masked objects .le .ls interact=yes Boolean: Interactively examine normalized image? .le .ls inv=yes Boolean: Invert mask so objects are zero? .le .ls threshold Cutoff point for replacement .ih DESCRIPTION mkobjmask calls the scripts makeobjmask, sigmanorm, and iterstat. .sp mkobjmask takes a coadded image and its corresponding exposure map and creates an object mask. First, the image is normalized to uniform pixel-to-pixel rms using the square root of the exposure map. The recommended threshold for identifying objects is (4.5/boxcar_smoothing_size) * rms of unsmoothed image. This threshold is applied to a boxcar smoothed version of the image, using the task makeobjmask, to produce the output object mask image. .sp The default parameters are for original-scale images. For images block replicated by a factor of two, I typically use nsmooth=5, subsample=2, filtsize=15, and ngrow=2 (or larger). .ih EXAMPLES .ih TIME REQUIREMENTS .ih BUGS .ih SEE ALSO makeobjmask, sigmanorm, iterstat .endhelp phat_alone/doc/photcheck.hlp100644 1332 567 6544 6503624115 15432 0ustar hallast_hyee.help photcheck Mar96 phiirs .ih NAME photcheck -- monitor photometric stability of a data set .ih USAGE photcheck image expmap starcoords output .ih PARAMETERS .ls image Mosaic image .le .ls expmap Exposure map image .le .ls starcoords File for reference star coordinates .le .ls output File for formatted output photometry .le .sp .ls imageshifts="" `imshifts' file (default = image//.imshifts) .le .ls interact=yes Boolean: Identify reference stars interactively? .le .ls dephot=yes Boolean: Use default values for critical PHOT params? .le .ls badcheck=yes Boolean: Check for bad pixels and return INDEF values? .le .ls verbose=yes Boolean: Verbose output? .le .ls cleanup=yes Boolean: Erase individual photometry files when done? .le .ls expname PHOT: exposure time header keyword (default="EXPTIME") .le .ls gain PHOT: gain of array (in electrons/ADU) .le .ls rn PHOT: readnoise of array (in electrons) .le .ls ann PHOT: inner radius of sky annulus .le .ls width PHOT: width of sky annulus .le .ls ap PHOT: radius of photometry aperture .le .ls zp=0. PHOT: zeropoint. Leaving this set to zero is usually fine, but if you have extremely bright (but still unsaturated) sources in the field you should set to set it to 10.0 or so, to avoid AWK formatting errors. .le .ih DESCRIPTION The user first identifies several suitable objects in a mosaiced image, using imexam if interact=yes, and/or using or appending to the file given by the `starcoords' parameter if that file already exists. These objects should be located on a portion of the mosaic with nearly maximum exposure time, so that they will appear in most or all of the individual input frames. .sp Photcheck then takes the list of star positions, transforms them back to the coordinate systems of the individual sky subtracted images which were summed to make the mosaic (the images are listed in the imshifts file, which is displayed for editing to ensure the correct images are listed), and uses digiphot.apphot.phot to compute accurate positions and measure magnitudes for the reference objects in each sky subtracted input frame. The critical parameters for phot are taken from the parameters listed in photcheck if dephot=yes; otherwise they are taken from phot directly. .sp If the user sets badcheck=yes, then each image's bad pixel mask is consulted, and if any bad pixels are within the photometric aperture, phot will return an INDEF value for the magnitude. Finally, the output files from phot are compiled using awk into a format suitable for input to "photscale", which allows interactive calculation of photometric scalings for the data set. If cleanup=no, then the output phot files (imagename//".mag.X") are not erased. .sp The default output uses the mosaic image as the reference photometric image. If another image is desired as a reference, that can be done in `photscale'. .sp The task requires the `photcheck.awk' awk script to reside in the phiirs directory, and exits with an error if this is not the case. .ih EXAMPLES .ih TIME REQUIREMENTS .ih BUGS Image names as listed in the imshifts file can be no more than 21 characters long; this is a limitation imposed by the output format of `txdump'. The task will stop with a warning if image names are too long. .ih SEE ALSO photscale .endhelp phat_alone/doc/photcomp.hlp100644 1332 567 3211 6503624115 15277 0ustar hallast_hyee.help photcomp Apr96 phiirs .ih NAME photcomp -- compare photometric properties of two images on same coord system .ih USAGE photcomp refimage compimage suffix .ih PARAMETERS .le .ls refimage Name of reference image .le .ls compimage Name of comparison image .le .ls suffix Suffix string for output files .le .sp .ls reflog="" Reference image imexam log to use (default=create new one) .le .ls center=yes Imexamine: center object in aperture? .le .ls background=yes Imexamine: fit and subtract background? .le .ls radius=5. Imexamine aperture photometry radius .le .ls buffer=10. Imexamine sky buffer .le .ls width=10. Imexamine sky annulus width .le .ls another Boolean: Do another comparison image? .le .ih DESCRIPTION This task calls the following other tasks: filecalc, fileroot. .sp This task allows you to do photometry on objects in two or more images on the same coordinate system. The positions and fluxes measured from the reference image or taken from the specified previously created reference image imexam log file, are used to do photometry on the comparison image and to compare the fluxes from both images. The individual percentage differences are plotted, the average percentage difference calculated and appended to the output "pcomp" file, the file is displayed for editing in case outliers should be removed, and then the average percentage difference is recalculated and displayed. .sp .sp The following files are created: .sp refimage//.pcomp//suffix output photometry for all image pairs .sp refimage//.plog//suffix imexam log for refimage .ih EXAMPLES .ih TIME REQUIREMENTS .ih BUGS .ih SEE ALSO ircoadd .endhelp phat_alone/doc/photscale.hlp100644 1332 567 7721 6503624116 15443 0ustar hallast_hyee.help photscale Mar96 phiirs .ih NAME photscale -- calculate photometric scalings of a data set .ih USAGE photscale photfile output .ih PARAMETERS .ls photfile Photometry data file from photcheck .le .ls output Root name for output file(s). If this file already exists, the magnitude differences in it will be plotted in the standard photscale format, but no changes can be made to it. .le .sp .ls apcor=no Use aperture corrections? Such corrections must have been previously calculated with e.g. photcal.mkapfile. .le .ls apfile File of aperture corrections (coadded image first), one value per image listed in column 1, no extraneous lines or columns please. .le .ls display=yes Boolean: Automatically display lightcurve (requires STSDAS)? .le .ls results=no Boolean: Output computed scales and weights? .le .ls newref=no Boolean: Select new reference image? .le .ls refimagenum Number of new reference image .le .ls replace=no Boolean: Replace a point with average of others? .le .ls newpoint Image number of point to replace .le .ls avgpoints Points to average for replacement (enter as `1,2') .le .ls reenter Re-enter points (enter as `1,2') .le .ls normal=no Boolean: Normalize scales to a certain image? .le .ls normimagenum Number of normalization image .le .ih DESCRIPTION This task takes the formatted output photometry from photcheck, determines the magnitude differences and scalings of all images relative to the reference image listed on the first line of the photcheck output file, and displays the magnitude differences graphically. The graphics cursor is activated in case a printout is desired; once the cursor has been deactivated by hitting any key, three optional steps can be performed: .sp .nf 1. Specify a new reference image 2. Replace a point with the average of two other points 3. Normalize magnitude differences and scales to those of a given image .fi .sp If any step is performed, the new magnitude differences are displayed, and the graphics cursor reactivated. These options should really be performed only in the listed order; i.e. you should decide on the reference image before replacing points, and normalize the magnitude differences and scales only as the last step. If none of the three steps is desired, the task ends and outputs: .sp .nf -- output//".photscales" main output file -- (results=yes) output//".scales" list of imcombine input scales -- (results=yes) output//".weights" list of imcombine input weights -- (newref=yes) output//".photfile" copy of input file w/new ref. image -- (normal=yes) output//".photold" pre-norm. scales & mag differences .fi .sp The main output file lists image name, airmass, magnitude difference and error, photometric scaling and error, number of stars used, and individual star magnitude differences. .sp The task requires the `photscale.awk' awk script to reside in the phiirs directory, and exits with an error if this is not the case. .sp NEW REFERENCE IMAGE .sp If this step is performed, the magnitude differences and photometric scalings are recalculated relative to the photometry for the specified image. .sp POINT REPLACEMENT .sp If this step is performed, the specified point's delta_m and scale values are replaced with the average values of two other specified points. The errors of the two points' values are added in quadrature to determine the errors of the new values for the replaced point. .sp NORMALIZATION .sp If this step is performed, the magnitude differences and photometric scalings are normalized such that the specified image has delta_m=0 and scale=1, i.e.: .sp .nf delta_m_new = delta_m_old - delta_m_normimage scale_new = scale_old / scale_normimage scale_err_new = scale_err_old / scale_normimage .fi .sp The errors in the value of delta_m_normimage and scale_normimage are not factored in to the new values because the magnitude differences and scalings are all relative. .ih EXAMPLES .ih TIME REQUIREMENTS .ih BUGS .ih SEE ALSO photcheck .endhelp phat_alone/doc/sctv.hlp100644 1332 567 1477 6503624116 14442 0ustar hallast_hyee.help sctv Feb95 phiirs .ih NAME sctv -- display image with display scaled to full range of image values .ih USAGE sctv image frame .ih PARAMETERS .ls image Input mask image to be displayed .le .ls frame Frame buffer for image display .le .ls fill Boolean: "Scale image to fit display window? .le .ls xcenter Display window horizontal center .le .ls ycenter Display window vertical center .le .ls xsize Display window horizontal size .le .ls ysize Display window horizontal size .le .ls xmag Display window horizontal magnification .le .ls ymag Display window horizontal magnification .ih DESCRIPTION This task displays an image with the display range forced to the minimum and maximum values in the image. .ih EXAMPLES .ih TIME REQUIREMENTS .ih BUGS .ih SEE ALSO .endhelp phat_alone/doc/sigmanorm.hlp100644 1332 567 1265 6503624117 15453 0ustar hallast_hyee.help sigmanorm Feb95 phiirs .ih NAME sigmanorm -- normalize image by the square root of its exposure map .ih USAGE sigmanorm image .ih PARAMETERS .ls image Name of image to renormalize .le .ls normimage="" Normalization image (exposure map) -- assumed to be exp//image if left as null .le .ls prefix="norm" Prefix for renormalized image .le .ih DESCRIPTION sigmanorm takes the exposure map for the input image, normalizes it to unit exposure time, takes its square root, and multiplies it into the input image to produce an image which should have uniform rms pixel-to-pixel noise across the entire exposed area. .ih EXAMPLES .ih TIME REQUIREMENTS .ih BUGS .ih SEE ALSO .endhelp phat_alone/doc/trim.hlp100644 1332 567 11741 6503624117 14452 0ustar hallast_hyee.help trim Feb95 phiirs .ih NAME trim -- create constant-rms image with a certain minimum exposure time .ih USAGE trim image mask stats .ih PARAMETERS .ls image Image (or image list) to trim .le .ls mask Exposure map or list (default=image//em) .le .ls stats File to contain trimmed image RMS values .le .sp .ls out="trim" Prefix for trimmed images .le .ls mingoodexp=0.36 Minimum acceptable exptime (fraction of maximum) .le .ih DESCRIPTION trim allows you to trim an image so that only areas with a certain minimum exposure time are included in the output image. The default minimum exposure time is 0.36 of the maximum, which corresponds to a limiting magnitude 0.55 mags (=2.5*log10(sqrt(0.36))) shallower than the deeper part of the image. Similarly, 0.83 corresponds to 0.1 mag, and 0.91 to 0.05 mag. These shallower areas (typically around the edges of the mosaic) are perfectly good, just complicated to calibrate. The output image also includes a 5-pixel-wide border around the minimum exposure time area so that FOCAS will not toss out images lying within the minimum exptime area. .sp Along with the output image, a companion exposure map is created, as well as a mask image which blocks out all areas with less than the minimum exposure time. The RMS of the image(s) is calculated using maskstat with this mask and output to the specified file. .sp The output image is normalized by its exposure map so that the RMS is constant across the image. Thus the image can be directly input to object detection programs such as FOCAS. The detection significance of objects is constant across the output image (ie a 3sig detection is correct regardless of location on the image) **BUT THE MAGNITUDE SCALE IS NOT CONSTANT!** (The edges of the image have been divided by some factor <~2 to bring the RMS down, so the magnitudes of objects near the edges will be erroneously faint.) .sp If you set mingoodexp >= 0.83, the edge magnitudes will be accurate to <=10%. But if mingoodexp = 0.36 (the default and minimum recommended), you should do the following to correct the magnitudes of objects detected in the trimmed image. (With mingoodexp=0.36, the shallowest 3-sigma limiting magnitude in the resulting image will be equal to the deepest 5-sigma limiting magnitude, approximately. This allows you to uniformly detect objects down to the deepest 5-sigma limiting magnitude if you require only a 3-sigma detection.) .sp First, produce a list of the objects' INTEGER x,y coordinates and their total COUNTS. (If necessary, convert from magnitudes back to counts.) For example, in FOCAS: .sp .nf filter H < outimage.cat > outimage.cat catlist x y Ltotal < outimage.cat >> untrim.image .fi .sp Then run the following IRAF script (available as untrim.cl). It's slow, but it works; hopefully someday "imedit" will be able to do the job faster. It requires insertion of the photometric zeropoint and a value for the counts corresponding to whatever limit you're interested in (ie. 1 sigma/arcsec limit, or, more likely, the counts corresponding to an object at the 3sigma limiting magnitude in the deepest part of the image. The optional steps can be used to limit the effects of bad pixels on the exposure map in the central region of the image. Bad pixels are really a separate effect but were incorporated with the exposure map anyway since they do increase the RMS noise; however, they don't affect the true exposure time for that pixel. Thus for accuracy in this step one should add to the exposure map the sigma in the central exposure time produced by the bad pixels. .sp .nf imar outimage * (insert_desired_limit_counts_here) untrim.imagetmp.imh list="untrim.image" while (fscan (list, i, j, z) !=EOF) { imdel ("tmp.imh", ver-, >& "dev$null") imar("outmaskmask["//i//":"//i//","//j//":"//j//"]", "*", z, "tmp.imh") imcopy ("tmp.imh", "untrim.imagetmp.imh["//i//":"//i//","//j//":"//j//"]") imdel ("tmp.imh", ver-, >& "dev$null") } imcopy outmask outmasktmp #optional imar outmasktmp + 0.03 outmasktmp #optional imreplace outmasktmp 1. lower=1. upper=INDEF imcalc untrim.imagetmp.imh,outmasktmp untrim.image.imh "(insert_zeropoint_here)-2.5*log10(im1/(sqrt(im2)))" imdel outmasktmp ver- imdel untrim.imagetmp.imh ver- list="untrim.image" while (fscan (list, i, j, z) !=EOF) { imstat("untrim.image.imh["//i//":"//i//","//j//":"//j//"]", fields="mean", format-, >> "untrim.image.truemags") } .fi .sp The file "untrim.image.truemags" contains the corrected magnitudes of each object. The image "untrim.image.imh" can be used to compute the area surveyed as a function of magnitude; directly so if the 3sigma limiting object magnitude was used as the limiting counts value in the "untrim.cl" script. .sp .sp Output: .sp out//img trimmed image .sp out//mask NORMALIZED exposure map for trimmed image .sp out//mask//"mask" exposed/unexposed area mask for trimmed image .sp stats file of trimmed image RMS values (from maskstat) .ih EXAMPLES .ih TIME REQUIREMENTS .ih BUGS .ih SEE ALSO addring, fileroot, maskstat, sigmanorm, untrim .endhelp phat_alone/phat.cl100644 1332 567 4460 6503631644 13464 0ustar hallast_hyee# Package script task for PHAT: Pat Hall's Add-on Tasks ##these next bits are for if there was spp code ## load necessary packages #images #tv #ctio # #cl < "phat$lib/zzsetenv.def" #package phat, bin = phatbin$ set phat = /d/baobab/hall/iraf/phat_alone/ #set phat = /u2/phall/CL/phat_alone/ package phat set helpdb = phat$helpdb.mip # CL scripts # $ means task has no parameters # no $ means task has parameters task addcomment = "phat$src/addcomment.cl" task addpars = "phat$src/addpars.par" task addring = "phat$src/addring.cl" task biasfix = "phat$src/biasfix.cl" task bindata = "phat$src/bindata.cl" task bscount = "phat$src/bscount.cl" task btc_gainflip = "phat$src/btc_gainflip.cl" task checkfringe = "phat$src/checkfringe.cl" task complete = "phat$src/complete.cl" task cubeexam = "phat$src/cubeexam.cl" task cut = "phat$src/cut.cl" task defringe = "phat$src/defringe.cl" task destripe = "phat$src/destripe.cl" task fileroot = "phat$src/fileroot.cl" task $fixbias = "phat$src/fixbias.cl" task focasflat = "phat$src/focasflat.cl" task imswap = "phat$src/imswap.cl" task irrotate = "phat$src/irrotate.cl" task irshift2 = "phat$src/irshift2.cl" task iteravg = "phat$src/iteravg.cl" task iterstat = "phat$src/iterstat.cl" task makeobjmask = "phat$src/makeobjmask.cl" task maskstat = "phat$src/maskstat.cl" task minv = "phat$src/minv.cl" task mkobjmask = "phat$src/mkobjmask.cl" task mkrgb = "phat$src/mkrgb.cl" task offlist = "phat$src/offlist.cl" task offset = "phat$src/offset.cl" task optcoadd = "phat$src/optcoadd.cl" task optcoaddirtf = "phat$src/optcoaddirtf.cl" task optcoaddpars = "phat$src/optcoaddpars.par" task patcopy = "phat$src/patcopy.cl" task patrename = "phat$src/patrename.cl" task patpostproc = "phat$src/patpostproc.cl" task photcheck = "phat$src/photcheck.cl" task photcomp = "phat$src/photcomp.cl" task photscale = "phat$src/photscale.cl" task quickfringe = "phat$src/quickfringe.cl" task sctv = "phat$src/sctv.cl" task shiftnadd = "phat$src/shiftnadd.cl" task strrev = "phat$src/strrev.cl" task sigmanorm = "phat$src/sigmanorm.cl" task swap = "phat$src/swap.cl" task trim = "phat$src/trim.cl" task undel = "phat$src/undel.cl" # SPP tasks #task igraph = "phat$src/x_phat.e" clbye() phat_alone/root.hd100644 1332 567 351 6306670750 13465 0ustar hallast_hyee# Root help directory for PHAT: Pat Hall's Add-on Tasks. This dummy package is # needed to have `phat' appear as a module in some package, so that # the user can type "help phat" (with `phat' given as a task). _phat pkg = _phat.hd phat_alone/_phat.hd100644 1332 567 207 6306670677 13605 0ustar hallast_hyee# Help definitions for PHAT: Pat Hall's Add-on Tasks phat men = phat.men, hlp = .., sys = phat.hlp, pkg = phat.hd, src = phat.cl phat_alone/optcoaddirtf.par100644 1332 567 3015 6426265447 15401 0ustar hallast_hyeei_sigma,s,h,"",,,"IMCOMBINE: Sigma image (optional)" i_plfile,s,h,"",,,"IMCOMBINE: Rejected pixel list image (optional)" i_combine,s,h,"average",average|median,,"IMCOMBINE: Type of combine operation (median|average)" i_reject,s,h,"sigclip",none|minmax|ccdclip|crreject|sigclip|avsigclip|pclip,,"IMCOMBINE: Type of rejection" i_masktyp,s,h,"badvalue",none|goodvalue|badvalue|goodbits|badbits,,"IMCOMBINE: Mask type" i_maskval,r,h,0.,,,"IMCOMBINE: Mask value" i_blank,r,h,0.,,,"IMCOMBINE: Value if there are no pixels" i_statsec,s,h,"",,,"IMCOMBINE: Image section for computing statistics" i_expname,s,h,"exptime",,,"IMCOMBINE: Image header exposure time keyword" i_lthresh,r,h,INDEF,,,"IMCOMBINE: Lower threshold" i_hthresh,r,h,INDEF,,,"IMCOMBINE: Upper threshold" i_nlow,r,h,1.,0.,,"IMCOMBINE: minmax: Number of low pixels to reject" i_nhigh,r,h,1.,0.,,"IMCOMBINE: minmax: Number of high pixels to reject" i_nkeep,r,h,-2.,,,"IMCOMBINE: Minimum to keep (+) or maximum to reject(-)" i_lsigma,r,h,5.,0.,,"IMCOMBINE: Lower sigma clipping factor" i_hsigma,r,h,5.,0.,,"IMCOMBINE: Upper sigma clipping factor" i_rdnoise,s,h,"rn",,,"IMCOMBINE: ccdclip: CCD readout noise (electrons)" i_gain,s,h,"gain",,,"IMCOMBINE: ccdclip: CCD gain (electrons/ADU)" i_snoise,s,h,"0.",,,"IMCOMBINE: ccdclip: Sensitivity noise (fraction)" i_sigscale,r,h,0.1,0.,,"IMCOMBINE: Tolerance for sig-clip scaling corrections" i_pclip,r,h,-0.5,,,"IMCOMBINE: pclip: Percentile clipping parameter" i_grow,r,h,0.,,,"IMCOMBINE: Radius (pixels) for 1D neighbor rejection" mode,s,h,"q",,, phat_alone/optcoadd2kx2k.par100644 1332 567 3014 6353543452 15367 0ustar hallast_hyeei_sigma,s,h,"",,,"IMCOMBINE: Sigma image (optional)" i_plfile,s,h,"",,,"IMCOMBINE: Rejected pixel list image (optional)" i_combine,s,h,"average",average|median,,"IMCOMBINE: Type of combine operation (median|average)" i_reject,s,h,"sigclip",none|minmax|ccdclip|crreject|sigclip|avsigclip|pclip,,"IMCOMBINE: Type of rejection" i_masktyp,s,h,"badvalue",none|goodvalue|badvalue|goodbits|badbits,,"IMCOMBINE: Mask type" i_maskval,r,h,0.,,,"IMCOMBINE: Mask value" i_blank,r,h,0.,,,"IMCOMBINE: Value if there are no pixels" i_statsec,s,h,"",,,"IMCOMBINE: Image section for computing statistics" i_expname,s,h,"exptime",,,"IMCOMBINE: Image header exposure time keyword" i_lthresh,r,h,INDEF,,,"IMCOMBINE: Lower threshold" i_hthresh,r,h,INDEF,,,"IMCOMBINE: Upper threshold" i_nlow,r,h,1.,0.,,"IMCOMBINE: minmax: Number of low pixels to reject" i_nhigh,r,h,1.,0.,,"IMCOMBINE: minmax: Number of high pixels to reject" i_nkeep,r,h,1.,,,"IMCOMBINE: Minimum to keep (+) or maximum to reject(-)" i_lsigma,r,h,5.,0.,,"IMCOMBINE: Lower sigma clipping factor" i_hsigma,r,h,5.,0.,,"IMCOMBINE: Upper sigma clipping factor" i_rdnoise,s,h,"11.",,,"IMCOMBINE: ccdclip: CCD readout noise (electrons)" i_gain,s,h,"1.8",,,"IMCOMBINE: ccdclip: CCD gain (electrons/ADU)" i_snoise,s,h,"0.",,,"IMCOMBINE: ccdclip: Sensitivity noise (fraction)" i_sigscale,r,h,0.1,0.,,"IMCOMBINE: Tolerance for sig-clip scaling corrections" i_pclip,r,h,-0.5,,,"IMCOMBINE: pclip: Percentile clipping parameter" i_grow,r,h,0.,,,"IMCOMBINE: Radius (pixels) for 1D neighbor rejection" mode,s,h,"q",,, phat_alone/optcoadd8x12.par100644 1332 567 3014 6353543461 15130 0ustar hallast_hyeei_sigma,s,h,"",,,"IMCOMBINE: Sigma image (optional)" i_plfile,s,h,"",,,"IMCOMBINE: Rejected pixel list image (optional)" i_combine,s,h,"average",average|median,,"IMCOMBINE: Type of combine operation (median|average)" i_reject,s,h,"ccdclip",none|minmax|ccdclip|crreject|sigclip|avsigclip|pclip,,"IMCOMBINE: Type of rejection" i_masktyp,s,h,"badvalue",none|goodvalue|badvalue|goodbits|badbits,,"IMCOMBINE: Mask type" i_maskval,r,h,0.,,,"IMCOMBINE: Mask value" i_blank,r,h,0.,,,"IMCOMBINE: Value if there are no pixels" i_statsec,s,h,"",,,"IMCOMBINE: Image section for computing statistics" i_expname,s,h,"exptime",,,"IMCOMBINE: Image header exposure time keyword" i_lthresh,r,h,INDEF,,,"IMCOMBINE: Lower threshold" i_hthresh,r,h,INDEF,,,"IMCOMBINE: Upper threshold" i_nlow,r,h,1.,0.,,"IMCOMBINE: minmax: Number of low pixels to reject" i_nhigh,r,h,1.,0.,,"IMCOMBINE: minmax: Number of high pixels to reject" i_nkeep,r,h,1.,,,"IMCOMBINE: Minimum to keep (+) or maximum to reject(-)" i_lsigma,r,h,5.,0.,,"IMCOMBINE: Lower sigma clipping factor" i_hsigma,r,h,5.,0.,,"IMCOMBINE: Upper sigma clipping factor" i_rdnoise,s,h,"7.7",,,"IMCOMBINE: ccdclip: CCD readout noise (electrons)" i_gain,s,h,"2.2",,,"IMCOMBINE: ccdclip: CCD gain (electrons/ADU)" i_snoise,s,h,"0.",,,"IMCOMBINE: ccdclip: Sensitivity noise (fraction)" i_sigscale,r,h,0.1,0.,,"IMCOMBINE: Tolerance for sig-clip scaling corrections" i_pclip,r,h,-0.5,,,"IMCOMBINE: pclip: Percentile clipping parameter" i_grow,r,h,0.,,,"IMCOMBINE: Radius (pixels) for 1D neighbor rejection" mode,s,h,"q",,, phat_alone/phat.hd100644 1332 567 4340 6503630005 13444 0ustar hallast_hyee# Help directory for PHAT: Pat Hall's Add-on Tasks $defdir = "phat$src/" $doc = "phat$doc/" addcomment hlp = doc$addcomment.hlp, src=addcomment.cl addring hlp = doc$addring.hlp, src=addring.cl biasfix hlp = doc$biasfix.hlp, src=biasfix.cl bindata hlp = doc$bindata.hlp, src=bindata.cl bscount hlp = doc$bscount.hlp, src=bscount.cl btc_gainflip hlp = doc$btc_gainflip.hlp, src=btc_gainflip.cl checkfringe hlp = doc$checkfringe.hlp, src=checkfringe.cl complete hlp = doc$complete.hlp, src=complete.cl cubeexam hlp = doc$cubeexam.hlp, src=cubeexam.cl cut hlp = doc$cut.hlp, src=cut.cl defringe hlp = doc$defringe.hlp, src=defringe.cl destripe hlp = doc$destripe.hlp, src=destripe.cl fileroot hlp = doc$fileroot.hlp, src=fileroot.cl fixbias hlp = doc$fixbias.hlp, src=fixbias.cl focasflat hlp = doc$focasflat.hlp, src=focasflat.cl imswap hlp = doc$imswap.hlp, src=imswap.cl irrotate hlp = doc$irrotate.hlp, src = irrotate.cl irshift2 hlp = doc$irshift2.hlp, src = irshift2.cl iteravg hlp = doc$iteravg.hlp, src=iteravg.cl iterstat hlp = doc$iterstat.hlp, src=iterstat.cl makeobjmask hlp = doc$makeobjmask.hlp, src = makeobjmask.cl maskstat hlp = doc$maskstat.hlp, src = maskstat.cl minv hlp = doc$minv.hlp, src = minv.cl mkobjmask hlp = doc$mkobjmask.hlp, src = mkobjmask.cl mkrgb hlp = doc$mkrgb.hlp, src = mkrgb.cl offlist hlp = doc$offlist.hlp, src=offlist.cl offset hlp = doc$offset.hlp, src=offset.cl optcoadd hlp = doc$optcoadd.hlp, src=optcoadd.cl optcoaddirtf hlp = doc$optcoaddirtf.hlp, src=optcoaddirtf.cl patcopy hlp = doc$patcopy.hlp, src=patcopy.cl patpostproc hlp = doc$patpostproc.hlp, src=patpostproc.cl patrename hlp = doc$patrename.hlp, src=patrename.cl photcheck hlp = doc$photcheck.hlp, src = photcheck.cl photcomp hlp = doc$photcomp.hlp, src=photcomp.cl photscale hlp = doc$photscale.hlp, src = photscale.cl quickfringe hlp = doc$quickfringe.hlp, src = quickfringe.cl sctv hlp = doc$sctv.hlp, src=sctv.cl shiftnadd hlp = doc$shiftnadd.hlp, src=shiftnadd.cl sigmanorm hlp = doc$sigmanorm.hlp, src = sigmanorm.cl strrev hlp = doc$strrev.hlp, src=strrev.cl swap hlp = doc$swap.hlp, src=swap.cl trim hlp = doc$trim.hlp, src = trim.cl undel hlp = doc$undel.hlp, src=undel.cl #task hlp=doc$task.hlp, src=task.cl phat_alone/phat.hlp100644 1332 567 26140 6503630035 13661 0ustar hallast_hyee.help phat Apr95 phat .ih NAME phat -- Pat Hall's Add-on Tasks .ih DESCRIPTION .nf addcomment - add comment flag to image header addring - add rings around all objects in a mask image biasfix - fix discontinuities in the bias level bindata - bin data and plot histograms of it bscount - estimate Bahcall & Soneira star counts for given (l,b) btc_gainflip - for BTC data: flip data so NE=UL, and mult by gain so gain=1 checkfringe - interactively adjust defringing complete - calculate completeness corrections for mosaiced image cubeexam - apply imexam to one band of a 3-D image cube cut - cut a distribution on specified limits defringe - do sky illumination correction & defringe images fileroot - parse a filename into root and extension fixbias - script for biasfix focasflat - remove sky gradients from images using FOCAS sky determination imswap - swap two images irrotate - rotate and resample images and recalculate shifts for them irshift2 - measure scale and rotation between two images' coord systems iteravg - find iterative average and sigma of a list of numbers iterstat - find image statistics excluding deviant pixels makeobjmask - create object masks for input images maskstat - calculate images statistics from unmasked regions of an image minv - invert a mask of zeros and ones mkobjmask - interactively create object mask mkrgb - create color image from IRAF images patcopy - copy one list of files to another list of files patrename - rename one list of files to another list of files offlist - find offsets on sky between lists of objects offset - find the offset on the sky between a pair of objects optcoadd - coadd a list of offset CCD images optcoaddirtf - coadd a list of offset CCD images (IRTF version, w/o STSDAS,CTIO) patpostproc - display new image & its statistics photcheck - monitor photometric stability of a data set photcomp - compare photometric properties of 2 images on same coord sys. photscale - compute photometric scalings of a data set quickfringe - interactively adjust defringing sctv - display image with display scaled to full range of values shiftnadd - find offsets for a set of CCD images and coadd them sigmanorm - normalize image by the square root of its exposure map strrev - parse a string into its reverse swap - swap the contents of two files trim - create constant-rms image with a certain minimum exposure time undel - unprotect and delete a file in one fell swoop .fi .sp .nf Here is a very rudimentary guide to the tasks in the PHAT (and/or PHIIRS) package which relate to CCD imaging reductions. For the rest, see the individual help files. IMAGES TO OBTAIN EACH NIGHT, OR AT LEAST EACH RUN Rule of thumb: 100,000e- total in each pixel, so that sqrt-N is <0.5%) BIAS: 30 frames DARK: at least 1 at each program exposure time; preferably 10 DOMEFLAT: 100,000e-/pix total, w/individ. exposures at same level as sky i.e. w/gain=2.2 and sky~3000 adu, 6600e-/pix/flat means 15 flats. (Or is it better to get 10,000e-/adu in each shot?) TWILIGHT FLAT: 50,000e-/pix total, w/individ. exposures at same level as sky ie w/gain=2.2 and sky~3000 adu, 6600e-/pix/flat means 8 flats. TURN TRACKING ON (make sure no bright star) and offset scope 30" in random direction between frames so that stars can be removed later. OK to combine twilight flats from more than one night on the same run. CCD DATA REDUCTION NOTES 1. setinstrument direct instrument=ccddb$kpno/direct.dat Input nonstandard biassec/trimsec params now if desired. If you transpose images to put NE more or less at top left from the start, be sure to edit the various *SEC params in the image headers! 2. ccdlist a*.imh Check to see that objects are objects, etc. Also insert filter header keywords as needed. 3. biasfix @fixlist (After inspecting to see if any images need fixing, that is.) If bias level jump is <~10 ADU, and sky is 2000+ ADU, then <0.5% effect. 4. MKBIAS: zerocombine a*.imh output=zero.imh ccdtype=zero 5. BIASSUB: ccdproc a*.imh ccdtype="" overscan+ trim+ zerocor+ zero=zero.imh flatcor- ":order 2 + f" seems the best fit to overscan region 6. MKDARK: darkcombine @list.dark1 output=dark1.imh scale=exposure rej=minmax nlo=0 nhi=1: darks of different exptimes should be combined separately. 7. DARKSUB (optional): ccdproc @list1 darkcor+ dark=dark1.imh make sure that the dark's integration time is matched to the images FLATFIELDING NOTES: --Ideal is blank sky (BLANK SKY FLAT). Usually there is not enough signal in such an image to flatfield without introducing additional noise. But if enough BLANK SKY FLATS (i.e. sparse object frames) can be coaveraged, ok; if there are not enough, they should be combined AND smoothed. --DOME FLATS would also be ideal if the dome illumination was truly uniform. But usually dome flats leave a large-scale residual illumination pattern on flatfielded images, necessitating an ILLUMINATION CORRECTION created from (in order of preference) BLANK SKY FLATS, TWILIGHT SKY FLATS, or the DOME FLATS themselves. You might want to do two illumination corrections, one using twilight flats and another with blank sky flats, if for example the blank sky flats have too little S/N and must be smoothed but there are small-scale features in the flattened images that can be removed with the (unsmoothed) twilight flats. --ILLUMCOR is most logically done by correcting just the flat field, using BLANK SKY or TWILIGHT SKY FLATS (MKSKYFLAT) or DOME FLATS (MKILLUMFLAT). --In practice, ILLUMCOR is most easily done as a separate step, using either flatfielded BLANK SKY FLATS (possibly smoothed with MKSKYCOR), TWILIGHT SKY FLATS (no special processing needed) or DOME FLATS (MKILLUMCOR). Thus, DO FLATCOR WITH DOMEFLATS AND ILLUMCOR WITH (TWIFLATS+)SKYFLATS. 8. MKFLAT: flatcombine a*.imh rej=crreject gain=gain scale=mode rdnoise=rdnoise For some reason you must make sure "zero" in ccdproc" is set correctly; can set this on the command line of course. Beware flats in same filter w/dift exptimes, & dome- vs. twilight- flats. (Flat/Dome)YYMMDD.*.imh are twilight/dome flats. Sky*.imh are blank sky flats. 9. FLATTEN: ccdproc a*.imh ccdtype="" flatcor+ flat=Flat* (fixpix+) Be careful since each night might have identically named Flat*imh. If you want to interpolate bad pixels with fixpix+, now is the time. 10. ILLUMCOR: USUALLY DONE USING #11: DEFRINGE.CL --Check the exposure in a given filter, skyflat or object, with the most sky counts, and see if it has structure. --If so, decide whether to use BLANK or TWILIGHT SKY FLATS to make the ILLUMINATION CORRECTION (or possibly DOMEFLATS). 10a. Defringing needed, BLANK SKY FLATS used for ILLUMINATION CORRECTION: Use the task DEFRINGE (see #11 below). 10b. Defringing needed, TWILIGHT SKY FLATS used for ILLUMINATION CORRECTION: Create the Sky flat using `combine': combine @skylist Sky subset+ scale=mode weight=mode combine=average rej=ccdclip gain=gain rdnoise=rdnoise where `skylist' is a list of twilight (or blank) sky exposures. Next, check Sky*imh to make sure stars are filtered out. If they aren't, run makeobjmask @skylist suffix=om ngrow=1 ver- 10c. ILLUMCOR but not defringing needed, BLANK or TWILIGHT SKY FLATS used: `mkskycor' is optional, depending on S/N. If it is done, hedit need not be done, and vice versa: (mkskycor @skylist n//@skylist boxmax=0.25 boxmin=5) or (hedit @skylist MKILLUM "fake" add+ ver- show+) ccdproc a*.imh illumcor+ illum=(n)Sky* 10d. DOME FLATS: not recommended for ILLUMCOR with the 8x12. 11. FRINGECOR: (DEFRINGE.CL) --make lists of temporally close blank-sky/sparse-object frames; one for each field is good start --combine images to create skyfringe frame: iterstat @list, 1./valmed-->SKYFRING imcombine @list skyfringe scale=!SKYFRING weight=!SKYFRING rej=ccdclip gain=gain rdnoise=rdnoise **note that if BPM exists in the image headers, it will get used!!!** **this allows for a redo of this step using object masks if desired** --mkskycor skyfringe out=sky --ccdproc @list illumcor+ illum=sky --imar skyfringe - sky = fringe --fringmed=iterstat.median*(real(imgets.value)) --imcalc @list,fringe @listout "im1-im2*"//fringmed 12: INSPECTION Inspect images to a) see which ones are good and should be kept for future processing b) see which ones of the above didn't get adequately defringed 13: CHECKFRINGE.CL If previous automatic defringing didn't work, use this interactive task to redo the fringe scaling & subtraction until you get it right. One image at a time; you must specify the name of the fringe image to scale and subtract and the name of the output image. 14: COADDING/COSMIC RAY & BAD PIXEL REJECTION (SHIFTNADD.CL/OPTCOADD.CL) `shiftnadd' combines image offsets calculation with first-step coadding. If you are comparing the images with others of different orientations or scales, you can use the shiftnadd output coadded image to measure the rotation or scaling parameters. `shiftnadd' can also include default airmass scaling if desired, avoiding an extra step to include it later. `optcoadd' is a much fancier program to produce a final coadded image, exposure map, and sky-subtracted coadded image. 15. IRSHIFT2 : get data needed to measure scale and rotation between two images' coordinate systems 16. IMMATCH.GEOMAP : calculate scale and rotation from irshift2 data 17. IRROTATE : rotate and resample images and recalculate shifts for them 18. PHOTCHECK : measure photometric stability of the individual images 19. PHOTSCALE : calculate photometric scalings from photcheck output 20. OPTCOADD : final coadd of the (possibly scaled and rotated) images using photometric scalings and magfac>1 if desired 21. TRIM : create constant-rms image w/a certain minimum exposure time 22. PHOTCAL : --When you have lots of stds, use `tvmark img coordsfile number+ interact+' to mark them in order using 'a', then edit coordsfile & put right numbers by them, then redo tvmark label+ and hit 'l' to put right labels on. --Do `phot coords=coordsfile' (maybe after `imexam imagec=coordsfile defk=a' to get better coords, but phot centering should be ok) --If you have other images, use irshift to get offsets, then lintran coordsfile >> coordsfilenew for each new image, and then phot coords=coordsfilenew. --Once you have done phot, do the following (adjusting parameters as needed): files *mag.2 >> data.photlist vi data.photlist # format: "std1 : im1" etc. mkapfile @data.photlist 7 data.apcor smallap=2 largeap=7 magf=data.apmags mknobsfile @data.photlist 1 data.imsets data.obs apercor=data.apcor apert=2 copy data.obs data.obsorig vi data.obs # Insert standard star codes into this file. vi data.config # Set up configuration file as desired fitparams data.obs photcal$catalogs/cat.dat data.config data.params --Note that mkimsets is not necessary. Just group the different standard fields and images together as follows: std1 : im1 #will be im1 im2 im3 if e.g. U B V std1 : im2 std2 : im3 ...etc. .fi .sp .ih SEE ALSO phiirs .endhelp phat_alone/phat.men100644 1332 567 5061 6503631652 13642 0ustar hallast_hyee PHAT --- Pat Hall's Add-on Tasks addcomment - add comment flag to image header addring - add rings around all objects in a mask image biasfix - fix discontinuities in the bias level bindata - bin data and plot histograms of it bscount - estimate Bahcall & Soneira star counts for given (l,b) btc_gainflip - for BTC data: flip data so NE=UL, and mult by gain so gain=1 checkfringe - interactively adjust defringing complete - calculate completeness corrections for mosaiced image cubeexam - apply imexam to one band of a 3-D image cube cut - cut a distribution on specified limits defringe - do sky illumination correction & defringe images fileroot - parse a filename into root and extension fixbias - script for biasfix focasflat - remove sky gradients from images using FOCAS sky determination imswap - swap two images irrotate - rotate and resample images and recalculate shifts for them irshift2 - measure scale and rotation between two images' coord systems iteravg - find iterative average and sigma of a list of numbers iterstat - find image statistics excluding deviant pixels makeobjmask - create object masks for input images maskstat - calculate images statistics from unmasked regions of an image minv - invert a mask of zeros and ones mkobjmask - interactively create object mask mkrgb - create color image from IRAF images offlist - find offsets on sky between lists of objects offset - find the offset on the sky between a pair of objects optcoadd - coadd a list of offset CCD images optcoaddirtf - coadd a list of offset CCD images (IRTF version w/o STSDAS,CTIO) patcopy - copy one list of files to another list of files patpostproc - display new image & its statistics patrename - rename one list of files to another list of files photcheck - monitor photometric stability of a data set photcomp - compare photometric properties of two images on same coord sys. photscale - compute photometric scalings of a data set quickfringe - interactively adjust defringing sctv - display image with display scaled to full range of image values shiftnadd - find offsets for a set of CCD images and coadd them sigmanorm - normalize image by the square root of its exposure map strrev - parse a string into its reverse swap - swap the contents of two files trim - create constant-rms image with a certain minimum exposure time undel - unprotect and delete a file in one fell swoop phat_alone/src/ 40755 1332 567 0 6503630325 12671 5ustar hallast_hyeephat_alone/src/biasfix.cl100644 1332 567 4340 6171341046 14734 0ustar hallast_hyee# biasfix.cl-- fix the 1200x800's bias discontinuities. # # This script deals with the problem of the ~3 ADU discontinuities in the bias # level shown by the 1200x800 CCD when binning. The location of the # discontinuity is roughly dependent on the exposure time but will wander # slightly and occasionally will jump by over 100 pixels. Fortunately the # problem seems to be removable (to first order) using the overscan region. # # 1) Examine each image to identify the TOP row of the BOTTOM bias section, # if there is a jump in the bias level at all. # 2) Copy the images to a safe location, since the biasfix (and ccdproc) # operations done "in place". # 3) Run this routine, which computes the mean of 2 blocks of pixels, one each # just below and just above the discontinuity, calculates the difference, # and adds that # constant into the entire bottom half of the image. # 4) Do the first pass through "ccdproc". The overscan correction in this # pass (polynomial-fitting) can proceed normally. # # 21/04/93 created by Brian McLeod procedure biasfix(imname,toprow) string imname {prompt="Name of image"} int toprow {prompt="Top row of bottom section"} int numrows {20,prompt="Number of rows to use for computing statistics"} int leftcol {603,prompt="Leftmost column to use for statistics"} int rightcol {620,prompt="Rightmost column to use for statistics"} begin string iname,tname int ttoprow real bot,top,diff string botsection,topsection,botfixsection iname = imname ttoprow=toprow tname = mktemp("12x8") botsection = "["//leftcol//":"//rightcol//","//ttoprow-numrows+1//":"//ttoprow//"]" topsection = "["//leftcol//":"//rightcol//","//ttoprow+1//":"//ttoprow+numrows//"]" botfixsection = "[*,1:"//ttoprow//"]" print(botsection) print(topsection) print(botfixsection) imstat (iname//botsection, fields="mean", lower=INDEF, upper=INDEF, binwidth=0.1, format=no) | scan(bot) imstat (iname//topsection, fields="mean", lower=INDEF, upper=INDEF, binwidth=0.1, format=no) | scan(top) diff = bot - top print (bot,top,diff) imarith (iname//botfixsection, "-", diff, tname, title="", divzero=0., hparams="", pixtype="", calctype="", verbose=no, noact=no) imcopy (tname,iname//botfixsection, verbose=no) imdelete(tname,ver-) end phat_alone/src/bindata.cl100644 1332 567 11622 6370206000 14721 0ustar hallast_hyee# bindata.cl -- bin data and plot histograms of it # # This program reads in one or two columns of data (call them 1 and 2), # bins them as specified, and outputs one of three histogram types: # normal plots 1 (cumulative: sum1) # percent plots 1/2 (cumulative: (sum1)/(sum2) # sumpercent plots 1/(1+2) (cumulative: (sum1)/(sum(1+2))) # # Currently there is a limit of 1000 bins. # # 950724: created by Pat Hall # 950725: autoscaling ability & other minor bits added # 960226: option to print midpoint of bin as x coordinate # 970104: numerous revisions to (auto)scaling procedure bindata (histype, cumulative, autoscale, binwidth, firstfile, firstcol) string histype {enum="normal|percent|sumpercent",prompt="Histogram type"} bool cumulative {prompt="Cumulative histogram?"} bool autoscale {prompt="Automatically determine start & end bin values?"} real binwidth {prompt="Bin width"} string firstfile {prompt="File containing first variable"} int firstcol=1 {prompt="Column containing first variable"} string secondfile {prompt="File containing second variable",mode="q"} int secondcol=1 {prompt="Column containing second variable",mode="q"} real z1 {prompt="Starting value for bins",mode="q"} real z2 {prompt="Ending value for bins",mode="q"} bool midpt=yes {prompt="List midpoint coord instead of start for each bin?"} string outfile="" {prompt="List out histogram to this filename"} bool include=no {prompt="Include z2 in top bin?"} struct *name begin real low, high, wide, val, x, plotval, xval, graphval, a, b, c real numer, denom, numerold, denomold real bin1[1000], bin2[1000] int onecol, twocol, z, y string hertype, test0, test1, test2, file1, file2, ooutfile bool go, ccumul, aauto, iinclude, mmidpt # struct val hertype = histype ccumul = cumulative aauto = autoscale if(!aauto){ low = z1 high = z2 } wide = binwidth file1 = firstfile onecol = firstcol if(hertype!="normal"){ file2 = secondfile twocol = secondcol } mmidpt=midpt ooutfile=outfile if(ooutfile=="")ooutfile="_temp_file_" del("_temp_file_", ver-, >& "dev$null") iinclude=include # make sure necessary packages are loaded go = yes # if(!defpac("focas")) {go=no} if(go) { #setup if(aauto){ test0=mktemp("auto") if(hertype=="normal"){ # copy(file1, test0, ver-, >& "dev$null") fields(file1, onecol, lines=1-999999999, >> test0) } else { concat(file1//","//file2, "._test0") fields("._test0", onecol, lines=1-999999999, >> test0) } # sort (test0, col=onecol, num+, rev-, >> test0//"x") sort (test0, col=1, num+, rev-, >> test0//"x") head (test0//"x", nlines=1) | scan(low) tail (test0//"x", nlines=1) | scan(high) z=1+int((high-low)/wide) #number of bins } else { z=int((high-low)/wide) #number of bins } #print(z) bin1=0. bin2=0. x=0 y=0 #read first dataset test1=mktemp(file1) fields(file1, onecol, >> test1) name=test1 while (fscan (name, val) !=EOF) { x=1+int((val - low)/wide) #= 1,2,... (bin number) if(iinclude){ if(val==z2)x=z } # print(x,bin1[x]) bin1[x]=bin1[x]+1 # print(bin1[x]) } #read second dataset, if necessary if(hertype!="normal"){ test2=mktemp(file2) fields(file2, twocol, >> test2) name = test2 while (fscan (name, val) !=EOF) { x=1+int((val - low)/wide) #= 1,2,... (bin number) bin2[x]=bin2[x]+1 } } #Compute and output plotting value for each bin plotval=0 #start numerold=0 #start denomold=0 #start for (y=1; y<=z; y+=1) { graphval=0. if (mmidpt) { #middle xval=((y-1)*wide)+low+(wide/2.) } else { #start xval=((y-1)*wide)+low } #print(xval, bin1[y], bin2[y]) if(hertype=="normal")graphval=bin1[y] #Avoid division by zero by setting 0/0=0 or x/0=1 if(hertype=="percent"){ if(bin2[y]==0.){ if(bin1[y]!=0.){ graphval=1. } else{ graphval=0. } } else{ graphval=bin1[y]/bin2[y] } } #Avoid division by zero by setting 0/0=0 or x/0=1 if(hertype=="sumpercent"){ if((bin1[y]+bin2[y])==0.){ if(bin1[y]!=0.){ graphval=1. } else{ graphval=0. } } else{ graphval=bin1[y]/(bin1[y]+bin2[y]) } } #Sum appropriately if cumulative=yes if(ccumul){ numer=bin1[y] if(hertype=="percent"){ denom=bin2[y] } else { denom=bin1[y]+bin2[y] } if(hertype=="normal"){ plotval=plotval+numer } else { numerold=numerold+numer denomold=denomold+denom if(denomold==0){ if(numerold==0){ plotval=plotval+0 } else { plotval=1 } } else { plotval=numerold/denomold } } } else { plotval=graphval } print(xval,plotval, >> ooutfile) #next y } #Plot the histogram and delete plotting file if list=no graph(ooutfile,point-) if(ooutfile=="_temp_file_")delete(ooutfile, ver-, >& "dev$null") } else { #print("WARNING: package FOCAS is not loaded, or package SYSTEM is.") #print("Please load FOCAS or unload SYSTEM and restart this task.") } if(aauto)del(test0//"*", ver-, >& "dev$null") del(test1, ver-, >& "dev$null") if(hertype!="normal")del(test2, ver-, >& "dev$null") del("_temp_file_", ver-, >& "dev$null") beep end phat_alone/src/bscount.cl100644 1332 567 5426 6171341047 14773 0ustar hallast_hyee# bscount.cl -- estimate Bahcall & Soneira star counts for given (l,b) # # Taken from Appendix B of Bahcall & Soneira 1980, ApJS 44, 73. (B&S80) # # 950807: created # ...might eventually add capability to do multiple fields/mag ranges at once, # taking input from a file perhaps. procedure bscount (long,lat,mag,filter,option,xtinct) real long {min=0.,max=360.,prompt="Galactic longitude (l) of field"} real lat {min=-90.,max=90.,prompt="Galactic latitude (b) of field"} real mag {prompt="Apparent magnitude at which to calculate counts"} string filter {enum="B|V",prompt="Filter in which to calculate counts"} string option {enum="differential|integral",prompt="Differential or integral counts?"} real xtinct=0.0 {min=0.,prompt="Extinction (obscuration), in magnitudes"} bool verbose {prompt="Verbose output? (mag, counts, l, b, ext., filter, option)"} begin real l, b, m, extinct, mtmp, pi real c1, beta, mstar, alpha, mu, gamma, delta real c2, eta, mcross, kappa, lambda, sigma real T1a, T1b, T1, T2, T2a, T2b, T, A string ffilter, ooption bool verb pi=3.1415926 #l=long*2*pi/360. #b=lat*2*pi/360. l=abs(long*2*pi/360.) b=abs(lat*2*pi/360.) mtmp=mag ffilter=filter ooption=option extinct=xtinct m=mtmp-extinct verb=verbose #set up magnitude-dependent constants if(m<=12){ mu=0.03 gamma=0.36 } else { if(m>=20){ mu=0.09 gamma=0.04 } else { mu=0.0075*(m-12)+0.03 gamma=0.04*(12-m)+0.36 } } #set up option-dependent constants #differential V counts, stars mag-1 deg-2 if(ffilter=="V" && ooption=="differential"){ c1=200 alpha=-0.2 beta=0.01 delta=2 mstar=15 c2=400 kappa=-0.26 eta=0.065 lambda=1.5 mcross=17.5 } #integral V counts, stars deg-2 if(ffilter=="V" && ooption=="integral"){ c1=925 alpha=-0.132 beta=0.035 delta=3.0 mstar=15.75 c2=1050 kappa=-0.180 eta=0.087 lambda=2.50 mcross=17.5 } #differential B counts, stars mag-1 deg-2 if(ffilter=="B" && ooption=="differential"){ c1=235 alpha=-0.227 beta=0.0 delta=1.50 mstar=17 c2=370 kappa=-0.175 eta=0.06 lambda=2.0 mcross=18 } #integral B counts, stars deg-2 if(ffilter=="B" && ooption=="integral"){ c1=950 alpha=-0.124 beta=0.027 delta=3.1 mstar=16.60 c2=910 kappa=-0.167 eta=0.083 lambda=2.50 mcross=18 } #do the calculation. T is from eq. B1 of B&S80. T1a=(c1*10**(beta*(m-mstar)))/((1+10**(alpha*(m-mstar)))**delta) #T1b=((sin(b)*(1-mu*cos(l)/abs(tan(b))))**(3-5*gamma))**(-1.0) T1b=((sin(b)*(1-mu*cos(l)/(tan(b))))**(3-5*gamma))**(-1.0) T1=T1a*T1b T2a=(c2*10**(eta*(m-mcross)))/((1+10**(kappa*(m-mcross)))**lambda) #T2b=((1-abs(cos(b))*cos(l))**(1.45-0.20*abs(cos(b))*cos(l)))**(-1.0) T2b=((1-(cos(b))*cos(l))**(1.45-0.20*(cos(b))*cos(l)))**(-1.0) T2=T2a*T2b T=T1+T2 if(verb){ print(m//" "//T//" "//long//" "//lat//" "//extinct//" "//ffilter//" "//ooption) } else { print(T) } end phat_alone/src/checkfringe.cl100644 1332 567 7044 6306672633 15574 0ustar hallast_hyee# checkfringe.cl -- interactively adjust defringing # 950322: created from tpl.cl # 970227: added iterstat determination of RMS of each defringing test procedure checkfringe(fiximage,fringe,outname) string fiximage {prompt="Name of (original) image to be defringed"} string fringe {prompt="Fringe image to scale and subtract"} string outname {prompt="Name of defringed image to create"} #string imagelist {prompt="List of images to use to create fringe image"} bool fit=yes {prompt="Adjust parameters and refit image?",mode="q"} real scale {prompt="Scaling to use on fringe image",mode="q"} int z {0,prompt="Number of image to save?",mode="q"} begin string logimex, logsurf, countfile, rrootname, iimagelist, ooutname, ffunc string wweighting, fiximg, ffringe, titlestring real max, nncols, nnlines, sscale, indiv_exptime, avg_exptime, sum_exptime int x, y, zz, xxord, yyord, xx bool go, ffit, xxterms fiximg=fiximage ffringe=fringe ooutname=outname zz=0 #countfile="log."//rrootname//".tplcount" # check for addcomment; if not defined abort task. go=yes if(!deftask("addcomment")) {go=no} if(go) { # Get initial scaling print("===> Displaying fringe image and original image...") display(ffringe,1) display(fiximg,2) imgets(fiximg,"FRINGMED",>&"dev$null") if(imgets.value!="0"){ sscale=real(imgets.value) } else { print(" ") print("===> Calculating initial fringe image scaling...") imgets(ffringe,"exptime") avg_exptime=real(imgets.value) imgets(fiximg,"exptime") indiv_exptime=real(imgets.value) imgets(fiximg,"SKYFRING") iterstat(fiximg,nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print-,ver-) # new scaling = new median from iterstat * old scaling * exptime * avg_exptime sscale=iterstat.median*(real(imgets.value))*indiv_exptime/avg_exptime } #need to create countfile x=1 y=2 ffit=yes # Fitting loop while(ffit) { # (get new list of images) # copy(countfile,countfile//"_"//str(x)) if(x!=1){ # get new scaling sscale=scale # vi(countfile//"_"//str(x)) } # scale and subtract the fringe image print ("===> Scaling the fringe image by "//sscale//" and subtracting...") # imar (ffringe, "/", sscale, ffringe//"_"//str(x), ver-) # imar (ooutname//"_0", "-", ffringe//"_"//str(x), ooutname//"_"//str(x), ver-) imcalc(fiximg//","//ffringe,ooutname//"_"//str(x),"im1-im2*"//sscale,ver-) hedit(ooutname//"_"//str(x),"title","Defringed image using scale="//sscale,ver-,add+,update+,show-) # inspect the subtracted image print ("===> Displaying defringed image #"//str(x)//"...") y=y+1 if(y>4)y=1 displ (ooutname//"_"//str(x), y) iterstat (ooutname//"_"//str(x),nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print-,ver-) print ("===> RMS of defringed image #"//str(x)//" is "//iterstat.sigma) # clean up # abort loop? ffit=fit x+=1 } # clean up zz=z if(zz!=0){ imcopy(ooutname//"_"//str(zz),ooutname,ver-) hedit(ooutname,"FRINGMED",sscale,add+,ver-,show-,update+) addcomment(ooutname,"Defringed using FRINGMED-scaled copy of "//ffringe,ver-) imgets(fiximg,"title") titlestring=str(imgets.value) hedit(ooutname,"title",titlestring,add+,ver-,update+,show-) #del(countfile,ver-, >& "dev$null") #rename(countfile//"_"//str(zz),countfile, >& "dev$null") } else{ print("No images saved.") } y=0 zz=0 while(y& "dev$null") # del(countfile//"_"//str(y),ver-, >& "dev$null") y+=1 } } else{ print("The tasks `addcomment' are not loaded,") print("and this task needs them to run. Please load it and start again.") } beep end phat_alone/src/cubeexam.cl100644 1332 567 1010 6171341047 15070 0ustar hallast_hyee# CUBEEXAM -- script to apply IMEXAM to a band of a 3D cube. # Notes: All IMEXAM parameters are used with their current settings. # Only one image and band may be specified at a time. # # usage: cubeexam band procedure cubeexam (cube, band) string cube {prompt="cube to be examined"} int band {prompt="band in cube to be examined"} begin string im3, sec, im2 im3 = cube im2 = mktemp (im3) imcopy (im3 // "[*,*,"//band//"]", im2, verbose=no) imexamine (im2) imdelete (im2, verify=no) end phat_alone/src/defringe.cl100644 1332 567 15756 6361775363 15145 0ustar hallast_hyee# defringe.cl -- do sky illumination correction & remove fringing from images # # Calls routines iterstat and addcomment. # # CHANGES: # 95/01/27: created # 95/03/22: many modifications begun # 96/02/26: allow saving of sky+fringe image when stopping task procedure defringe(rootname,imagelist,logfile,defstring,biasimage) string rootname {prompt="Rootname for output images and image list"} string imagelist {prompt="List of images to process (do not use an `@')"} string logfile {prompt="Name of log file"} string defstring {prompt="String to be appended to output images"} string biasimage {prompt="Zero level calibration image for ccdproc"} bool dofringe {yes,prompt="Do fringe removal step?"} real gain {prompt="Gain of CCD (for ccdclip in imcombine)"} real rdnoise {prompt="Read noise of CCD (for ccdclip in imcombine)"} bool forcescale {no,prompt="Force recalculation of image scales?"} bool goon=yes {prompt="Continue with task using displayed sky+fringe image?",mode="q"} bool ssave=no {prompt="Save sky+fringe image?",mode="q"} struct *list struct *list2 struct *list3 struct *datelist begin string ddefstring, ffringename, outlist, sskyfringename, sskyname, biasimg string rrootname, ddark, llogfile, bbadmask, eextension, normfile, img string flatlist, flat, flatbase, meanfile, currentflat, base, mmaskname string iimagelist, FlatImageList, fflatstr, check, ttplname, templist, flatdiv string datefile, thedate, ickinfo, name, tempstring, otherstring, tempfile real mean, nnumber, flatnorm, valmed, fringmed, ggain, rrdnoise, scale, scale2 real indiv_exptime, avg_exptime, sum_exptime int sstartno, eendno, i, j, numpix, x, y, z bool zzeroout, ttpl, sstdpars, go, fflatsave, force, ggoon rrootname = rootname iimagelist = imagelist llogfile = logfile ddefstring = defstring biasimg = biasimage ggain = gain rrdnoise = rdnoise force = forcescale outlist = "list."//rrootname//ddefstring sskyfringename=rrootname//ddefstring//".skyfringe.imh" # sky+fringe image ffringename=rrootname//ddefstring//".fringe.imh" # fringe image sskyname=rrootname//ddefstring//".sky.imh" # sky-flat image #The "go" parameter won't let the task run if you haven't loaded ccdred. go=yes if(!defpac("ccdred")) {go=no} if(!deftask("imcalc")) {go=no} if(!deftask("iterstat")) {go=no} if(!deftask("addcomment")) {go=no} if(go) { #Set up log file, appending if it already exists if(llogfile == "") llogfile=rrootname//".log" print(" ", >> llogfile) # Do iterstat to find each image's "true" median for use in scaling print("===> Finding image scales and weights...") tempfile = iimagelist list2 = tempfile sum_exptime = 0. scale = 1 scale2 = 1 i = 0 while (fscan(list2,img) !=EOF) { fileroot(img,validim+) flat=fileroot.root//ddefstring//".imh" print(flat, >> outlist) i = i + 1 force = forcescale imgets (img, "exptime") sum_exptime=sum_exptime+real(imgets.value) if (!force) { imgets (img,"SKYFRING",>&"dev$null") mean=real(imgets.value) if (mean == 0) { force = yes } else { scale = scale + 1./real(imgets.value) } } if (force) { iterstat.nsigrej=5 iterstat.maxiter=10 iterstat(img,nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print-,ver-) valmed = 1./iterstat.median hedit (img,"SKYFRING",valmed,add+,ver-,show-,update+) scale = scale + (1./valmed) } } sum_exptime=sum_exptime/i # Use this list of images to make the sky-fringe frame print("===> Creating template sky + fringe frame...") imcombine("@"//tempfile, sskyfringename, sigma="", plfile="", combine="median", reject="ccdclip", project-, offsets="none", blank=0., scale="!SKYFRING", zero="none", weight="!SKYFRING", statsec="", lthresh=-100000, hthresh=100000, nlow=1, nhigh=1, nkeep=1, mclip+, lsigma=3, hsigma=3, rdnoise=rrdnoise, gain=ggain, snoise="0.", sigscale=0.1, pclip=-0.5, grow=0., logfile='STDOUT', >> llogfile) hedit(sskyfringename,"exptime",sum_exptime,add+,ver-,show-,update+) print("===> Displaying sky+fringe image for inspection. If object residuals") print("===> are present, you may wish to stop, create object masks, and rerun") print("===> the task. You can use makeobjmask on the non-defringed images to") print("===> create object masks for them directly, or you can use shiftnadd on") print("===> the non-defringed images, run mkobjmask on the skysubbed output,") print("===> insert the object mask names into the non-defringed image headers,") print("===> and then rerun this task so that the objects are masked out during") print("===> the creation of the sky+fringe image.") displ(sskyfringename,1) ggoon=goon if(!ggoon){ print("Task aborted-- illumination correction & defringing not done.") if(!ssave)imdel(sskyfringename,ver-) del(outlist,ver-) return } # "scale" is set equal to the average median of the input images. # It is multiplied into the sky-fringe frame to keep fringe counts accurate. scale = scale / i imar (sskyfringename, "*", scale, sskyfringename) # Insert title into fringe image header hedit (sskyfringename, "title", "Sky+fringe image for "//tempfile, add+,ver-,show-,update+) # Create sky illumination correction image mkskycor(sskyfringename,sskyname,xboxmin=5.,xboxmax=0.25,yboxmin=5.,yboxmax=0.25) #mkskycor(sskyfringename,out=sskyname,xboxmin=5.,xboxmax=0.25,yboxmin=5., #yboxmax=0.25) hedit (sskyname, "title", "Sky illumination correction image for "//iimagelist, add+,ver-,show-,update+) # Do illumination correction *on output images only* imcopy("@"//iimagelist, "@"//outlist, ver-) ccdproc("@"//outlist, illumcor+, illum=sskyname, zero=biasimg) imcopy(sskyfringename, ffringename, ver-) imar (ffringename, "-", sskyname, ffringename) # Subtract accurately scaled fringe image from each input image, if desired if(dofringe){ print("===> Subtracting scaled fringe image from each input image...") imgets(ffringename,"exptime") avg_exptime=real(imgets.value) #list = iimagelist list = outlist while (fscan (list, name) !=EOF) { # x=strlen(name) # check=substr(name,x-3,x) # base=substr(name,1,x) # if(check==".imh")base=substr(name,1,x-4) # flat=base//ddefstring//".imh" # print(flat, >> outlist) imgets(name,"exptime") indiv_exptime=real(imgets.value) imgets(name,"SKYFRING") iterstat(name,nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print-,ver-) # new scaling = new median from iterstat * old scaling * exptime / avg_exptime fringmed=iterstat.median*(real(imgets.value))*indiv_exptime/avg_exptime imren (name, "_"//name, ver-) imcalc ("_"//name//","//ffringename, name, "im1-im2*"//fringmed, ver-) imdel ("_"//name, ver-) hedit(name,"FRINGMED",fringmed,add+,ver-,show-,update+) addcomment(name,"Defringed using scaled copy of "//ffringename,ver-) print(name//" was defringed using "//ffringename//" scaled by "//fringmed) } } print("===> Wrapping up... ") datefile = mktemp("date") date(>>datefile) datelist = datefile print("finished at "//datelist, >> llogfile) datelist = "" del(datefile, ver-) } else { beep print("WARNING: one or more of the packages `noao.imred.ccdred' or") print("`stsdas.toolbox.imgtools' or `PHIIRS' are not loaded!") print("Please load them and restart this task.") } beep end phat_alone/src/fixbias.cl100644 1332 567 155 6171341050 14707 0ustar hallast_hyeedispl b0069 1 zr- zs- z1=900 z2=950 imcopy b0069 b0069orig biasfix b0069 displ b0069 2 zr- zs- z1=900 z2=950 phat_alone/src/imswap.cl100644 1332 567 455 6305446032 14572 0ustar hallast_hyee# Swap two images procedure imswap(img1,img2) string img1 {prompt = "Name of first image"} string img2 {prompt = "Name of second image"} begin imrename(img2,"tmpswapdude",ver-) imrename(img1,img2,ver-) imrename("tmpswapdude",img1,ver-) print("Contents of "//img1//" and "//img2//" swapped.") end phat_alone/src/offlist.cl100644 1332 567 5432 6171341051 14754 0ustar hallast_hyee# offlist.cl -- find the offsets on the sky between two lists of objects # # Input format for both lists is: # 1 2 3 # ra dec id# # # Output is: # 1 2 3 4 5 6 7 8 9 # id1 ra1 dec1 id2 ra2 dec2 distance @ angle (measured E from N) # # ...for all objects closer than "limit" if all=yes, or just the closest # object closer than "limit" if all=no. procedure offlist(list1,list2,outlist,limit) string list1 {prompt = "First list of coordinates"} string list2 {prompt = "Second list of coordinates"} string outlist {prompt = "Output file"} real limit {prompt = "Max separation, in arcmin, to save"} bool all {prompt = "List all objects closer than limit?"} struct *el1 struct *el2 begin real dist, cdist, sdist, tdist, rn1, rn2, dn1, dn2, rt1, rt2, sigdig, distold real pa, cpa, spa, tpa, rd, dd, rds, dds, dt1, dt2, r1, r2, d1, d2, lim real pi=3.141592653585 int ipa string ir1, ir2, id1, id2, num1, num2, ooutlist, el3 string ir1old, ir2old, id1old, id2old, num1old, num2old bool aall, go el1=list1 el2=list2 el3=list2 ooutlist=outlist lim=limit distold=lim+1. aall=all go=no while(fscan(el1,ir1,id1,num1) !=EOF) { while(fscan(el2,ir2,id2,num2) !=EOF) { r1=real(ir1) d1=real(id1) r2=real(ir2) d2=real(id2) #convert input RA to degrees rt1=15.0*r1 rt2=15.0*r2 #convert input RA,dec to radians rn1=rt1*pi/180.0 rn2=rt2*pi/180.0 dn1=d1*pi/180.0 dn2=d2*pi/180.0 #compute the distance using the formula: #cosine(distance) = sin(dn1)*sin(dn2) + cos(dn1)cos(dn2)cos(rn2-rn1) cdist = sin(dn1)*sin(dn2) + cos(dn1)*cos(dn2)*cos(rn2-rn1) if(cdist**2>=1.00)cdist=1.00 #fixes roundoff prob sdist = sqrt(1.00 - cdist**2) tdist = atan2(sdist,cdist) #theta=atan2(y,x) dist = tdist*180.00/pi #compute the position angle using the formula: #cos(pa)=(cos(dn1)sin(dn2) - sin(dn1)cos(dn2)cos(rn2-rn1))/(sin(tdist)) #cpa = (cos(dn1)*sin(dn2) - sin(dn1)*cos(dn2)*cos(rn2-rn1))/(sdist) cpa = cos(dn1)*sin(dn2) - sin(dn1)*cos(dn2)*cos(rn2-rn1) if(sdist==0.0){ pa = 360.0 } else { cpa = cpa/sdist if(cpa**2>=1.00)cpa=1.00 #fixes roundoff prob spa = sqrt(1.00 - cpa**2) tpa = atan2(spa,cpa) #theta=atan2(y,x) pa = tpa*180.00/pi } #is this the closest match found so far for this object? if(dist*60<=lim){ if(!aall && dist<=distold) { go=yes distold=dist ir1old=ir1 id1old=id1 ir2old=ir2 id2old=id2 num1old=num1 num2old=num2 } #output all matches if(aall){ print(num1//" "//ir1//" "//id1//" "//num2//" "//ir2//" "//id2//" "//dist*60//" @ "//pa, >> ooutlist) } } } #output closest match if(!aall && go)print(num1old//" "//ir1old//" "//id1old//" "//num2old//" "//ir2old//" "//id2old//" "//distold*60//" @ "//pa, >> ooutlist) distold=lim+1. go=no el2=el3 } end phat_alone/src/offset.cl100644 1332 567 4306 6171341051 14573 0ustar hallast_hyee# offset.cl -- Find the offset on the sky between two objects. # # This task takes the ID numbers and coordinates of two objects and computes # the offset on the sky between them, in seconds of time E-W and arcsec N-S, # as well as the distance between them in arcminutes. # Optionally these values can be output to a file instead of STDOUT. # #procedure offset(num1,ir1,id1,num2,ir2,id2) procedure offset(list1,list2) #string num1 {prompt = "ID number of CANDIDATE"} #real ir1 {prompt = "RA coordinate of CANDIDATE"} #real id1 {prompt = "Dec coordinate of CANDIDATE"} #string num2 {prompt = "ID number of OFFSET STAR"} #real ir2 {prompt = "RA coordinate of OFFSET STAR"} #real id2 {prompt = "Dec coordinate of OFFSET STAR"} string list1 {prompt = "First list of coordinates"} string list2 {prompt = "Second list of coordinates"} string outfile="STDOUT" {prompt = "Output file"} struct *el1 struct *el2 begin string ir1, ir2, id1, id2, num1, num2 real dist, cdist, sdist, tdist, rn1, rn2, dn1, dn2, rt1, rt2, sigdig real rd, dd, rds, dds, dt1, dt2, r1, r2, d1, d2 real pi=3.141592653585 string ooutlist ooutlist=outfile el1=list1 el2=list2 while(fscan(el1,ir1,id1,num1) !=EOF) { while(fscan(el2,ir2,id2,num2) !=EOF) { #set up dummy variables r1=real(ir1) d1=real(id1) r2=real(ir2) d2=real(id2) #convert input RA to degrees rt1=15.0*r1 rt2=15.0*r2 #convert input RA,dec to radians rn1=rt1*pi/180.0 rn2=rt2*pi/180.0 dn1=d1*pi/180.0 dn2=d2*pi/180.0 #compute the distance using the formula: #cosine(distance) = sin(d1)*sin(d2) + cos(d1)cos(d2)cos(r1-r2) #theta=atan2(y,x) cdist = sin(dn1)*sin(dn2) + cos(dn1)*cos(dn2)*cos(rn1-rn2) sdist = sqrt(1.00 - cdist**2) tdist = atan2(sdist,cdist) dist = tdist*180.00/pi #delta ra and dec rd=(rt2-rt1)*cos((dn1+dn2)/2.) dd=d2-d1 #Option 2: difference in RA and Dec (accurate for small separations only) # print("E-W on-sky separation in seconds of time: "//rd*240, >> ooutlist) print("E-W on-sky separation in arcsec: "//rd*3600, >> ooutlist) print("N-S on-sky separation in arcsec: "//dd*3600, >> ooutlist) print(num1//" is "//dist*60//" arcmin from "//num2, >> ooutlist) } } end phat_alone/src/irtfcoadd_1.p100644 1332 567 450 6427031077 15311 0ustar hallast_hyee#!/usr/local/bin/perl -w # cycle thru contents of file(s) given on command line using <> while (<>) { # skip blank lines or lines with # as first non-whitespace character next if (/^\s+$/ or /^#/ or /^\s+#/); ($one, $two) = split " "; $out=$two/($one*$one); print "$out\n"; } phat_alone/src/optcoadd.cl100644 1332 567 152516 6427030735 15161 0ustar hallast_hyee# optcoadd -- coadd images with sub-pixel shift options and much, much more # # Calls addcomment, iterstat, fileroot, filecalc, stsdas.toolbox.imgtools.imcalc # # 960712: created from phiirs$ircoadd.cl # 960716: deleted internal scaling check, added subtracted-image creation # 960723: fixed edge problem in sky-subtracted image # 960806: made sky-subtracted image creation optional # 960807: fixed minor bug of ccomblist2 not existing in expmap creation only # 960812: fixed exposure map creation & created normalization map creation # 960815: fixed bug in normalization of expmap when dividing into outimage # 960816: changed so that statfile is used only if directly requested, # and added optional insertion of variances into image headers # 960817: fixed occasional bug in skysub + weighted-expmap normalization # 960822: moved check for necessary tasks earlier to avoid errors # 970425: added check for tpl image # 970429: changed expmap -- now sets bad pixels to -99999. # Also several other minor changes to bring in line with ircoadd # 970505: changed default expmap suffix from "em" to "exp" to avoid confusion # with ircoadd, whose output expmap is different than optcoadd's # 970507: changed creation of individual expmaps to replace pixels above # -10000. with exptime -- allows for -99999. bad pixels to be excluded # 970623: added ability to use imcombine snoise parameter # # **Could cut down on transient memory needs by finding "wtfactor" needed to # convert _nm image to _wt image -- stack norm, then do wtfactor & stack wt # **Note that weights should add to 1 if taken from a file (probably matters # only when stacking and creating expmap, but do it always just to be safe) procedure optcoadd(comblist,outimage,expmap,normmap,shiftlist,scaling,zeroing,weighting,magfac,stack,logfile) string comblist {prompt="List of images to combine"} string outimage {prompt="Output coadded image"} string expmap {prompt="Output exposure map (default=outimage//exp)"} string normmap {prompt="Output normalization map (default=outimage//norm)"} string shiftlist {prompt="File with image shifts"} string scaling {prompt="Imcombine scaling (none|@file|!|etc.)"} string zeroing {"mode",prompt="Imcombine zero offsets (none|@file|mode|etc.)"} string weighting {prompt="Imcombine weighting (none|@file|!|etc.)"} int magfac {1,min=1,max=10,prompt="Magnification factor for subpixel shifting"} bool stack {prompt="Combine images by stacking & projecting?"} string logfile {prompt="Name of log file"} string normname {prompt="Header keyword for normalization factor",mode="q"} bool newmask=no {prompt="Override bad pixel masks listed in image headers?"} string badmask {prompt="Bad pixel mask to use instead",mode="q"} bool spshift=no {prompt="Do image shifts account for subpix shifting?",mode="q"} bool prescale=no {prompt="Scale images before, not during, imcombine?",mode="q"} bool unscale=yes {prompt="Undo scaling factors when done?",mode="q"} real extcoeff {prompt="Extinction coefficient for default scalings",mode="q"} real airzero {INDEF,min=0.,max=99.,prompt="Airmass to scale to? (INDEF=min. observed)",mode="q"} bool scalecombine=no {prompt="Combine default & additional scalings?",mode="q"} string morescalename {prompt="@filename or !keyword for additional scalings",mode="q"} bool putscale {prompt="Insert scaling factors into image headers?",mode="q"} string wordscale="SCALEFAC" {prompt="Scaling factor header keyword",mode="q"} bool defscale=no {prompt="Do scales include default airmass scaling?",mode="q"} bool prezero=no {prompt="Do zero offseting before, not during, imcombine?",mode="q"} bool unzero=yes {prompt="Undo zero offsets when done?",mode="q"} bool putzero=no {prompt="Insert zero offsets into image headers?",mode="q"} string wordzero="ZEROVAL" {prompt="Zero offset header keyword",mode="q"} bool putweight=no {prompt="Insert weights into image headers?",mode="q"} string wordweight="WEIGHT" {prompt="Weighting factor header keyword",mode="q"} string stackimage {prompt="Name of stacked image", mode="q"} bool unstack {prompt="Delete stacked image & expmap when done?",mode="q"} bool spscale=no {prompt="Do zero offsets account for subpix shifting?",mode="q"} string expname="EXPTIME" {prompt="Header keyword for exposure time"} bool maskedstat=no {prompt="Use maskstat to find default zeros & wts?"} string statfile="" {prompt="File for image statistics"} bool stdpars=yes {prompt="Use std imcombine parameters for coadd?"} bool makeavg=no {prompt="Make pure coadd (comb=average,rej=none)?"} bool flip=no {prompt="Flip image L-R after coadd?"} bool cleanup=yes {prompt="Clean up new created blkrep'd images after use?"} bool tpl=no {prompt="Account for throughput correction in norm. map?"} pset optcoaddpars {prompt="Imcombine parameters"} struct *list begin string sshiftfraclist, iinterp, sshiftlist, subimg, explist, sect, skysubimg string ccomblist, bbadmask, sshiftintlist, ooutimage, zzeroing, sstackimage string llogfile, check, zzeroname, sscalefile, sscalename, img, eexpname, blk string s_sigma, s_plfile, s_combine, s_reject, s_offsets, s_masktyp, eexpmap string s_scale, s_weight, s_statsec, s_expname, sscaling, intcosca, expmask string listimshift, wwordscale, wwordzero, subimgold, expmaskold, checkmore string ccomblist1, ccomblist2, sshiftexactlist, image, newbp, newzzeroname string oldbp, bprotlist, file_of_zeros, list_of_zeros, checkscale, checkweight string checkzero, newwweightname, oldzs, newzs, oldwts, newwts, wweightname string file_of_more, mmorescalename, file_of_air, wweighting, wwordweight string file_of_scales, list_of_scales, sstatfile, s_gain, s_rdnoise, nnormname string nnormmap, wtimg, wtlist, wtimgold, tplimg, tplimgold, oextimage, tpltmp string tmpimg, tmpimg2, s_snoise real s_maskval, s_blank, s_lthresh, s_hthresh, s_nlow, s_nhigh, s_nkeep, avg, x real s_lsigma, s_hsigma, s_pclip, s_grow, s_sigscale, sig real effairmass, wtavg, nncombine, exp, exposure, sf, zf, testold, eexptime real xold, yold, xnew, ynew, xshift, yshift, sscale, p, b, h, levelzero, wt real wt_avg_exptime, unwt_avg_exptime, eextcoeff, aairzero, air, sfavg, sfmin real sfmax, tmpzero, wait, waitold int mag, mag2, j, k, tpl1, tpl2 int xmin, ymin, newx, newy, oldx, oldy, test1, test1old, test2, test2old int sstartno, eendno, i, numpix, num, xdim, ydim, newxsize, newysize, ncoadds bool mmakescalefile, mmakestack, go, mmorehow, pputzero, ddefscale, pputscale bool nnewmask, uunstack, pprescale, uunscale, pputweight, sstack, getnorm, ttpl bool sspscale, ccleanup, noappend, pprezero, uunzero, sscalecombine, sspshift struct theadline #for zero/scale/weight=* # *ing how to do it # *name filename, if substr(*ing,1,1)==@ # word* header keyword, if substr(*ing,1,1)==! (or @ && pre*=yes) # pre* do zero/scale before imcombine # un* undo zero/scale after imcombine # Certain tasks/packages must be loaded for task to run. go=yes if(!defpac("imgtools")) {go=no} if(!deftask("addcomment")) {go=no} if(!deftask("fileroot")) {go=no} if(!deftask("filecalc")) {go=no} if(!deftask("iterstat")) {go=no} if(go) { # Set up parameters ccomblist = comblist ccomblist1 = ccomblist fileroot (outimage,validim+) ooutimage = fileroot.root oextimage = fileroot.extension if(oextimage=="")oextimage="imh" fileroot (expmap,validim+) eexpmap = fileroot.root if(eexpmap=="")eexpmap=ooutimage//"exp" nnormmap=normmap if(nnormmap=="")nnormmap=ooutimage//"norm" sshiftexactlist = shiftlist sshiftintlist = sshiftexactlist sscaling = scaling if(sscaling=="")sscaling="none" ddefscale=no aairzero=100. pprescale=no uunscale=no sscalename="_.imag_in_ary_fileJ" checkscale=substr(sscaling,1,1) if(checkscale=="!" || checkscale=="@"){ wwordscale = substr(sscaling,2,strlen(sscaling)) pprescale=prescale if(pprescale)uunscale=unscale if(checkscale=="@"){ sscalename = substr(sscaling,2,strlen(sscaling)) if(!access(sscalename)){ ddefscale=yes eextcoeff=extcoeff aairzero=airzero sscalecombine=scalecombine if(sscalecombine){ mmorescalename=morescalename checkmore=substr(mmorescalename,1,1) while(checkmore!="@" && checkmore!="!"){ print("Additional scales must have format ! or @filename.") mmorescalename=morescalename checkmore=substr(mmorescalename,1,1) } } } pputscale=putscale if(pputscale)wwordscale=wordscale } if(!ddefscale)ddefscale=defscale if(ddefscale && aairzero==100.)aairzero=airzero # if airzero=INDEF and airzero is needed later in the task, airzero=min(airmass) if(aairzero==INDEF && (ddefscale || (pprescale && checkscale=="@" && access(sscalename)))){ print("...one moment please...") file_of_air=mktemp(".foa") hsel("@"//ccomblist1,"AIRMASS",yes, >> file_of_air) list=file_of_air aairzero=100. while (fscan (list,air) != EOF) { aairzero=min(air,aairzero) } del(file_of_air,ver-,>&"dev$null") list="" } } zzeroing = zeroing if(zzeroing=="")zzeroing="none" pprezero=no uunzero=no checkzero=substr(zzeroing,1,1) if(checkzero=="!" || checkzero=="@"){ wwordzero = substr(zzeroing,2,strlen(zzeroing)) pprezero=prezero if(pprezero)uunzero=unzero if(checkzero=="@"){ zzeroname = substr(zzeroing,2,strlen(zzeroing)) pputzero=putzero if(pputzero)wwordzero=wordzero } } wweighting = weighting wwordweight="" if(wweighting=="")wweighting="none" checkweight=substr(wweighting,1,1) if(checkweight=="!")wwordweight=substr(wweighting,2,strlen(wweighting)) if(checkweight=="@"){ wweightname = substr(wweighting,2,strlen(wweighting)) pputweight=putweight if(pputweight)wwordweight=wordweight } mag = magfac mag2=mag*mag blk = "br"//mag ccomblist2 = ccomblist//blk bprotlist = ccomblist//blk//"pl" sspscale=no sspshift=no if(mag!=1){ if(zzeroing!="none")sspscale=spscale sspshift=spshift } sstack=stack sstackimage="fake_image_oog" if(sstack) { fileroot(stackimage,validim+) sstackimage = fileroot.root uunstack=unstack } llogfile = logfile nnormname=normname getnorm=no if(nnormname=="")getnorm=yes if(nnormname=="")nnormname="variance" if(wwordweight=="")wwordweight=wordweight nnewmask = newmask if(nnewmask)bbadmask = badmask eexpname = expname sstatfile = statfile if(sstatfile=="")sstatfile="_nonexistentFILEname_" ttpl = tpl ccleanup = cleanup # Check for bad parameter combinations and exit if necessary if(!pprescale && sstack && checkscale=="!"){ print("WARNING! You can't scale during imcombine from a header keyword") print("when stack=yes! (There is only one header for a stacked image.)") print("Use `@file' or prescale=yes instead.") return } if(!pprezero && sstack && checkzero=="!"){ print("WARNING! You can't take the zero offsets from a header keyword") print("when stack=yes! (There is only one header for a stacked image.)") print("Use `@filename' or prezero=yes instead.") return } if(checkweight!="@" && wweighting!="none" && sstack){ print("WARNING! Output image exposure time would have been incorrect.") print("If you want to use weights and stacking, put the weights in a file") print("before running the task; that way the output image exposure time") print("will be correctly calculated.") return } wt_avg_exptime=-1. unwt_avg_exptime=-1. s_sigma = i_sigma # imcombine parameters s_plfile = i_plfile s_combine = i_combine s_reject = i_reject s_masktyp = i_masktyp s_maskval = i_maskval s_blank = i_blank s_statsec = i_statsec s_expname = i_expname s_lthresh = i_lthresh s_hthresh = i_hthresh s_nlow = i_nlow s_nhigh = i_nhigh s_nkeep = i_nkeep s_lsigma = i_lsigma s_hsigma = i_hsigma s_rdnoise = i_rdnoise s_gain = i_gain s_snoise = i_snoise s_sigscale = i_sigscale s_pclip = i_pclip s_grow = i_grow # Set up log file, appending if it already exists. if(llogfile == "") llogfile="log."//ooutimage print("", >> llogfile) print("===> PHAT.OPTCOADD:", >> llogfile) if(mag!=1){ print("===> Input images from "//ccomblist1//" replicated by factor "//mag//" in each direction.", >> llogfile) print("===> Replicated images in "//ccomblist2//" coadded w/offsets from "//sshiftexactlist//blk, >> llogfile) } else { print("===> Images in "//ccomblist1//" coadded w/offsets from "//sshiftexactlist//",", >> llogfile) } print("===> weights="/wweighting//", stdpars="/stdpars//", makeavg="/makeavg//",", >> llogfile) print("===> scales="/sscaling//", zero offsets="/zzeroing//",", >> llogfile) print("===> pre-scaling="/pprescale//", un-scaling="/uunscale//", pre-zeroing="/pprezero//", un-zeroing="/uunzero//",", >> llogfile) print("===> defscale="/ddefscale//", subpixscale="/sspscale//", subpixshift="/sspshift//",", >> llogfile) print("===> to make image "//ooutimage//" and exposure map "//eexpmap, >> llogfile) # PRE-SCALING AND DEFAULT SCALING FACTORS FILE CREATION if(pprescale){ # Prevent imcombine from scaling twice sscaling="none" # If stacking, and image already exists, do not bother # if(sstack && access(sstackimage//".imh")){ # print("Not bothering to pre-scale... stacked image already exists.") # } else { print("===> Multiplying by additional scaling factors...") # In case of scalings taken from header keyword, make file_of_scales if(checkscale=="!"){ file_of_scales=mktemp(".fos") hsel("@"//ccomblist1,wwordscale,yes, >> file_of_scales) } # In case of scalings taken from file... if(checkscale=="@"){ # # ...create file of DEFAULT SCALING FACTORS if it doesn't exist... # if(!access(sscalename)){ file_of_air=mktemp(".foa") # get airmasses hsel("@"//ccomblist1,"AIRMASS",yes, >> file_of_air) # turn airmasses into scales list=file_of_air while (fscan (list,air) != EOF) { sf=10**(0.4*eextcoeff*(air-aairzero)) print(sf, >> sscalename) } del(file_of_air,ver-) # If combining default scales with other pre-existing scales... if(sscalecombine){ file_of_more=mktemp(".fom") if(checkmore=="@"){ copy(substr(mmorescalename,2,strlen(mmorescalename)),file_of_more,ver-) } if(checkmore=="!"){ hsel("@"//ccomblist1,substr(mmorescalename,2,strlen(mmorescalename)),yes, >> file_of_more) } # join files of default and additional scales del("tmp_."//sscalename,ver-,>&"dev$null") join(sscalename,file_of_more,output="tmp_."//sscalename) del(sscalename,ver-,>&"dev$null") del(file_of_more,ver-,>&"dev$null") list="" list="tmp_."//sscalename # create new scales & put into scale file while(fscan (list,air,sf) != EOF) { print(air*sf, >> sscalename) } del("tmp_."//sscalename,ver-,>&"dev$null") } # Finished with creation of default scalings file } list="" file_of_scales=sscalename # End of taking scales from list subroutine } list="" # Allow imcombine to do sigscaling as requested even when pre-scaling if(s_sigscale!=0.){ del ("_avg.file.tmp", ver-, >& "dev$null") type (file_of_scales | average opt="new_sample", >> "_avg.file.tmp") sfavg=average.mean sfmin=1.E20 sfmax=-1.E20 list=file_of_scales while (fscan (list,sf) != EOF) { sfmin=min(sfmin,sf) sfmax=max(sfmax,sf) } if((sfavg-sfmin/sfavg)>=s_sigscale || (sfmax-sfavg/sfavg)>=s_sigscale)s_sigscale=0. del ("_avg.file.tmp", ver-, >& "dev$null") list="" } # Do multiplicative scaling unless it has already been done list_of_scales=mktemp(".los") join(ccomblist1,file_of_scales,output=list_of_scales) if(checkscale=="!")del(file_of_scales,ver-) list=list_of_scales while (fscan (list,img,sf) != EOF) { imgets(img,"PRESCALE",>&"dev$null") if(imgets.value=="0"){ imar(img,"*",sf,img,pixt="real",calct="real",ver-) hedit(img,"PRESCALE",sf,add+,ver-,show-,update+,>&"dev$null") if(ddefscale){ imgets(img,"AIRMASS",>&"dev$null") hedit(img,"AIRMOLD",imgets.value,add+,ver-,show-,update+,>&"dev$null") hedit(img,"AIRMASS",aairzero,add+,ver-,show-,update+,>&"dev$null") } } else { print("No action -- image "//img//" already pre-scaled by factor "//imgets.value) } } # } } list="" # put scale factors into image headers if desired if(checkscale=="@"){ if(pputscale){ del("_tmp.sscaling",ver-,>&"dev$null") join(ccomblist1,sscalename,out="_tmp.sscaling") list="_tmp.sscaling" while(fscan (list, img, sf) != EOF) { hedit(img,wwordscale,sf,add+,ver-,show-,update+,>&"dev$null") } del("_tmp.sscaling",ver-,>&"dev$null") } } list="" # DETERMINE ZERO-LEVEL OFFSETS IF NEEDED AND INSERT INTO HEADERS IF DESIRED if(checkzero=="@"){ if(!access(zzeroname)){ print("===) Finding iterative median zero offsets for the images...") del ("_zero.file.tmp?", ver-, >& "dev$null") del ("_avg.file.tmp", ver-, >& "dev$null") # first find iterative median of each image if(!access(sstatfile)){ if(maskedstat){ iterstat.nsigrej=5. iterstat.maxiter=10 maskstat("@"//ccomblist1,"!BPM",1,lower=INDEF,upper=INDEF,iterstat+,ver-,printit+, >> "_zero.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_zero.file.tmp1", sstatfile, ver-) } else { iterstat("@"//ccomblist1,nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print+,ver-, >> "_zero.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_zero.file.tmp1", sstatfile, ver-) } } else { if(sstatfile!="_nonexistentFILEname_")print("Using statistics from"//sstatfile) copy(sstatfile, "_zero.file.tmp1", ver-) } # next find the overall average of the means fields ("_zero.file.tmp1", 5, >> "_zero.file.tmp2") type ("_zero.file.tmp2" | average opt="new_sample", >> "_avg.file.tmp") # now compute the offset of each image from the overall average mean list="_avg.file.tmp" while (fscan (list, avg, sig, num) !=EOF) { lintran("_zero.file.tmp2",min=2,x2=avg,yfield=1,angle=180, >> zzeroname) } del ("_zero.file.tmp?", ver-) del ("_avg.file.tmp", ver-) } # now insert into image headers if desired if(pputzero) { if(access("_tmp.zzeroing"))del("_tmp.zzeroing",ver-) join(ccomblist1,zzeroname,out="_tmp.zzeroing") list="" list="_tmp.zzeroing" while (fscan (list, img, zf) !=EOF) { hedit(img,wwordzero,zf,add+,ver-,show-,update+) } del("_tmp.zzeroing",ver-,>&"dev$null") } } list="" # DETERMINE WEIGHTS IF NEEDED AND ADD TO IMAGE HEADERS IF DESIRED if(checkweight=="@"){ if(!access(wweightname)){ print("===) Creating file of optimal exptime/rms**2 weights for the images...") del ("_weight.file.tmp?", ver-, >& "dev$null") del ("_avg.file.tmp", ver-, >& "dev$null") # first find iterative rms of each image #hsel("@"//ccomblist1,"PRESCALE",yes, >> "_weight.file.tmp9") #count("_weight.file.tmp9") | scan (i,j,k) #if(j!=0){ #beep #print("WARNING! At least one image in "//ccomblist//" was pre-scaled;") #print("thus, the image weights being calculated will be erroneous.") #} if(!access(sstatfile)){ if(maskedstat){ iterstat.nsigrej=5. iterstat.maxiter=10 if(!access("_weight.file.tmp1"))maskstat("@"//ccomblist1,"!BPM",1,lower=INDEF,upper=INDEF,iterstat+,ver-,printit+, >> "_weight.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_weight.file.tmp1", sstatfile, ver-) } else { if(!access("_weight.file.tmp1"))iterstat("@"//ccomblist1,nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print+,ver-, >> "_weight.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_weight.file.tmp1", sstatfile, ver-) } } else { copy (sstatfile, "_weight.file.tmp1", ver-) } fields ("_weight.file.tmp1", 3, >> "_weight.file.tmp2") # get the exptimes for the images hsel("@"//ccomblist1,eexpname,yes, >> "_weight.file.tmp0") join("_weight.file.tmp2","_weight.file.tmp0",out="_weight.file.tmp3") # compute the weights = exptime./(rms**2.) filecalc ("_weight.file.tmp3", "$2/($1*$1)", calctype="real", >> "_weight.file.tmp4") # find the sum of the weights type ("_weight.file.tmp4" | average opt="new_sample",>> "_avg.file.tmp") # normalize by the sum of the weights filecalc ("_weight.file.tmp4", "$1/"//average.sum, calctype="real", >> wweightname) del ("_weight.file.tmp?", ver-) del ("_avg.file.tmp", ver-) } if(pputweight){ if(access("_tmp.wweighting"))del("_tmp.wweighting",ver-) join(ccomblist1,wweightname,out="_tmp.wweighting") list="_tmp.wweighting" while (fscan (list, img, wt) !=EOF) { hedit(img,wwordweight,wt,add+,ver-,show-,update+) } del("_tmp.wweighting",ver-) } } list="" # IF DESIRED, DETERMINE NORMALIZATION FACTORS AND ADD TO IMAGE HEADERS if(getnorm){ print("===) Finding normalization factors (variances) and putting into image headers...") del ("_norm.file.tmp?", ver-, >& "dev$null") # first find iterative rms of each image if(!access(sstatfile)){ if(maskedstat){ iterstat.nsigrej=5. iterstat.maxiter=10 if(!access("_norm.file.tmp1"))maskstat("@"//ccomblist1,"!BPM",1,lower=INDEF,upper=INDEF,iterstat+,ver-,printit+, >> "_norm.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_norm.file.tmp1", sstatfile, ver-) } else { if(!access("_norm.file.tmp1"))iterstat("@"//ccomblist1,nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print+,ver-, >> "_norm.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_norm.file.tmp1", sstatfile, ver-) } } else { copy (sstatfile, "_norm.file.tmp1", ver-) } fields ("_norm.file.tmp1", 3, >> "_norm.file.tmp2") # compute the normalization factor = (rms**2.) filecalc ("_norm.file.tmp2", "$1*$1", calctype="real", >> "_norm.file.tmp4") if(access("_tmp.norm"))del("_tmp.norm",ver-) join(ccomblist1,"_norm.file.tmp4",out="_tmp.norm") list="_tmp.norm" while (fscan (list, img, wt) !=EOF) { hedit(img,nnormname,wt,add+,ver-,show-,update+) } del("_tmp.norm",ver-) del ("_norm.file.tmp?", ver-) } list="" # SUBPIXEL SHIFTING noappend=no # First expand images if subpixel shifting is desired if (mag!=1){ if(!sspshift)sshiftintlist=sshiftexactlist//blk # If output image list already exists, do not append to it if (access(ccomblist2)){ noappend=yes print("WARNING! Output image list "//ccomblist2//" already exists.") print("Any images listed therein will be created if they do not exist,") print("but no image names will be appended to this preexisting file.") } print("===) Expanding images by factor "//mag//" in both directions...") list=ccomblist1 # Go through image list while (fscan (list, img) !=EOF) { fileroot(img,validim+) image=fileroot.root # Do the magnification as long as the image does not already exist or has not # already been rotated/magnified if(!access(image//blk//".imh")){ imgets(image,"ROTATED",>&"dev$null") if(imgets.value=="0"){ # Divide by mag squared to conserve total number of counts in input image. imar(image,"/",mag2,"_"//blk//image,pixt="real",calc="real",ver-) blkrep("_"//blk//image,image//blk,mag,mag) imdel("_"//blk//image,ver-) if(!noappend)print (image//blk, >> ccomblist2) # Now replicate the bad pixel mask, if not already done. imgets(image//blk,"BPMASK",>&"dev$null") if(imgets.value=="0")imgets(image//blk,"BPM",>&"dev$null") oldbp=imgets.value newbp=blk//oldbp if(!access(newbp)){ blkrep(oldbp,newbp,mag,mag) print(newbp//".pl", >> bprotlist) } # Insert the replicated bad pixel mask in the image header hedit(image//blk,"BPMASK",newbp,add+,ver-,show-,update+) hedit(image//blk,"BPM",newbp,add+,ver-,show-,update+) } else { # If input image already rotated, only print a warning. print("WARNING! "//image//".imh already rotated; not rotated again") } } else { # If output image already exists, only print a warning. print("WARNING! "//image//blk//".imh already exists; not overwritten") } # Next image } # # If output subpixel shifts file doesn't exist, create it if(!access(sshiftintlist)) { print("===> Calculating shifts for expanded images...") if (access("tmp"//sshiftintlist))del("tmp"//sshiftintlist,ver-) list="" list=sshiftexactlist # Convert old shifts to new while (fscan (list,xold,yold) != EOF) { xnew=mag*xold ynew=mag*yold print (xnew, ynew, >> "tmp"//sshiftintlist) } # Round off to integer shifts (in units of new pixels, natch). filecalc("tmp"//sshiftintlist,"$1;$2",format="%4.0f %4.0f", >> sshiftintlist) del("tmp"//sshiftintlist,ver-) # If output subpixel shifts file does exist, just print warning } else { if(sshiftintlist==sshiftexactlist//blk)print("WARNING! "//sshiftintlist//" already exists; not overwritten") } # Correction of zero offsets for lower flux/pixel in blkrep'd images, if needed if(!sspscale) { # Zero offsets from list if(checkzero=="@") { if(!access(zzeroname//blk)) { filecalc(zzeroname,"$1/"//mag2,format="%9.7f", >> zzeroname//blk) newzzeroname=zzeroname//blk zzeroname=newzzeroname zzeroing="@"//newzzeroname } } # Zero offsets from header keyword if(checkzero=="!"){ oldzs=mktemp(".oz") newzs=mktemp(".nz") hsel("@"//ccomblist1,wwordzero,yes, >> oldzs) filecalc(oldzs,"$1/"//mag2,format="%9.7f", >> newzs) join(ccomblist2,oldzs,output=newzs) list="" list=newzs while (fscan (list,img,levelzero) != EOF) { hedit(img,wwordzero,levelzero,add+,ver-,show-,update+) } del(oldzs,ver-) del(newzs,ver-) } } # End of subpixel shift option } list="" # INSERT NEW ZERO OFFSETS INTO REPLICATED IMAGE HEADERS IF DESIRED. if(access(ccomblist2) && checkzero=="@"){ if(pputzero) { if(!sspscale && access(zzeroname//blk))zzeroname=zzeroname//blk del("_tmp.zzeroing",ver-,>&"dev$null") join(ccomblist2,zzeroname,out="_tmp.zzeroing") list="_tmp.zzeroing" while (fscan (list, img, zf) !=EOF) { hedit(img,wwordzero,zf,add+,ver-,show-,update+) } del("_tmp.zzeroing",ver-,>&"dev$null") } } list="" # PRE-ZEROING: INCORPORATE ZERO OFFSETS BEFORE IMCOMBINE IF DESIRED if(pprezero){ print("===> Doing zero offsetting prior to imcombine...") # Prevent imcombine from zeroing twice zzeroing="none" # If list of images to coadd doesn't exist, create it! if (!access(ccomblist2))copy(ccomblist1,ccomblist2,ver-) # In case of zero offsets taken from header keyword, make file_of_zeros if(checkzero=="!"){ file_of_zeros=mktemp(".foz") hsel("@"//ccomblist2,wwordzero,yes, >> file_of_zeros) } if(checkzero=="@")file_of_zeros=zzeroname list_of_zeros=mktemp(".loz") join(ccomblist2,file_of_zeros,output=list_of_zeros) if(checkzero=="!")del(file_of_zeros,ver-) # If stacking, and image already exists, do not bother if(sstack && access(sstackimage//".imh")){ print("Not bothering to pre-zero... stacked image already exists.") } else { # Do zero offsetting unless it has already been done list=list_of_zeros while (fscan (list,img,levelzero) != EOF) { imgets(img,"PREZERO",>&"dev$null") if(imgets.value=="0"){ imar(img,"+",levelzero,img,pixt="real",calc="real",ver-) hedit(img,"PREZERO",levelzero,add+,ve-,sho-,updat+,>&"dev$null") } else { print("No action -- image "//img//" already zero-offset by "//imgets.value) } } } } list="" # COADD images # If output coadded image doesn't exist, create it! if (!access(ooutimage//"."//oextimage)){ # If list of images to coadd doesn't exist, create it! if (!access(ccomblist2))copy(ccomblist1,ccomblist2,ver-) if (sstack){ # If output stacked image doesn't exist, create it! if (!access(sstackimage//"."//oextimage)){ print("===) Stacking the images...") imstack("@"//ccomblist2,sstackimage,title="Stacked images listed in "//ccomblist2) } if(nnewmask) { hedit(sstackimage,"BPM",bbadmask,add+,ver-,show-,update+) } print("===) Combining the images...") if (makeavg){ imcombine(sstackimage, ooutimage, sigma=s_sigma, plfile=s_plfile, combine="average", reject="none", project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale=sscaling, zero=zzeroing, weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=s_lthresh, hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=s_rdnoise, gain=s_gain, snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } else{ if (stdpars) { imcombine(sstackimage, ooutimage, sigma="", plfile="", combine="average", reject="ccdclip", project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale=sscaling, zero=zzeroing, weight=wweighting, statsec="", expname=eexpname, lthresh=INDEF, hthresh=INDEF, nlow=1., nhigh=1., nkeep=1., mclip+, lsigma=5., hsigma=5., rdnoise=s_rdnoise, gain=s_gain, snoise="0.", sigscale=s_sigscale, pclip=-0.5, grow=0., logfile='STDOUT', >> llogfile) } else { imcombine(sstackimage, ooutimage, sigma=s_sigma, plfile=s_plfile, combine=s_combine, reject=s_reject, project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale=sscaling, zero=zzeroing, weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=s_lthresh, hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=s_rdnoise, gain=s_gain, snoise=s_snoise, sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } } # Stacked images only: compute correct UNWEIGHTED average exposure time del("tmp_"//ccomblist2,ver-,>&"dev$null") hsel ("@"//ccomblist2,eexpname,yes, >> "tmp_"//ccomblist2) type ("tmp_"//ccomblist2) | average (opt="new_sample") | scan (eexptime,p,b) hedit(ooutimage,eexpname,eexptime,add+,ver-,show-,update+) del("tmp_"//ccomblist2,ver-,>&"dev$null") # if(uunstack)imdel(sstackimage,ver-) } else{ if(nnewmask) { list=ccomblist2 while (fscan (list, img) !=EOF) { imgets(img,"BPMASK",>&"dev$null") if(imgets.value=="0") { imgets(img,"BPM",>&"dev$null") hedit(img,"BPMASK",imgets.value,add+,ver-,show-,update+) hedit(img,"BPM",bbadmask,add+,ver-,show-,update+) } else { hedit(img,"BPM",bbadmask,add+,ver-,show-,update+) } } } print("===) Combining the images...") if (makeavg){ imcombine("@"//ccomblist2, ooutimage, sigma=s_sigma, plfile=s_plfile, combine="average", reject="none", project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale=sscaling, zero=zzeroing, weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=s_lthresh, hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=s_rdnoise, gain=s_gain, snoise=s_snoise, sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } else{ if (stdpars) { imcombine("@"//ccomblist2, ooutimage, sigma="", plfile="", combine="average", reject="ccdclip", project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale=sscaling, zero=zzeroing, weight=wweighting, statsec="", expname=eexpname, lthresh=INDEF, hthresh=INDEF, nlow=1., nhigh=1., nkeep=1., mclip+, lsigma=5., hsigma=5., rdnoise=s_rdnoise, gain=s_gain, snoise="0.", sigscale=0.1, pclip=-0.5, grow=0., logfile='STDOUT', >> llogfile) } else { imcombine("@"//ccomblist2, ooutimage, sigma=s_sigma, plfile=s_plfile, combine=s_combine, reject=s_reject, project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale=sscaling, zero=zzeroing, weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=s_lthresh, hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=s_rdnoise, gain=s_gain, snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } } } list="" # Put original BPM back if necessary if(nnewmask) { list=ccomblist2 while (fscan (list, img) !=EOF) { imgets(img,"BPMASK",>&"dev$null") hedit(img,"BPM",imgets.value,add+,ver-,show-,update+) } } list="" # Header parameters for the coadded image hedit(ooutimage,"title","Coadded image from "//ccomblist2//" and "//sshiftintlist,ver-,show-,update+) time | scan (theadline) addcomment(ooutimage,"phat.optcoadd: "//theadline,ver-) addcomment(ooutimage,"Coadded from "//ccomblist2//" and "//sshiftintlist,ver-) addcomment(ooutimage,"makeavg="/makeavg//", zero shifts from "//zzeroing,ver-) addcomment(ooutimage,"scaling factors from "//sscaling//", and stdpars="//stdpars,ver-) # AIRMASS # Set airmass of coadded image to effective airmass if default scaling !used if(!ddefscale){ del("_airmass.tmp?",ver-,>&"dev$null") hsel("@"//ccomblist2, "airmass", yes, >> "_airmass.tmp1") type("_airmass.tmp1" | average opt="new_sample", >> "_airmass.tmp2") effairmass=real(average.mean) hedit(ooutimage,"airmass",(effairmass),add+,ver-,show-,update+) del("_airmass.tmp?",ver-,>&"dev$null") # Set airmass of coadded image to reference airmass if default scaling was used } else { hedit(ooutimage,"airmass",(aairzero),add+,ver-,show-,update+) } # EXPOSURE NORMALIZATION -- normalize coadded image to total exposure time. # If weighting was done w/a stacked image, first find correct WEIGHTED exptime del ("_exptime.tmp?", ver-, >& "dev$null") if(sstack && wweighting!="none"){ # First get individual image exposure times del ("_exptime.tmp?", ver-, >& "dev$null") hsel("@"//ccomblist2,eexpname,yes, >> "_exptime.tmp1") # Join individual image exptimes with weights join("_exptime.tmp1", wweightname, output="_exptime.tmp3") # Calculate individual image weighted exposure times filecalc ("_exptime.tmp3", "$1*$2", calctype="real", >> "_exptime.tmp4") # Calculate correct weighted exposure time type ("_exptime.tmp4" | average opt="new_sample",>> "_exptime.tmp5") # Insert correct weighted exposure time into image header hedit(ooutimage,eexpname,average.sum,add+,ver-,show-,update+) } # First find total exposure time of input images hsel("@"//ccomblist2,eexpname,yes, >> "_exptime.tmp6") type("_exptime.tmp6" | average opt="new_sample", >> "_exptime.tmp7") del ("_exptime.tmp?", ver-, >& "dev$null") unwt_avg_exptime=real(average.mean) eexptime=real(average.sum) # Get output exposure time of coadded image imgets(ooutimage,eexpname) wt_avg_exptime=real(imgets.value) # Insert total exposure time into coadded image header hedit(ooutimage,eexpname,eexptime,add+,ver-,show-,update+) # Multiply coadded image by (total_exposure_time/output_exposure_time) imar(ooutimage, "*", eexptime/wt_avg_exptime, ooutimage) print("", >> llogfile) print("Coadded image multiplied by "//eexptime/wt_avg_exptime//" to bring its flux", >> llogfile) print("in line with the total exposure time of "//eexptime//" s.", >> llogfile) # CREATE WEIGHTED EXPOSURE MAP # Create exposure maps if the output coadded-image exposure map does not exist. # Routine allows for images of different exposure times, sizes, and BPMs, while # creating as few images as possible consistent with meeting those criteria. explist="" if(!access(eexpmap//"."//oextimage)){ # Don't recreate exposure maps to be stacked if stacked expmap image exists if(!sstack || (sstack && !access("exp"//sstackimage//"."//oextimage))) { print("===) Creating exposure maps...") subimgold="_oops" testold=0. test1old=0 test2old=0 expmaskold="" # If list of images to coadd doesn't exist, create it! if (!access(ccomblist2))copy(ccomblist1,ccomblist2,ver-) list=ccomblist2 explist=ccomblist2//"exp" if(access(explist))del(explist,ver-,>&"dev$null") while (fscan (list, img) !=EOF) { # get image parameters: xsize, ysize, exptime, badpixelmask fileroot(img,validim+) imgets(img,"i_naxis1") test1=int(imgets.value) imgets(img,"i_naxis2") test2=int(imgets.value) imgets(img,eexpname) exposure=real(imgets.value) imgets(img,"BPMASK") expmask=str(imgets.value) # if any of those parameters differ from the previous image, need to create a # new exposure map for eventual coadding. if(test1!=test1old || test2!=test2old || exposure!=testold || expmask!=expmaskold) { subimg = mktemp(fileroot.root) print (subimg, >> explist) # imcalc(img,subimg,"im1*0+"//exposure,ver-) imcopy(img,subimg,ver-) imreplace(subimg,exposure,lower=-10000.,upper=INDEF) if(nnewmask)hedit(subimg,"BPM",bbadmask,add+,ver-,show-,update+) test1old=test1 test2old=test2 testold=exposure expmaskold=expmask subimgold=subimg } else { print (subimgold, >> explist) } } } # Create coadded-image exposure map print("===> Creating coadded-image exposure map...") if(sstack) { if(!access("exp"//sstackimage//"."//oextimage)) { print("===> Stacking exposure maps...") imstack("@"//explist,"exp"//sstackimage,title="Stacked exposure maps listed in "//explist) } else { print("Stacked exposure map image already exists-- not overwritten.") } if(nnewmask) { hedit("exp"//sstackimage,"BPM",bbadmask,add+,ver-,show-,update+) } imcombine("exp"//sstackimage, eexpmap, sigma="", plfile="", combine="average", reject="none", project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale="none", zero="none", weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) if(nnewmask) { imgets("exp"//sstackimage,"BPMASK",>&"dev$null") hedit("exp"//sstackimage,"BPM",imgets.value,add+,ve-,sho-,upda+) } if(uunstack)imdel("exp"//sstackimage,ver-) } else { imcombine("@"//explist, eexpmap, sigma="", plfile="", combine="average", reject="none", project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale="none", zero="none", weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } # following line had been commented out; replaced with 2nd line following # imreplace(eexpmap, -99999., lower=INDEF, upper=-10000.) imreplace(eexpmap, -99999., lower=INDEF, upper=-1.) hedit(eexpmap,"title","Weighted exposure map for "//ooutimage,add+,ve-,sho-,updat+) imgets(eexpmap,"ncombine") nncombine=int(imgets.value) if(explist!=""){ imdel("@"//explist, ver-, >& "dev$null") del(explist, ver-, >& "dev$null") } } else { print("Output exposure map already exists-- new one not created.") print("Output exposure map already exists-- new one not created.", >> llogfile) } # SUBTRACT constant background from image and DIVIDE by normalized # WEIGHTED EXPOSURE MAP to get image with globally constant exposure time if(!access(ooutimage//"mask.pl")){ # create mask image with border pixels = 0 whether originally 0 or -99999 imar(eexpmap, "+", "99999.", "j1"//eexpmap, noact-, ver-) imar(eexpmap, "*", "j1"//eexpmap, "j2"//eexpmap, noact-, ver-) imreplace("j2"//eexpmap, 1., lower=0.01, upper=INDEF) imcopy("j2"//eexpmap, ooutimage//"mask.pl", ver-) imdel("j1"//eexpmap, ver-) imdel("j2"//eexpmap, ver-) } maskstat(ooutimage, ooutimage//"mask.pl", 1, lower=INDEF, upper=INDEF, iterstat+, ver-, printit+, >> llogfile) imar(ooutimage, "-", iterstat.mean, ooutimage, ver-, noact-) # imar(eexpmap,"/",wt_avg_exptime,"j1"//eexpmap,ver-,noact-) imar("j1"//eexpmap,"/",ooutimage//"mask.pl","j2"//eexpmap,ver-,noact-,divze=-99999.) imar(ooutimage,"/","j2"//eexpmap//"."//oextimage,ooutimage,ver-,noact-,divze=-99999.) imdel("j?"//eexpmap//"."//oextimage,ver-) # print("Weighted exposure map normalized by "//wt_avg_exptime, >> llogfile) print("and divided into output coadded image.", >> llogfile) # FLIP image over to correct orientation if necessary (N is up, E is left) if(flip){ imcopy(ooutimage//"[-*,*]", ooutimage, ver-) addcomment(ooutimage,"Image has been flipped L-R from orig. orientation",ver-) print("WARNING! Image has been flipped L-R! (i.e. imcopy orig[-*,*] new)") } } else { print("Output coadded image already exists-- coadding not done.") print("Output coadded image already exists-- coadding not done.", >> llogfile) } # NORMALIZATION MAPS # Create normalization maps if the output normalization map does not exist. # Routine allows for images of different exposure times, sizes, and BPMs, while # creating as few images as possible consistent with meeting those criteria. explist="" wtlist="" if(!access(nnormmap//"."//oextimage)){ # Don't recreate normalization maps to be stacked if stacked norm. image exists if(!sstack || (sstack && !access("norm"//sstackimage//"."//oextimage))) { print("===) Creating normalization maps...") subimgold="_oops" wtimgold="_oops" waitold=0. testold=0. test1old=0 test2old=0 expmaskold="" tplimgold="" # If list of images to coadd doesn't exist, create it! if (!access(ccomblist2))copy(ccomblist1,ccomblist2,ver-) list=ccomblist2 explist=ccomblist2//"norm" wtlist=ccomblist2//"wt" if(access(explist))del(explist,ver-,>&"dev$null") if(access(wtlist))del(wtlist,ver-,>&"dev$null") while (fscan (list, img) !=EOF) { # get image parameters: xsize, ysize, weight, norm.factor, badpixelmask fileroot(img,validim+) imgets(img,"i_naxis1") test1=int(imgets.value) imgets(img,"i_naxis2") test2=int(imgets.value) imgets(img,wwordweight) wait=real(imgets.value) imgets(img,nnormname) exposure=real(imgets.value) imgets(img,"BPMASK") expmask=str(imgets.value) imgets(img,"TPLIMG",>&"dev$null") tplimg=str(imgets.value) # if any of those parameters differ from the previous image, need to create a # new normalization map for eventual coadding. if(test1!=test1old || test2!=test2old || wait!=waitold || exposure!=testold || expmask!=expmaskold || tplimg!=tplimgold) { tmpimg = mktemp("_tmp") tmpimg2 = mktemp("_tmp2") subimg = mktemp("_nm") wtimg = mktemp("_wt") print (subimg, >> explist) print (wtimg, >> wtlist) # want to end up with wtimg = wait or -99999.; # subimg = exposure * (tpl**2.) * wait**2. or -99999.; # make tmpimg -99999 where img < -10000, 0 elsewhere imcopy(img,tmpimg,ver-) imreplace(tmpimg,0.,lower=-10000.,upper=INDEF) imreplace(tmpimg,-99999.,lower=INDEF,upper=-9999.) # make wtimg 0 where img < -10000, "wait" elsewhere imar(tmpimg,"+",99999.,wtimg,ver-) imreplace(wtimg,wait,lower=10000.,upper=INDEF) # tpl if(ttpl && access(tplimg)) { tpltmp=mktemp("tpltmp") imgets(tplimg,"i_naxis1") tpl1=int(imgets.value) imgets(tplimg,"i_naxis2") tpl2=int(imgets.value) # if tpl image is not same size as actual image, assume the image has been # copied to subsection of bigger image starting at (1,1), and that the rest of # the image is -99999 (thus no imar(img,"-",img,subimg) needed. (ie 61"+90") if(tpl1!=test1 || tpl2!=test2) { imcopy(img,subimg,ver-) # tpltmp = tmpimg + exposure * (wtimg / tplimg)**2. #imcalc(tmpimg//","//wtimg//","//tplimg,tpltmp,"im1+"//str(exposure)//"*(im2/im3)**2.",ver-) imcalc(wtimg//","//tplimg,tmpimg2,str(exposure)//"*(im1/im2)**2.",ver-) imar(tmpimg, "+", tmpimg2, tpltmp, ver-, noact-) imcopy(tpltmp, subimg//"[1:"//str(tpl1)//",1:"//str(tpl2)//"]", ver-) imdel(tmpimg2, ver-) imdel(tpltmp, ver-) } else { # subimg = tmpimg + exposure * (wtimg / tplimg)**2. #imcalc(tmpimg//","//wtimg//","//tplimg,subimg,"im1+"//str(exposure)//"*(im2/im3)**2.",ver-) imcalc(wtimg//","//tplimg,tmpimg2,str(exposure)//"*(im1/im2)**2.",ver-) imar(tmpimg,"+",tmpimg2,subimg,ver-,noact-) imdel(tmpimg2,ver-) } # no tpl } else { # subimg = tmpimg + exposure * wtimg**2. (exposure=exptime or variance) imcalc(wtimg,tmpimg2,"(im1**2.)*"//str(exposure),ver-) imar(tmpimg,"+",tmpimg2,subimg,ver-,noact-) imdel(tmpimg2,ver-) } # now make wtimg -99999 where img < -10000, "wait" elsewhere # tmpimg2 = mktemp("_tmp2") imren(wtimg,tmpimg2,ver-) imar(tmpimg2,"+",tmpimg,wtimg,ver-) imdel(tmpimg2,ver-) imdel(tmpimg,ver-) if(nnewmask)hedit(wtimg,"BPM",bbadmask,add+,ver-,show-,update+) if(nnewmask)hedit(subimg,"BPM",bbadmask,add+,ver-,show-,update+) test1old=test1 test2old=test2 tplimgold=tplimg waitold=wait testold=exposure expmaskold=expmask subimgold=subimg wtimgold=wtimg } else { print (subimgold, >> explist) print (wtimgold, >> wtlist) } } } # Create coadded-image normalization map # First create variance map print("===> Creating coadded-image normalization map...") if(sstack) { if(!access("norm"//sstackimage//"."//oextimage)) { print("===> Stacking variance maps...") imstack("@"//explist,"norm"//sstackimage,title="Stacked normalization maps listed in "//explist) } else { print("Stacked variance map image already exists-- not overwritten.") } if(nnewmask) { hedit("norm"//sstackimage,"BPM",bbadmask,add+,ver-,show-,updat+) } if(access("junknorm."//oextimage))imdel("junknorm."//oextimage,ver-) if(access(nnormmap//"pl.pl"))imdel(nnormmap//"pl.pl",ver-) imcombine("norm"//sstackimage, "junknorm", sigma="", plfile=nnormmap//"pl", combine="average", reject="none", project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale="none", zero="none", weight="none", statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) if(nnewmask){ imgets("norm"//sstackimage,"BPMASK",>&"dev$null") hedit("norm"//sstackimage,"BPM",imgets.value,ad+,ve-,sho-,upda+) } if(uunstack)imdel("norm"//sstackimage,ver-) } else { if(access("junknorm."//oextimage))imdel("junknorm."//oextimage,ver-) if(access(nnormmap//"pl.pl"))imdel(nnormmap//"pl.pl",ver-) imcombine("@"//explist, "junknorm", sigma="", plfile=nnormmap//"pl", combine="average", reject="none", project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale="none", zero="none", weight="none", statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } if(explist!=""){ imdel("@"//explist, ver-, >& "dev$null") del(explist, ver-, >& "dev$null") } # Now create weight map if(sstack) { if(!access("wt"//sstackimage//"."//oextimage)) { print("===> Stacking weight maps...") imstack("@"//wtlist,"wt"//sstackimage,title="Stacked weight maps listed in "//wtlist) } else { print("Stacked weight map image already exists-- not overwritten.") } if(nnewmask) { hedit("wt"//sstackimage,"BPM",bbadmask,add+,ver-,show-,updat+) } if(access("junkweight."//oextimage))imdel("junkweight."//oextimage,ver-) imcombine("wt"//sstackimage, "junkweight", sigma="", plfile="", combine="average", reject="none", project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale="none", zero="none", weight="none", statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) if(nnewmask){ imgets("wt"//sstackimage,"BPMASK",>&"dev$null") hedit("wt"//sstackimage,"BPM",imgets.value,add+,ve-,sho-,upda+) } if(uunstack)imdel("wt"//sstackimage,ver-) } else { if(access("junkweight."//oextimage))imdel("junkweight."//oextimage,ver-) imcombine("@"//wtlist, "junkweight", sigma="", plfile="", combine="average", reject="none", project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale="none", zero="none", weight="none", statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } if(wtlist!=""){ imdel("@"//wtlist, ver-, >& "dev$null") del(wtlist, ver-, >& "dev$null") } # Final steps to create normalization image imgets("junknorm","ncombine") nncombine=int(imgets.value) if(access(nnormmap//"num."//oextimage))imdel(nnormmap//"num."//oextimage,ver-) imar(nnormmap//"pl","-",nncombine,nnormmap//"num.imh") imar(nnormmap//"num.imh","*",-1.,nnormmap//"num.imh") imar("junknorm","*",nnormmap//"num.imh","junknorm",ver-,noact-) imar("junkweight","*",nnormmap//"num.imh","junkweight",ver-,noact-) #imar("junkweight","*",eexpmap,"junkweight",ver-,noact-) #imar("junkweight","*","junkweight","junkweight",ver-,noact-) #imar("junkweight","/","junknorm",nnormmap,ver-,noact-) imcalc("junkweight,"//eexpmap//",junknorm",nnormmap,"((im1*im2)**2.)/im3",nullval=0.,ver-) minmax(nnormmap,force+,update+,ver-) imar(nnormmap,"/",minmax.maxval,nnormmap,ver-,noact-) hedit(nnormmap,"title","Normalization map for "//ooutimage,add+,ve-,sho-,updat+) imdel("junkweight."//oextimage,ver-) imdel("junknorm."//oextimage,ver-) imdel(nnormmap//"num.imh",ver-) imdel(nnormmap//"pl.pl",ver-) if(flip){ imcopy(nnormmap//"[-*,*]", nnormmap, ver-) addcomment(nnormmap,"Image has been flipped L-R from orig. orientation",ver-) } } else { print("Output normalization map already exists-- new one not created.") print("Output normalization map already exists-- new one not created.", >> llogfile) } # UNDO PRE-ZEROING: if zeroing was done before imcombine, undo it if desired if(pprezero && uunzero){ # If block-replication was done, skip step if those images are to be deleted if(mag!=1 && ccleanup && !noappend){ print("", >> llogfile) } else { print("===> Undoing zero offsetting...") list=list_of_zeros while (fscan (list,img,levelzero) != EOF) { imgets(img,"PREZERO",>&"dev$null") if(imgets.value!="0"){ tmpzero=real(imgets.value) imar(img,"-",tmpzero,img,pixt="real",calc="real",ver-) hedit(img,"PREZERO",del+,ver-,show-,updat+,>&"dev$null") } else { print("No action -- "//img//" not pre-zeroed in the first place!") } } } } if(pprezero){ if(sstack && access(sstackimage//"."//oextimage)){print("", >> llogfile)} else{del(list_of_zeros,ver-,>&"dev$null")} } list="" # UNDO PRE-SCALING: if scaling was done before imcombine, undo it if desired if(pprescale && uunscale){ # If block-replication was done, skip step if those images are to be deleted if(mag!=1 && ccleanup && !noappend){ print("", >> llogfile) } else { print("===> Undoing scaling factors...") list=list_of_scales while (fscan (list,img,sf) != EOF) { imgets(img,"PREZERO",>&"dev$null") if(imgets.value!="0"){ print("WARNING! "//img//" still pre-scaled: pre-zeroing not undone first") } else { imgets(img,"PRESCALE",>&"dev$null") if(imgets.value!="0"){ imar(img,"/",sf,img,pixt="real",calct="real",ver-) hedit(img,"PRESCALE",del+,ver-,sho-,updat+,>&"dev$null") if(ddefscale){ imgets(img,"AIRMOLD",>&"dev$null") hedit(img,"AIRMASS",imgets.value,add+,del-,ver-,sho-,updat+,>&"dev$null") hedit(img,"AIRMOLD",del+,ver-,sho-,updat+,>&"dev$null") } } else { print("No action -- "//img//" not pre-scaled in the first place!") } } } } } if(pprescale)del(list_of_scales,ver-,>&"dev$null") list="" # IMSHIFTS FILE # Create *.imshifts file, listing images & offsets used by masklet & photcheck if (!access(ooutimage//".imshifts")) { print("===> Creating output imshifts file...") if (!access(ccomblist2))copy(ccomblist1,ccomblist2,ver-) join(ccomblist2,sshiftintlist,output=ooutimage//".imshifts_tmp") # Find minimum x and y shift values and subtract them from output offsets listimshift=ooutimage//".imshifts_tmp" list="" list=listimshift xmin=100000 ymin=100000 while (fscan (list,img,newx,newy) != EOF) { if (newx < xmin) { xmin = newx } if (newy < ymin) { ymin = newy } } newx=0 newy=0 list="" list=listimshift while (fscan (list,img,oldx,oldy) != EOF) { newx = oldx - xmin newy = oldy - ymin print(img, " ", newx, newy, >> ooutimage//".imshifts") } del(ooutimage//".imshifts_tmp",ver-) } else { print("Output imshifts file already exists-- not overwritten.") } # Clean up. if(mag!=1){ if(ccleanup && !noappend){ if(access(bprotlist)){ imdel("@"//bprotlist,ver-,>&"dev$null") del(bprotlist,ver-,>&"dev$null") } if(access(ccomblist2))imdel("@"//ccomblist2,ver-,>&"dev$null") del(ccomblist2,ver-,>&"dev$null") del(sshiftexactlist//blk,ver-,>&"dev$null") del(zzeroname//blk,ver-,>&"dev$null") } } else { del(ccomblist2,ver-,>&"dev$null") } print(" ") print(ooutimage//", "//eexpmap//" (exposure map), imshifts file,") print("and "//nnormmap//" (normalization map) have been created.") #print("Next task is `mkobjmask' or `photcheck'.") } else { print("WARNING: tasks stsdas.toolbox.imgtools.imcalc, addcomment,") print("filecalc, fileroot, and/or iterstat are not loaded!") print("Please load the appropriate package(s) and restart this task.") } list="" print(" ") beep end phat_alone/src/irtfcoadd_2.p100644 1332 567 570 6427031100 15300 0ustar hallast_hyee#!/usr/local/bin/perl # cycle thru contents of file(s) given on command line using <> $iter=0; while (<>) { # skip blank lines or lines with # as first non-whitespace character next if (/^\s+$/ or /^#/ or /^\s+#/); if($iter==0) { ($avg, $rms, $num) = split " "; } else { ($one) = split " "; $out=$one/$avg; print "$out\n"; } $iter=1; } phat_alone/src/patpostproc.cl100644 1332 567 1004 6171341052 15654 0ustar hallast_hyee#patpostproc.cl -- get stats for and display a new CCD image procedure patpostproc(image) string image {prompt="Image to get stats for and display"} int frame {1,min=1,max=4,prompt="Frame in which to display image"} begin string iimage int fframe, ival iimage=image fframe=frame imget(iimage,"insfilte", >& "dev$null") ival=int(imgets.value) if (ival==0) { display(iimage, fframe) } else { display(iimage, fframe) hedit(iimage,"filters","(insfilte)",add+,ver-,show+,update+) } imstat(iimage) end phat_alone/src/shiftnadd.cl100644 1332 567 42756 6275746151 15323 0ustar hallast_hyee#shiftnadd.cl--script to find offsets for a set of CCD images and coadd them. # # Procedure: # 1. Choose one image (which all images overlap) to be the reference image. # 2. imexam the reference image & get the coordinates (using 'r' or 'a') of # ALL REFERENCE OBJECTS that are to be used. # 3. imexam all the images and get the coordinates (using 'r' or 'a' and 'n' # to go to the next image) of ONLY THE BRIGHTEST or "BEST" reference object # in each. # 4. You are asked for the X and Y coordinates of this "BEST" reference object. # the coords file is printed to jog your memory. # 5. lintran is used to calculate the coarse shifts from just the "BEST" object # 6. The coarse shifts are used as input to imcentroid, which finds the final # offsets using ALL reference objects available. The imcentroid parameters # (e.g. boxsize) can be adjusted if deemed necessary. # # Output: # prefix.refcoords.outstring registration objects' reference image coords # prefix.allcoords.outstring registration objects' coordinates in all images # prefix.coarse.outstring coarse shifts # prefix.shiftnadd.outstring final shifts, imcombine log, & misc. other info # prefix.shiftfrac.outstring fractional part of final shifts # prefix.shiftint.outstring integer part of final shifts # prefix.roundoff.outstring final shifts rounded off to integer shifts # coaddname.imh coadded image # # CHANGES: # 94/12/28: created from irshift.cl # 95/01/27: added check for ctio package # 95/03/21: started to add in exposure map stuff, many other changes # 96/07/12: added output "shiftexact" file # 96/07/22: added default airmass scaling option # 96/07/23: fixed edge problem in sky-subracted image procedure shiftnadd(flatlist,refimage,prefix,outstring,fracshift,coaddname,expmap) string flatlist {prompt="List of images for which to find offsets"} string refimage {prompt="Name of (flattened) reference image"} string prefix {prompt="Prefix string for output files"} string outstring {prompt="Suffix string for output files"} bool fracshift {prompt="Create fractional-pixel-offset images? (yes|no)"} string coaddname {prompt="Name for output coadded image"} string expmap {prompt="Name of output exposure map image"} bool airscale {prompt="Use default airmass scaling?"} string shiftlist {prompt="List of output, offset images",mode="q"} real extcoeff {prompt="Extinction coefficient for default scalings",mode="q"} real airzero {INDEF,min=0.,max=99.,prompt="Airmass to scale to? (INDEF=min. observed)",mode="q"} bool combdata=no {prompt="Combine shifts with earlier dataset? (yes|no)"} string expname="exptime" {prompt="Header keyword for exposure time"} int xref {prompt="Reference object x coordinate (nearest integer)"} int yref {prompt="Reference object y coordinate (nearest integer)"} real xshiftold {prompt="Reference image x shift in earlier dataset"} real yshiftold {prompt="Reference image y shift in earlier dataset"} real radius=5. {prompt="Aperture photometry radius for imexamine"} real buffer=10. {prompt="Aperture photometry sky buffer for imexamine"} real width=10. {prompt="Aperture photometry sky annulus width for imexamine"} real bs=9. {prompt="Centering box size for final shift calculation"} bool doshift=yes {prompt="Do offset measuring step?"} bool stdpars=yes {prompt="Use std imcombine parameters for coadd?"} bool makeavg=no {prompt="Make pure coadd (comb=average,rej=none)?"} pset addpars {prompt="Imcombine parameters"} struct *list begin string subimg, explist, sect, check, img, eexpname, eexpmap, listimshift string subimgold, rrefimage, fflatlist, rrefcoords, aallcoords, rroundname string sshiftlist, coarsefile, ooffname, ooutstring, iintname, ffracname string pprefix, logoffname, ccoaddname, sl, sx, coaddlist, offsetlist string t_sigma, t_plfile, t_combine, t_reject, t_offsets, t_masktyp string t_scale, t_weight, t_zero, t_statsec, t_expname, file_of_air real t_maskval, t_blank, t_lthresh, t_hthresh, t_nlow, t_nhigh, t_nkeep real t_lsigma, t_hsigma, t_rdnoise, t_gain, t_pclip, t_grow, t_sigscale real weight, scalemed, stcoordx, stcoordy, nrows, ncols real xold, yold, bbs, xxshiftold, yyshiftold, xshiftnew, yshiftnew, astcoordx real astcoordy, avg, x, sig, nl, nx, y, eextcoeff, aairzero, air, texp real effairmass, wtavg, nncombine, exp, exposure, sf, zf, testold, eexptime int xmin, ymin, newx, newy, oldx, oldy, test1, test1old, test2, test2old, p int sstartno, eendno, i, numpix, num, xdim, ydim, newxsize, newysize, ncoadds bool ffracshift, ccombdata, go, dosh, aairscale fflatlist = flatlist rrefimage = refimage pprefix = prefix ooutstring = outstring ffracshift = fracshift if(ffracshift){ sshiftlist = shiftlist } ccoaddname = coaddname eexpmap = expmap if(eexpmap==""){ fileroot(ccoaddname,validim+) eexpmap=fileroot.root//"em" } aairscale=airscale eextcoeff=0. aairzero=100. if(aairscale){ eextcoeff=extcoeff aairzero=airzero if(aairzero==INDEF){ print("...one moment please...") file_of_air=mktemp("foa") hsel("@"//fflatlist,"AIRMASS",yes, >> file_of_air) list=file_of_air aairzero=100. while (fscan (list,air) != EOF) { aairzero=min(air,aairzero) } del(file_of_air,ver-,>&"dev$null") list="" } } ccombdata = combdata eexpname = expname bbs = bs #print("test1") #Do not let task run if needed tasks are not loaded go=yes if(!deftask("filecalc")){go=no} if(!deftask("fileroot")){go=no} if(!deftask("imcalc")){go=no} if(!deftask("iterstat")){go=no} if(go){ ooffname = pprefix//".shiftexact."//ooutstring logoffname = pprefix//".shiftnadd."//ooutstring rrefcoords = pprefix//".refcoords."//ooutstring aallcoords = pprefix//".allcoords."//ooutstring coarsefile = pprefix//".coarse."//ooutstring iintname = pprefix//".shiftint."//ooutstring ffracname = pprefix//".shiftfrac."//ooutstring rroundname = pprefix//".roundoff."//ooutstring t_sigma = j_sigma # imcombine parameters t_plfile = j_plfile t_combine = j_combine t_reject = j_reject t_masktyp = j_masktyp t_maskval = j_maskval t_blank = j_blank t_scale = j_scale t_weight = j_weight t_zero = j_zero t_statsec = j_statsec t_expname = j_expname t_lthresh = j_lthresh t_hthresh = j_hthresh t_nlow = j_nlow t_nhigh = j_nhigh t_nkeep = j_nkeep t_lsigma = j_lsigma t_hsigma = j_hsigma t_rdnoise = j_rdnoise t_gain = j_gain t_sigscale = j_sigscale t_pclip = j_pclip t_grow = j_grow if(doshift){ if(ccombdata){ print(" ") print("===) So you wanna add some new images to an old coadd, eh? Well, first make") print("===) sure you're using the same reference image as that old set. Then, take") print("===) a look at the *.shiftnadd.* file from that set, find the fractional") print("===) offsets made on the reference image, and enter them here:") xxshiftold=xshiftold yyshiftold=yshiftold } print(" ") print("===) Get the coordinates, in the reference image, of all objects you wish to") print(" use for registration, starting with the `best' reference object-- one") print(" which appears in all images.") print(" ") rimexam.radius=radius rimexam.buffer=buffer rimexam.width=width imexam(rrefimage, frame=1, logfile=rrefcoords, keep+) #Interactively ID objects print(" ") print("===) Choose one object that appears in all images, and find the position") print("===) (type 'a') of this best registration object in each frame (hit 'n' to go on") print("===> to the next frame, and 'q' when done). The file containing these positions") print("===> will be displayed for editing when done, in case mistakes were made.") print(" ") imexam("@"//fflatlist, frame=1, logfile=aallcoords, keep+) print(" ") print("===> In case mistakes were made, the coordinate file can now be edited.") vi(aallcoords) # Find offsets fields (rrefcoords, "1-2") | scan (xref, yref) lintran(aallcoords, x1=0.001, y1=0.001, x2=xref, y2=yref, angle=180, > coarsefile) print("===) Finding the final offsets, and saving to `shiftnadd' file.") del(logoffname, ver-, >& "dev$null") imcentroid("@"//fflatlist, rrefcoords, reference=rrefimage, shift=coarsefile, boxsize=bbs, > logoffname) del("temp.joinfile", ver-, >& "dev$null") del("temp.joinfile?", ver-, >& "dev$null") # read in length of temp.joinfile0 and cut out last two lines copy(logoffname,"temp.joinfile0") count("temp.joinfile0") | scan (nl) nx=nl-2 head("temp.joinfile0", nlines=nx, >> "temp.joinfile1") # find line on which the string "X-s" appears and cut out that line & all before !grep -n X-s temp.joinfile1 > temp.joinfile2 type("temp.joinfile2") | scan (sl) x=stridx(":",sl) sx=substr(sl,1,x) x=nx-real(sx) tail("temp.joinfile1", nlines=x, >> "temp.joinfile") # Cut down on number of output files print(" ", >> logoffname) print("#Coarse offsets:", >> logoffname) print(" ", >> logoffname) type(coarsefile, >> logoffname) del(coarsefile, ver-) if(ccombdata){ # Extract the new reference image shifts from the offsets file del("temp.joinfile?",ver-, >& "dev$null") grep(rrefimage,"temp.joinfile") | fields ("junk", "2", >> "temp.joinfile2") type("temp.joinfile2") | average >> "temp.joinfile3" xshiftnew=real(average.sum) del("temp.joinfile?",ver-) grep(rrefimage,"temp.joinfile") | fields ("junk", "4", >> "temp.joinfile2") type("temp.joinfile2") | average >> "temp.joinfile3" yshiftnew=real(average.sum) del("temp.joinfile?",ver-) # Want to take the calculated shift ($2 for x), cancel out the newly calculated # reference image shift ($2 - xshiftnew = -xnew+$2 = -1*xnew+$2) and add in # the old reference image shift (xold+(-1*xnew+$2) filecalc("temp.joinfile",xxshiftold//"+(-1*"//xshiftnew//"+$2);"//yyshiftold//"+(-1*"//yshiftnew//"+$4)",format="%8.2f%8.2f ", >> ooffname) # filecalc("temp.joinfile",xxshiftold//"+$2;"//yyshiftold//"+$4",format="%8.2f%8.2f ", >> ooffname) } else{ fields("temp.joinfile", "2,4", >> ooffname) } del("temp.joinfile*", ver-) list=ooffname while(fscan(list,x,y) !=EOF) { print(int(x),int(y), >> iintname) } join(iintname,ooffname,out="temp.joinfile") filecalc("temp.joinfile","$3-$1;$4-$2",forma="%6.2f%6.2f", >> ffracname) filecalc(ooffname,"$1;$2",format="%4.0f %4.0f", >> rroundname) print(" ", >> logoffname) print("#Final offsets:", >> logoffname) print(" ", >> logoffname) type(ooffname, >> logoffname) # del(ooffname, ver-) del("temp.joinfile", ver-) # End of "if doshift" } # Find & insert header parameter "SCALEFAC" used by imcombine print("===) Finding scales for coadding images...") file_of_air=mktemp("foa") hsel("@"//fflatlist,"$I,AIRMASS,"//eexpname,yes, >> file_of_air) list=file_of_air while (fscan (list,img,air,texp) != EOF) { imgets(img,"SCALEFAC",>&"dev$null") if(imgets.value=="0"){ sf=10**(0.4*eextcoeff*(air-aairzero)) hedit(img,"AIRSCALE",sf,add+,ver-,show-,update+) sf=texp*sf imgets(img,"scalefac") hedit(img,"SCALEFAC",sf,add+,ver-,show-,update+) } else { print("Image "//img//" already has SCALEFAC header keyword.") } } del(file_of_air,ver-) list="" # Find & insert header parameter "WEIGHT" used by imcombine print("===) Finding weights for coadding images...") list=fflatlist while(fscan(list,img) !=EOF) { imgets(img,"weight",>&"dev$null") if(imgets.value=="0"){ iterstat(img,nsigrej=5.,maxiter=10,print-,ver-) imgets(img,t_expname) weight=iterstat.median*real(imgets.value) hedit(img,"weight",weight,add+,ver-,show-,update+) } } list="" if(ffracshift){ print("===) Creating fractional-pixel-shifted images.") sshiftlist=fflatlist//ooutstring list=fflatlist while(fscan(list,img) !=EOF) { fileroot(img,validim+) print(fileroot.root//ooutstring//".imh",>>sshiftlist) } imshift("@"//fflatlist, "@"//sshiftlist, shifts=ffracname, interp="poly5", bound="nearest") } if(!access(eexpmap//".imh")){ print("===) Shifting and coadding the images.") if(ffracshift){ coaddlist=sshiftlist offsetlist=iintname } else { coaddlist=fflatlist offsetlist=rroundname } if (makeavg) { imcombine("@"//coaddlist, ccoaddname, sigma="", plfile="", combine="average", rej="none", project-, offsets=offsetlist, masktype="none", blank=0., scale="!SCALEFAC", zero="mode", weight="!WEIGHT", statsec="", expname=t_expname, lthresh=-100000, hthresh=100000, lsig=5., hsig=5., nkeep=1, mclip+, rdnoise=t_rdnoise, gain=t_gain, sigscale=0.1, grow=0., logfile='STDOUT', >> logoffname) } else { if(stdpars){ imcombine("@"//coaddlist, ccoaddname, sigma="", plfile="", combine="average", rej="ccdclip", project-, offsets=offsetlist, masktype="none", blank=0., scale="!SCALEFAC", zero="mode", weight="!WEIGHT", statsec="", expname=t_expname, lthresh=-100000, hthresh=100000, lsig=5., hsig=5., nkeep=1, mclip+, rdnoise=t_rdnoise, gain=t_gain, sigscale=0.1, grow=0., logfile='STDOUT', >> logoffname) } else{ imcombine("@"//coaddlist, ccoaddname, sigma=t_sigma, plfile=t_plfile, combine=t_combine, reject=t_reject, project-, offsets=offsetlist, masktype=t_masktyp, maskvalue=t_maskval, blank=t_blank, scale=t_scale, zero=t_zero, weight=t_weight, statsec=t_statsec, expname=t_expname, lthresh=t_lthresh, hthresh=t_hthresh, nlow=t_nlow, nhigh=t_nhigh, nkeep=t_nkeep, mclip+, lsigma=t_lsigma, hsigma=t_hsigma, rdnoise=t_rdnoise, gain=t_gain, sigscale=t_sigscale, pclip=t_pclip, grow=t_grow, logfile='STDOUT', >> logoffname) } } hedit(ccoaddname,"title","Coadded image from "//coaddlist//" using "//offsetlist,add+,ver-,show-,update+) iterstat(ccoaddname,nsigrej=5.,maxiter=10.,print-,ver-) fileroot(ccoaddname,validim+) imar(ccoaddname,"-",iterstat.median,fileroot.root//"sub",title="Sky-subtracted version of "//ccoaddname,ver-) # Set airmass of coadded image to "effective airmass" if(access(coaddlist//".airmass.tmp"))del(coaddlist//".airmass.tmp",ver-) if(access(coaddlist//".airmass.tmp2"))del(coaddlist//".airmass.tmp2",ver-) hsel("@"//coaddlist, "airmass", "yes", >> coaddlist//".airmass.tmp") type(coaddlist//".airmass.tmp" | average opt="new_sample", >> coaddlist//".airmass.tmp2") effairmass=real(average.mean) hedit(ccoaddname,"airmass",(effairmass),add+,ver-,show-,update+) del (coaddlist//".airmass.tmp*", ver-) } else{ print("Output coadded image already exists-- new one not created.") } # Create exposure maps if the output coadded-image exposure map does not exist. # The routine should allow for images of different exposure times and sizes, # while at the same time cutting down on the number of images that need to be # created if many input images have the same size and exposure time. if(!access(eexpmap//".imh")){ print("===) Creating exposure maps...") subimgold="_oops" testold=0. test1old=0 test2old=0 list=coaddlist explist=coaddlist//"exp" while (fscan (list, img) !=EOF) { fileroot(img,validim+) imgets(img,"i_naxis1") test1=int(imgets.value) imgets(img,"i_naxis2") test2=int(imgets.value) imgets(img,eexpname) exposure=real(imgets.value) if(test1!=test1old || test2!=test2old || exposure!=testold) { subimg = mktemp(fileroot.root) print (subimg, >> explist) imcalc(img,subimg,"im1*0+"//exposure,ver-) test1old=test1 test2old=test2 testold=exposure subimgold=subimg } else { print (subimgold, >> explist) } } # Create coadded-image exposure map print("===> Creating coadded-image exposure map...") imcombine("@"//explist, "junk"//eexpmap, sigma="", plfile=eexpmap//"pl", combine="average", reject="none", project-, offsets=rroundname, masktype="none", scale="none", zero="none", weight="none", expname=eexpname, mclip+, logfile='STDOUT', >> logoffname) imgets("junk"//eexpmap,"ncombine") nncombine=int(imgets.value) imdel("junk"//eexpmap, ver-, >& "dev$null") imdel("@"//explist, ver-, >& "dev$null") del(explist, ver-) # Following should yield accurate exposure map. We use the plfile from the # above imcombining, not the actual imcombined image. # Step 1: just to be safe, get rid of any possible negative values imreplace(eexpmap//"pl",0.,lower=INDEF,upper=0.) # Step 2: Since the plfile lists # images *not* used, we subtract total # images imar(eexpmap//"pl","-",nncombine,eexpmap//".imh") # Step 3: Then multiplying by -1 gives # of images used (positive quantity) imar(eexpmap,"*",-1.,eexpmap) imdel(eexpmap//"pl.pl",ver-) hedit(eexpmap,"title","Exposure map image for coadded image "//ccoaddname,ver-,show-,update+) } else{ print("Output exposure map already exists-- new one not created.") } # Create *.imshifts file, listing images & offsets used by masklet task print("===> Creating output imshifts file...") join(coaddlist,rroundname,output=ccoaddname//".imshiftt_tmp") # Find minimum x and y shift values and subtract them from output offsets listimshift=ccoaddname//".imshiftt_tmp" list=listimshift xmin=100000 ymin=100000 while (fscan (list,img,newx,newy) != EOF) { if (newx < xmin) { xmin = newx } if (newy < ymin) { ymin = newy } } newx=0 newy=0 list=listimshift while (fscan (list,img,oldx,oldy) != EOF) { newx = oldx - xmin newy = oldy - ymin print(img, " ", newx, newy, >> ccoaddname//".imshifts") } del(ccoaddname//".imshiftt_tmp",ver-) # Set edges of sky-subtracted image to zero. fileroot(ccoaddname,validim+) imar(fileroot.root//"sub","*",eexpmap,fileroot.root//"sub") imar(fileroot.root//"sub","/",eexpmap,fileroot.root//"sub",divzero=0.) print("===> All done. *sub.imh can be used with mkobjmask.") } else{ print("WARNING: task(s) filecalc, fileroot, imcalc and/or iterstat are not") print("loaded! Please load the unloaded task(s) and restart this task.") } beep end phat_alone/src/strrev.cl100644 1332 567 1036 6171341054 14632 0ustar hallast_hyeeprocedure strrev(forward) # Routine to parse a string into its reverse. string forward {prompt="Input string") string reverse {"",prompt="Reversed string") begin string fname # Equals filename string revname # Reversed version of input string int ilen,ipos,ic # String position markers # Get query parameter. fname = forward # Reverse filename string character by character --> revname. ilen = strlen(fname) revname = "" for (ic=ilen; ic>=1; ic-=1) { revname = revname // substr(fname,ic,ic) } reverse = revname end phat_alone/src/swap.cl100644 1332 567 454 6207451246 14247 0ustar hallast_hyee#Swap the contents of two files procedure swap(file1,file2) string file1 {prompt = "Name of first file"} string file2 {prompt = "Name of second file"} begin rename(file2,"tmpswapdude") rename(file1,file2) rename("tmpswapdude",file1) print("Contents of "//file1//" and "//file2//" swapped.") end phat_alone/src/undel.cl100644 1332 567 454 6171341054 14377 0ustar hallast_hyee#Unprotect and delete a file(s) in one fell swoop procedure undel(file1) string file1 {prompt = "File(s) to unprotect and delete"} bool verify=yes {prompt = "Verify deletion?"} begin bool yesno yesno=verify unprotect(file1) print(file1//" is now unprotected.") delete(file1, verify=yesno) end phat_alone/src/addpars.par100644 1332 567 3205 6173013567 15116 0ustar hallast_hyee#pset imcomcoaddpars {prompt="Imcombine parameters"} j_sigma,s,h,"",,,"IMCOMBINE: Sigma image (optional)" j_plfile,s,h,"",,,"IMCOMBINE: Rejected pixel list image (optional)" j_combine,s,h,"average",average|median,,"IMCOMBINE: Type of combine operation (median|average)" j_reject,s,h,"ccdclip",none|minmax|ccdclip|crreject|sigclip|avsigclip|pclip,,"IMCOMBINE: Type of rejection" j_masktyp,s,h,"none",none|goodvalue|badvalue|goodbits|badbits,,"IMCOMBINE: Mask type" j_maskval,r,h,0.,,,"IMCOMBINE: Mask value" j_blank,r,h,0.,,,"IMCOMBINE: Value if there are no pixels" j_scale,s,h,"exposure",,,"IMCOMBINE: Image scaling" j_weight,s,h,"exposure",,,"IMCOMBINE: Image weights" j_zero,s,h,"none",,,"IMCOMBINE: Image zero point offsets" j_statsec,s,h,"",,,"IMCOMBINE: Image section for computing statistics" j_expname,s,h,"exptime",,,"IMCOMBINE: Image header exposure time keyword" j_lthresh,r,h,INDEF,,,"IMCOMBINE: Lower threshold" j_hthresh,r,h,INDEF,,,"IMCOMBINE: Upper threshold" j_nlow,r,h,1.,0,,"IMCOMBINE: minmax: Number of low pixels to reject" j_nhigh,r,h,1.,0,,"IMCOMBINE: minmax: Number of high pixels to reject" j_nkeep,r,h,-1.,,,"IMCOMBINE: Minimum to keep (+) or maximum to reject(-)" j_lsigma,r,h,5.,0.,,"IMCOMBINE: Lower sigma clipping factor" j_hsigma,r,h,10.,0.,,"IMCOMBINE: Upper sigma clipping factor" j_rdnoise,r,h,7.7,,,"IMCOMBINE: ccdclip: CCD readout noise (electrons)" j_gain,r,h,2.2,,,"IMCOMBINE: ccdclip: CCD gain (electrons/ADU)" j_sigscale,r,h,0.1,0.,,"IMCOMBINE: Tolerance for sig-clip scaling corrections" j_pclip,r,h,-0.5,,,"IMCOMBINE: pclip: Percentile clipping parameter" j_grow,r,h,0.,,,"IMCOMBINE: Radius (pixels) for 1D neighbor rejection" phat_alone/src/optcoaddpars.par100644 1332 567 3014 6353543521 16157 0ustar hallast_hyeei_sigma,s,h,"",,,"IMCOMBINE: Sigma image (optional)" i_plfile,s,h,"",,,"IMCOMBINE: Rejected pixel list image (optional)" i_combine,s,h,"average",average|median,,"IMCOMBINE: Type of combine operation (median|average)" i_reject,s,h,"ccdclip",none|minmax|ccdclip|crreject|sigclip|avsigclip|pclip,,"IMCOMBINE: Type of rejection" i_masktyp,s,h,"badvalue",none|goodvalue|badvalue|goodbits|badbits,,"IMCOMBINE: Mask type" i_maskval,r,h,0.,,,"IMCOMBINE: Mask value" i_blank,r,h,0.,,,"IMCOMBINE: Value if there are no pixels" i_statsec,s,h,"",,,"IMCOMBINE: Image section for computing statistics" i_expname,s,h,"exptime",,,"IMCOMBINE: Image header exposure time keyword" i_lthresh,r,h,INDEF,,,"IMCOMBINE: Lower threshold" i_hthresh,r,h,INDEF,,,"IMCOMBINE: Upper threshold" i_nlow,r,h,1.,0.,,"IMCOMBINE: minmax: Number of low pixels to reject" i_nhigh,r,h,1.,0.,,"IMCOMBINE: minmax: Number of high pixels to reject" i_nkeep,r,h,1.,,,"IMCOMBINE: Minimum to keep (+) or maximum to reject(-)" i_lsigma,r,h,5.,0.,,"IMCOMBINE: Lower sigma clipping factor" i_hsigma,r,h,5.,0.,,"IMCOMBINE: Upper sigma clipping factor" i_rdnoise,s,h,"7.7",,,"IMCOMBINE: ccdclip: CCD readout noise (electrons)" i_gain,s,h,"2.2",,,"IMCOMBINE: ccdclip: CCD gain (electrons/ADU)" i_snoise,s,h,"0.",,,"IMCOMBINE: ccdclip: Sensitivity noise (fraction)" i_sigscale,r,h,0.1,0.,,"IMCOMBINE: Tolerance for sig-clip scaling corrections" i_pclip,r,h,-0.5,,,"IMCOMBINE: pclip: Percentile clipping parameter" i_grow,r,h,0.,,,"IMCOMBINE: Radius (pixels) for 1D neighbor rejection" mode,s,h,"q",,, phat_alone/src/patcopy.cl100644 1332 567 2405 6316401211 14756 0ustar hallast_hyeeprocedure patcopy(oldlist,newlist) string oldlist {prompt="List of original file names"} string newlist {prompt="List of copied file names"} bool verb {yes,prompt="Print names of files as they are copied?"} struct *list begin string ooldlist, nnewlist, errstring, oldname, newname, ooldtemp, nnewtemp, y real x int errflag bool vverb ooldtemp=oldlist nnewtemp=newlist ooldlist=oldlist nnewlist=newlist vverb=verb x=strlen(ooldlist) y=substr(ooldlist,1,1) if(y=="@")ooldlist=substr(ooldlist,2,x) x=strlen(nnewlist) y=substr(nnewlist,1,1) if(y=="@")nnewlist=substr(nnewlist,2,x) del ("tmp.err", ver-, >& "dev$null") del ("tmp.copylist", ver-, >& "dev$null") join (ooldlist, nnewlist, output="tmp.copylist", >& "tmp.err") errflag=0 list="tmp.err" while (fscan (list, errstring) !=EOF) { if (errstring=="WARNING:") errflag=1 } if (errflag==0) { list="tmp.copylist" if(vverb){ while (fscan (list, oldname, newname) !=EOF) { copy (oldname, newname) print (oldname//" --> "//newname) } } else{ while (fscan (list, oldname, newname) !=EOF) { copy (oldname, newname) } } } else { print("WARNING! Number of input files does not match number of output files.") print("No copying done.") } del ("tmp.err", ver-) del ("tmp.copylist", ver-) end phat_alone/src/patrename.cl100644 1332 567 2450 6316401217 15261 0ustar hallast_hyeeprocedure patrename(oldlist,newlist) string oldlist {prompt="List of old file names"} string newlist {prompt="List of new file names"} bool verb {yes,prompt="Print names of files as they are copied?"} struct *list begin string ooldlist, nnewlist, errstring, oldname, newname, ooldtemp, nnewtemp, y real x int errflag bool vverb ooldtemp=oldlist nnewtemp=newlist ooldlist=oldlist nnewlist=newlist vverb=verb x=strlen(ooldlist) y=substr(ooldlist,1,1) if(y=="@")ooldlist=substr(ooldlist,2,x) x=strlen(nnewlist) y=substr(nnewlist,1,1) if(y=="@")nnewlist=substr(nnewlist,2,x) del ("tmp.err", ver-, >& "dev$null") del ("tmp.renamelist", ver-, >& "dev$null") join (ooldlist, nnewlist, output="tmp.renamelist", >& "tmp.err") errflag=0 list="tmp.err" while (fscan (list, errstring) !=EOF) { if (errstring=="WARNING:") errflag=1 } if (errflag==0) { list="tmp.renamelist" if(vverb){ while (fscan (list, oldname, newname) !=EOF) { rename (oldname, newname, field="root") print (oldname//" --> "//newname) } } else{ while (fscan (list, oldname, newname) !=EOF) { rename (oldname, newname, field="root") } } } else { print("WARNING! Number of input files does not match number of output files.") print("No renaming done.") } del ("tmp.err", ver-) del ("tmp.renamelist", ver-) end phat_alone/src/mkrgb.cl100644 1332 567 6544 6362227545 14432 0ustar hallast_hyee# mkrgb -- Make Sun rgb rasterfiles from IRAF images # # -- needs "color" package # -- needs "iterstat" previously run on images, and "zeropt" keyword in headers # (note that "zeropt" has the opposite sign than typ. used in phot. solutions # -- defaults are neg=0 pos=8 magr=19 magg=21 magb=23 log- # # 970712: created by Pat Hall # # -- add in (optional) (interactive) looping procedure mkrgb(red,green,blue,neg,pos,rgb) string red {prompt = "Input image for the red component"} string green {prompt = "Input image for the green component"} string blue {prompt = "Input image for the blue component"} real neg {0,prompt = "Number of sigma for minimum intensity"} real pos {8,prompt = "Number of sigma for maximum intensity"} string rgb {prompt = "Output root name for Sun 24-bit RGB rasterfiles"} real magred {19.,prompt = "Maximum mag/sqarcsec for red-gun image"} real maggreen {21.,prompt = "Maximum mag/sqarcsec for green-gun image"} real magblue {23.,prompt = "Maximum mag/sqarcsec for blue-gun image"} real pixfact {2.6,prompt = "2.5*log10((pixels/arcsec)**2."} bool gogreen {no,prompt = "Independent green-gun image?"} bool orient {yes,prompt = "Preserve orientation of IRAF images?"} bool log {no,prompt = "Use logarithmic intensity mapping?"} #bool interact {prompt = "Interactive parameter adjustment?"} string logfile {"",prompt = "Logfile of rgbsun commands; null string=no logging"} begin string imgred, imgblue, imggreen, rgbroot real sigred, siggreen, sigblue, zpred, zpgreen, zpblue real maxred, maxblue, maxgreen real mag_red, mag_blue, mag_green, negsig, possig if(orient) { imgred=red//"[*,-*]"; imgblue=blue//"[*,-*]"; imggreen=green//"[*,-*]" } else { imgred=red; imgblue=blue; imggreen=green } mag_red=magred; mag_blue=magblue; mag_green=maggreen negsig=neg; possig=pos; rgbroot=rgb print ("If error, check that images have had iterstat previously run on them.") # Faintest-object print hsel (imgred, "itersig", yes) | scan (sigred) hsel (imggreen, "itersig", yes) | scan (siggreen) hsel (imgblue, "itersig", yes) | scan (sigblue) rgbsun (imgred, imggreen, imgblue, rgbroot//"_faint", rz1=negsig*sigred, rz2=possig*sigred, gz1=negsig*siggreen, gz2=possig*siggreen, bz1=negsig*sigblue, bz2=possig*sigblue, logmap=log) if (logfile!="") { print ("rgbsun "//imgred//" "//imggreen//" "//imgblue//" "//rgbroot//"_faint rz1="//negsig*sigred//" rz2="//possig*sigred//" gz1="//negsig*siggreen//" gz2="//possig*siggreen//" bz1="//negsig*sigblue//" bz2="//possig*sigblue//" logmap="//log, >> logfile) } # Common magnitude scale print hsel (imgred, "zeropt", yes) | scan (zpred) hsel (imgblue, "zeropt", yes) | scan (zpblue) maxred=10**(-0.4*(mag_red+pixfact-zpred)) maxblue=10**(-0.4*(mag_blue+pixfact-zpblue)) if (gogreen) { hsel (imggreen, "zeropt", yes) | scan (zpgreen) maxgreen=10**(-0.4*(mag_green+pixfact-zpgreen)) } else { maxgreen=maxred+maxblue } rgbsun (imgred, imggreen, imgblue, rgbroot//"_scale", rz1=0, rz2=maxred, gz1=0, gz2=maxgreen, bz1=0, bz2=maxblue, logmap=log) if (logfile!="") { print ("rgbsun "//imgred//" "//imggreen//" "//imgblue//" "//rgbroot//"_scale rz1=0 rz2="/maxred//" gz1=0 gz2="/maxgreen//" bz1=0 bz2="/maxblue//" logmap="//log, >> logfile) } print("Display "//rgbroot//"_faint and "//rgbroot//"_scale with xview.") if(!orient){ print("Be sure to flip up/down before saving as PostScript") print("to preserve IRAF image orientation.") } beep end phat_alone/src/iteravg.cl100644 1332 567 5206 6352651102 14750 0ustar hallast_hyee#{ AVERAGE -- Compute the average and standard deviation of a list of numbers. # Numeric input is via the standard input (one number per line). The mean, # sigma, and number of samples are written to the standard output. # # By default (Average called with no arguments), the sample is taken # to be the set of numbers in the standard input when Average is run. # Additional points can be added to or deleted from the sample by # rerunning Average with one of the following arguments: # # add - add points to the sample, recalculate mean and sigma # sub - subtract points from the sample { if ($nargs == 0) # if no arguments, don't query opstring = "new_sample" else opstring = option # get parameter "option" if (opstring == "add") # add, subtract, or start over? addsub_flag = 1 else if (opstring == "sub" || opstring == "subtract") addsub_flag = -1 else { # new sample (default) addsub_flag = 1 n = 0 # number of points in sample sum = 0 sumsqrs = 0 variance = 0 sigma = 0 mean = 0 } # Process data and save to temporary file del ("__iteravgtmp", ver-, >& "dev$null") while (scan (data_value) != EOF) if (nscan() == 1 && data_value != INDEF) { n += addsub_flag sum += addsub_flag * data_value sumsqrs += addsub_flag * data_value * data_value print (data_value, >> "__iteravgtmp") } # Iterate iter=0 nold=0 minval=-100000000000000000000 maxval=100000000000000000000 for (iter=0; iter<=maxiter; iter+=1) { list="__iteravgtmp" if(iter>0) { while (fscan (list, data_value) != EOF) { if (data_value != INDEF && data_value<=maxval && data_value>=minval) { n += addsub_flag sum += addsub_flag * data_value sumsqrs += addsub_flag * data_value * data_value } } } # Find mean, var, sig if (n > 1) { mean = sum / n variance = (n * sumsqrs - sum * sum) / (n * (n-1)) if (variance < 0) # possible with roundoff error sigma = 0.0 else sigma = sqrt (variance) } # End loop? if ((n != 0 && n == nold) || iter==maxiter) { iter=maxiter+1 } else { nold=n maxval=mean+nsigrej*sigma minval=mean-nsigrej*sigma n=0 sum=0 sumsqrs=0 mean=0 sigma=0 variance=0 } } #type ("__iteravgtmp", >> "oog") #count ("__iteravgtmp") del ("__iteravgtmp", ver-, >& "dev$null") # print output if (n <= 0) print ("INDEF ", "INDEF ", n) else if (n == 1) print (sum, "INDEF ", 1) else { mean = sum / n variance = (n * sumsqrs - sum * sum) / (n * (n-1)) if (variance < 0) # possible with roundoff error sigma = 0.0 else sigma = sqrt (variance) print (mean, sigma, n) } } phat_alone/src/complete.cl100644 1332 567 62203 6372235746 15155 0ustar hallast_hyeeprocedure complete(image1,image2,image3,untrim1,untrim2,untrim3,mask,sum,color21,color31,mlim1,spacing,nbins,nobjs,nrepeat,pixscale) # complete.cl -- calculate completeness corrections for mosaiced image # # **OUTPUT: comparea_image? and complete_image? where ?=1,2,3 as appropriate # # **REQUIRES packages FOCAS, ARTDATA (mkobjects), CTIO (filecalc), # PHIIRS (fileroot), PHAT (imswap), # **REQUIRES rlambda, ebv, gain, rdnoise, fwhmpix, & zeropt in each image header # **REQUIRES existing image1.cat, image2.cat, image3.cat, & sum.cat # # 970731: working version finally debugged, by Pat Hall. # 970806: added insertion of xyminmax, and fixed minor related inefficiency bug # # **comparea_image? output will be ERRONEOUS unless mag limits input to the # task bracket all mlims which exist in the image(s). # **CANNOT BE RUN IN BATCH MODE due to focas.mfilter/ffilter problem. # # --could replace bright magnitude C(m) with (sum(areas,objs> logname) if(ddis)displ(ssum, 1) #--get Atot, minus border region print ("get total area, minus border region") print ("get total area, minus border region", >> logname) imdel ("tmp_"//msk, ver-, >& "dev$null") addring (msk, "tmp_"//msk, ngrow=bborder, badval=0) imstat ("tmp_"//msk, fields="mean,npix", format-, lower=INDEF, upper=INDEF) | scan(mmean,nnpix) Atot=(mmean*nnpix*ppixscale**2.)/3600. print(Atot, >> logname) print(Atot) imdel ("tmp_"//msk, ver-) #--get xminmax for the field print ("get xminmax for the field", >> logname) imtranspose (msk//"[*,-*]", "tmp_"//msk) minmax ("tmp_"//msk, force+, update-, ver-) s1=minmax.maxpix; x=stridx(",",s1); s2=substr(s1,x+1,strlen(s1)-1) print (s2) | scan (xmin) minmax ("tmp_"//msk//"[*,-*]", force+, update-, ver-) s1=minmax.maxpix; x=stridx(",",s1); s2=substr(s1,x+1,strlen(s1)-1) print (s2) | scan (xmax) hsel ("tmp_"//msk, "i_naxis2", yes) | scan (xlong) xmax=xlong+1-xmax imdel ("tmp_"//msk, ver-) #--get yminmax for the field print ("get yminmax for the field", >> logname) minmax (msk, force+, update-, ver-) s1=minmax.maxpix; x=stridx(",",s1); s2=substr(s1,x+1,strlen(s1)-1) print (s2) | scan (ymin) minmax (msk//"[*,-*]", force+, update-, ver-) s1=minmax.maxpix; x=stridx(",",s1); s2=substr(s1,x+1,strlen(s1)-1) print (s2) | scan (ymax) hsel (msk, "i_naxis2", yes) | scan (ylong) ymax=ylong+1-ymax #--border zones ymin=ymin+bborder; xmin=xmin+bborder ymax=ymax-bborder; xmax=xmax-bborder hedit (msk//","//ssum, "xmin", xmin, add+, ver-, show+, update+) hedit (msk//","//ssum, "ymin", ymin, add+, ver-, show+, update+) hedit (msk//","//ssum, "xmax", xmax, add+, ver-, show+, update+) hedit (msk//","//ssum, "ymax", ymax, add+, ver-, show+, update+) hedit (msk//","//ssum, "border", bborder, add+, ver-, show+, update+) #--copy all imgs to temporary imgs, get galactic extinction for that filter, # find equal skysig scales for tmp imgs, generate random object x,y positions, # match all r(j)k images' catalogs plus the summed image, addring to norm.imgs del ("_match1.mcat", ver-, >& "dev$null") match ("_match1.mcat", ssum//".cat", img1//".cat") # imdel("tmp_"//img1,ver-,>&"dev$null") imcopy(img1,"tmp_"//img1,ver-) # k=0; kmax=1; f1=1; f="f" hsel (img1, "itersig", yes) | scan (x) # hsel (ssum, "ebv", yes) | scan (ebv) hsel (img1, "rlambda", yes) | scan (rlambda1) alambda1=ebv*rlambda1 hedit (img1, "alambda1", alambda1, add+, ver-, update+, show-) # imdel ("tmp_"//msk, ver-, >& "dev$null") imdel ("tmp_"//norm1, ver-, >& "dev$null") addring (msk, "tmp_"//msk, ngrow=bborder, badval=0) imar (norm1, "*", "tmp_"//msk, "tmp_"//norm1, ver-, noact-) # if(img2!="") { match ("_match1.mcat", img2//".cat") imdel("tmp_"//img2,ver-,>&"dev$null") imcopy(img2,"tmp_"//img2,ver-) hsel (img2, "itersig", yes) | scan (y) f2=x/y print("f2="//f2) print("f2="//f2, >> logname) hsel (img2, "rlambda", yes) | scan (rlambda2) alambda2=ebv*rlambda2 kmax=2 imdel ("tmp_"//norm2, ver-, >& "dev$null") imar (norm2, "*", "tmp_"//msk, "tmp_"//norm2, ver-, noact-) # if(img3!="") { match ("_match1.mcat", img3//".cat") imdel("tmp_"//img3,ver-,>&"dev$null") imcopy(img3,"tmp_"//img3,ver-) hsel (img3, "itersig", yes) | scan (y) f3=x/y print("f3="//f3) print("f3="//f3, >> logname) hsel (img3, "rlambda", yes) | scan (rlambda3) alambda3=ebv*rlambda3 kmax=3 imdel ("tmp_"//norm3, ver-, >& "dev$null") imar (norm3, "*", "tmp_"//msk, "tmp_"//norm3, ver-, noact-) } } imdel ("tmp_"//msk, ver-) del ("_tmprandfile", ver-, >& "dev$null") total=nnrepeat*nnobjs*nnbins urand (total, 5, scale=1, >> "_tmprandfile") #--for each FINAL magnitude bin (index i) after g.e. correction # (i.e. detected mag is g.e. mags fainter) for (i=1; i<=nnbins; i+=1) { mag1=llimbin1-(i-1)*sspacing+alambda1 if(kmax>=2)mag2=llimbin1-(i-1)*sspacing+alambda2+color_21 if(kmax>=3)mag3=llimbin1-(i-1)*sspacing+alambda3+color_31 mag=mag1 #--extract cat of fainter-than-this objs from matched r(j)k+sum mcat print ("extract cat of objs w/m>"//mag//" in filter #1 from matched r(j)k+sum mcat") print ("extract cat of objs w/m>"//mag//" in filter #1 from matched r(j)k+sum mcat", >> logname) del ("_matchf.*cat", ver-, >& "dev$null") #--mfilter has problems in batch mode; none of the following work in batch mode. #--can't use ffilter instead, either. # mfilter ("f2 \"M "//mag//" 100\"", < "_match1.mcat", > "_matchf.mcat") # mfilter ("f2 'M "//mag//" 100'", < "_match1.mcat", > "_matchf.mcat") # s1="f2 \"M "//mag//" 100\"" # mfilter ("f2", s1, < "_match1.mcat", > "_matchf.mcat") # mfilter ("f2", "\"M "//mag//" 100\"", < "_match1.mcat", > "_matchf.mcat") # mfilter ("f2", "'M "//mag//" 100'", < "_match1.mcat", > "_matchf.mcat") mfilter ("f2 'M "//mag//" 100'", < "_match1.mcat", > "_matchf.mcat") mextract (1, < "_matchf.mcat", > "_matchf.cat") objects("_matchf.cat") #--clean summed image of objects w/this flux or less in this filter print ("clean summed image of objects w/this flux or less in this filter", >> logname) imdel ("cl_sum.imh", ver-, >& "dev$null") imcopy (ssum, "cl_sum", ver-) clean (cf, < "_matchf.cat") imswap (ssum, "cl_sum") del ("_matchf.*cat", ver-, >& "dev$null") if(ddis)displ("cl_sum", 2) #--COMPARISON CAT print("COMPARISON CAT") print("COMPARISON CAT", >> logname) #--rerun focas: create catalog del ("cl_sum.ar", ver-, >& "dev$null") del ("cl_sum.cat", ver-, >& "dev$null") hsel (ssum, "variance", yes) | scan (variance) del ("temp.file", ver-, >& "dev$null") skysig=sqrt(variance) print("cl_sum.cat", " ", "cl_sum", " ", "artdata", " ", skysig, "21", " ", "cl_sum.ar", >> "temp.file") !set catpars=`awk -f iraf2unix temp.file`; mysetcathesis $catpars del ("temp.file", ver-, >& "dev$null") #--detect detect ("cl_sum.cat", 1, ylong, -5*skysig, 5*skysig) sky ("cl_sum.cat") evaluate ("cl_sum.cat") #--splits del ("temp.file", ver-, >& "dev$null") print("cl_sum.cat", " ", "10", >> "temp.file") !set catpars=`awk -f iraf2unix temp.file`; mysetcatsize $catpars del ("temp.file", ver-, >& "dev$null") splits ("cl_sum.cat") del ("cl_sum.sky.imh", ver-, >& "dev$null") del ("cl_sum.sky.pix", ver-, >& "dev$null") #--for j=1 to nnrepeat iterations at each magnitude nrecovsum=0. ndenomsum=0. for (j=1; j<=nnrepeat; j+=1) { l=1; del ("_tmpcoo?", ver-, >& "dev$null") #--create coords+mag list of nnobjs psf objs to add to x,y image region for (l=1; l<=nnobjs; l+=1) { running=(i-1)*nnrepeat*nnobjs+(j-1)*nnobjs+l fields("_tmprandfile", "1-5", lines=running) | scan (x,y,z,a,b) x=x*(xmax-xmin)+xmin; y=y*(ymax-ymin)+ymin z=mag1+sspacing*(z-0.5) print (x, y, z, >> "_tmpcoo1") if (kmax>=2) { a=mag2+sspacing*(a-0.5) print (x, y, a, >> "_tmpcoo2") } if (kmax>=3) b=mag3+sspacing*(b-0.5) print (x, y, b, >> "_tmpcoo3") } #--ARTDATA CAT print ("ARTDATA CAT, filter 1 ("//img1//") mag #"//i//" ("//mag//") iteration #"//j) print ("ARTDATA CAT, filter 1 ("//img1//") mag #"//i//" ("//mag//") iteration #"//j, >> logname) #--recreate tmp image imdel ("tmp_"//img1, ver-, >& "dev$null") imcopy (img1, "tmp_"//img1, ver-) #--add objs+noise to img hsel ("tmp_"//img1, "zeropt", yes) | scan (zeropt) hsel ("tmp_"//img1, "gain", yes) | scan (g) hsel ("tmp_"//img1, "rdnoise", yes) | scan (rn) #print (zeropt, " ", g, " ", rn) hsel ("tmp_"//img1, "fwhmpix", yes) | scan (ffwhmpix) mkobjects ("tmp_"//img1, header="", background=0., objects="_tmpcoo1", star=sstar, radius=0.9*(ffwhmpix/2.), beta=2.5, ar=1., dist=1., exptime=1., magzero=zeropt, pa=0., poisson+, gain=g, rdnoise=rn, seed=sseed, comments+, xoff=0., yoff=0.) #--subtract original image imar ("tmp_"//img1, "-", img1, "tmp_"//img1, ver-) #--scale artdata-only image to equal skysub imar ("tmp_"//img1, "*", f1, "tmp_"//img1, ver-) #--add scaled residual images to summed-cleaned-img imdel ("do_img", ver-, >& "dev$null") imar ("tmp_"//img1, "+", "cl_sum", "do_img", ver-, noact-) if(kmax>=2){ #--recreate tmp image imdel ("tmp_"//img2, ver-, >& "dev$null") imcopy (img2, "tmp_"//img2, ver-) hsel ("tmp_"//img2, "zeropt", yes) | scan (zeropt) hsel ("tmp_"//img2, "gain", yes) | scan (g) hsel ("tmp_"//img2, "rdnoise", yes) | scan (rn) #print (zeropt, " ", g, " ", rn) hsel ("tmp_"//img2, "fwhmpix", yes) | scan (ffwhmpix) mkobjects ("tmp_"//img2, header="", background=0., objects="_tmpcoo2", star=sstar, radius=0.9*(ffwhmpix/2.), beta=2.5, ar=1., dist=1., exptime=1., magzero=zeropt, pa=0., poisson+, gain=g, rdnoise=rn, seed=sseed, comments+, xoff=0., yoff=0.) #--subtract original image imar ("tmp_"//img2, "-", img2, "tmp_"//img2, ver-) #--scale artdata-only image to equal skysub imar ("tmp_"//img2, "*", f2, "tmp_"//img2, ver-) #--add scaled residual images to summed-cleaned-img imar("do_img","+","tmp_"//img2,"do_img",ver-,noact-) } if(kmax>=3){ #--recreate tmp image imdel ("tmp_"//img3, ver-, >& "dev$null") imcopy (img3, "tmp_"//img3, ver-) hsel ("tmp_"//img3, "zeropt", yes) | scan (zeropt) hsel ("tmp_"//img3, "gain", yes) | scan (g) hsel ("tmp_"//img3, "rdnoise", yes) | scan (rn) hsel("tmp_"//img3, "fwhmpix", yes) | scan (ffwhmpix) mkobjects ("tmp_"//img3, header="", background=0., objects="_tmpcoo3", star=sstar, radius=0.9*(ffwhmpix/2.), beta=2.5, ar=1., dist=1., exptime=1., magzero=zeropt, pa=0., poisson+, gain=g, rdnoise=rn, seed=sseed, comments+, xoff=0., yoff=0.) #--subtract original image imar ("tmp_"//img3, "-", img3, "tmp_"//img3, ver-) #--scale artdata-only image to equal skysub imar ("tmp_"//img3, "*", f3, "tmp_"//img3, ver-) #--add scaled residual images to summed-cleaned-img imar("do_img","+","tmp_"//img3,"do_img",ver-,noact-) } #--mask summed image imar ("do_img", "*", msk, "do_img", ver-, noact-) if(ddis)displ("do_img", 3) if(ddis)sctv("tmp_"//img1, 4) #if(ddis)imexam("tmp_"//img1, keeplog+, logfile=logname) #--rerun focas: create catalog print("rerun focas & create catalog") hsel (ssum, "variance", yes) | scan (variance) del ("do_sum.ar", ver-, >& "dev$null") del ("do_sum.cat", ver-, >& "dev$null") del ("temp.file", ver-, >& "dev$null") skysig=sqrt(variance) print("do_img.cat", " ", "do_img", " ", "artdata", " ", skysig, "21", " ", "do_img.ar", >> "temp.file") !set catpars=`awk -f iraf2unix temp.file`; mysetcathesis $catpars #--detect detect ("do_img.cat", 1, ylong, -5*skysig, 5*skysig) sky ("do_img.cat") evaluate ("do_img.cat") #--splits del ("temp.file", ver-, >& "dev$null") print("do_img.cat", " ", "10", >> "temp.file") !set catpars=`awk -f iraf2unix temp.file`; mysetcatsize $catpars del ("temp.file", ver-, >& "dev$null") splits ("do_img.cat") del ("do_img.sky.imh", ver-, >& "dev$null") del ("do_img.sky.pix", ver-, >& "dev$null") #--create focas cat of artdata objects only imar ("tmp_"//img1, "*", msk, "tmp_"//img1, ver-, noact-) print("tmp_"//img1//".cat", " ", "tmp_"//img1, " ", "artdata", " ", 0.025*skysig, "6", " ", "tmpimg.ar", >> "temp.file") !set catpars=`awk -f iraf2unix temp.file`; mysetcathesis $catpars del ("temp.file", ver-, >& "dev$null") detect ("tmp_"//img1//".cat", 1, ylong, -0.025*skysig, 0.025*skysig) sky ("tmp_"//img1//".cat") evaluate ("tmp_"//img1//".cat") del ("tmp_"//img1//".sky.imh", ver-, >& "dev$null") del ("tmp_"//img1//".sky.pix", ver-, >& "dev$null") #--match summed-altered-img cat w/summed-cleaned-img cat, tossing matches print ("match summed-altered-img cat w/summed-cleaned-img cat, tossing matches", >> logname) #if(ddis)review("cl_sum.cat", "do_img.cat", "tmp_"//img1//".cat") match ("_match.mcat", "cl_sum.cat", "do_img.cat", "tmp_"//img1//".cat") mfilter ("e1", "i2", "i3", < "_match.mcat", > "_matchf.mcat") mextract (2, < "_matchf.mcat", > "_do_imgf.cat") #if(ddis)review("_do_imgf.cat") objects ("cl_sum.cat") objects ("do_img.cat") objects ("_do_imgf.cat") objects ("tmp_"//img1//".cat") objects ("_do_imgf.cat") | scan (s1, s2, s3, s4, s5, nrecov) objects ("tmp_"//img1//".cat") | scan (s1, s2, s3, s4, s5, ndenom) #--delete temporary images & catalogs imdel ("do_img", ver-, >& "dev$null") imdel ("tmp_"//img1, ver-, >& "dev$null") imdel ("tmp_"//img2, ver-, >& "dev$null") imdel ("tmp_"//img3, ver-, >& "dev$null") del ("tmpimg.ar", ver-, >& "dev$null") del ("tmp_"//img1//".cat", ver-, >& "dev$null") del ("_tmpcoo?", ver-, >& "dev$null") del ("_do_img*.cat", ver-) del ("_do_img*.ar", ver-) del ("do_img*.cat", ver-) del ("do_img*.ar", ver-) del ("_match.mcat", ver-) del ("_matchf.mcat", ver-) #--next j (nnrepeat iterations at each magnitude) nrecovsum=nrecovsum+nrecov ndenomsum=ndenomsum+ndenom print("nrecov="//nrecov, >> logname) print("nrecovsum="//nrecovsum, >> logname) print("ndenomsum="//ndenomsum, >> logname) } #--save info on the ith mag bin mnorm=mag1 if(ndenomsum==0.) { frecover=0. } else { frecover=nrecovsum/ndenomsum } print ("frecover="//frecover, >> logname) farray[i,1]=frecover farray[i,2]=mnorm #=mag1=mag print ("farray["//i//",1-2]="//farray[i,1]//" "//farray[i,2], >> logname) if (kmax>=2) { farray[i,3]=mag2 print ("farray["//i//",3]="//farray[i,3], >> logname) } if (kmax>=3) { farray[i,4]=mag3 print ("farray["//i//",4]="//farray[i,4], >> logname) } #farray 1 2 3 4 #i=1 frecov mag1=mnorm mag2 mag3 #i=2 frecov mag1=mnorm mag2 mag3 #... #--next magnitude bin i imdel ("cl_sum", ver-, >& "dev$null") del ("cl_sum.cat", ver-) del ("cl_sum.ar", ver-) } #--for each r(j)k image (index k), compute C(mfinal) for k-mag in filter #k for (k=1; k<=kmax; k+=1){ img=img1; norm="tmp_"//norm1; mag=mag1; llimbin=llimbin1; alambda=alambda1 if(k==2){ img=img2; norm="tmp_"//norm2; mag=mag2; llimbin=llimbin2; alambda=alambda2 } if(k==3){ img=img3; norm="tmp_"//norm3; mag=mag3; llimbin=llimbin3; alambda=alambda3 } print ("compute C(mfinal) for "//mag//" to "//llimbin//" in filter #"//k) print ("compute C(mfinal) for "//mag//" to "//llimbin//" in filter #"//k, >> logname) if(access("complete_"//img))print("Appending to complete_"//img) if(access("comparea_"//img))print("Appending to comparea_"//img) print("#"//img, >> "complete_"//img) print("#mag completeness raw", >> "complete_"//img) print("#"//img, >> "comparea_"//img) print("#mag area(sqarcmin) lost_area", >> "comparea_"//img) #--take untrim*orig image and subtract from maximum to get deltam at each pixel minmax (norm, force+, update-, ver-) imar (norm, "-", minmax.maxval, "_tmp_"//norm, ver-, noact-) imar ("_tmp_"//norm, "*", "-1.", "_tmp_"//norm, ver-, noact-) #if(ddis)sctv(norm, 3) #if(ddis)sctv("_tmp_"//norm, 4) #--get Area(delm) binned in (spacing) bins centered at #--0,1*spacing,2*spacing ... (z1=-0.5*spacing,z2=0.5*spacing) print("get Area(delm)", >> logname) del ("_Alist", ver-, >& "dev$null"); del ("_Zlist", ver-, >& "dev$null") binmax=1+int(2.5/sspacing) imhistog ("_tmp_"//norm, z1=-0.5*sspacing, z2=(binmax-0.5)*sspacing, binw=sspacing, top_closed=no, listout+, >> "_Alist") filecalc ("_Alist", "$1;$2*("//ppixscale//"**2.)/3600.", >> "_Zlist") list="_Zlist" i=1 while (fscan(list, deltam, area) !=EOF) { print (area, >& "dev$null") aarray[i,1]=area print (deltam, >& "dev$null") aarray[i,2]=minmax.maxval-deltam print (deltam, >& "dev$null") aarray[i,3]=deltam print ("aarray["//i//",1-3]="//aarray[i,1]//" "//aarray[i,2]//" "//aarray[i,3], >> logname) i=i+1 } imdel ("_tmp_"//norm, ver-) #aarray 1 2 3 4 #i=1 area mlim deltam tmp #i=2 area mlim deltam tmp #... #--get Area(m) binned in (spacing) bins centered on mreal=mfinal+g.e. mag values print("get Area(m)", >> logname) del ("_Alist", ver-, >& "dev$null"); del ("_Zlist", ver-, >& "dev$null") imhistog (norm, z1=llimbin-(nnbins-0.5)*sspacing+alambda, z2=llimbin+0.5*sspacing+alambda, binw=sspacing, listout+, >> "_Alist") filecalc ("_Alist", "$1;$2*("//ppixscale//"**2.)/3600.", >> "_Zlist") list="_Zlist" Asum=0. while (fscan(list, mreal, area) !=EOF) { mfinal=mreal-alambda #--"area" is the area which has a limiting magnitude in this bin. #--"Asum" is the area which has a limiting magnitude in this bin or brighter. Asum=Asum+area #--"Atmp" is the area which has a limiting magnitude fainter than this bin. Atmp=Atot-Asum print(mfinal, Atmp, area, >> "comparea_"//img) } del ("_Alist", ver-, >& "dev$null"); del ("_Zlist", ver-, >& "dev$null") #--one mreal=mfinal+g.e. bin at a time print("one mreal=mfinal+g.e. bin at a time", >> logname) #--since m_norm goes in 0.5m steps, m_norm=m_real-delta_m will too for (i=1; i<=nnbins; i+=1) { mreal=llimbin-(i-1)*sspacing+alambda #mreal=mnorm in deepest part mfinal=mreal-alambda ctmp=0. print("i="//i, >> logname) #--for each deltam up to deltam=2.5 (corresponding to 1% of peak exposure time) #--(A(del_m+0.25,del_m-0.25)/Atot) * f(m_real-delta_m) where #--f(m_real-delta_m) is f(m_norm) for the m_norm nearest m_real-deltam deltamax=1+int(2.5/sspacing) #--guarantees at least 2.5m above mlim for (deltam=0; deltam<=deltamax; deltam+=sspacing) { j=1+deltam/sspacing #--jth array entry = deltam above mlim mnorm=mreal-deltam #--find f(m_real-delta_m) = f(m_norm) for the m_norm nearest m_real-deltam index=1 diff=10. for (i2=1; i2<=nnbins; i2+=1) { mtmp=farray[i2,k+1] if ((abs(mtmp-mnorm)) < diff) { index=i2 diff=abs(mtmp-mnorm) #print ("deltam="//deltam, " i2="//i2, " mtmp="//mtmp, " index="//index, " mnorm="//mnorm, " diff="//diff, >> logname) } } # --(A(del_m+0.25,del_m-0.25)/Atot) * f(m_real-delta_m) aarray[j,4]=aarray[j,1]*farray[index,1]/Atot print ("j="/j//": aarray[j,4]="//aarray[j,4]//" aarray[j,1]="//aarray[j,1]//" farray["//index//",1]="//farray[index,1]//" ctmp="//ctmp, >> logname) # --sum individual A*f terms to get C(mfinal)=C(mreal) ctmp=ctmp+aarray[j,4] #--next delta_m } #--output C(mfinal) ctrue=ctmp if (ctmp>=1.) { ctmp=1. } print (mfinal, ctmp, ctrue, >> "complete_"//img) #--next filter k } #--next mfinal (magnitude) bin i } del ("_tmprandfile", ver-, >& "dev$null") del ("_match.mcat", ver-, >& "dev$null") del ("_match1.mcat", ver-, >& "dev$null") imdel ("tmp_"//norm1, ver-, >& "dev$null") imdel ("tmp_"//norm2, ver-, >& "dev$null") imdel ("tmp_"//norm3, ver-, >& "dev$null") } else { print("WARNING: packages FOCAS and/or ARTDATA, and/or tasks") print("filecalc, fileroot, and/or imswap are not loaded!") print("Please load the appropriate package(s) and restart this task.") } list="" beep end #--for each field # --get x,y limits for that field and filter # --get g.e. for each filter # --choose each filter's fluxes so m_final (= m_real-g.e.) # = e.g. 20.25, 20.75, thus in the deepest part of the image where # m_norm1=m_real1, m_norm1 = e.g. 20.25+ge1, 20.75+ge1, ... # m_norm2=m_real2, m_norm2 = e.g. 20.25+ge2, 20.75+ge2, ... # --find scalings for individual-filter images # **for each mag bin: each mag bin represents a different mag in each filter # (m1=m1, m2=m1+color21, m3=m1+color31), but should really repeat for # each filter since the crowding is different to each filter's limit # (i.e. mk=mminval) { if(val<=mmaxval) { print(val, >> ooutfile) } } } count (iinfile//","//ooutfile) end phat_alone/src/iteravg.par100644 1332 567 353 6352643236 15123 0ustar hallast_hyeeoption,s,a,new_sample,,,'Type of sample (new_sample, add, subtract)' opstring,s,h maxiter,i,h nsigrej,r,h addsub_flag,i,h data_value,r,h n,i,h sum,r,h sumsqrs,r,h mean,r,h variance,r,h sigma,r,h iter,i,h nold,i,h minval,r,h maxval,r,h phat_alone/src/quickfringe.cl100644 1332 567 7662 6406756707 15647 0ustar hallast_hyee# quickfringe.cl -- interactively adjust defringing ...and fast! # 950322: created from tpl.cl # 970227: added iterstat determination of RMS of each defringing test procedure quickfringe(fiximage,fringe,outname) string fiximage {prompt="Name of (original) image to be defringed"} string fringe {prompt="Fringe image to scale and subtract"} string outname {prompt="Name of defringed image to create"} bool dis=yes {prompt="Display fringe and original image at start?",mode="q"} bool fit=yes {prompt="Adjust parameters and refit image?",mode="q"} real scale {prompt="Scaling to use on fringe image",mode="q"} int z {0,prompt="Number of image to save?",mode="q"} begin string logimex, logsurf, countfile, rrootname, iimagelist, ooutname, ffunc string wweighting, fiximg, ffringe, titlestring real max, nncols, nnlines, sscale, indiv_exptime, avg_exptime, sum_exptime real skyfring, ll, ul, mn, sig, nx, npx int x, y, zz, xxord, yyord, xx, m bool go, ffit, xxterms, ddis fiximg=fiximage ffringe=fringe ooutname=outname ddis=dis zz=0 # check for addcomment; if not defined abort task. go=yes if(!deftask("addcomment")) {go=no} if(go) { # Get initial scaling if(ddis){ print("===> Displaying fringe image and original image...") display(ffringe,1) display(fiximg,2) } imgets(fiximg,"FRINGMED",>&"dev$null") if(imgets.value!="0"){ sscale=real(imgets.value) } else { print(" ") print("===> Calculating initial fringe image scaling...") imgets(ffringe,"exptime") avg_exptime=real(imgets.value) imgets(fiximg,"exptime") indiv_exptime=real(imgets.value) imgets(fiximg,"SKYFRING") # iterstat(fiximg,nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print-,ver-) # new scaling = new median from iterstat * old scaling * exptime * avg_exptime # sscale=iterstat.median*(real(imgets.value))*indiv_exptime/avg_exptime skyfring=real(imgets.value) imgets(fiximg,"itermed") sscale=(real(imgets.value))*skyfring*indiv_exptime/avg_exptime } #need to create countfile x=1 y=2 ffit=yes # Fitting loop while(ffit) { if(x!=1){ # get new scaling sscale=scale # vi(countfile//"_"//str(x)) } # scale and subtract the fringe image print ("===> Scaling the fringe image by "//sscale//" and subtracting...") # imar (ffringe, "/", sscale, ffringe//"_"//str(x), ver-) # imar (ooutname//"_0", "-", ffringe//"_"//str(x), ooutname//"_"//str(x), ver-) imcalc(fiximg//","//ffringe,ooutname//"_"//str(x),"im1-im2*"//sscale,ver-) hedit(ooutname//"_"//str(x),"title","Defringed image using scale="//sscale,ver-,add+,update+,show-) # inspect the subtracted image print ("===> Displaying defringed image #"//str(x)//"...") y=y+1 if(y>4)y=1 displ (ooutname//"_"//str(x), y) print ("===> Computing RMS of defringed image #"//str(x)//"...) # iterstat (ooutname//"_"//str(x),nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print-,ver-) imstat (ooutname//"_"//str(x),fields="mean,stddev,npix",lower=INDEF,upper=INDEF,for-) | scan(mn,sig,npx) m = 1 while (m <= 10) { ll = mn-5*sig ul = mn+5*sig imstat (ooutname//"_"//str(x),fields="mean,stddev,npix",lower=ll,upper=ul,for-) | scan(mn,sig,nx) if (nx == npx) break npx = nx m = m + 1 } beep print ("===> RMS of defringed image #"//str(x)//" is "//sig) beep # abort loop? ffit=fit x+=1 } # clean up zz=z if(zz!=0){ imren(ooutname//"_"//str(zz),ooutname,ver-) hedit(ooutname,"FRINGMED",sscale,add+,ver-,show-,update+) addcomment(ooutname,"Defringed using FRINGMED-scaled copy of "//ffringe,ver-) imgets(fiximg,"title") titlestring=str(imgets.value) hedit(ooutname,"title",titlestring,add+,ver-,update+,show-) } else{ print("No images saved.") } y=0 zz=0 while(y& "dev$null") y+=1 } } else{ print("The tasks `addcomment' are not loaded,") print("and this task needs them to run. Please load it and start again.") } beep end phat_alone/src/focasflat.cl100644 1332 567 10125 6412773571 15301 0ustar hallast_hyeeprocedure focasflat (rootname, routname) # program to flatten a big (~2048**2) CCD image, ~20 minutes per image. # requires iterstat, iraf2unix and mysetcat string rootname {prompt="Name of original image (no .imh included)"} string routname {prompt="Name of output image (no .imh included)"} #bool check=yes {prompt="Inspect sky image before continuing?"} #bool doit=yes {prompt="Do subtraction?"} # int_time is the integration time in the filter # o is the total number of offset images in the filter # j is the number of the offset image whose parameters are specified in the particular line of the file # sky_sigma_j is the sky sigma of the image # f is the filter code letter, running in the order ubvriI begin real ftime, sig, a, mn int xmax, ymax, k, word, chars, num1, num2, st, d, o string image, root, l, catpars, tempname, i, h, f, m, rroutname struct c file temp.file, tmpsfiles root = rootname rroutname = routname imgets(root, "i_naxis1") xmax = real(imgets.value) imgets(root, "i_naxis2") ymax = real(imgets.value) imgets(root, "exptime") ftime = real(imgets.value) imgets(root, "itersig") if (imgets.value=="0") { iterstat (root, addh+, ver-, print-) imgets(root, "itersig") sig = real(imgets.value) imgets(root, "itermean") mn = real(imgets.value) } else { sig = real(imgets.value) imgets(root, "itermean") mn = real(imgets.value) } print ("Requires iraf2unix and mysetcat be in this directory...") print ("Now working on image "//root//". Rotating images...") imdel ("rtff*.imh", ver-, >& "dev$null") imcopy (root, "rtff"//"a", verbose-); imtrans ("rtff"//"a[*,-*]", "rtff"//"b") imtrans ("rtff"//"b[*,-*]", "rtff"//"c"); imtrans ("rtff"//"c[*,-*]", "rtff"//"d") # flatten the images using the FOCAS-based flattening routine. for (k=1; k <= 4; k+=1) { if (k<1.4) m = "a" if (k>1.5) m = "b" if (k>2.5) m = "c" if (k>3.5) m = "d" del ("temp.file", ver-, >& "dev$null") print ("Flattening image "//m//" using the FOCAS-based flattening routine...") print ("rtff"//m//".cat", " ", "rtff"//m, " ", "f", " ", ftime, " ", sig, >> "temp.file") !set catpars=`awk -f iraf2unix temp.file`; mysetcat $catpars # detect ("rtff"//m//".cat", "1", ymax, mn-5*sig, mn+5*sig) print ("detect rtff"//m//".cat 1 "//ymax//" "//mn-5*sig//" "//mn+5*sig, >> "do_detmp.cl") cl (< "do_detmp.cl") del ("do_detmp.cl", ver-) sky ("rtff"//m//".cat") evaluate ("rtff"//"a.cat") del ("temp.file", ver-, >& "dev$null") } imdel ("rtff"//"b.imh", ver-); imdel ("rtff"//"c.imh", ver-); imdel ("rtff"//"d.imh", ver-) # rotate sky images back to common orientation print ("Rotating sky images back to common orientation...") imtrans ("rtff"//"d.sky[*,-*]", "rtff"//"d.sky"); imtrans ("rtff"//"b.sky[-*,*]", "rtff"//"b.sky") imtrans ("rtff"//"c.sky[-*,*]", "rtff"//"c.sky"); imtrans ("rtff"//"c.sky[-*,*]", "rtff"//"c.sky") files ("rtff"//"*.sky.imh", > "tmpsfiles") # combine them into one print ("Combining sky images into one...") imcom ("@tmpsfiles", "rtff"//".avsky", combine="median", reject="minmax", nlow=0, nhigh=1, scale="none", weight="none", zero="none") # scale it to the original image size print ("Scaling sky image to original image size...") blkrep ("rtff"//".avsky", "rtff"//".avskye", 8, 8) imstat ("rtff"//".avsky", fields="mode", format-) | scan (a) imdel ("rtff"//".avsky", ver-) imcopy("rtff"//".avskye[1:"//xmax//",1:"//ymax//"]", root//".sky", ver-) imdel("rtff"//".avskye", ver-) #--check/doit here # clean up imdel ("@tmpsfiles", ver-); imdel ("rtff"//"*.sky.imh", ver-) del ("tmpsfiles", ver-); del ("rtff"//"*.ar", ver-); del ("rtff"//"*.cat", ver-) # subtract the focas sky image from the original image & add back in the mode print ("Subtracting sky image from original & adding mode back in...") imar ("rtff"//"a", "-", root//".sky", rroutname) imdel ("rtff"//"a.imh", ver-); imdel ("rtff"//"*sky.imh", ver-) imar (rroutname, "+", a, rroutname) minmax (rroutname, force+) iterstat (rroutname, addh+, ver-, print-) beep end phat_alone/src/btc_gainflip.cl100644 1332 567 6143 6412620441 15730 0ustar hallast_hyeeprocedure btc_gainflip(filename) # scale btc chips to gain=1, and flip as desired string filename {prompt="List of root names of image sets"} string bpmroot="" {prompt="Root name of bad pixel masks to add to header"} string getstats="" {prompt="Root name for iterstat output if desired"} bool gainmult=yes {prompt="Multiply all chips by their gain?"} bool flipns=yes {prompt="Flip chip #4 N-S (up-down)?"} bool flipew=yes {prompt="Flip all chips E-W (left-right)?"} struct *name # filename should list the names of the root image to be worked on begin string root, image, scales, bbpmroot, ggetstats real iteravg, chipscale bbpmroot=bpmroot ggetstats=getstats # -- cycle through image sets name = filename while (fscan (name, root) != EOF) { for (i=1; i<=4; i+=1) { image = root//"_"//i//".imh" # -- multiply image and existing iterstat header keywords by gain if (gainmult) { imgets(image, "gainold", >& "dev$null") if ((imgets.value)=="0") { imgets(image, "gain", >& "dev$null") imar (image,"*",real(imgets.value),image,ver-,noact-) hedit (image,"gainold","(gain)",add+,ve-,sho-,updat+) hedit (image,"gain",1.0,add+,ve-,sho+,updat+) imgets(image, "itermean", >& "dev$null") if ((imgets.value)!="0") { hedit(image,"itermean","(itermean*gainold)",add+,ve-,sho-,updat+) hedit(image,"itermode","(itermode*gainold)",add+,ve-,sho-,updat+) hedit(image,"itersig","(itersig*gainold)",add+,ve-,sho-,updat+) hedit(image,"itermed","(itermed*gainold)",add+,ve-,sho-,updat+) hedit(image,"variance","(variance*gainold*gainold)",ad+,ve-,sho-,updat+) } } else { print (image//" already multiplied by gain!") } } # -- flip chip #4 N-S if (flipns) { if(i==4) { imgets(image, "flipns", >& "dev$null") if ((str(imgets.value)) != "yes") { imgets(image, "flip", >& "dev$null") if ((str(imgets.value)) != "yes") { imcopy (image//"[*,-*]", image, ver-) hedit(image,"flipns","yes",add+,ve-,sho-,updat+) hedit(image,"flip","yes",add+,ve-,sho-,updat+) print (image//" flipped N-S...") } else { print (image//" already flipped N-S!") hedit(image,"flipns","yes",add+,ve-,sho-,updat+) } } else { print (image//" already flipped N-S!") hedit(image,"flip","yes",add+,ve-,sho-,updat+) } } } # -- flip all chips E-W if (flipew) { imgets(image, "flipew", >& "dev$null") if ((str(imgets.value)) != "yes") { imcopy (image//"[-*,*]", image, ver-) hedit (image,"flipew","yes",add+,ver-,show-,update+) print (image//" flipped E-W...") } else { print (image//" already flipped E-W!") } # -- add bad pixel mask names to headers if (bbpmroot!="") { hedit(image,"bpm",bbpmroot//"_"//i//".pl",add+,ver-,sho+,updat+) } } } # -- iterstat if desired if (ggetstats!="") { print (root//" images flipped and gain-multiplied. Running iterstat.") iterstat (root//"_?.imh", >> ggetstats) } } beep end phat_alone/src/irtfcoadd_3.p100644 1332 567 443 6427031100 15300 0ustar hallast_hyee#!/usr/local/bin/perl -w # cycle thru contents of file(s) given on command line using <> while (<>) { # skip blank lines or lines with # as first non-whitespace character next if (/^\s+$/ or /^#/ or /^\s+#/); ($one, $two) = split " "; printf "%4.0f%4.0f\n", $one, $two; } phat_alone/src/optcoaddirtf.cl100644 1332 567 156126 6427025044 16044 0ustar hallast_hyee# optcoadd -- coadd images with sub-pixel shift options and much, much more # # Calls addcomment, iterstat, fileroot, filecalc, stsdas.toolbox.imgtools.imcalc # # 960712: created from phiirs$ircoadd.cl # 960716: deleted internal scaling check, added subtracted-image creation # 960723: fixed edge problem in sky-subtracted image # 960806: made sky-subtracted image creation optional # 960807: fixed minor bug of ccomblist2 not existing in expmap creation only # 960812: fixed exposure map creation & created normalization map creation # 960815: fixed bug in normalization of expmap when dividing into outimage # 960816: changed so that statfile is used only if directly requested, # and added optional insertion of variances into image headers # 960817: fixed occasional bug in skysub + weighted-expmap normalization # 960822: moved check for necessary tasks earlier to avoid errors # 970425: added check for tpl image # 970429: changed expmap -- now sets bad pixels to -99999. # Also several other minor changes to bring in line with ircoadd # 970505: changed default expmap suffix from "em" to "exp" to avoid confusion # with ircoadd, whose output expmap is different than optcoadd's # 970507: changed creation of individual expmaps to replace pixels above # -10000. with exptime -- allows for -99999. bad pixels to be excluded # 970623: added ability to use imcombine snoise parameter # 971031: IRTF version: filecalc and imcalc not used, so tpl can't be done # # **Could cut down on transient memory needs by finding "wtfactor" needed to # convert _nm image to _wt image -- stack norm, then do wtfactor & stack wt # **Note that weights should add to 1 if taken from a file (probably matters # only when stacking and creating expmap, but do it always just to be safe) procedure optcoadd(comblist,outimage,expmap,normmap,shiftlist,scaling,zeroing,weighting,magfac,stack,logfile) string comblist {prompt="List of images to combine"} string outimage {prompt="Output coadded image"} string expmap {prompt="Output exposure map (default=outimage//exp)"} string normmap {prompt="Output normalization map (default=outimage//norm)"} string shiftlist {prompt="File with image shifts"} string scaling {prompt="Imcombine scaling (none|@file|!|etc.)"} string zeroing {"mode",prompt="Imcombine zero offsets (none|@file|mode|etc.)"} string weighting {prompt="Imcombine weighting (none|@file|!|etc.)"} int magfac {1,min=1,max=10,prompt="Magnification factor for subpixel shifting"} bool stack {prompt="Combine images by stacking & projecting?"} string logfile {prompt="Name of log file"} string normname {prompt="Header keyword for normalization factor",mode="q"} bool newmask=no {prompt="Override bad pixel masks listed in image headers?"} string badmask {prompt="Bad pixel mask to use instead",mode="q"} bool spshift=no {prompt="Do image shifts account for subpix shifting?",mode="q"} bool prescale=no {prompt="Scale images before, not during, imcombine?",mode="q"} bool unscale=yes {prompt="Undo scaling factors when done?",mode="q"} real extcoeff {prompt="Extinction coefficient for default scalings",mode="q"} real airzero {INDEF,min=0.,max=99.,prompt="Airmass to scale to? (INDEF=min. observed)",mode="q"} bool scalecombine=no {prompt="Combine default & additional scalings?",mode="q"} string morescalename {prompt="@filename or !keyword for additional scalings",mode="q"} bool putscale {prompt="Insert scaling factors into image headers?",mode="q"} string wordscale="SCALEFAC" {prompt="Scaling factor header keyword",mode="q"} bool defscale=no {prompt="Do scales include default airmass scaling?",mode="q"} bool prezero=no {prompt="Do zero offseting before, not during, imcombine?",mode="q"} bool unzero=yes {prompt="Undo zero offsets when done?",mode="q"} bool putzero=no {prompt="Insert zero offsets into image headers?",mode="q"} string wordzero="ZEROVAL" {prompt="Zero offset header keyword",mode="q"} bool putweight=no {prompt="Insert weights into image headers?",mode="q"} string wordweight="WEIGHT" {prompt="Weighting factor header keyword",mode="q"} string stackimage {prompt="Name of stacked image", mode="q"} bool unstack {prompt="Delete stacked image & expmap when done?",mode="q"} bool spscale=no {prompt="Do zero offsets account for subpix shifting?",mode="q"} string expname="EXPTIME" {prompt="Header keyword for exposure time"} bool maskedstat=no {prompt="Use maskstat to find default zeros & wts?"} string statfile="" {prompt="File for image statistics"} bool stdpars=yes {prompt="Use std imcombine parameters for coadd?"} bool makeavg=no {prompt="Make pure coadd (comb=average,rej=none)?"} bool flip=no {prompt="Flip image L-R after coadd?"} bool cleanup=yes {prompt="Clean up new created blkrep'd images after use?"} bool tpl=no {prompt="Account for throughput correction in norm. map?"} pset optcoaddpars {prompt="Imcombine parameters"} struct *list begin string sshiftfraclist, iinterp, sshiftlist, subimg, explist, sect, skysubimg string ccomblist, bbadmask, sshiftintlist, ooutimage, zzeroing, sstackimage string llogfile, check, zzeroname, sscalefile, sscalename, img, eexpname, blk string s_sigma, s_plfile, s_combine, s_reject, s_offsets, s_masktyp, eexpmap string s_scale, s_weight, s_statsec, s_expname, sscaling, intcosca, expmask string listimshift, wwordscale, wwordzero, subimgold, expmaskold, checkmore string ccomblist1, ccomblist2, sshiftexactlist, image, newbp, newzzeroname string oldbp, bprotlist, file_of_zeros, list_of_zeros, checkscale, checkweight string checkzero, newwweightname, oldzs, newzs, oldwts, newwts, wweightname string file_of_more, mmorescalename, file_of_air, wweighting, wwordweight string file_of_scales, list_of_scales, sstatfile, s_gain, s_rdnoise, nnormname string nnormmap, wtimg, wtlist, wtimgold, tplimg, tplimgold, oextimage, tpltmp string tmpimg, tmpimg2, s_snoise real s_maskval, s_blank, s_lthresh, s_hthresh, s_nlow, s_nhigh, s_nkeep, avg, x real s_lsigma, s_hsigma, s_pclip, s_grow, s_sigscale, sig real effairmass, wtavg, nncombine, exp, exposure, sf, zf, testold, eexptime real xold, yold, xnew, ynew, xshift, yshift, sscale, p, b, h, levelzero, wt real wt_avg_exptime, unwt_avg_exptime, eextcoeff, aairzero, air, sfavg, sfmin real sfmax, tmpzero, wait, waitold int mag, mag2, j, k, tpl1, tpl2 int xmin, ymin, newx, newy, oldx, oldy, test1, test1old, test2, test2old int sstartno, eendno, i, numpix, num, xdim, ydim, newxsize, newysize, ncoadds bool mmakescalefile, mmakestack, go, mmorehow, pputzero, ddefscale, pputscale bool nnewmask, uunstack, pprescale, uunscale, pputweight, sstack, getnorm, ttpl bool sspscale, ccleanup, noappend, pprezero, uunzero, sscalecombine, sspshift struct theadline #for zero/scale/weight=* # *ing how to do it # *name filename, if substr(*ing,1,1)==@ # word* header keyword, if substr(*ing,1,1)==! (or @ && pre*=yes) # pre* do zero/scale before imcombine # un* undo zero/scale after imcombine # Certain tasks/packages must be loaded for task to run. go=yes #if(!defpac("imgtools")) {go=no} if(!deftask("addcomment")) {go=no} if(!deftask("fileroot")) {go=no} #if(!deftask("filecalc")) {go=no} if(!deftask("iterstat")) {go=no} if(go) { # Set up parameters ccomblist = comblist ccomblist1 = ccomblist fileroot (outimage,validim+) ooutimage = fileroot.root oextimage = fileroot.extension if(oextimage=="")oextimage="imh" fileroot (expmap,validim+) eexpmap = fileroot.root if(eexpmap=="")eexpmap=ooutimage//"exp" nnormmap=normmap if(nnormmap=="")nnormmap=ooutimage//"norm" sshiftexactlist = shiftlist sshiftintlist = sshiftexactlist sscaling = scaling if(sscaling=="")sscaling="none" ddefscale=no aairzero=100. pprescale=no uunscale=no sscalename="_.imag_in_ary_fileJ" checkscale=substr(sscaling,1,1) if(checkscale=="!" || checkscale=="@"){ wwordscale = substr(sscaling,2,strlen(sscaling)) pprescale=prescale if(pprescale)uunscale=unscale if(checkscale=="@"){ sscalename = substr(sscaling,2,strlen(sscaling)) if(!access(sscalename)){ ddefscale=yes eextcoeff=extcoeff aairzero=airzero sscalecombine=scalecombine if(sscalecombine){ mmorescalename=morescalename checkmore=substr(mmorescalename,1,1) while(checkmore!="@" && checkmore!="!"){ print("Additional scales must have format ! or @filename.") mmorescalename=morescalename checkmore=substr(mmorescalename,1,1) } } } pputscale=putscale if(pputscale)wwordscale=wordscale } if(!ddefscale)ddefscale=defscale if(ddefscale && aairzero==100.)aairzero=airzero # if airzero=INDEF and airzero is needed later in the task, airzero=min(airmass) if(aairzero==INDEF && (ddefscale || (pprescale && checkscale=="@" && access(sscalename)))){ print("...one moment please...") file_of_air=mktemp(".foa") hsel("@"//ccomblist1,"AIRMASS",yes, >> file_of_air) list=file_of_air aairzero=100. while (fscan (list,air) != EOF) { aairzero=min(air,aairzero) } del(file_of_air,ver-,>&"dev$null") list="" } } zzeroing = zeroing if(zzeroing=="")zzeroing="none" pprezero=no uunzero=no checkzero=substr(zzeroing,1,1) if(checkzero=="!" || checkzero=="@"){ wwordzero = substr(zzeroing,2,strlen(zzeroing)) pprezero=prezero if(pprezero)uunzero=unzero if(checkzero=="@"){ zzeroname = substr(zzeroing,2,strlen(zzeroing)) pputzero=putzero if(pputzero)wwordzero=wordzero } } wweighting = weighting wwordweight="" if(wweighting=="")wweighting="none" checkweight=substr(wweighting,1,1) if(checkweight=="!")wwordweight=substr(wweighting,2,strlen(wweighting)) if(checkweight=="@"){ wweightname = substr(wweighting,2,strlen(wweighting)) pputweight=putweight if(pputweight)wwordweight=wordweight } mag = magfac mag2=mag*mag blk = "br"//mag ccomblist2 = ccomblist//blk bprotlist = ccomblist//blk//"pl" sspscale=no sspshift=no if(mag!=1){ if(zzeroing!="none")sspscale=spscale sspshift=spshift } sstack=stack sstackimage="fake_image_oog" if(sstack) { fileroot(stackimage,validim+) sstackimage = fileroot.root uunstack=unstack } llogfile = logfile nnormname=normname getnorm=no if(nnormname=="")getnorm=yes if(nnormname=="")nnormname="variance" if(wwordweight=="")wwordweight=wordweight nnewmask = newmask if(nnewmask)bbadmask = badmask eexpname = expname sstatfile = statfile if(sstatfile=="")sstatfile="_nonexistentFILEname_" ttpl = tpl ccleanup = cleanup # Check for bad parameter combinations and exit if necessary if(!pprescale && sstack && checkscale=="!"){ print("WARNING! You can't scale during imcombine from a header keyword") print("when stack=yes! (There is only one header for a stacked image.)") print("Use `@file' or prescale=yes instead.") return } if(!pprezero && sstack && checkzero=="!"){ print("WARNING! You can't take the zero offsets from a header keyword") print("when stack=yes! (There is only one header for a stacked image.)") print("Use `@filename' or prezero=yes instead.") return } if(checkweight!="@" && wweighting!="none" && sstack){ print("WARNING! Output image exposure time would have been incorrect.") print("If you want to use weights and stacking, put the weights in a file") print("before running the task; that way the output image exposure time") print("will be correctly calculated.") return } wt_avg_exptime=-1. unwt_avg_exptime=-1. s_sigma = i_sigma # imcombine parameters s_plfile = i_plfile s_combine = i_combine s_reject = i_reject s_masktyp = i_masktyp s_maskval = i_maskval s_blank = i_blank s_statsec = i_statsec s_expname = i_expname s_lthresh = i_lthresh s_hthresh = i_hthresh s_nlow = i_nlow s_nhigh = i_nhigh s_nkeep = i_nkeep s_lsigma = i_lsigma s_hsigma = i_hsigma s_rdnoise = i_rdnoise s_gain = i_gain s_snoise = i_snoise s_sigscale = i_sigscale s_pclip = i_pclip s_grow = i_grow # Set up log file, appending if it already exists. if(llogfile == "") llogfile="log."//ooutimage print("", >> llogfile) print("===> PHAT.OPTCOADD:", >> llogfile) if(mag!=1){ print("===> Input images from "//ccomblist1//" replicated by factor "//mag//" in each direction.", >> llogfile) print("===> Replicated images in "//ccomblist2//" coadded w/offsets from "//sshiftexactlist//blk, >> llogfile) } else { print("===> Images in "//ccomblist1//" coadded w/offsets from "//sshiftexactlist//",", >> llogfile) } print("===> weights="/wweighting//", stdpars="/stdpars//", makeavg="/makeavg//",", >> llogfile) print("===> scales="/sscaling//", zero offsets="/zzeroing//",", >> llogfile) print("===> pre-scaling="/pprescale//", un-scaling="/uunscale//", pre-zeroing="/pprezero//", un-zeroing="/uunzero//",", >> llogfile) print("===> defscale="/ddefscale//", subpixscale="/sspscale//", subpixshift="/sspshift//",", >> llogfile) print("===> to make image "//ooutimage//" and exposure map "//eexpmap, >> llogfile) # PRE-SCALING AND DEFAULT SCALING FACTORS FILE CREATION if(pprescale){ # Prevent imcombine from scaling twice sscaling="none" # If stacking, and image already exists, do not bother # if(sstack && access(sstackimage//".imh")){ # print("Not bothering to pre-scale... stacked image already exists.") # } else { print("===> Multiplying by additional scaling factors...") # In case of scalings taken from header keyword, make file_of_scales if(checkscale=="!"){ file_of_scales=mktemp(".fos") hsel("@"//ccomblist1,wwordscale,yes, >> file_of_scales) } # In case of scalings taken from file... if(checkscale=="@"){ # # ...create file of DEFAULT SCALING FACTORS if it doesn't exist... # if(!access(sscalename)){ file_of_air=mktemp(".foa") # get airmasses hsel("@"//ccomblist1,"AIRMASS",yes, >> file_of_air) # turn airmasses into scales list=file_of_air while (fscan (list,air) != EOF) { sf=10**(0.4*eextcoeff*(air-aairzero)) print(sf, >> sscalename) } del(file_of_air,ver-) # If combining default scales with other pre-existing scales... if(sscalecombine){ file_of_more=mktemp(".fom") if(checkmore=="@"){ copy(substr(mmorescalename,2,strlen(mmorescalename)),file_of_more,ver-) } if(checkmore=="!"){ hsel("@"//ccomblist1,substr(mmorescalename,2,strlen(mmorescalename)),yes, >> file_of_more) } # join files of default and additional scales del("tmp_."//sscalename,ver-,>&"dev$null") join(sscalename,file_of_more,output="tmp_."//sscalename) del(sscalename,ver-,>&"dev$null") del(file_of_more,ver-,>&"dev$null") list="" list="tmp_."//sscalename # create new scales & put into scale file while(fscan (list,air,sf) != EOF) { print(air*sf, >> sscalename) } del("tmp_."//sscalename,ver-,>&"dev$null") } # Finished with creation of default scalings file } list="" file_of_scales=sscalename # End of taking scales from list subroutine } list="" # Allow imcombine to do sigscaling as requested even when pre-scaling if(s_sigscale!=0.){ del ("_avg.file.tmp", ver-, >& "dev$null") type (file_of_scales | average opt="new_sample", >> "_avg.file.tmp") sfavg=average.mean sfmin=1.E20 sfmax=-1.E20 list=file_of_scales while (fscan (list,sf) != EOF) { sfmin=min(sfmin,sf) sfmax=max(sfmax,sf) } if((sfavg-sfmin/sfavg)>=s_sigscale || (sfmax-sfavg/sfavg)>=s_sigscale)s_sigscale=0. del ("_avg.file.tmp", ver-, >& "dev$null") list="" } # Do multiplicative scaling unless it has already been done list_of_scales=mktemp(".los") join(ccomblist1,file_of_scales,output=list_of_scales) if(checkscale=="!")del(file_of_scales,ver-) list=list_of_scales while (fscan (list,img,sf) != EOF) { imgets(img,"PRESCALE",>&"dev$null") if(imgets.value=="0"){ imar(img,"*",sf,img,pixt="real",calct="real",ver-) hedit(img,"PRESCALE",sf,add+,ver-,show-,update+,>&"dev$null") if(ddefscale){ imgets(img,"AIRMASS",>&"dev$null") hedit(img,"AIRMOLD",imgets.value,add+,ver-,show-,update+,>&"dev$null") hedit(img,"AIRMASS",aairzero,add+,ver-,show-,update+,>&"dev$null") } } else { print("No action -- image "//img//" already pre-scaled by factor "//imgets.value) } } # } } list="" # put scale factors into image headers if desired if(checkscale=="@"){ if(pputscale){ del("_tmp.sscaling",ver-,>&"dev$null") join(ccomblist1,sscalename,out="_tmp.sscaling") list="_tmp.sscaling" while(fscan (list, img, sf) != EOF) { hedit(img,wwordscale,sf,add+,ver-,show-,update+,>&"dev$null") } del("_tmp.sscaling",ver-,>&"dev$null") } } list="" # DETERMINE ZERO-LEVEL OFFSETS IF NEEDED AND INSERT INTO HEADERS IF DESIRED if(checkzero=="@"){ if(!access(zzeroname)){ print("===) Finding iterative median zero offsets for the images...") del ("_zero.file.tmp?", ver-, >& "dev$null") del ("_avg.file.tmp", ver-, >& "dev$null") # first find iterative median of each image if(!access(sstatfile)){ if(maskedstat){ iterstat.nsigrej=5. iterstat.maxiter=10 maskstat("@"//ccomblist1,"!BPM",1,lower=INDEF,upper=INDEF,iterstat+,ver-,printit+, >> "_zero.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_zero.file.tmp1", sstatfile, ver-) } else { iterstat("@"//ccomblist1,nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print+,ver-, >> "_zero.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_zero.file.tmp1", sstatfile, ver-) } } else { if(sstatfile!="_nonexistentFILEname_")print("Using statistics from"//sstatfile) copy(sstatfile, "_zero.file.tmp1", ver-) } # next find the overall average of the means fields ("_zero.file.tmp1", 5, >> "_zero.file.tmp2") type ("_zero.file.tmp2" | average opt="new_sample", >> "_avg.file.tmp") # now compute the offset of each image from the overall average mean list="_avg.file.tmp" while (fscan (list, avg, sig, num) !=EOF) { lintran("_zero.file.tmp2",min=2,x2=avg,yfield=1,angle=180, >> zzeroname) } del ("_zero.file.tmp?", ver-) del ("_avg.file.tmp", ver-) } # now insert into image headers if desired if(pputzero) { if(access("_tmp.zzeroing"))del("_tmp.zzeroing",ver-) join(ccomblist1,zzeroname,out="_tmp.zzeroing") list="" list="_tmp.zzeroing" while (fscan (list, img, zf) !=EOF) { hedit(img,wwordzero,zf,add+,ver-,show-,update+) } del("_tmp.zzeroing",ver-,>&"dev$null") } } list="" # DETERMINE WEIGHTS IF NEEDED AND ADD TO IMAGE HEADERS IF DESIRED if(checkweight=="@"){ if(!access(wweightname)){ print("===) Creating file of optimal exptime/rms**2 weights for the images...") del ("_weight.file.tmp?", ver-, >& "dev$null") del ("_avg.file.tmp", ver-, >& "dev$null") # first find iterative rms of each image #hsel("@"//ccomblist1,"PRESCALE",yes, >> "_weight.file.tmp9") #count("_weight.file.tmp9") | scan (i,j,k) #if(j!=0){ #beep #print("WARNING! At least one image in "//ccomblist//" was pre-scaled;") #print("thus, the image weights being calculated will be erroneous.") #} if(!access(sstatfile)){ if(maskedstat){ iterstat.nsigrej=5. iterstat.maxiter=10 if(!access("_weight.file.tmp1"))maskstat("@"//ccomblist1,"!BPM",1,lower=INDEF,upper=INDEF,iterstat+,ver-,printit+, >> "_weight.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_weight.file.tmp1", sstatfile, ver-) } else { if(!access("_weight.file.tmp1"))iterstat("@"//ccomblist1,nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print+,ver-, >> "_weight.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_weight.file.tmp1", sstatfile, ver-) } } else { copy (sstatfile, "_weight.file.tmp1", ver-) } fields ("_weight.file.tmp1", 3, >> "_weight.file.tmp2") # get the exptimes for the images hsel("@"//ccomblist1,eexpname,yes, >> "_weight.file.tmp0") join("_weight.file.tmp2","_weight.file.tmp0",out="_weight.file.tmp3") # compute the weights = exptime./(rms**2.) #filecalc ("_weight.file.tmp3", "$2/($1*$1)", calctype="real", >> "_weight.file.tmp4") !/scrs1/pathall/irtfcoadd_1.p _weight.file.tmp3 > _weight.file.tmp4 # find the sum of the weights type ("_weight.file.tmp4" | average opt="new_sample",>> "_avg.file.tmp") # normalize by the sum of the weights #filecalc ("_weight.file.tmp4", "$1/"//average.sum, calctype="real", >> wweightname) !/scrs1/pathall/irtfcoadd_2.p _avg.file.tmp _weight.file.tmp4 > _weight.file.tmp5 rename ("_weight.file.tmp5", wweightname) del ("_weight.file.tmp?", ver-) del ("_avg.file.tmp", ver-) } if(pputweight){ if(access("_tmp.wweighting"))del("_tmp.wweighting",ver-) join(ccomblist1,wweightname,out="_tmp.wweighting") list="_tmp.wweighting" while (fscan (list, img, wt) !=EOF) { hedit(img,wwordweight,wt,add+,ver-,show-,update+) } del("_tmp.wweighting",ver-) } } list="" # IF DESIRED, DETERMINE NORMALIZATION FACTORS AND ADD TO IMAGE HEADERS if(getnorm){ print("===) Finding normalization factors (variances) and putting into image headers...") del ("_norm.file.tmp?", ver-, >& "dev$null") # first find iterative rms of each image if(!access(sstatfile)){ if(maskedstat){ iterstat.nsigrej=5. iterstat.maxiter=10 if(!access("_norm.file.tmp1"))maskstat("@"//ccomblist1,"!BPM",1,lower=INDEF,upper=INDEF,iterstat+,ver-,printit+, >> "_norm.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_norm.file.tmp1", sstatfile, ver-) } else { if(!access("_norm.file.tmp1"))iterstat("@"//ccomblist1,nsigrej=5.,maxiter=10,lower=INDEF,upper=INDEF,print+,ver-, >> "_norm.file.tmp1") if(sstatfile!="_nonexistentFILEname_")copy("_norm.file.tmp1", sstatfile, ver-) } } else { copy (sstatfile, "_norm.file.tmp1", ver-) } # compute the normalization factor = (rms**2.) #fields ("_norm.file.tmp1", 3, >> "_norm.file.tmp2") #filecalc ("_norm.file.tmp2", "$1*$1", calctype="real", >> "_norm.file.tmp4") fields ("_norm.file.tmp1", "3,3", >> "_norm.file.tmp2") !/scrs1/pathall/irtfcoadd_5.p _norm.file.tmp2 > _norm.file.tmp4 if(access("_tmp.norm"))del("_tmp.norm",ver-) join(ccomblist1,"_norm.file.tmp4",out="_tmp.norm") list="_tmp.norm" while (fscan (list, img, wt) !=EOF) { hedit(img,nnormname,wt,add+,ver-,show-,update+) } del("_tmp.norm",ver-) del ("_norm.file.tmp?", ver-) } list="" # SUBPIXEL SHIFTING noappend=no # First expand images if subpixel shifting is desired if (mag!=1){ if(!sspshift)sshiftintlist=sshiftexactlist//blk # If output image list already exists, do not append to it if (access(ccomblist2)){ noappend=yes print("WARNING! Output image list "//ccomblist2//" already exists.") print("Any images listed therein will be created if they do not exist,") print("but no image names will be appended to this preexisting file.") } print("===) Expanding images by factor "//mag//" in both directions...") list=ccomblist1 # Go through image list while (fscan (list, img) !=EOF) { fileroot(img,validim+) image=fileroot.root # Do the magnification as long as the image does not already exist or has not # already been rotated/magnified if(!access(image//blk//".imh")){ imgets(image,"ROTATED",>&"dev$null") if(imgets.value=="0"){ # Divide by mag squared to conserve total number of counts in input image. imar(image,"/",mag2,"_"//blk//image,pixt="real",calc="real",ver-) blkrep("_"//blk//image,image//blk,mag,mag) imdel("_"//blk//image,ver-) if(!noappend)print (image//blk, >> ccomblist2) # Now replicate the bad pixel mask, if not already done. imgets(image//blk,"BPMASK",>&"dev$null") if(imgets.value=="0")imgets(image//blk,"BPM",>&"dev$null") oldbp=imgets.value newbp=blk//oldbp if(!access(newbp)){ blkrep(oldbp,newbp,mag,mag) print(newbp//".pl", >> bprotlist) } # Insert the replicated bad pixel mask in the image header hedit(image//blk,"BPMASK",newbp,add+,ver-,show-,update+) hedit(image//blk,"BPM",newbp,add+,ver-,show-,update+) } else { # If input image already rotated, only print a warning. print("WARNING! "//image//".imh already rotated; not rotated again") } } else { # If output image already exists, only print a warning. print("WARNING! "//image//blk//".imh already exists; not overwritten") } # Next image } # # If output subpixel shifts file doesn't exist, create it if(!access(sshiftintlist)) { print("===> Calculating shifts for expanded images...") if (access("tmp"//sshiftintlist))del("tmp"//sshiftintlist,ver-) list="" list=sshiftexactlist # Convert old shifts to new while (fscan (list,xold,yold) != EOF) { xnew=mag*xold ynew=mag*yold print (xnew, ynew, >> "tmp"//sshiftintlist) } # Round off to integer shifts (in units of new pixels, natch). #filecalc("tmp"//sshiftintlist,"$1;$2",format="%4.0f %4.0f", >> sshiftintlist) del("tmp?.sshiftintlist",ver-) copy ("tmp"//sshiftintlist, "tmp1.sshiftintlist") !/scrs1/pathall/irtfcoadd_3.p tmp1.sshiftintlist > tmp2.sshiftintlist rename ("tmp2.sshiftintlist", sshiftintlist) del("tmp?.sshiftintlist",ver-) del("tmp"//sshiftintlist,ver-) # If output subpixel shifts file does exist, just print warning } else { if(sshiftintlist==sshiftexactlist//blk)print("WARNING! "//sshiftintlist//" already exists; not overwritten") } # Correction of zero offsets for lower flux/pixel in blkrep'd images, if needed if(!sspscale) { # Zero offsets from list if(checkzero=="@") { if(!access(zzeroname//blk)) { #filecalc(zzeroname,"$1/"//mag2,format="%9.7f", >> zzeroname//blk) del ("_tmpmag2", ver-, >& "dev$null") del ("_zzeroname*", ver-, >& "dev$null") print (mag2, >> "_tmpmag2") copy (zzeroname, "_zzeroname", ver-) !/scrs1/pathall/irtfcoadd_4.p _tmpmag2 _zzeroname > _zzeronameblk rename ("_zzeronameblk", zzeroname//blk) del ("_zzeroname*", ver-, >& "dev$null") del ("_tmpmag2", ver-, >& "dev$null") newzzeroname=zzeroname//blk zzeroname=newzzeroname zzeroing="@"//newzzeroname } } # Zero offsets from header keyword if(checkzero=="!"){ oldzs=mktemp(".oz") newzs=mktemp(".nz") hsel("@"//ccomblist1,wwordzero,yes, >> oldzs) #filecalc(oldzs,"$1/"//mag2,format="%9.7f", >> newzs) del ("_???zs", ver-, >& "dev$null") del ("_tmpmag2", ver-, >& "dev$null") print (mag2, >> "_tmpmag2") copy (oldzs, "_oldzs", ver-) !/scrs1/pathall/irtfcoadd_4.p _tmpmag2 _oldzs > _newzs rename ("_newzs", newzs, ver-) del ("_???zs", ver-, >& "dev$null") del ("_tmpmag2", ver-, >& "dev$null") join(ccomblist2,oldzs,output=newzs) list="" list=newzs while (fscan (list,img,levelzero) != EOF) { hedit(img,wwordzero,levelzero,add+,ver-,show-,update+) } del(oldzs,ver-) del(newzs,ver-) } } # End of subpixel shift option } list="" # INSERT NEW ZERO OFFSETS INTO REPLICATED IMAGE HEADERS IF DESIRED. if(access(ccomblist2) && checkzero=="@"){ if(pputzero) { if(!sspscale && access(zzeroname//blk))zzeroname=zzeroname//blk del("_tmp.zzeroing",ver-,>&"dev$null") join(ccomblist2,zzeroname,out="_tmp.zzeroing") list="_tmp.zzeroing" while (fscan (list, img, zf) !=EOF) { hedit(img,wwordzero,zf,add+,ver-,show-,update+) } del("_tmp.zzeroing",ver-,>&"dev$null") } } list="" # PRE-ZEROING: INCORPORATE ZERO OFFSETS BEFORE IMCOMBINE IF DESIRED if(pprezero){ print("===> Doing zero offsetting prior to imcombine...") # Prevent imcombine from zeroing twice zzeroing="none" # If list of images to coadd doesn't exist, create it! if (!access(ccomblist2))copy(ccomblist1,ccomblist2,ver-) # In case of zero offsets taken from header keyword, make file_of_zeros if(checkzero=="!"){ file_of_zeros=mktemp(".foz") hsel("@"//ccomblist2,wwordzero,yes, >> file_of_zeros) } if(checkzero=="@")file_of_zeros=zzeroname list_of_zeros=mktemp(".loz") join(ccomblist2,file_of_zeros,output=list_of_zeros) if(checkzero=="!")del(file_of_zeros,ver-) # If stacking, and image already exists, do not bother if(sstack && access(sstackimage//".imh")){ print("Not bothering to pre-zero... stacked image already exists.") } else { # Do zero offsetting unless it has already been done list=list_of_zeros while (fscan (list,img,levelzero) != EOF) { imgets(img,"PREZERO",>&"dev$null") if(imgets.value=="0"){ imar(img,"+",levelzero,img,pixt="real",calc="real",ver-) hedit(img,"PREZERO",levelzero,add+,ve-,sho-,updat+,>&"dev$null") } else { print("No action -- image "//img//" already zero-offset by "//imgets.value) } } } } list="" # COADD images # If output coadded image doesn't exist, create it! if (!access(ooutimage//"."//oextimage)){ # If list of images to coadd doesn't exist, create it! if (!access(ccomblist2))copy(ccomblist1,ccomblist2,ver-) if (sstack){ # If output stacked image doesn't exist, create it! if (!access(sstackimage//"."//oextimage)){ print("===) Stacking the images...") imstack("@"//ccomblist2,sstackimage,title="Stacked images listed in "//ccomblist2) } if(nnewmask) { hedit(sstackimage,"BPM",bbadmask,add+,ver-,show-,update+) } print("===) Combining the images...") if (makeavg){ imcombine(sstackimage, ooutimage, sigma=s_sigma, plfile=s_plfile, combine="average", reject="none", project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale=sscaling, zero=zzeroing, weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=s_lthresh, hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=s_rdnoise, gain=s_gain, snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } else{ if (stdpars) { imcombine(sstackimage, ooutimage, sigma="", plfile="", combine="average", reject="ccdclip", project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale=sscaling, zero=zzeroing, weight=wweighting, statsec="", expname=eexpname, lthresh=INDEF, hthresh=INDEF, nlow=1., nhigh=1., nkeep=1., mclip+, lsigma=5., hsigma=5., rdnoise=s_rdnoise, gain=s_gain, snoise="0.", sigscale=s_sigscale, pclip=-0.5, grow=0., logfile='STDOUT', >> llogfile) } else { imcombine(sstackimage, ooutimage, sigma=s_sigma, plfile=s_plfile, combine=s_combine, reject=s_reject, project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale=sscaling, zero=zzeroing, weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=s_lthresh, hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=s_rdnoise, gain=s_gain, snoise=s_snoise, sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } } # Stacked images only: compute correct UNWEIGHTED average exposure time del("tmp_"//ccomblist2,ver-,>&"dev$null") hsel ("@"//ccomblist2,eexpname,yes, >> "tmp_"//ccomblist2) type ("tmp_"//ccomblist2) | average (opt="new_sample") | scan (eexptime,p,b) hedit(ooutimage,eexpname,eexptime,add+,ver-,show-,update+) del("tmp_"//ccomblist2,ver-,>&"dev$null") # if(uunstack)imdel(sstackimage,ver-) } else{ if(nnewmask) { list=ccomblist2 while (fscan (list, img) !=EOF) { imgets(img,"BPMASK",>&"dev$null") if(imgets.value=="0") { imgets(img,"BPM",>&"dev$null") hedit(img,"BPMASK",imgets.value,add+,ver-,show-,update+) hedit(img,"BPM",bbadmask,add+,ver-,show-,update+) } else { hedit(img,"BPM",bbadmask,add+,ver-,show-,update+) } } } print("===) Combining the images...") if (makeavg){ imcombine("@"//ccomblist2, ooutimage, sigma=s_sigma, plfile=s_plfile, combine="average", reject="none", project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale=sscaling, zero=zzeroing, weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=s_lthresh, hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=s_rdnoise, gain=s_gain, snoise=s_snoise, sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } else{ if (stdpars) { imcombine("@"//ccomblist2, ooutimage, sigma="", plfile="", combine="average", reject="ccdclip", project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale=sscaling, zero=zzeroing, weight=wweighting, statsec="", expname=eexpname, lthresh=INDEF, hthresh=INDEF, nlow=1., nhigh=1., nkeep=1., mclip+, lsigma=5., hsigma=5., rdnoise=s_rdnoise, gain=s_gain, snoise="0.", sigscale=0.1, pclip=-0.5, grow=0., logfile='STDOUT', >> llogfile) } else { imcombine("@"//ccomblist2, ooutimage, sigma=s_sigma, plfile=s_plfile, combine=s_combine, reject=s_reject, project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale=sscaling, zero=zzeroing, weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=s_lthresh, hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=s_rdnoise, gain=s_gain, snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } } } list="" # Put original BPM back if necessary if(nnewmask) { list=ccomblist2 while (fscan (list, img) !=EOF) { imgets(img,"BPMASK",>&"dev$null") hedit(img,"BPM",imgets.value,add+,ver-,show-,update+) } } list="" # Header parameters for the coadded image hedit(ooutimage,"title","Coadded image from "//ccomblist2//" and "//sshiftintlist,ver-,show-,update+) time | scan (theadline) addcomment(ooutimage,"phat.optcoadd: "//theadline,ver-) addcomment(ooutimage,"Coadded from "//ccomblist2//" and "//sshiftintlist,ver-) addcomment(ooutimage,"makeavg="/makeavg//", zero shifts from "//zzeroing,ver-) addcomment(ooutimage,"scaling factors from "//sscaling//", and stdpars="//stdpars,ver-) # AIRMASS # Set airmass of coadded image to effective airmass if default scaling !used if(!ddefscale){ del("_airmass.tmp?",ver-,>&"dev$null") hsel("@"//ccomblist2, "airmass", yes, >> "_airmass.tmp1") type("_airmass.tmp1" | average opt="new_sample", >> "_airmass.tmp2") effairmass=real(average.mean) hedit(ooutimage,"airmass",(effairmass),add+,ver-,show-,update+) del("_airmass.tmp?",ver-,>&"dev$null") # Set airmass of coadded image to reference airmass if default scaling was used } else { hedit(ooutimage,"airmass",(aairzero),add+,ver-,show-,update+) } # EXPOSURE NORMALIZATION -- normalize coadded image to total exposure time. # If weighting was done w/a stacked image, first find correct WEIGHTED exptime del ("_exptime.tmp?", ver-, >& "dev$null") if(sstack && wweighting!="none"){ # First get individual image exposure times del ("_exptime.tmp?", ver-, >& "dev$null") hsel("@"//ccomblist2,eexpname,yes, >> "_exptime.tmp1") # Join individual image exptimes with weights join("_exptime.tmp1", wweightname, output="_exptime.tmp3") # Calculate individual image weighted exposure times #filecalc ("_exptime.tmp3", "$1*$2", calctype="real", >> "_exptime.tmp4") !/scrs1/pathall/irtfcoadd_5.p _exptime.tmp3 > _exptime.tmp4 # Calculate correct weighted exposure time type ("_exptime.tmp4" | average opt="new_sample",>> "_exptime.tmp5") # Insert correct weighted exposure time into image header hedit(ooutimage,eexpname,average.sum,add+,ver-,show-,update+) } # First find total exposure time of input images hsel("@"//ccomblist2,eexpname,yes, >> "_exptime.tmp6") type("_exptime.tmp6" | average opt="new_sample", >> "_exptime.tmp7") del ("_exptime.tmp?", ver-, >& "dev$null") unwt_avg_exptime=real(average.mean) eexptime=real(average.sum) # Get output exposure time of coadded image imgets(ooutimage,eexpname) wt_avg_exptime=real(imgets.value) # Insert total exposure time into coadded image header hedit(ooutimage,eexpname,eexptime,add+,ver-,show-,update+) # Multiply coadded image by (total_exposure_time/output_exposure_time) imar(ooutimage, "*", eexptime/wt_avg_exptime, ooutimage) print("", >> llogfile) print("Coadded image multiplied by "//eexptime/wt_avg_exptime//" to bring its flux", >> llogfile) print("in line with the total exposure time of "//eexptime//" s.", >> llogfile) # CREATE WEIGHTED EXPOSURE MAP # Create exposure maps if the output coadded-image exposure map does not exist. # Routine allows for images of different exposure times, sizes, and BPMs, while # creating as few images as possible consistent with meeting those criteria. explist="" if(!access(eexpmap//"."//oextimage)){ # Don't recreate exposure maps to be stacked if stacked expmap image exists if(!sstack || (sstack && !access("exp"//sstackimage//"."//oextimage))) { print("===) Creating exposure maps...") subimgold="_oops" testold=0. test1old=0 test2old=0 expmaskold="" # If list of images to coadd doesn't exist, create it! if (!access(ccomblist2))copy(ccomblist1,ccomblist2,ver-) list=ccomblist2 explist=ccomblist2//"exp" if(access(explist))del(explist,ver-,>&"dev$null") while (fscan (list, img) !=EOF) { # get image parameters: xsize, ysize, exptime, badpixelmask fileroot(img,validim+) imgets(img,"i_naxis1") test1=int(imgets.value) imgets(img,"i_naxis2") test2=int(imgets.value) imgets(img,eexpname) exposure=real(imgets.value) imgets(img,"BPMASK") expmask=str(imgets.value) # if any of those parameters differ from the previous image, need to create a # new exposure map for eventual coadding. if(test1!=test1old || test2!=test2old || exposure!=testold || expmask!=expmaskold) { subimg = mktemp(fileroot.root) print (subimg, >> explist) # imcalc(img,subimg,"im1*0+"//exposure,ver-) imcopy(img,subimg,ver-) imreplace(subimg,exposure,lower=-10000.,upper=INDEF) if(nnewmask)hedit(subimg,"BPM",bbadmask,add+,ver-,show-,update+) test1old=test1 test2old=test2 testold=exposure expmaskold=expmask subimgold=subimg } else { print (subimgold, >> explist) } } } # Create coadded-image exposure map print("===> Creating coadded-image exposure map...") if(sstack) { if(!access("exp"//sstackimage//"."//oextimage)) { print("===> Stacking exposure maps...") imstack("@"//explist,"exp"//sstackimage,title="Stacked exposure maps listed in "//explist) } else { print("Stacked exposure map image already exists-- not overwritten.") } if(nnewmask) { hedit("exp"//sstackimage,"BPM",bbadmask,add+,ver-,show-,update+) } imcombine("exp"//sstackimage, eexpmap, sigma="", plfile="", combine="average", reject="none", project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale="none", zero="none", weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) if(nnewmask) { imgets("exp"//sstackimage,"BPMASK",>&"dev$null") hedit("exp"//sstackimage,"BPM",imgets.value,add+,ve-,sho-,upda+) } if(uunstack)imdel("exp"//sstackimage,ver-) } else { imcombine("@"//explist, eexpmap, sigma="", plfile="", combine="average", reject="none", project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=s_blank, scale="none", zero="none", weight=wweighting, statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } # following line had been commented out; replaced with 2nd line following # imreplace(eexpmap, -99999., lower=INDEF, upper=-10000.) imreplace(eexpmap, -99999., lower=INDEF, upper=-1.) hedit(eexpmap,"title","Weighted exposure map for "//ooutimage,add+,ve-,sho-,updat+) imgets(eexpmap,"ncombine") nncombine=int(imgets.value) if(explist!=""){ imdel("@"//explist, ver-, >& "dev$null") del(explist, ver-, >& "dev$null") } } else { print("Output exposure map already exists-- new one not created.") print("Output exposure map already exists-- new one not created.", >> llogfile) } # SUBTRACT constant background from image and DIVIDE by normalized # WEIGHTED EXPOSURE MAP to get image with globally constant exposure time if(!access(ooutimage//"mask.pl")){ # create mask image with border pixels = 0 whether originally 0 or -99999 imar(eexpmap, "+", "99999.", "j1"//eexpmap, noact-, ver-) imreplace("j1"//eexpmap, 1., lower=0.1, upper=INDEF) imar(eexpmap, "*", "j1"//eexpmap, "j2"//eexpmap, noact-, ver-) imreplace("j2"//eexpmap, 1., lower=0.1, upper=INDEF) imcopy("j2"//eexpmap, ooutimage//"mask.pl", ver-) imdel("j?"//eexpmap//"."//oextimage,ver-) } maskstat(ooutimage, ooutimage//"mask.pl", 1, lower=INDEF, upper=INDEF, iterstat+, ver-, printit+, >> llogfile) imar(ooutimage, "-", iterstat.mean, ooutimage, ver-, noact-) # imar(eexpmap,"/",wt_avg_exptime,"j1"//eexpmap,ver-,noact-) imar("j1"//eexpmap,"/",ooutimage//"mask.pl","j2"//eexpmap,ver-,noact-,divze=-99999.) imar(ooutimage,"/","j2"//eexpmap//"."//oextimage,ooutimage,ver-,noact-,divze=-99999.) imdel("j?"//eexpmap//"."//oextimage,ver-) # print("Weighted exposure map normalized by "//wt_avg_exptime, >> llogfile) print("and divided into output coadded image.", >> llogfile) # FLIP image over to correct orientation if necessary (N is up, E is left) if(flip){ imcopy(ooutimage//"[-*,*]", ooutimage, ver-) addcomment(ooutimage,"Image has been flipped L-R from orig. orientation",ver-) print("WARNING! Image has been flipped L-R! (i.e. imcopy orig[-*,*] new)") } } else { print("Output coadded image already exists-- coadding not done.") print("Output coadded image already exists-- coadding not done.", >> llogfile) } # NORMALIZATION MAPS # Create normalization maps if the output normalization map does not exist. # Routine allows for images of different exposure times, sizes, and BPMs, while # creating as few images as possible consistent with meeting those criteria. explist="" wtlist="" if(!access(nnormmap//"."//oextimage)){ # Don't recreate normalization maps to be stacked if stacked norm. image exists if(!sstack || (sstack && !access("norm"//sstackimage//"."//oextimage))) { print("===) Creating normalization maps...") subimgold="_oops" wtimgold="_oops" waitold=0. testold=0. test1old=0 test2old=0 expmaskold="" tplimgold="" # If list of images to coadd doesn't exist, create it! if (!access(ccomblist2))copy(ccomblist1,ccomblist2,ver-) list=ccomblist2 explist=ccomblist2//"norm" wtlist=ccomblist2//"wt" if(access(explist))del(explist,ver-,>&"dev$null") if(access(wtlist))del(wtlist,ver-,>&"dev$null") while (fscan (list, img) !=EOF) { # get image parameters: xsize, ysize, weight, norm.factor, badpixelmask fileroot(img,validim+) imgets(img,"i_naxis1") test1=int(imgets.value) imgets(img,"i_naxis2") test2=int(imgets.value) imgets(img,wwordweight) wait=real(imgets.value) imgets(img,nnormname) exposure=real(imgets.value) imgets(img,"BPMASK") expmask=str(imgets.value) imgets(img,"TPLIMG",>&"dev$null") tplimg=str(imgets.value) # if any of those parameters differ from the previous image, need to create a # new normalization map for eventual coadding. if(test1!=test1old || test2!=test2old || wait!=waitold || exposure!=testold || expmask!=expmaskold || tplimg!=tplimgold) { tmpimg = mktemp("_tmp") tmpimg2 = mktemp("_tmp2") subimg = mktemp("_nm") wtimg = mktemp("_wt") print (subimg, >> explist) print (wtimg, >> wtlist) # want to end up with wtimg = wait or -99999.; # subimg = exposure * (tpl**2.) * wait**2. or -99999.; # make tmpimg -99999 where img < -10000, 0 elsewhere imcopy(img,tmpimg,ver-) imreplace(tmpimg,0.,lower=-10000.,upper=INDEF) imreplace(tmpimg,-99999.,lower=INDEF,upper=-9999.) # make wtimg 0 where img < -10000, "wait" elsewhere imar(tmpimg,"+",99999.,wtimg,ver-) imreplace(wtimg,wait,lower=10000.,upper=INDEF) # tpl if(ttpl && access(tplimg)) { tpltmp=mktemp("tpltmp") imgets(tplimg,"i_naxis1") tpl1=int(imgets.value) imgets(tplimg,"i_naxis2") tpl2=int(imgets.value) # if tpl image is not same size as actual image, assume the image has been # copied to subsection of bigger image starting at (1,1), and that the rest of # the image is -99999 (thus no imar(img,"-",img,subimg) needed. (ie 61"+90") if(tpl1!=test1 || tpl2!=test2) { imcopy(img,subimg,ver-) # tpltmp = tmpimg + exposure * (wtimg / tplimg)**2. #imcalc(tmpimg//","//wtimg//","//tplimg,tpltmp,"im1+"//str(exposure)//"*(im2/im3)**2.",ver-) imcalc(wtimg//","//tplimg,tmpimg2,str(exposure)//"*(im1/im2)**2.",ver-) imar(tmpimg, "+", tmpimg2, tpltmp, ver-, noact-) imcopy(tpltmp, subimg//"[1:"//str(tpl1)//",1:"//str(tpl2)//"]", ver-) imdel(tmpimg2, ver-) imdel(tpltmp, ver-) } else { # subimg = tmpimg + exposure * (wtimg / tplimg)**2. #imcalc(tmpimg//","//wtimg//","//tplimg,subimg,"im1+"//str(exposure)//"*(im2/im3)**2.",ver-) imcalc(wtimg//","//tplimg,tmpimg2,str(exposure)//"*(im1/im2)**2.",ver-) imar(tmpimg,"+",tmpimg2,subimg,ver-,noact-) imdel(tmpimg2,ver-) } # no tpl } else { # subimg = tmpimg + exposure * wtimg**2. (exposure=exptime or variance) #imcalc(wtimg,tmpimg2,"(im1**2.)*"//str(exposure),ver-) imar (wtimg,"*",wtimg,tmpimg2,ver-,noact-) imar (tmpimg2,"*",str(exposure),tmpimg2,ver-,noact-) imar(tmpimg,"+",tmpimg2,subimg,ver-,noact-) imdel(tmpimg2,ver-) } # now make wtimg -99999 where img < -10000, "wait" elsewhere # tmpimg2 = mktemp("_tmp2") imren(wtimg,tmpimg2,ver-) imar(tmpimg2,"+",tmpimg,wtimg,ver-) imdel(tmpimg2,ver-) imdel(tmpimg,ver-) if(nnewmask)hedit(wtimg,"BPM",bbadmask,add+,ver-,show-,update+) if(nnewmask)hedit(subimg,"BPM",bbadmask,add+,ver-,show-,update+) test1old=test1 test2old=test2 tplimgold=tplimg waitold=wait testold=exposure expmaskold=expmask subimgold=subimg wtimgold=wtimg } else { print (subimgold, >> explist) print (wtimgold, >> wtlist) } } } # Create coadded-image normalization map # First create variance map print("===> Creating coadded-image normalization map...") if(sstack) { if(!access("norm"//sstackimage//"."//oextimage)) { print("===> Stacking variance maps...") imstack("@"//explist,"norm"//sstackimage,title="Stacked normalization maps listed in "//explist) } else { print("Stacked variance map image already exists-- not overwritten.") } if(nnewmask) { hedit("norm"//sstackimage,"BPM",bbadmask,add+,ver-,show-,updat+) } if(access("junknorm."//oextimage))imdel("junknorm."//oextimage,ver-) if(access(nnormmap//"pl.pl"))imdel(nnormmap//"pl.pl",ver-) imcombine("norm"//sstackimage, "junknorm", sigma="", plfile=nnormmap//"pl", combine="average", reject="none", project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale="none", zero="none", weight="none", statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) if(nnewmask){ imgets("norm"//sstackimage,"BPMASK",>&"dev$null") hedit("norm"//sstackimage,"BPM",imgets.value,ad+,ve-,sho-,upda+) } if(uunstack)imdel("norm"//sstackimage,ver-) } else { if(access("junknorm."//oextimage))imdel("junknorm."//oextimage,ver-) if(access(nnormmap//"pl.pl"))imdel(nnormmap//"pl.pl",ver-) imcombine("@"//explist, "junknorm", sigma="", plfile=nnormmap//"pl", combine="average", reject="none", project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale="none", zero="none", weight="none", statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } if(explist!=""){ imdel("@"//explist, ver-, >& "dev$null") del(explist, ver-, >& "dev$null") } # Now create weight map if(sstack) { if(!access("wt"//sstackimage//"."//oextimage)) { print("===> Stacking weight maps...") imstack("@"//wtlist,"wt"//sstackimage,title="Stacked weight maps listed in "//wtlist) } else { print("Stacked weight map image already exists-- not overwritten.") } if(nnewmask) { hedit("wt"//sstackimage,"BPM",bbadmask,add+,ver-,show-,updat+) } if(access("junkweight."//oextimage))imdel("junkweight."//oextimage,ver-) imcombine("wt"//sstackimage, "junkweight", sigma="", plfile="", combine="average", reject="none", project+, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale="none", zero="none", weight="none", statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) if(nnewmask){ imgets("wt"//sstackimage,"BPMASK",>&"dev$null") hedit("wt"//sstackimage,"BPM",imgets.value,add+,ve-,sho-,upda+) } if(uunstack)imdel("wt"//sstackimage,ver-) } else { if(access("junkweight."//oextimage))imdel("junkweight."//oextimage,ver-) imcombine("@"//wtlist, "junkweight", sigma="", plfile="", combine="average", reject="none", project-, offsets=sshiftintlist, masktype=s_masktyp, maskvalue=s_maskval, blank=0., scale="none", zero="none", weight="none", statsec=s_statsec, expname=s_expname, lthresh=0., hthresh=s_hthresh, nlow=s_nlow, nhigh=s_nhigh, nkeep=s_nkeep, mclip+, lsigma=s_lsigma, hsigma=s_hsigma, rdnoise=0., gain=1., snoise="0.", sigscale=s_sigscale, pclip=s_pclip, grow=s_grow, logfile='STDOUT', >> llogfile) } if(wtlist!=""){ imdel("@"//wtlist, ver-, >& "dev$null") del(wtlist, ver-, >& "dev$null") } # Final steps to create normalization image imgets("junknorm","ncombine") nncombine=int(imgets.value) if(access(nnormmap//"num."//oextimage))imdel(nnormmap//"num."//oextimage,ver-) imar(nnormmap//"pl","-",nncombine,nnormmap//"num.imh") imar(nnormmap//"num.imh","*",-1.,nnormmap//"num.imh") imar("junknorm","*",nnormmap//"num.imh","junknorm",ver-,noact-) imar("junkweight","*",nnormmap//"num.imh","junkweight",ver-,noact-) #imcalc("junkweight,"//eexpmap//",junknorm",nnormmap,"((im1*im2)**2.)/im3",nullval=0.,ver-) imar("junkweight","*",eexpmap,"junkweight",ver-,noact-) imar("junkweight","*","junkweight","junkweight",ver-,noact-) imar("junkweight","/","junknorm",nnormmap,ver-,noact-) minmax(nnormmap,force+,update+,ver-) imar(nnormmap,"/",minmax.maxval,nnormmap,ver-,noact-) hedit(nnormmap,"title","Normalization map for "//ooutimage,add+,ve-,sho-,updat+) imdel("junkweight."//oextimage,ver-) imdel("junknorm."//oextimage,ver-) imdel(nnormmap//"num.imh",ver-) imdel(nnormmap//"pl.pl",ver-) if(flip){ imcopy(nnormmap//"[-*,*]", nnormmap, ver-) addcomment(nnormmap,"Image has been flipped L-R from orig. orientation",ver-) } } else { print("Output normalization map already exists-- new one not created.") print("Output normalization map already exists-- new one not created.", >> llogfile) } # UNDO PRE-ZEROING: if zeroing was done before imcombine, undo it if desired if(pprezero && uunzero){ # If block-replication was done, skip step if those images are to be deleted if(mag!=1 && ccleanup && !noappend){ print("", >> llogfile) } else { print("===> Undoing zero offsetting...") list=list_of_zeros while (fscan (list,img,levelzero) != EOF) { imgets(img,"PREZERO",>&"dev$null") if(imgets.value!="0"){ tmpzero=real(imgets.value) imar(img,"-",tmpzero,img,pixt="real",calc="real",ver-) hedit(img,"PREZERO",del+,ver-,show-,updat+,>&"dev$null") } else { print("No action -- "//img//" not pre-zeroed in the first place!") } } } } if(pprezero){ if(sstack && access(sstackimage//"."//oextimage)){print("", >> llogfile)} else{del(list_of_zeros,ver-,>&"dev$null")} } list="" # UNDO PRE-SCALING: if scaling was done before imcombine, undo it if desired if(pprescale && uunscale){ # If block-replication was done, skip step if those images are to be deleted if(mag!=1 && ccleanup && !noappend){ print("", >> llogfile) } else { print("===> Undoing scaling factors...") list=list_of_scales while (fscan (list,img,sf) != EOF) { imgets(img,"PREZERO",>&"dev$null") if(imgets.value!="0"){ print("WARNING! "//img//" still pre-scaled: pre-zeroing not undone first") } else { imgets(img,"PRESCALE",>&"dev$null") if(imgets.value!="0"){ imar(img,"/",sf,img,pixt="real",calct="real",ver-) hedit(img,"PRESCALE",del+,ver-,sho-,updat+,>&"dev$null") if(ddefscale){ imgets(img,"AIRMOLD",>&"dev$null") hedit(img,"AIRMASS",imgets.value,add+,del-,ver-,sho-,updat+,>&"dev$null") hedit(img,"AIRMOLD",del+,ver-,sho-,updat+,>&"dev$null") } } else { print("No action -- "//img//" not pre-scaled in the first place!") } } } } } if(pprescale)del(list_of_scales,ver-,>&"dev$null") list="" # IMSHIFTS FILE # Create *.imshifts file, listing images & offsets used by masklet & photcheck if (!access(ooutimage//".imshifts")) { print("===> Creating output imshifts file...") if (!access(ccomblist2))copy(ccomblist1,ccomblist2,ver-) join(ccomblist2,sshiftintlist,output=ooutimage//".imshifts_tmp") # Find minimum x and y shift values and subtract them from output offsets listimshift=ooutimage//".imshifts_tmp" list="" list=listimshift xmin=100000 ymin=100000 while (fscan (list,img,newx,newy) != EOF) { if (newx < xmin) { xmin = newx } if (newy < ymin) { ymin = newy } } newx=0 newy=0 list="" list=listimshift while (fscan (list,img,oldx,oldy) != EOF) { newx = oldx - xmin newy = oldy - ymin print(img, " ", newx, newy, >> ooutimage//".imshifts") } del(ooutimage//".imshifts_tmp",ver-) } else { print("Output imshifts file already exists-- not overwritten.") } # Clean up. if(mag!=1){ if(ccleanup && !noappend){ if(access(bprotlist)){ imdel("@"//bprotlist,ver-,>&"dev$null") del(bprotlist,ver-,>&"dev$null") } if(access(ccomblist2))imdel("@"//ccomblist2,ver-,>&"dev$null") del(ccomblist2,ver-,>&"dev$null") del(sshiftexactlist//blk,ver-,>&"dev$null") del(zzeroname//blk,ver-,>&"dev$null") } } else { del(ccomblist2,ver-,>&"dev$null") } print(" ") print(ooutimage//", "//eexpmap//" (exposure map), imshifts file,") print("and "//nnormmap//" (normalization map) have been created.") #print("Next task is `mkobjmask' or `photcheck'.") } else { print("WARNING: tasks addcomment, fileroot, and/or iterstat are not loaded!") print("Please load the appropriate package(s) and restart this task.") } list="" print(" ") beep end phat_alone/src/addcomment.cl100644 1332 567 2461 6503624107 15425 0ustar hallast_hyeeprocedure addcomment (image,comment) # Script to append 'COMMENT' cards to the image header. # All existing 'COMMENT' cards are collated and moved to the end of # the header, and the new card is added afterward. # # 930730: created by Mark Dickinson string image {prompt="Image(s) to which to append comment card"} string comment {prompt="Comment"} bool verify {no,prompt="Verify header?"} bool answer {yes,prompt="Update header?",mode="q"} struct *imglist begin string im,com,inlist,headfile,img,check bool setheader if (!verify) setheader = yes im = image com = comment inlist = mktemp("tmp$addc") sections (im,option="fullname",>inlist) imglist = inlist while (fscan(imglist,img) != EOF) { headfile = mktemp("_headerjj") hfix (img,command="!grep -v 'COMMENT =' $fname > "//headfile,update-) hfix (img,command="!grep 'COMMENT =' $fname >> "//headfile,update-) print("COMMENT = '",com,"'",>>headfile) if (verify) { print ("Comment cards currently read:") match ("COMMENT =",headfile,stop-,print+) if (answer) { setheader = yes } else { setheader = no print ("Header will be left unchanged.") } } if (setheader) hfix (img,command="delete $fname ver- ; copy "//headfile//" $fname",update+) delete (headfile,ve-) } delete (inlist,ver-) imglist = "" end phat_alone/src/addring.cl100644 1332 567 3070 6503624110 14711 0ustar hallast_hyee# addring.cl -- add rings around all objects in a mask image # # Calls task "minv" if bad pixels are zero-valued, since this task needs "bad" # pixels (the ones around which rings are added) to have values of 1 to work. # # 920711: created by John S. Ward # 930519: Mod. by MD to make it compatable with .pl masks, to add mask # as query parameter, to make number of added rings a variable. # 950220: modified for different input, output names and bad pixel values # 950725: fixed bug of too many minv's if outmask=inmask # 970801: changed so that it copies to an intermediate image, thus avoiding # problem of minv messing up original input files procedure addring(inmask,outmask) string inmask {prompt="Name of input mask image"} string outmask {prompt="Name of output mask image"} int ngrow {1,min=0,prompt="Number of pixel rings to grow around mask"} int badval {0,min=0,max=1,prompt="Value for `bad' pixels around which to grow rings"} begin string inmi # equals inmask string outmi # equals outmask int nbox int nbox2 inmi = inmask outmi = outmask # imcopy (inmi, "_tmp_"//inmi, ver-) # if(badval==0)minv("_tmp_"//inmi,"_tmp_"//inmi) imcopy (inmi, outmi, ver-) if(badval==0)minv(outmi,outmi) nbox = 2 * ngrow + 1 nbox2 = nbox * nbox # imarith ("_tmp_"//inmi,"*",nbox2,outmi,ver-) imarith (outmi,"*",nbox2,outmi,ver-) boxcar (outmi,outmi,nbox,nbox) imreplace (outmi,1.,lower=1.,upper=INDEF) imdel ("_tmp_"//inmi, ver-, >& "dev$null") if(badval==0)minv(outmi,outmi) # if(badval==0) { # minv(inmi,inmi) # if(inmi!=outmi)minv(outmi,outmi) # } end phat_alone/src/destripe.cl100644 1332 567 14547 6503624111 15154 0ustar hallast_hyee# destripe -- interactively remove striping from a coadded image # # 960405: created by Pat Hall from phip$checkfringe.cl # 960805: fixed error of default objmask value not being !OBJMASK as claimed # # **edit image list & display option? # **want a mkskycor that is not line-by-line... **images/mfilters package? test procedure destripe(fiximage,outname,objmask) string fiximage {prompt="Name of image to be corrected"} string outname {prompt="Name of image to create"} string objmask {prompt="Object mask to use (default=!OBJMASK)"} int ngrow {1,min=0,max=10,prompt="Number of rings to grow around bad pixels",mode="q"} int boxmin {5,prompt="MKSKYCOR: Minimum smoothing box size at edges",mode="q"} int boxmax {5,prompt="MKSKYCOR: Maximum smoothing box size",mode="q"} bool ok=no {prompt="Continue to next step (yes) or redo (no)?",mode="q"} bool rot=no {prompt="Redo using rotated image?",mode="q"} int z {0,prompt="Number of image to save (0 to delete all)?",mode="q"} begin string logimex, logsurf, countfile, rrootname, iimagelist, ooutname, ffunc string wweighting, fiximg, ffringe, titlestring, fixin, oobjmask, objminv string fixroot, outroot real max, nncols, nnlines, sscale, rorig int x, y, zz, xxord, yyord, xx, nngrow, bboxmin, bboxmax, r, s bool go, ffit, xxterms, ook, first, rrot fixin=fiximage fiximg="_z."//fixin fileroot(fixin,validim+) fixroot="_z."//fileroot.root ooutname=outname fileroot(ooutname,validim+) outroot=fileroot.root oobjmask=objmask fileroot(oobjmask,validim+) if(fileroot.root==""){ imgets(fixin,"OBJMASK") fileroot(imgets.value,validim+) oobjmask=fileroot.root } objminv=fileroot.root//"inv_z.pl" if(access(objminv))objminv=mktemp("objminv") print("Enter initial values of adjustable parameters:") nngrow=ngrow bboxmin=boxmin bboxmax=boxmax zz=0 # check for necessary stuff; if not defined abort task. go=yes if(!deftask("addring")) {go=no} if(!deftask("fileroot")) {go=no} if(!deftask("minv")) {go=no} if(!defpac("nmisc")) {go=no} if(!defpac("ccdred")) {go=no} if(go) { print("Beginning...") imdel(fiximg,ver-,>&"dev$null") imdel("_.tmp"//fiximg,ver-,>&"dev$null") imdel("_.tmp"//objminv,ver-,>&"dev$null") # iterstat to get mode iterstat(fixin,nsigrej=5.,maxiter=10.,print-,verbose-) # imar to subtract mode imar(fixin,"-",iterstat.valmode,fiximg,divzero=0.,ver-,noact-) # OBJECT MASKING STEP ook=no first=yes while(!ook){ print("Masking objects on coadded image...") # if not first time through, get params if(!first){ nngrow=ngrow imdel("_.tmp"//fiximg,ver-) imdel(objminv,ver-) } # addring and/or minv if(nngrow!=0){ addring(oobjmask,"_.tmp"//objminv,ngrow=nngrow,badval=0) minv("_.tmp"//objminv,objminv) imdel("_.tmp"//objminv,ver-,>&"dev$null") } else { minv(oobjmask,objminv) } # nmisc$fixpix imcopy(fiximg,"_.tmp"//fiximg,ver-) fixpix("_.tmp"//fiximg,objminv,ninterp="1") # acceptable? if(first)display(fixin, 1) display("_.tmp"//fiximg, 2) beep ook=ok first=no } imdel(objminv,ver-) imdel(fiximg,ver-) imcopy("_.tmp"//fiximg,fiximg,ver-) # SKY SMOOTHING & SUBTRACTION STEP ccdproc.fixpix=no ccdproc.overscan=no ccdproc.trim=no ccdproc.zerocor=no ccdproc.darkcor=no ccdproc.flatcor=no ccdproc.illumcor=no ccdproc.fringecor=no ccdproc.readcor=no ccdproc.scancor=no x=1 y=2 r=0 ook=no rrot=no # loop as long as desired while(!ook) { print("Making stripe image and subtracting from original image...") # get new params if redoing things if(x!=1){ bboxmin=boxmin bboxmax=boxmax # If rotating, copy original image to temporary image, rotate by 90 degrees # r number of times, transposing first if rotating 360 degrees or more, # and not doing anything if more than 720 degrees of rotation are requested. if(rot){ rrot=yes s=1 r=r+1 rorig=r imdel(fiximg,ver-) imcopy("_.tmp"//fiximg,fiximg,ver-) if(r>=8){ print("WARNING! All possible permutations of rotation and transposition") print("have been done, so pick one as the best and stick with it.") } else { if(r>=4){ print("Transposing image...") imtranspose(fiximg,fiximg) r=r-4 } while(s<=r){ print("Rotating image by "//r*90//" degrees...") imtranspose(fiximg//"[*,-*]",fiximg) s+=1 } } } } # make the stripe correction image if(access(fixroot//"_"//str(x)//".imh"))imdel(fixroot//"_"//str(x),ver-) if(access(fixroot//"_"//str(x)//".hhh"))imdel(fixroot//"_"//str(x),ver-) mkskycor(fiximg,fixroot//"_"//str(x),ccdtype="",xboxmin=bboxmin,yboxmin=bboxmin,xboxmax=bboxmax,yboxmax=bboxmax,clip+,lowsig=2.5,highsig=2.5,>&"dev$null") # if rotating if(rrot){ s=1 if(rorig<8){ print("Setting images back to original orientation...") if(rorig>=4){ imtranspose(fixroot//"_"//str(x),fixroot//"_"//str(x)) imtranspose(fiximg,fiximg) rorig=rorig-4 } while(s<=rorig){ imtranspose(fixroot//"_"//str(x)//"[-*,*]",fixroot//"_"//str(x)) imtranspose(fiximg//"[-*,*]",fiximg) s+=1 } } } # imar orig - mkskycor if(access(outroot//"_"//str(x)//".imh"))imdel(outroot//"_"//str(x),ver-) if(access(outroot//"_"//str(x)//".hhh"))imdel(outroot//"_"//str(x),ver-) imar(fixin,"-",fixroot//"_"//str(x),outroot//"_"//str(x),divzero=0.,ver-,noact-) # inspect the subtracted image print ("===> Displaying striped and de-striped images #"//str(x)//"...") display(fixroot//"_"//str(x), 3) display(outroot//"_"//str(x), 4) # abort loop? beep ook=ok rrot=no x+=1 } # CLEAN UP zz=z if(zz!=0){ imcopy(fixroot//"_"//str(zz),outroot//"stripe",ver-) imcopy(outroot//"_"//str(zz),ooutname,ver-) print("Image "//ooutname//" created using stripe model "//outroot//"stripe") hedit(ooutname,"STRIPEIM",outroot//"stripe",add+,ver-,show-,update+) hedit(outroot//"stripe","title","Stripe image used to create "//ooutname,add+,ver-,update+,show-) } else{ print("No images saved.") } y=0 zz=0 while(y& "dev$null") imdel(ooutname//"_"//str(y),ver-, >& "dev$null") y+=1 } imdel("_.tmp"//fiximg,ver-,>&"dev$null") imdel(fiximg,ver-) } else{ print("Tasks/packages `nmisc', `ccdred', `minv', `addring', or `fileroot' aren't loaded") print("and this task needs them to run. Please load them (nmisc last) and start again.") } beep end phat_alone/src/fileroot.cl100644 1332 567 4753 6503624111 15136 0ustar hallast_hyeeprocedure fileroot(filename) # Routine to parse a file name into its root and extension. # The extension is assumed to be the portion of the file name # which follows the last period in the input string supplied # by the user; the root is everything which preceeds that period. # # 930816: Included parameter 'validim' to force a check to see if the extension # represents a valid IRAF image datatype, and if not, to negate the parsing. # This would be a common usage; often the user only wants to strip off the # portion of the filename after the last period if that substring represents a # valid IRAF image type such as .imh or .pl. Without the 'validim' parameter, # if the file included another period somewhere in its name, then the portion # of the filename after that period would be erroneously returned as an image # extension. At present, the routine only checks for a few datatypes; # this should be expanded in the future. string filename {prompt="File name"} bool validim {yes,prompt="Parse only if extension represents valid image datatype?"} string root {"",prompt="Returned filename root"} string extension {"",prompt="Returned filename extension"} begin string fname # Equals filename string revname # Reversed version of input string int ilen,ipos,ic # String position markers int ii # Counter string imtype = "imh", "pl", "hhh", "qpoe", "qp", "" # Must use null string to terminate! # Get query parameter. fname = filename # Reverse filename string character by character --> revname. ilen = strlen(fname) revname = "" for (ic=ilen; ic>=1; ic-=1) { revname = revname // substr(fname,ic,ic) } # Look for the first period in the reversed name. ipos = stridx(".",revname) # If period exists, break filename into root and extension. Otherwise, # return null values for the extension, and the whole file name for the root. if (ipos != 0) { root = substr(fname,1,ilen-ipos) extension = substr(fname,ilen-ipos+2,ilen) } else { root = fname extension = "" } # If validim = yes and extension != "", check to see if the parsed extension # is a string indicating a valid image data type, e.g. "imh", "pl", etc. # If not, then undo the parsing, replacing the root with the complete input # string 'filename' and setting the extension to null. if (validim && extension != "") { ii = 1 while (imtype[ii] != "") { if (extension == imtype[ii]) break ii += 1 } if (imtype[ii] == "") { root = fname extension = "" } } end phat_alone/src/irrotate.cl100644 1332 567 32355 6503624112 15164 0ustar hallast_hyee# irrotate -- rotate and resample images and recalculate shifts for them # # Calls scripts fileroot, filecalc, addcomment. # # Output: # "*br"//mag//ssuffix//".imh" output rotated, resampled images # inputlist//"br"//mag//ssuffix list of above images # shiftexactlist//"br"//mag//suffix list of shifts for above images # inputlist//"br"//mag//ssuffix//"pl" list of new bad pixel images created # # 960307: created from ircoadd2.cl # 960402: add header keyword ROTATED = angle//"x"//magfac # 960817: allowed for non-creation of shifts file if desired # 970426: added rotation of TPLIMG images # 970505: fixed bug -- need boundary=nearest for rotation of TPLIMG images # 970513: fixed bug which made offsets -0.5 < offsets < 0.5 round to 1. not 0 # 970630: fixed minv bugs, nothing major # # **should include optional tpl division, before bp zeroing procedure irrotate(rotlist,suffix,angle,scale,magfac,shiftexactlist,logfile) string rotlist {prompt="List of images to rotate"} string suffix {prompt="UNIQUE suffix to append to rotated images"} real angle {prompt="Rotation angle in degrees"} real scale {prompt="Input image scale compared to reference image"} int magfac {2,min=1,max=10,prompt="Output image magnification factor (subpix shifts)"} string shiftexactlist="" {prompt="File with EXACT image shifts"} string logfile {prompt="Name of log file"} string i_interp {"linear",enum="nearest|linear|poly3|poly5|spline3",prompt="IMLINTRAN: Interpolation type"} string i_boundary {"constant",enum="nearest|constant|reflect|wrap",prompt="IMLINTRAN: Boundary extension type"} real i_constant {0.,prompt="IMLINTRAN: Value for constant boundary"} bool bpzero=no {prompt="Zero images by bad pixel masks before rotating?"} bool newmask=no {prompt="Override bad pixel masks listed in image headers?"} string badmask {prompt="Bad pixel mask to use instead",mode="q"} bool invert=no {prompt="Invert output bad pixel masks so bad pixels=0?"} real bpfrac {0.75,min=0.,max=0.99,prompt="Threshold bad pixel value in the rotated bp mask"} bool norot=no {prompt="Skip image rotation and calculate shifts only?"} struct *list begin string sshiftfraclist, iinterp, ssuffix, sshiftlist, subimg, explist, bpmimg string rrotlist, bbadmask, sshiftoutlist, ooutimage, zzerofile, sstackimage string llogfile, check, zzeroname, sscalefile, sscalename, img, eexpname, blk string listimshift, mmoreword, wwordzero, mmorename, subimgold, expmaskold, ext string rrotlist1, rrotlist2, sshiftexactlist, newzzeroname, image, newbp, sect string oldbp, holesmask, tmpstring, s1, s2, s3, bprotlist, o_interp, o_boundary string oldtpl, newtpl real avg, x, sig, invmag, valmax, bbpfrac, outfactor, invfactor, aangle real effairmass, wtavg, nncombine, exp, exposure, sf, zf, testold, eexptime real xold, yold, xnew, ynew, angrad, x_shift, y_shift, sscale, tmpreal, y, z real o_constant int mag, mag2, xlength, ylength, j, k, n_cols, n_lines int xmin, ymin, newx, newy, oldx, oldy, test1, test1old, test2, test2old int sstartno, eendno, i, numpix, num, xdim, ydim, newxsize, newysize, ncoadds bool mmakescalefile, sstack, mmakestack, mmorescale, go, mmorehow, pputzero bool nnewmask, sstackdel, sstdstar, ssubpixscale, noappend, iinvert, bbpzero struct theadline rrotlist = rotlist rrotlist1 = rrotlist ssuffix=suffix if(ssuffix==""){ date | scan(s1,s2,i,x,s3,k) y=int(100*x) ssuffix="rot"//i//s2//y//"_" print("Auto-generated image suffix is "//ssuffix) } aangle=angle angrad=aangle*3.1415926535/180. sscale = scale mag = magfac invmag=1./mag invfactor=sscale*invmag mag2=mag*mag blk = "br"//mag rrotlist2 = rrotlist//blk//ssuffix bprotlist = rrotlist//blk//ssuffix//"pl" sshiftexactlist = shiftexactlist sshiftoutlist=sshiftexactlist//blk//ssuffix #sshiftoutlist = sshiftexactlist//blk llogfile = logfile o_interp = i_interp o_boundary = i_boundary o_constant=0. if(o_boundary=="constant")o_constant=i_constant bbpzero = bpzero nnewmask = newmask if(nnewmask)bbadmask=badmask iinvert = invert bbpfrac = bpfrac # Certain tasks/packages must be loaded for task to run. go=yes if(!deftask("fileroot")) {go=no} if(!deftask("filecalc")) {go=no} if(go) { # Set up log file, overwriting if it already exists. if(llogfile == "") llogfile="log."//ooutimage print("", >> llogfile) print("===> PHIIRS.IRROTATE:", >> llogfile) print("===> Input images from "//rrotlist1//" rotated by angle "//aangle, >> llogfile) if(bbpzero)print("===> (after having all bad pixels zeroed), then", >> llogfile) print("===> rescaled by factor "//sscale//" to match reference image,", >> llogfile) print("===> and resampled by factor "//mag//" in each direction.", >> llogfile) print("===> New x-y shifts for the output images listed in "//rrotlist2, >> llogfile) print("===> can be found in "//sshiftoutlist, >> llogfile) # BP ZEROING IF DESIRED if (bbpzero) { print("Zeroing images in "//rrotlist1//" by their bad pixel masks.") list=rrotlist1 while (fscan (list, img) !=EOF) { fileroot(img,validim+) image=fileroot.root imgets(image,"BPM",>&"dev$null") bpmimg=str(imgets.value) imar(img,"*",bpmimg,img,pixtype="real",calctype="real",noact-,ver-) } } # ROTATION # If output image list already exists, do not append to it. if (!norot) { noappend=no if (access(rrotlist2)) { noappend=yes beep print("WARNING! Output image list "//rrotlist2//" already exists.") print("Any images listed therein will be created if they do not exist,") print("but no image names will be appended to this preexisting file.") } print("===) Rotating images and expanding by factor "//mag//" in both directions...") list=rrotlist1 while (fscan (list, img) !=EOF) { fileroot(img,validim+) image=fileroot.root ext=fileroot.extension if(ext==""){ ext=".imh" } else { ext="."//ext } imgets(image,"ROTATED",>&"dev$null") if(imgets.value=="0"){ if(!noappend)print(image//blk//ssuffix, >> rrotlist2) imgets(image,"i_naxis1") xlength=int(imgets.value) imgets(image,"i_naxis2") ylength=int(imgets.value) n_cols=int(xlength/invfactor) n_lines=int(ylength/invfactor) # Increasing output sizes by 1 does preserve all info, but makes coadding with # nonrotated images painful. # n_cols=int(xlength/invfactor)+1 # n_lines=int(ylength/invfactor)+1 # If output rotated & resampled image does not exist, create it if(!access(image//blk//ssuffix//ext)){ imlintran(image, image//blk//ssuffix, xrotation=aangle, yrotation=aangle, xmag=invfactor, ymag=invfactor, xin=INDEF, yin=INDEF, xout=INDEF, yout=INDEF, ncols=n_cols, nlines=n_lines, interpolant=o_interp, boundary=o_boundary, constant=o_constant, fluxconserve+, nxblock=512, nyblock=512) # imlintran(image, image//blk//ssuffix, xrotation=aangle, #yrotation=aangle, xmag=invfactor, ymag=invfactor, xin=INDEF, yin=INDEF, #xout=INDEF, yout=INDEF, ncols=n_cols, nlines=n_lines, interpolant="linear", #boundary="constant", constant=0., fluxconserve+, nxblock=512, nyblock=512) imgets(image//blk//ssuffix,"TPLIMG",>&"dev$null") if(imgets.value!="0")hedit(image//blk//ssuffix,"TPORIG",imgets.value,add+,ver-,show-,update+) imgets(image//blk//ssuffix,"BPMASK",>&"dev$null") if(imgets.value=="0")imgets(image//blk//ssuffix,"BPM",>&"dev$null") hedit(image//blk//ssuffix,"BPORIG",imgets.value,add+,ver-,show-,update+) } else { # If output image already exists, only print a warning. print("WARNING! "//image//blk//ssuffix//" already exists; not overwritten") } # imlintran the TPL image, if not already done. imgets(image//blk//ssuffix,"TPORIG",>&"dev$null") if(imgets.value=="0"){ print("Image "//image//blk//ssuffix//" is missing TPORIG keyword!") } else { fileroot(imgets.value,validim+) oldtpl=fileroot.root newtpl=oldtpl//blk//ssuffix if(!access(oldtpl//blk//ssuffix//ext)){ imlintran(oldtpl, oldtpl//blk//ssuffix//ext, xrotation=aangle, yrotation=aangle, xmag=invfactor, ymag=invfactor, xin=INDEF, yin=INDEF, xout=INDEF, yout=INDEF, ncols=n_cols, nlines=n_lines, interpolant=o_interp, boundary="nearest", constant=o_constant, fluxconserve-, nxblock=512, nyblock=512) } hedit(image//blk//ssuffix,"TPLIMG",oldtpl//blk//ssuffix//ext,add+,ver-,show-,update+) } # imlintran the bad pixel mask, if not already done. Include "edge effects". imgets(image//blk//ssuffix,"BPORIG",>&"dev$null") if(imgets.value=="0"){ beep print("Image "//image//blk//ssuffix//" is missing BPORIG keyword!") } else { fileroot(imgets.value,validim+) oldbp=fileroot.root newbp=oldbp//blk//ssuffix if(!access(oldbp//blk//ssuffix//".pl")){ if(!iinvert){ imcopy(oldbp,oldbp//"tmp"//ext,ver-) } else { minv(oldbp,oldbp//"tmp"//ext) } imar(oldbp//"tmp"//ext,"/",oldbp//"tmp"//ext,oldbp//"tmpe"//ext, divzero=0., pixtype="real", calctype="real",ver-) imlintran(oldbp//"tmp"//ext//","//oldbp//"tmpe"//ext, newbp//"tmp"//ext//","//newbp//"tmpe"//ext, xrotation=aangle, yrotation=aangle, xmag=invfactor, ymag=invfactor, xin=INDEF, yin=INDEF, xout=INDEF, yout=INDEF, ncols=n_cols, nlines=n_lines, interpolant=o_interp, boundary=o_boundary, constant=o_constant, fluxconserve+, nxblock=512, nyblock=512) # imlintran(oldbp//"tmp"//ext//","//oldbp//"tmpe"//ext, #newbp//"tmp"//ext//","//newbp//"tmpe"//ext, xrotation=aangle, yrotation=aangle, #xmag=invfactor, ymag=invfactor, xin=INDEF, yin=INDEF, xout=INDEF, yout=INDEF, #ncols=n_cols, nlines=n_lines, interpolant="linear", boundary=" #constant", constant=0., fluxconserve+, nxblock=512, nyblock=512) # Replace edge pixels in the edge mask minmax(newbp//"tmpe"//ext,force+,ver-) valmax=minmax.maxval imreplace(newbp//"tmpe"//ext,0.,lower=INDEF,upper=0.99*valmax) imreplace(newbp//"tmpe"//ext,1.,lower=0.98*valmax,upper=INDEF) # Replace only slightly bad pixels in the bad pixel mask with 1. minmax(newbp//"tmp"//ext,force+,ver-) valmax=minmax.maxval imreplace(newbp//"tmp",0.,lower=INDEF,upper=bbpfrac*valmax) imreplace(newbp//"tmp",1.,lower=0.99*bbpfrac*valmax,upper=INDEF) # Multiply bad pixel mask by edge mask and convert to .pl format imar(newbp//"tmp","*",newbp//"tmpe",newbp//"tmp",pixt="real",calct="real",ver-) if(!iinvert){ imcopy(newbp//"tmp"//ext,newbp//".pl",ver-) } else { minv(newbp//"tmp"//ext,newbp//".pl") } # Clean up imdel(oldbp//"tmp*"//ext,ver-) imdel(newbp//"tmp*"//ext,ver-) print(newbp//".pl", >> bprotlist) } # Insert the rotated & resampled bad pixel mask in the image header hedit(image//blk//ssuffix,"BPM",newbp//".pl",add+,ver-,show-,update+) hedit(image//blk//ssuffix,"BPMASK",newbp//".pl",add+,ver-,show-,update+) } # # addcomment ROTATED w/angle, magfac hedit(image//blk//ssuffix,"ROTATED",str(aangle)//"x"//str(mag),add+,ver-,show-,update+) # # If image has already been rotated, do not rotate. } else { print("WARNING! Image "//image//" already rotated; not rotated again.") } # Rotate/resample next image... } } else { print("===> Image rotation not done.") } # CALCULATE SUBPIXEL SHIFTS # Create subpixel shift file if desired and if not already in existence if (sshiftexactlist!="" && !access(sshiftoutlist)){ print("===> Calculating shifts for rotated, resampled images...") if (access("tmp"//sshiftoutlist))del("tmp"//sshiftoutlist,ver-) list=sshiftexactlist while (fscan (list,xold,yold) != EOF) { xnew=(mag/sscale)*(xold*cos(angrad) - yold*sin(angrad)) ynew=(mag/sscale)*(yold*cos(angrad) + xold*sin(angrad)) print (xnew, ynew, >> "tmp"//sshiftoutlist) } # Round off to integer shifts (in units of new pixels, natch). # Extensive code needed to make sure offsets -0.5 < offsets < 0.5 round to 0. list="tmp"//sshiftoutlist while(fscan(list,x,y) !=EOF) { if(((abs(x))>=0.5) && ((abs(y))>=0.5)) { print(x,y, >> "temp."//sshiftoutlist) filecalc("temp."//sshiftoutlist,"$1;$2",format="%4.0f %4.0f", >> sshiftoutlist) del ("temp."//sshiftoutlist, ver-, >& "dev$null") } else { if((abs(x))<=0.5) { x=0. } if((abs(y))<=0.5) { y=0. } print(x,y, >> "temp."//sshiftoutlist) filecalc("temp."//sshiftoutlist,"$1;$2",format="%4.0f %4.0f", >> sshiftoutlist) del ("temp."//sshiftoutlist, ver-, >& "dev$null") } } del("tmp"//sshiftoutlist,ver-,>&"dev$null") del("temp"//sshiftoutlist,ver-,>&"dev$null") } else { beep print("WARNING! "//sshiftoutlist//" not created (may already exist).") } ## Temporary fix -- correction of zero offsets #if(!ssubpixscale && !access(zzeroname//blk)) { # filecalc(zzeroname,"$1/"//mag2,format="%16.12f", >> zzeroname//blk) # newzzeroname=zzeroname//blk # zzeroname=newzzeroname #} # Clean up. (IRCOADD2 ONLY!) # imdel("@"//rrotlist2, ver-) # del(rrotlist2, ver-) # imdel("@"//bprotlist, ver-) # del(bprotlist, ver-) # del(sshiftoutlist, ver-) if(!norot)print("Images in "//rrotlist//" were rotated to make "//rrotlist2) if(sshiftexactlist!="")print("Next run `ircoadd' w/shifts from "//sshiftoutlist) } else { print("WARNING: tasks filecalc, and/or fileroot are not loaded!") print("Please load the appropriate package(s) and restart this task.") } print(" ") beep end phat_alone/src/irshift2.cl100644 1332 567 10711 6503624112 15055 0ustar hallast_hyee# irshift2 -- measure scale and rotation between two images' coord systems # # Task calls following other tasks: filecalc. # # Output: # prefix.georefin.suffix object coordinates in ref and input images # prefix.geomapin.suffix input file for geomap task # # CHANGES: # 960307: created from irshift.cl procedure irshift2(refimage,inimage,prefix,suffix) string refimage {prompt="Reference image"} string inimage {prompt="Input image"} string prefix {prompt="Prefix string for output files"} string suffix {prompt="Suffix string for output files"} real radius=5. {prompt="Imexamine aperture photometry radius"} real buffer=10. {prompt="Imexamine sky buffer"} real width=10. {prompt="Imexamine sky annulus width"} struct *list begin string rrefimage, fflatlist, rrefcoords, bbadmask, rroundname string sshiftlist, coarsefile, ooffname, ssuffix, iintname, ffracname string pprefix, logoffname, sl, sx, img, iinterp, bboundary string iinimage, stringline1, stringline2, stringline1old, stringline2old string stringline1tmp, stringline2tmp, georefin, geomapin real p, pixscale, stcoordx, stcoordy, nrows, ncols, delx, dely, adelx, adely real xold, yold, xxshiftold, yyshiftold, xshiftnew, yshiftnew, astcoordx real astcoordy, nl, nx, x, y int xref # Reference object x coordinate (nearest integer) int yref # Reference object y coordinate (nearest integer) int number, xtmp, ytmp, z bool go #The "go" parameter won't let the task run if you haven't loaded the ctio pkg. go=yes if(!deftask("filecalc")) {go=no} if(go) { rrefimage = refimage iinimage = inimage pprefix = prefix ssuffix = suffix rimexam.radius=radius rimexam.buffer=buffer rimexam.width=width georefin = pprefix//".georefin."//ssuffix geomapin = pprefix//".geomapin."//ssuffix print(" ") print("===) Choose an object that appears in both images, find its coordinates") print("===) (type 'a') first in frame 1 and then in frame 2, and repeat with as many") print("===) objects as desired. The separation of coordinates from the different") print("===> images will be done later, but **THE SEPARATION WILL FAIL** if the") print("===> frame1/frame2 cycle is deviated from even slightly! The imexam output") print("===> log will be displayed for editing when done, in case mistakes were made.") print(" ") display(iinimage,2) display(rrefimage,1) imexam(logfile=georefin, keep+) print(" ") print("===> In case mistakes were made, the coordinate file can now be edited.") vi(georefin) print("===> Constructing geomap input file...") del("temp.joinfile*", ver-) # copy the imexam output to a working file copy(georefin,"temp.joinfile",ver-) # remove all comment lines !grep -v '^#' temp.joinfile >> temp.joinfile1 # make sure there is an even number of lines remaining count("temp.joinfile1") | scan (nl) if((frac(nl/2.))!=0.){ beep print ("ERROR! Odd number of coordinates in this file! Fix it!", >> "temp.joinfile1") vi("-c ':$'", "temp.joinfile1") } # number the lines in the input file linenum("temp.joinfile1","temp.joinfile0",first_line=1,increment=1) # extract the first 3 columns in appropriate format filecalc("temp.joinfile0","$1;$2;$3",lines="1-99999",format="%5.0f%9.2f%9.2f", >> "temp.joinfile2") # initialize loop list="temp.joinfile2" stringline1="" stringline2="" stringline1old="" stringline2old="" stringline1tmp="" stringline2tmp="" # create one string of odd line numbers "1,3,5,..." and one of even. # both of which will eventually be used as parameters for filecalc while(fscan(list, number, xtmp, ytmp) !=EOF) { if((frac(number/2.))!=0.){ stringline1tmp=stringline1old//number//"," } else { stringline2tmp=stringline2old//number//"," } stringline1old=stringline1tmp stringline2old=stringline2tmp } # cut off trailing comma z=strlen(stringline1tmp)-1 stringline1=substr(stringline1tmp,1,z) z=strlen(stringline2tmp)-1 stringline2=substr(stringline2tmp,1,z) # extract coords from image 1 filecalc("temp.joinfile1","$1;$2",lines=stringline1,format="%9.2f%9.2f", >> "temp.joinfile1a") # extract coords from image 2 filecalc("temp.joinfile1","$1;$2",lines=stringline2,format="%9.2f%9.2f", >> "temp.joinfile1b") # join coords from images 1 and 2 join("temp.joinfile1a","temp.joinfile1b",out=geomapin) del("temp.joinfile*", ver-) print("Next: `immatch.geomap "//geomapin//" "//pprefix//".geomapout."//ssuffix//"`.") } else { print("WARNING: task `ctio.filecalc' is not loaded!") print("Please load it and restart this task.") } beep end phat_alone/src/iterstat.cl100644 1332 567 13073 6503624113 15167 0ustar hallast_hyeeprocedure iterstat(image) # Script to find image statistics excluding deviant pixels # originally created 4 August 1992 by John Ward # 930818: revisions by MD # 950201: changed output formatting-- still prob. w/short values/image names. # 950209: simple string check for INDEF, for IRAF 2.10.4? patch # 950314: adjusted use of "sections" task # 970227: optionally add header keywords ITERMEAN, ITERSIG, ITERMED, ITERMODE # 970401: optionally add header keyword VARIANCE = ITERSIG**2. string image {prompt="Input image(s)"} real nsigrej {5.,min=0.,prompt="Number of sigmas for limits"} int maxiter {10,min=1,prompt="Maximum number of iterations"} bool print {yes,prompt="Print final results?"} bool verbose {no,prompt="Show results of all iterations?"} bool addheader {yes,prompt="Put returned values into image header keywords?"} real lower {INDEF,prompt="Initial lower limit for data range"} real upper {INDEF,prompt="Initial upper limit for data range"} real mean {prompt="Returned value of mean"} real sigma {prompt="Returned value of sigma"} real variance {prompt="Returned value of variance (sigma**2)"} real median {prompt="Returned value of median"} real valmode {prompt="Returned value of mode"} #Above must be "valmode" to avoid conflict w/ omnipresent task parameter "mode" struct *inimglist begin string im # equals image string imglist # equals image string infile # temporary list for files string img # image name from fscan string check # string for `@filename' checking string blankstring # long blank string string headstring # strings for output formatting string mnstring # string sigstring # string npxstring # string medstring # real mn # mean from imstat real sig # stddev from imstat real med # midpt from imstat real mod # mode from imstat real ll # lower limit for imstat real ul # upper limit for imstat int nx, npx # number of pixels used int m # dummy for countdown int i # length of image string int j # dummy integer int x # dummy integer # Expand file lists into temporary files. imglist = image infile = imglist check = substr(imglist,1,1) if(check=="@") { infile=substr(imglist,2,strlen(imglist)) } else { infile = mktemp("tmp$iterstat") sections (imglist,option="fullname",>infile) } inimglist = infile j = 0 # Loop through images while (fscan(inimglist,img) != EOF) { # Calculate stats using initial lower & upper limits imstat(img,fields="mean,stddev,npix,midpt,mode", lower=lower,upper=upper,for-) | scan(mn,sig,npx,med,mod) # If verbose+, print output header if(verbose){ blankstring=" " i=strlen(str(img)) if (i<=6) i=7 headstring=substr(blankstring,1,i-6) i=strlen(str(mn)) if (i<=4) i=5 mnstring=substr(blankstring,1,i-4) i=strlen(str(sig)) if (i<=3) i=4 sigstring=substr(blankstring,1,i-3) i=strlen(str(npx)) if (i<=4) i=5 npxstring=substr(blankstring,1,i-4) i=strlen(str(med)) if (i<=6) i=7 medstring=substr(blankstring,1,i-6) print("#IMAGE"//headstring//" MEAN"//mnstring//" RMS"//sigstring//" NPIX"//npxstring//" MEDIAN"//medstring//" MODE") } m = 1 while (m <= maxiter) { if (verbose) print(img," ",mn,sig,npx,med,mod) # Calculate new lower & upper limits by tossing out values nsigrej from the mean ll = mn - (nsigrej*sig) ul = mn + (nsigrej*sig) if (lower != INDEF && ll < lower) ll = lower if (upper != INDEF && ul > upper) ul = upper imstat(img,fields="mean,stddev,npix,midpt,mode",lower=ll,upper=ul,for-) | scan(mn,sig,nx,med,mod) # If mean is INDEF, set it to zero if(mn==INDEF) { mn=0. print("#WARNING: mean of "//img//" is INDEF! Setting mean equal to zero.") } # If stddev is INDEF, set it to 32767 if(sig==INDEF) { sig=32767. print("#WARNING: stddev of "//img//" is INDEF! Setting stddev equal to 32767.") } # If midpt (median) is INDEF, set it to the mean if(med==INDEF) { med=mn print("#WARNING: median of "//img//" is INDEF! Setting median equal to mean.") } # If mode is INDEF, set it to the mean if(mod==INDEF) { mod=mn print("#WARNING: mode of "//img//" is INDEF! Setting mode equal to mean.") } # If after this recalculation the same number of pixels are accepted, end loop if (nx == npx) break npx = nx m = m + 1 } # If first image, print output header j+=1 if(j==1 && !verbose){ blankstring=" " i=strlen(str(img)) if (i<=6) i=7 headstring=substr(blankstring,1,i-6) i=strlen(str(mn)) if (i<=4) i=5 mnstring=substr(blankstring,1,i-4) i=strlen(str(sig)) if (i<=3) i=4 sigstring=substr(blankstring,1,i-3) i=strlen(str(npx)) if (i<=4) i=5 npxstring=substr(blankstring,1,i-4) i=strlen(str(med)) if (i<=6) i=7 medstring=substr(blankstring,1,i-6) if (print && !verbose) print("#IMAGE"//headstring//" MEAN"//mnstring//" RMS"//sigstring//" NPIX"//npxstring//" MEDIAN"//medstring//" MODE") } # Print statistics if (print && !verbose) print(img," ",mn,sig,npx,med,mod) mean = mn sigma = sig variance = sig**2. median = med valmode = mod if(addheader) { hedit (img, "ITERMEAN", mean, add+, ver-, show-, update+) hedit (img, "ITERSIG", sigma, add+, ver-, show-, update+) hedit (img, "VARIANCE", variance, add+, ver-, show-, update+) hedit (img, "ITERMED", median, add+, ver-, show-, update+) hedit (img, "ITERMODE", valmode, add+, ver-, show-, update+) } } if(check!="@") delete (infile,ver-, >& "dev$null") inimglist = "" #!time end phat_alone/src/makeobjmask.cl100644 1332 567 23533 6503624113 15616 0ustar hallast_hyee# makeobjmask.cl -- Create object masks for input images. # # Image is sky subtracted, either using a constant value, or optionally by # median filtering the image on a specified spatial scale and subtracting # filtered image. If the desired filtering scale is large, the user may want # to first subsample the image to a smaller size before filtering in order to # speed up the calculation -- the resulting sky frame is then block replicated # back up to the original image size before subtracting. # # After sky subtraction, a threshold is applied to the image after optional # boxcar smoothing. The threshold may be specified in terms of a number of sky # sigma above the median sky level as measured using iterative sigma rejection, # or as a specified constant number of ADU above the sky level. The resulting # thresholded image is turned into a mask with "sky" set to 0 and "objects" set # to 1. The user may "grow" additional rings of pixels around masked regions # to increase their area. # # Finally, the resulting mask may optionally be recorded in the input image # header keywords BPM and OBJMASK. The user may in fact create a mask from one # input image and add it into the header of another by specifying different # lists for inlist and headlist. # # Calls tasks "fileroot" and "addcomment" # # 950208: renamed makeobjmask. Switched output prefix to suffix. # 950314: adjusted use of "sections" task # 950324: added "invert" option here instead of in mkobjmask.cl # 960226: use `hedit' to give mask a proper title... # 960301: ...but make sure you do it correctly. procedure makeobjmask(inlist) string inlist {prompt="Image(s) to mask"} string suffix {"objmask",prompt="Suffix for mask files."} string headlist="!default" {prompt="Image(s) to which to add BPM cards"} int subsample {1,min=0,prompt="Block averaging factor before median filtering"} int filtsize {15,min=0,prompt="Median filter size for local sky evaluation"} int nsmooth {3,min=0,prompt="Scale for boxcar smothing before thresholding"} string threshtype {"nsigma",enum="nsigma|constant",prompt="Thresholding type: nsigma or constant"} real nsigthresh {2.,prompt="Threshold for masking in sky sigma"} real constthresh {0.,prompt="Constant threshold above sky for masking"} int ngrow {0,min=0,prompt="Width of rings to grow around masked objects"} string statsec {"",prompt="Image region to use for computing sky statistics"} bool checklimits {yes,prompt="Check min and max pix values before filtering?"} real zmin {-32767.,prompt="Minimum data value for fmedian"} real zmax {32767.,prompt="Minimum data value for fmedian"} bool inv {yes,prompt="Invert output mask so objects are zero?"} bool verbose {yes,prompt="Verbose output?"} struct *imglist struct *imglist2 begin string inl,check,inh int nbox,narea int ix,iy real thresh, dmin, dmax, realsize string infile, img, workimg, ext string infile2, img2 string cutsec # Get query parameter. inl = inlist inh = headlist # Check validity of boxcar smoothing scale. if (nsmooth > 0) { if (2*int(nsmooth/2) == nsmooth) { # i.e. if nsmooth is even... print ("ERROR: parameter nsmooth should be set to an odd value.") return } } # Notify user of effective median filter scale. if (subsample > 1 && filtsize > 0) { realsize = subsample * filtsize print ("After subsampling image, effective median filter scale will be ", realsize) } # Size for boxcar smoothing in growing stage. nbox = (2*ngrow + 1) narea = nbox * nbox # Expand input file list. infile = inl check = substr(infile,1,1) if(check=="@") { infile=substr(inl,2,strlen(inl)) } else { infile = mktemp("tmp$makeobjmask") print(inl,>>infile) } imglist = infile # infile = mktemp("tmp$makeobjmask") # sections (inl,option="fullname",>infile) # imglist = infile # If parameter headlist != "", update image headers with bad pixel list. if (headlist != "") { infile2 = headlist check = substr(infile2,1,1) if(check=="@") { infile2=substr(inh,2,strlen(inh)) } else { if(check=="!") { infile2=infile } else { infile2 = mktemp("tmp$makeobjmask") print(inh,>>infile2) } } imglist2 = infile2 # infile2 = mktemp("tmp$makeobjmask") # sections (headlist,option="fullname",>infile2) # imglist2 = infile2 } # Loop through input files. while (fscan(imglist,img) != EOF) { # Strip ".imh" extension off filename if present. fileroot (img,validim+) img = fileroot.root ext = fileroot.extension if (ext!="") ext = "."//ext if (verbose) print (" Working on image ",img,"-------------------------------") if (verbose) print (" Subtracting local sky.") # If filtsize > 0, median filter image to produce local sky, then subtract # that from the image. if (filtsize > 0) { # If subsample > 1, block average input image to smaller size. if (subsample > 1) { if (verbose) print (" Block averaging.") blkavg (img,"_blk_"//img,subsample,subsample,option="average") workimg = "_blk_"//img } else { workimg = img } # First, check limits of data range. Wildly large (positive or negative) data # values will screw up fmedian calculation unless checklimits = yes and zmin # and zmax are set to appropriate values, e.g. zmin=-32768, zmax=32767. # Note that the old fmedian bug which occurred if zmin=hmin and zmax=hmax # has been fixed in IRAF version 2.10.1. if (verbose) print (" Median filtering sky.") if (checklimits) { minmax (workimg,force+,update+,ve-) if (verbose) print(" Data minimum = ",minmax.minval, " maximum = ",minmax.maxval) } if (checklimits && (minmax.minval < zmin || minmax.maxval > zmax)) { if (minmax.minval < zmin) { dmin = zmin } else { dmin = minmax.minval } if (minmax.maxval > zmax) { dmax = zmax } else { dmax = minmax.maxval } if (verbose) print (" Truncating data range ",dmin," to ",dmax) fmedian (workimg,"_fmed_"//workimg,xw=filtsize,yw=filtsize, boundary="nearest",hmin=-32768,hmax=32767, zmin=dmin,zmax=dmax,>&"dev$null") } else { fmedian (workimg,"_fmed_"//workimg,xw=filtsize,yw=filtsize,boundary="nearest", hmin=-32768,hmax=32767,zmin=INDEF,zmax=INDEF,>&"dev$null") } # If we have block averaged, block replicate median filtered image back to original size. if (subsample > 1) { if (verbose) print (" Block reproducing.") blkrep ("_fmed_"//workimg,"_fmed_"//img,subsample,subsample) imgets(img,"i_naxis1") ix = int(imgets.value) imgets(img,"i_naxis2") iy = int(imgets.value) cutsec = "[1:"//ix//",1:"//iy//"]" imcopy ("_fmed_"//img//cutsec,"_fmed_"//img,ver-) } imarith (img,"-","_fmed_"//img,"_mask_"//img) } else { # ...or, just copy the image to a working mask frame. imcopy (img,"_mask_"//img) } # Calculate image statistics to determine median sky level and RMS noise. if (verbose) print (" Computing sky statistics.") iterstat ("_mask_"//img//statsec,verbose=verbose,print=verbose) if (nsmooth > 0) { if (verbose) print (" Smoothing image before thresholding.") boxcar ("_mask_"//img,"_mask_"//img,nsmooth,nsmooth) } # Calculate threshold. if (threshtype == "constant") { thresh = iterstat.median + constthresh } else { thresh = iterstat.median + nsigthresh * iterstat.sigma } if (verbose) print (" Thresholding image at level ",thresh) # Apply threshold to image, setting "objects" to 1 and "sky" to 0. # The order of the imreplace statments must be different if threshold is # greater than or less than 1. if (thresh >= 0.) { imreplace ("_mask_"//img//ext,0.,upper=thresh,lower=INDEF) imreplace ("_mask_"//img//ext,1.,lower=thresh,upper=INDEF) } else if (thresh < 0.) { imreplace ("_mask_"//img//ext,1.,lower=thresh,upper=INDEF) imreplace ("_mask_"//img//ext,0.,upper=thresh,lower=INDEF) } # Copy mask to .pl file. if (verbose) print (" Saving mask as ",img//suffix//".pl") imcopy ("_mask_"//img,img//suffix//".pl",ve-) # If desired, grow rings around masked objects. if (ngrow > 0) { if (verbose) print (" Growing rings around masked objects.") imarith (img//suffix//".pl","*",narea,img//suffix//".pl") boxcar (img//suffix//".pl",img//suffix//".pl",nbox,nbox) imreplace (img//suffix//".pl",1,lower=1,upper=INDEF) } # Invert mask if desired. if(inv){ if (verbose) print (" Inverting mask so objects=zero.") minv(img//suffix//".pl",img//suffix//".pl") } # add title and comment cards to mask hedit(img//suffix//".pl","title","Object Mask for "//img,add+,ver-,show-,updat+) if(deftask("addcomment")){ addcomment(img//suffix//".pl","phiirs.makeobjmask: mask made w/subsample="//subsample,ver-) addcomment(img//suffix//".pl","filtsize="/filtsize//", nsmooth="//nsmooth,ver-) if(threshtype=="nsigma"){ addcomment(img//suffix//".pl","threshtype=nsigma, nsigthresh="//nsigthresh,ver-) } else { addcomment(img//suffix//".pl","threshtype=constant, constthresh="//constthresh,ver-) } addcomment(img//suffix//".pl","ngrow="/ngrow//", statsec="/statsec//", checklimits="//checklimits,ver-) addcomment(img//suffix//".pl","zmin="/zmin//", zmax="/zmax//", inverse="//inv,ver-) } # Record mask name into BPM keyword in image header of files specified # by inlist2. if (headlist != "") { if (fscan(imglist2,img2) != EOF) { if(verbose)print(" Recording pixel mask into header of image ",img2) hedit(img2,"BPM",img//suffix//".pl",add+,ver-,update+,show-) hedit(img2,"OBJMASK",img//suffix//".pl",add+,ver-,update+,show-) } } # Clean up. if (filtsize > 0) { imdelete ("_fmed_"//img//ext,ve-) if (subsample > 1 ) { imdelete ("_blk_"//img//ext,ve-) imdelete ("_fmed_"//workimg//ext,ve-) } } imdelete ("_mask_"//img//ext,ve-) } # delete (infile,ver-) if (headlist != "" && check != "!") delete (infile2,ver-) imglist = "" imglist2 = "" end phat_alone/src/maskstat.cl100644 1332 567 22223 6503624114 15155 0ustar hallast_hyeeprocedure maskstat(image,mask,goodvalue) # Calculates images statistics from unmasked regions of an input frame. # * Mask file must have only values of 0 and 1! # * Parameter 'iterstat' gives the option of calling iterative statistics # routine iterstat instead of imstat. # * It is assumed that the user will have set the parameters for imstat # or iterstat in whatever manner is desired. This routine does not # set those parameters except using lower= to exclude the masked pixels. # * Checks to see if stsdas.tools is loaded. If so, it uses imcalc to do the # calculation; otherwise, it uses a slower combination of imarith statements. # Calls scripts minv and possibly iterstat. # **BUG** minmax step means that in an image with a high and nonzero mean, # 0-valued pixels will not be outside the initial iterstat range, which might # make itersig high enough that such pixels will (erroneously, presumably) # not be excluded in any of the iterations. # Date: Fri, 21 Oct 94 04:07:39 PDT # From: prme (Peter Eisenhardt) # Subject: Re: more on negative scale factors # # iterstat was not converging - not even iterating, actually, leaving me with # the initial (negative) median value. This is due to two problems, really: # # 1) the flag value in maskstat is (minval - 1) which is not in some cases # different enough from the lower threshold (minval) sent to iterstat/imstat # to be noticeable by imstat. Basically roundoff error, I guess, the # result of which is that NONE of the "flagged" pixels are excluded by # the lower threshold, so no convergence from this approach. # This has probably been happening frequently, # but was not a problem because iterstat picked up the slack. # # 2) The second problem is when the initial sigma becomes so large that # mean +/- 5 sigma exceeds the range of data values - thus no # pixels get rejected in the second iteration. This happened for # the first time I think because there are a vast number (1386) # of bad pixels in the J data, all of which got set to a very low # flag value in maskstat. This created a bimodal distribution where sigma # is very large and all of the data is within 5 sigma of the mean. # # A fix which I am implementing is to change the # flagvalue in maskstat from (minval - 1) to (2*minval - maxval), # which ensures that the flagvalue is always well below the range of values # in the unmasked image, so that the lower threshold in imstat will work. # 930722: created by Mark Dickinson # 950216: got rid of imcalc option-- couldn't handle long input image names # 950314: adjusted use of `sections' task-- risk of collision w/other tasks # 960405: added option to take masks from a header keyword # 960413: added option to not print iterstat output # 960416: fixed bug for 1-entry list, and cleaned up code using `| scan' # 970429: added insertion of iterstat results into image header if iterstat+ # 970501: fixed bug that pixel masks can't have negative or non-integer values # 970508: insert iterstat results into image header if iterstat+ and addheader+ # 970620: allow for explicit temporary changing of iterstat params if desired # 970714: added MASKMASK header param (= mask used) if iterstat+ addheader+ # 970930: fixed bug relating to .pl image being mulitplied by too large a # string image {prompt="Input image(s) or list"} string mask {prompt="Input mask(s), list, or !"} int goodvalue {1,min=0,max=1,prompt="Good pixel value in mask"} real nsigrej {5.,min=0.,prompt="Number of sigmas for limits"} int maxiter {10,min=1,prompt="Maximum number of iterations"} real lower {INDEF,prompt="Initial lower limit for data range"} real upper {INDEF,prompt="Initial upper limit for data range"} bool verbose {no,prompt="Verbose output?"} bool iterstat {no,prompt="Use iterstat instead of imstat?"} bool addheader {yes,prompt="Add iterstat output to image header?"} bool printit {yes,prompt="Print iterstat output?"} struct *inimglist struct *mlist begin string check # `@filename' check string imglist # equals image string ext # equals image extension string msk # equals mask string mskfile # temporary mask file string keyword # mask header keyword string mfile # name of individual mask file string mf # name of individual mask file without .pl string minvfile # inverted mask file string infile # temporary list for files string j4 # temp string int goodv # equals goodvalue int nimgs,nmask # number of input images and masks int j1,j2,j3 # temp values real minval # lower limit for image statistics calculation real maxval # upper limit of image statistics real flagval # flag value bool indel # delete input list file? bool maskdel # delete mask list file? # Get query parameters & expand input lists imglist = image msk = mask if(msk=="")msk="!BPM" goodv = goodvalue maskdel = no indel = no # Expand file lists into temporary files. infile = imglist check = substr(imglist,1,1) if(check=="@"){ infile=substr(imglist,2,strlen(imglist)) count(infile) | scan(nimgs) } else { infile = mktemp("tmp$maskstat") indel=yes sections(imglist,option="fullname",>infile) count(infile) | scan(nimgs) } inimglist = infile #print("one") # Exact same spiel for list of masks, with extra step if only one mask. mskfile = msk check = substr(msk,1,1) if(check=="@" || check=="!"){ if(check=="!"){ maskdel=yes keyword=substr(msk,2,strlen(msk)) mskfile = mktemp("tmp$maskstat") hsel("@"//infile,(keyword),yes, >> mskfile) } if(check=="@"){ mskfile=substr(msk,2,strlen(msk)) } count (mskfile) | scan (nmask) } else { mskfile = mktemp("tmp$maskstat") maskdel=yes sections(msk,option="fullname",>mskfile) count (mskfile) | scan (nmask) if (nmask == 1) { mfile = msk fileroot(mfile,validim+) minvfile = "_"//fileroot.root//".pl" if(access(minvfile))imdel(minvfile,ver-) minv (mfile,minvfile) } } mlist = mskfile if (nmask != nimgs && nmask != 1) { print ("ERROR: Numbers of image and mask files differ.") return } #print("two") # Loop through input files. while (fscan(inimglist,img) != EOF) { fileroot(img,validim+) ext=fileroot.extension if(ext!="")ext="."//ext if(access("_"//fileroot.root//ext))imdel("_"//fileroot.root//ext,ver-) if(access("_"//fileroot.root//".imh"))imdel("_"//fileroot.root//".imh",ver-) if(access("_"//fileroot.root//".hhh"))imdel("_"//fileroot.root//".hhh",ver-) #print("thr") # Get name of mask file # if (check == "@" || check == "!") { if (fscan(mlist,mfile) != EOF) { fileroot(mfile,validim+) # minvfile = "_"//fileroot.root//".pl" minvfile = "_"//fileroot.root//".imh" if(access(minvfile))imdel(minvfile,ver-) minv (mfile,minvfile) } else { print ("ERROR: Premature end of mask list.") return } # } #print("for") # Strip extension off mask name and save root as variable mf for later use. fileroot (mfile,validim+) mf = fileroot.root ext=fileroot.extension if(ext!="")ext="."//ext if(access("_x"//mf//ext))imdel("_x"//mf//ext,ver-) if(access("_x"//mf//".imh"))imdel("_x"//mf//".imh",ver-) if(access("_x"//mf//".hhh"))imdel("_x"//mf//".hhh",ver-) #print("fiv") if (verbose) print ("Calculating statistics for ",img," using mask ",mfile) minmax (img,force+,update-,ver-) minval = minmax.minval maxval = minmax.maxval if (lower == INDEF) { flagval = 2 * minval - maxval } else { minval = lower flagval = 2 * lower - maxval } #print("six") #print(img//" "//mfile//" "//minvfile) # Masking replaces bad pixels with "flagval" and leaves good pixels unchanged. if (goodv == 0) { imar (img,"*",minvfile,"_"//img,pixty="real",calcty="real",ver-) imar (mfile,"*",abs(int(flagval)),"_x"//mf,pixty="real",calcty="real",ver-) imar ("_"//img,"-","_x"//mf,"_"//img,pixty="real",calcty="real",ver-) } else { imar (img,"*",mfile,"_"//img,pixty="real",calcty="real",ver-) imar (minvfile,"*",abs(int(flagval)),"_x"//mf,pixty="real",calcty="real",ver-) imar ("_"//img,"-","_x"//mf,"_"//img,pixty="real",calcty="real",ver-) } #print("sev") if (iterstat) { if (printit) { iterstat ("_"//img,lower=minval,nsigrej=nsigrej,maxiter=maxiter,upper=upper,verbose=verbose,print+,addh-) } else { iterstat ("_"//img,lower=minval,nsigrej=nsigrej,maxiter=maxiter,upper=upper,verbose=verbose,print-,addh-) } if (addheader) { hedit (img, "MASKMASK", msk, add+, ver-,show-,update+) hedit (img, "ITERMEAN", iterstat.mean, add+, ver-,show-,update+) hedit (img, "ITERSIG", iterstat.sigma, add+, ver-,show-,update+) hedit (img, "VARIANCE", iterstat.variance,add+,ver-,sho-,updat+) hedit (img, "ITERMED", iterstat.median, add+,ver-,show-,update+) hedit (img, "ITERMODE", iterstat.valmode,add+,ver-,show-,updat+) } } else { imstat ("_"//img,lower=minval,upper=upper) } imdelete ("_"//img,ver-) imdelete ("_x"//mf,ver-) if (nmask != 1) imdelete (minvfile,ver-) } #print("ate") if (nmask == 1) imdelete (minvfile,ver-) #print("nin") if(indel)delete(infile,ver-,>&"dev$null") if(maskdel)delete(mskfile,ver-,>&"dev$null") inimglist = "" mlist = "" end phat_alone/src/minv.cl100644 1332 567 3020 6503624114 14251 0ustar hallast_hyeeprocedure minv(infile,outfile) # Routine to invert masks so that <=0 --> 1 and >0 --> 0 # # 960416: added check for 0-1 range, and more careful with image extension # 970430: changed so that all values >=1 now set to 0, with warning # 970730: changed so that values <=0 --> 1 and values >0 --> 0 # 970930: intermediate step: copy to .imh format & real pixtype # to avoid .pl limitations # 971101: modified so a fixed temporary image name is not created string infile {prompt = "Input mask image (best include .pl or .imh)"} string outfile {prompt = "Output (inverted) mask image"} begin string inf,outf,inex,outex,biteme # Get query parameters: fileroot(infile) inf = fileroot.root inex = "."//fileroot.extension if(inex==".")inex="" fileroot(outfile,validim+) outf = fileroot.root outex = "."//fileroot.extension if(outex==".")outex="" minmax (inf, force+, ver-) if ((minmax.minval < 0.) || (minmax.maxval > 1.)) { beep print("WARNING! Pixels in image range beyond 0-1.") # print("WARNING! Pixels in image range beyond 0-1... inversion not done.") # return } # if(inf//inex != outf//outex) biteme = mktemp("_biteme") imcopy(inf//inex,biteme//".imh",ver-) imar(biteme//".imh","+",0.,biteme//".imh",ver-,noact-,pixt="real") imreplace (biteme//".imh",1.,lower=0.01,upper=INDEF) imreplace (biteme//".imh",2.,lower=INDEF,upper=0.02) imarith (biteme//".imh","-",1.,biteme//".imh") if(inf//inex==outf//outex)imdel(inf//inex, ver-) imcopy(biteme//".imh",outf//outex,ver-) imdel(biteme//".imh",ver-) end phat_alone/src/mkobjmask.cl100644 1332 567 15021 6503624114 15302 0ustar hallast_hyee# mkobjmask.cl -- script to interactively create object mask # # originally created 11 July 1992 by John S. Ward # 930228: Now excludes zero exposure regions from computation of pixel sigma. # 930726: Modified by MD to call sigmanorm and use makeobjmask.cl. # 950208: Renamed mkobjmask. Various minor adjustments. # 950209: inv parameter: prefer to have masks with objects=0 not 1. # 960301: display object-masked image in interactive mode # 960405: removed "inv" param and added interactive iteration mode # # Calls scripts makeobjmask, sigmanorm, iterstat, sctv procedure mkobjmask(image,expname) string image {prompt="Name of image for making mask"} string expname {prompt="Exposure map (default=image//em)"} string suffix="objmask" {prompt="Suffix of output object mask"} string prefix="norm" {prompt="Prefix for temporary normalized image"} int nsmooth {3,min=0,prompt="Filter size for boxcar smoothing (ODD values only)"} int subsample {1,min=1,prompt="Block averaging factor before median filtering"} int filtsize {15,min=1,prompt="Median filter size for local sky evaluation"} int ngrow {1,min=0,prompt="Width of rings to grow around masked objects"} bool interact {yes,prompt="Interactively examine normalized image?"} real threshold {prompt="Cutoff point for replacement",mode="q"} bool redo {no,prompt="Redo with different parameters?",mode="q"} int z {0,prompt="Number of image to save (zero to delete all)?",mode="q"} int i_nsmooth {3,min=0,prompt="Filter size for boxcar smoothing (ODD values only)",mode="q"} int i_subsample {1,min=1,prompt="Block averaging factor before median filtering",mode="q"} int i_filtsize {15,min=1,prompt="Median filter size for local sky evaluation",mode="q"} int i_ngrow {1,min=0,prompt="Width of rings to grow around masked objects",mode="q"} begin string img # equals image string ext # equals image extension string eexpname # equals expname string ssuffix # equals suffix string pprefix # equals prefix real th # equals threshold real recthresh # recommended thresholding value real minval # minimum value in mask image real maxexp # peak exposure time real flagval # flag value bool rredo # iterate mask determination? int x # number to append to tmp. images; increased by 1 each time int y # dummy number; looped through to delete leftover images at end int zz # dummy variable for `z' bool ook # dummy variable set equal to `ok' to keep loop going or not int nnsmooth, ssubsample, ffiltsize, nngrow # dummy variables # Get query parameters fileroot (image,validim+) img = fileroot.root ext = fileroot.extension if(ext!="")ext="."//ext eexpname = expname if(eexpname=="")eexpname=img//"em" ssuffix = suffix pprefix = prefix nnsmooth=nsmooth ssubsample=subsample ffiltsize=filtsize nngrow=ngrow # Display initial image if (interact) { print ("Displaying image "//img//"...") display(img,1) } # Normalize image to uniform pixel-to-pixel rms using sq.root of exposure map. print ("Normalizing image "//img//" to uniform RMS...") if(!access(pprefix//img//ext))sigmanorm(img,normimage=eexpname,prefix=pprefix) # Set flag value at 1 DN below minimum pixel value in normalized image. minmax(pprefix//img,update-,ver-) minval = minmax.minval flagval = minval - 1. # Identify regions with zero exposure time and exclude from sigma calculation by # flagging them to the flagval and excluding them from the iterstat calculation. if(access("_zeroflag.imh"))imdel("_zeroflag.imh",ver-) if(access("_zeroflag.hhh"))imdel("_zeroflag.hhh",ver-) imcopy(eexpname,"_zeroflag",ver-) imreplace("_zeroflag",-1.,lower=INDEF,upper=0.) imreplace("_zeroflag",0.,lower=0.,upper=INDEF) imreplace("_zeroflag",flagval,lower=-1.,upper=-1.) imarith(pprefix//img,"+","_zeroflag","_norm"//img) imdelete ("_zeroflag",ver-) # Calculate rms of masked, normalized image with iterative sigma rejection. # Recommended threshold (to be applied to boxcar smoothed data) is approx. # (4.5/nsmooth) x unsmoothed rms. iterstat("_norm"//img,nsigrej=5.,maxiter=10.,lower=minval,upper=INDEF,ver-,print-) imdelete ("_norm"//img,ver-) recthresh = 4.5 / nsmooth * iterstat.sigma print ("Recommended thresholding level for mask is ",recthresh) # Allow user to interactively examine (unsmoothed) normalized image to set # threshold for masking. if (interact) imexamine(pprefix//img,display="display(image='$1',frame=2,zs+)") # If interactive, query for final threshold to adopt. # If not interactive, use the default recommended threshold. if (interact) { beep threshold = recthresh th = threshold } else { th = recthresh } # Apply thresholding to image using makeobjmask. makeobjmask (pprefix//img,suffix=ssuffix,headlist="",subsample=subsample,filtsize=filtsize,nsmooth=nsmooth,threshtype="constant",constthresh=th,ngrow=ngrow,statsec="",checklimits+,inv+,ver-) imrename (pprefix//img//ssuffix//".pl",img//ssuffix//".pl",ver-) # Display original image and mask if interact=yes. if (interact) { sctv(img//ssuffix//".pl",3) imarith(img,"*",img//ssuffix//".pl","del_"//img) display("del_"//img,4) imdel("del_"//img,ver-) # Allow iteration if desired. x=2 beep rredo=redo while(rredo){ if(x==2){ imren (img//ssuffix//".pl",pprefix//img//ssuffix//"_1.pl",ver-) if (!access(img//ssuffix//"orig.pl")) imcopy (pprefix//img//ssuffix//"_1.pl",img//ssuffix//"orig.pl",ver-, >& "dev$null") } print("Recommended thresholding level for mask is ",recthresh) th = threshold nnsmooth=i_nsmooth ssubsample=i_subsample ffiltsize=i_filtsize nngrow=i_ngrow makeobjmask (pprefix//img,suffix=ssuffix//"_"//str(x),headlist="",subsample=ssubsample,filtsize=ffiltsize,nsmooth=nnsmooth,threshtype="constant",constthresh=th,ngrow=nngrow,statsec="",checklimits+,inv+,ver-) sctv(pprefix//img//ssuffix//"_"//str(x)//".pl",3) imar(img,"*",pprefix//img//ssuffix//"_"//str(x)//".pl","del_"//img) display("del_"//img,4) imdel("del_"//img,ver-) # Another iteration? beep rredo=redo x+=1 } } # CLEAN UP zz=1 if(interact)zz=z if(zz!=0){ imren(pprefix//img//ssuffix//"_"//str(zz)//".pl",img//ssuffix//".pl",ver-, >& "dev$null") if(access(img//ssuffix//"orig.pl")){ print("Object masks "//img//ssuffix//".pl and "//img//ssuffix//"orig.pl created.") } else { print("Object mask "//img//ssuffix//".pl created.") } } else{ print("No images saved.") } y=0 zz=0 if(interact){ while(y& "dev$null") y+=1 } } print("Next task to run is `masklet'.") imdelete (pprefix//img,ver-) beep end phat_alone/src/photcheck.cl100644 1332 567 25703 6503624115 15305 0ustar hallast_hyee# photcheck -- monitor photometric stability of a data set. # # The user first identifies several suitable objects in a mosaiced image using # imexam. These objects should be located on a portion of the mosaic with # nearly maximum exposure time, so that they will appear in most or all of # the individual input frames. Photcheck then takes that input position list, # transforms it back to the coordinate systems of the individual sky subtracted # images which were summed to make the mosaic, and uses digiphot.apphot.phot to # compute accurate positions and measure magnitudes for the reference objects # in each sky subtracted input frame. # # If the user sets badcheck=yes, then each image's bad pixel mask is consulted, # and if any bad pixels are within the photometric aperture, phot will return # an INDEF value for the magnitude. Finally, the output files from phot are # compiled using awk into a format suitable for input to "photscale", which # allows interactive calculation of photometric scalings for the data set. # # The default output uses the mosaic image as the reference photometric image. # If another image is desired as a reference, that can be done in `photscale'. # # This routine requires: minv, fileroot, photcheck.awk; and that awk be # defined in the user package as a foreign task, i.e. task $awk = $foreign. # # 930803: originally created 2-3 Aug 1993 by Mark Dickinson # 960321: modified to include interactive identification of ref. stars, etc. # 960326: include editing of imshifts file, and check for overlong image names # 960409: changed _badpix.imh to unique filename, & removed duplicate creation # 960410: fixed bad pixel image bug # 960418: allowed for flipping of coadded image # 960420: removed dephot option in favor of editing PHOT parameter set # 960716: allow for multiple phot apertures by retrieving only mag[1] & merr[1] procedure photcheck(image,expmap,photcoords,output) string image {prompt="Mosaic image"} string expmap {prompt="Exposure map image"} string photcoords {prompt="File for reference star coordinates"} string output {prompt="File for formatted output photometry"} string imageshifts="" {prompt="`imshifts' file (default = image//.imshifts)"} bool flipped {no, prompt="Was coadded image flipped during ircoadd?"} bool interact {yes, prompt="Identify reference stars interactively?"} bool ephot {yes, prompt="Edit PHOT parameter sets before beginning?"} bool badcheck {yes, prompt="Check for bad pixels and return INDEF values?"} bool verbose {yes, prompt="Verbose output?"} bool cleanup {yes, prompt="Erase individual photometry files when done?"} struct *imglist begin string mimg,photc,outp # Equal query parameters int oxdim,oydim # Dimensions of mosaic image int ix, iy # Coordinate offsets of input images string img # Fscanned name of image string ext # extension of image (imh, hhh, etc.) string starshift # File for translated star coordinates string workimage # Copy of image for use with phot. real xstar, ystar # Star coordinates real temp # swap variable string photlist # temporary dump file string phiirsdir # pathname of PHIIRS source code directory real flagval # large flag value -- set to 1.e9 string mexp, bpmold, bpmnew, imagelist, s1, imgroot, morig, tempbp string old_exposure, old_gain, old_ccdread, old_apertures, old_filter real old_epadu, old_readnoise, old_annulus, old_dannulus, old_zmag real old_scale int x, y, z bool iinteract, eephot, fflipped flagval = 1.e9 # Check to make sure digiphot.apphot is loaded. if (!defpac("apphot")) { beep print ("Please load package digiphot.apphot before using this routine.") return } # Check for presence of the photcheck.awk script in the PHIIRS source # code directory. If that file is not present, return error message. phiirsdir = osfn("phiirs$") if (!access(phiirsdir//"photcheck.awk")) { beep print ("ERROR: Cannot access "//phiirsdir//"$photcheck.awk") return } # Check for presence tasks needed to run script if (!deftask("minv") || !deftask("fileroot")) { beep print ("ERROR: tasks `minv' and/or `fileroot' are not loaded.") print ("Please load them and restart task.") return } # Get query parameters. fileroot(image,validim+) mimg = fileroot.root morig = mimg mexp = expmap if(mexp=="")mexp=mimg//"em" photc = photcoords if(photc=="")photc=mimg//".photcoords" outp = output if(outp=="")outp=mimg//".photcheck" if (access(outp)) { beep print ("ERROR: File "//outp//" already exists. Choose another output name.") return } imagelist = imageshifts if(imagelist=="")imagelist=mimg//".imshifts" fflipped = flipped if(fflipped){ if(access(mimg//"_F.imh"))imdel(mimg//"_F", ver-) if(access(mimg//"_F.hhh"))imdel(mimg//"_F", ver-) imcopy(mimg//"[-*,*]", mimg//"_F", ver-) mimg=mimg//"_F" if(strlen(mimg)>=22){ print("WARNING! Image name "//mimg//" is too long!") print("Image names can't be longer than 21 characters.") print("Please rename image(s) and restart the task.") return } } # Check to make sure no image names are more than 21 characters long imglist=imagelist while (fscan(imglist,img,ix,iy) != EOF) { if(strlen(img)>=22){ beep print("WARNING! Image name "//img//" is too long! Image names as listed in") print(imagelist//" can be no longer than 21 characters.") print("Please rename image(s) and restart the task.") return } } imglist="" iinteract = interact eephot = ephot if(!eephot)print("PHOT task parameter sets will not be edited.") # Display mosaic image for reference star identification, if desired if(iinteract){ print("===> The mosaic image and exposure map are being displayed. Identify") print("===> several objects suitable for photometry in the mosaic image,") print("===> preferably ones located on parts of the mosaic with nearly") print("===> maximum exposure time, and get their coords (type 'a').") print("") print("===> When done, the coordinate file can be edited in case mistakes were made.") print("===> When using preexisting coordinate file, this temporary file will be blank.") print("") print("===> Finally, the imshifts file will be displayed for editing. Be sure the") print("===> listed images were the actual ones coadded to produce the mosaic.") if(fflipped){display(mexp//"[-*,*]",2)} else{display(mexp,2)} display(mimg,1) imexam(logfile="tmp"//photc, keep+) vi("tmp"//photc) vi(imagelist) # Output reference star x and y values to desired file if(fflipped)print("# WARNING! Coordinates are for "//morig//"[-*,*]",>>photc) fields("tmp"//photc,"1-2",lines="1-99999",>>photc) del("tmp"//photc,ver-) } # Get dimensions of mosaic image. imgets(mimg,"i_naxis1") oxdim=int(imgets.value) imgets(mimg,"i_naxis2") oydim=int(imgets.value) # If bad pixel checking is turned on, delete temporary files if present. if (badcheck) { # datapars.datamin is set to trigger 'INDEF' results for any object which has # a bad pixel within the aperture. If badcheck=no, then leave datamin = INDEF. datapars.datamin = -0.95 * flagval } else { datapars.datamin = INDEF } # If desired, set up default values for important PHOT parameters if(eephot){ epar("datapars") epar("fitskypars") epar("photpars") } # Create temporary file for phot output filenames. photlist = mktemp ("photcheck") # First, do photometry on stars in the mosaic image to act as reference values. if (verbose) print ("Measuring reference magnitudes from ",morig) if(access(morig//".mag.X")){ #del(morig//".mag.X",ver-) print("WARNING! "//morig//".mag.X already exists! Not overwritten.") } else { phot (mimg,skyfile="",centerpars="",fitskypars="",coords=photc,output=morig//".mag.X",inter-,verify-,verbose-) } # Record photometry output file name in temporary file photlist. print (morig//".mag.X", >photlist) # Next, loop through the individual images. bpmold="" bpmnew="" imglist=imagelist while (fscan(imglist,img,ix,iy) != EOF) { fileroot(img,validim+) if (badcheck) { workimage = "_"//img imgroot="_"//fileroot.root } else { workimage = img imgroot=fileroot.root } # If photometry files already exist, do not re-create them if(access(imgroot//".mag.X")){ print("WARNING! "//imgroot//".mag.X already exists! Not overwritten.") } else { # If photometry files do not exist, create them. Used to rename bad pixel mask # to *.imh, thus giving it datatype=real to allow large flag values used later, # but now I just use 1.e9 as the large flag value, which works for *.pl images. if (verbose) print ("Working on image ",img) if (badcheck) { imgets (img,"BPMASK") bpmnew=imgets.value fileroot(bpmnew,validim+) tempbp=fileroot.root ext=fileroot.extension if(ext!="")ext="."//ext # Only create new bad pixel mask if image BPM is different than previous image if(tempbp!=bpmold){ imdel ("_badp"//bpmold//ext,ver-,>&"dev$null") imdel ("_newp"//bpmold//ext,ver-,>&"dev$null") imdel ("_badp"//tempbp//ext,ver-,>&"dev$null") imdel ("_newp"//tempbp//ext,ver-,>&"dev$null") imcopy (tempbp,"_badp"//tempbp//ext,ver-) minv("_badp"//tempbp//ext,"_newp"//tempbp//ext) imar("_newp"//tempbp//ext,"*",flagval,"_newp"//tempbp//ext,ver-) } # Copy image and set bad pixels to a large, negative flag value. imar(img,"*","_badp"//tempbp//ext,"_"//img,ver-,noact-) imar("_"//img,"-","_newp"//tempbp//ext,"_"//img,ver-) bpmold=tempbp } # Apply translation to star coordinate file. starshift = mktemp("photcheck") lintran (photc,xf=1,yf=2,x1=ix,y1=iy,x2=0.,y2=0.,xsc=1.,ysc=1.,angle=0,min_sig=4,radians=no,>>starshift) # Do photometry on star list. Output goes to file named imgroot//.mag.X phot (workimage,skyfile="",centerpars="",fitskypars="",coords=starshift,output=imgroot//".mag.X",inter-,verify-,verbose-) # End of photometry file creation loop. Clean up. delete (starshift,ver-) if (badcheck) { imdelete ("_"//img,ver-) } } # Record photometry output file name in temporary file photlist. print (imgroot//".mag.X",>>photlist) # Next image } imdelete ("_badp"//bpmnew//ext,ver-,>&"dev$null") imdelete ("_newp"//bpmnew//ext,ver-,>&"dev$null") # Dump photometric records to output photometry file & format using awk scripts txdump ("@"//photlist,"image,xairmass,mag[1],merr[1]","yes",headers+,parameters-) | awk ("-f",phiirsdir//"photcheck.awk",> outp) print("", >> outp) if (verbose) { print ("") print ("Output data written to file "//outp//"; now, if desired,") print ("replace the first line in it with the desired reference") print ("photometry values, and then use it as input to task photscale") print ("to compute and plot photometric offsets between frames.") } # Clean up. if(fflipped) imdelete (mimg,ver-) imdelete ("_badp*"//ext,ver-,>&"dev$null") imdelete ("_newp*"//ext,ver-,>&"dev$null") if(cleanup){ delete ("@"//photlist,ver-) delete (photlist,ver-) } else { if(!access(morig//photlist)){ if(!access(morig//".photlist"))rename(photlist,morig//".photlist") print("Output photometry files are listed in "//morig//".photlist") } else { print("Output photometry files are listed in "//photlist) } } imglist = "" beep end phat_alone/src/photcomp.cl100644 1332 567 15305 6503624115 15163 0ustar hallast_hyee# photcomp -- compare photometry between two images on the same coord system # # Task calls following other tasks: filecalc, fileroot. # # Output: # # refimage//.pcomp//suffix Individual-star & avg. photometry for all images # refimage//.plog//suffix Imexam log for refimage # # 960402: created from irshift2.cl procedure photcomp(refimage,compimage,suffix) string refimage {prompt="Reference image"} string compimage {prompt="Comparison image"} string suffix="1" {prompt="Suffix string for output files"} string reflog="" {prompt="Ref. image imexam log (default=create new one)"} bool center=yes {prompt="Imexamine: center object in aperture?"} bool background=yes {prompt="Imexamine: fit and subtract background?"} real radius=5. {prompt="Imexamine aperture photometry radius"} real buffer=10. {prompt="Imexamine sky buffer"} real width=10. {prompt="Imexamine sky annulus width"} bool another {prompt="Do another comparison image?",mode="q"} struct *list begin string rrefimage, fflatlist, rrefcoords, bbadmask, rroundname string sshiftlist, coarsefile, ooffname, ssuffix, iintname, ffracname string pprefix, logoffname, sl, sx, img, iinterp, bboundary string ccompimage, stringline1, stringline2, stringline1old, stringline2old string stringline1tmp, stringline2tmp, georefin, geomapin real p, pixscale, stcoordx, stcoordy, nrows, ncols, delx, dely, adelx, adely real xold, yold, xxshiftold, yyshiftold, xshiftnew, yshiftnew, astcoordx real astcoordy, nl, nx, x, y int xref, yref, number, xtmp, ytmp, z bool go, aanother #The "go" parameter won't let the task run if you haven't loaded the ctio pkg. go=yes if(!deftask("filecalc") || (!deftask("fileroot"))) {go=no} if(go) { fileroot (refimage,validim+) rrefimage = fileroot.root fileroot (compimage,validim+) ccompimage = fileroot.root ssuffix = suffix rimexam.center=center rimexam.background=background rimexam.radius=radius rimexam.buffer=buffer rimexam.width=width del("_??g."//rrefimage,ver-,>&"dev$null") del("_??g."//ccompimage,ver-,>&"dev$null") del("_*refcomp",ver-,>&"dev$null") display(ccompimage,2) display(rrefimage,1) if(reflog==""){ print(" ") print("===) Choose an object that appears in both images, find its coordinates") print("===) (type 'a') in frame 1 (the reference image), and repeat with as many") print("===) objects as desired. The imexam output log will be displayed for") print("===> editing when done, in case mistakes were made.") print(" ") imexam(logfile="_log."//rrefimage, keep+) print(" ") print("===> In case mistakes were made, the imexam logfile can now be edited.") vi("_log."//rrefimage) } else { copy(reflog,"_log."//rrefimage,ver-) } print("===> Finding comparison image object fluxes...") del("_pxy",ver-,>&"dev$null") filecalc ("_log."//rrefimage, "$1;$2;2", lines="1-9999", format="%8.2f %8.2f %1d", calctype="real", >> "_pxy") imexam (ccompimage, defkey="a", imagecur="_pxy", keeplog+, logfile="_log."//ccompimage) print("===> Finding percentage differences (reference-comparison)/reference...") filecalc ("_log."//rrefimage, "$4", lines="1-9999", calctype="real", >> "_mag."//rrefimage) filecalc ("_log."//ccompimage, "$4", lines="1-9999", calctype="real", >> "_mag."//ccompimage) join("_mag."//rrefimage//",_mag."//ccompimage//",_pxy", out="_mag.refcomp") print("#", >> "_temp.refcomp") print("# Col. 1. X position", >> "_temp.refcomp") print("# Col. 2. Y position", >> "_temp.refcomp") print("# Col. 3. "//rrefimage//" flux", >> "_temp.refcomp") print("# Col. 4. "//ccompimage//" flux", >> "_temp.refcomp") print("# Col. 5. % difference ("//rrefimage//"-"//ccompimage//")/"//rrefimage, >> "_temp.refcomp") filecalc ("_mag.refcomp", "$3;$4;$1;$2;($1-$2)/$1", lines="1-9999", format="%8.2f %8.2f %10.4f %10.4f %10.6f", calctype="real", >> "_temp.refcomp") print("# Output of `average' task: avg rms #_of_pts",>> "_temp.refcomp") fields("_temp.refcomp","5") | average (opt="new_sample", >> "_temp.refcomp") fields("_temp.refcomp","5") | graph (point+,mark="cross",szm=0.005,logx-,logy-) vi ("_temp.refcomp") fields("_temp.refcomp", "5") | average (opt="new_sample") | scan (x,y,z) print("# Output of `average' task: avg rms #_of_pts",>> "_temp.refcomp") fields("_temp.refcomp","5") | average (opt="new_sample", >> "_temp.refcomp") print("Avg. (ref-comp)/ref = "//x//" +- "//y) # Clean up rename("_temp.refcomp", rrefimage//".pcomp"//ssuffix) rename("_log."//rrefimage, rrefimage//".plog"//ssuffix) del("_??g."//ccompimage,ver-,>&"dev$null") del("_*refcomp",ver-,>&"dev$null") #ANOTHER IMAGE? aanother=another while(aanother){ fileroot(compimage) ccompimage=fileroot.root del("_??g."//ccompimage,ver-,>&"dev$null") display(ccompimage,2) print("===> Finding comparison image object fluxes...") imexam (ccompimage, defkey="a", imagecur=coords, keeplog+, logfile="_log."//ccompimage) print("===> Finding percentage differences (reference-comparison)/reference...") filecalc ("_log."//ccompimage, "$4", lines="1-9999", calctype="real", >> "_mag."//ccompimage) join("_mag."//rrefimage//",_mag."//ccompimage//",_pxy", out="_mag.refcomp") print("#", >> "_temp.refcomp") print("# Col. 1. X position", >> "_temp.refcomp") print("# Col. 2. Y position", >> "_temp.refcomp") print("# Col. 3. "//rrefimage//" flux", >> "_temp.refcomp") print("# Col. 4. "//ccompimage//" flux", >> "_temp.refcomp") print("# Col. 5. % difference ("//rrefimage//"-"//ccompimage//")/"//rrefimage, >> "_temp.refcomp") filecalc ("_mag.refcomp", "$3;$4;$1;$2;($1-$2)/$1", lines="1-9999", format="%8.2f %8.2f %10.4f %10.4f %10.6f", calctype="real", >> "_temp.refcomp") print("# Output of `average' task: avg rms #_of_pts", >> "_temp.refcomp") fields("_temp.refcomp","5") | average (opt="new_sample", >> "_temp.refcomp") fields("_temp.refcomp","5") | graph (point+,mark="cross",szm=0.005,logx-,logy-) vi ("_temp.refcomp") fields("_temp.refcomp", "5") | average (opt="new_sample") | scan (x,y,z) print("# Output of `average' task: avg rms #_of_pts",>> "_temp.refcomp") fields("_temp.refcomp","5") | average (opt="new_sample", >> "_temp.refcomp") print("Avg. (ref-comp)/ref = "//x//" +- "//y) # Clean up del("_mag."//ccompimage,ver-,>&"dev$null") del("_??g."//ccompimage,ver-,>&"dev$null") type("_temp.refcomp", >> rrefimage//".pcomp"//ssuffix) del("_*refcomp",ver-,>&"dev$null") # Next comparison image, if desired aanother=another } # Clean up del("_mag."//rrefimage,ver-,>&"dev$null") del("_pxy",ver-,>&"dev$null") print("Files "//rrefimage//".pcomp"//ssuffix//" and "//rrefimage//".plog"//ssuffix//" have been created.") } else { print("WARNING: tasks `ctio.filecalc' and/or `phiirs.fileroot' not loaded!") print("Please load them and restart this task.") } beep end phat_alone/src/photscale.cl100644 1332 567 32304 6503624116 15313 0ustar hallast_hyee# photscale -- calculate photometric scalings of a data set. # # Originally created by Mark Dickinson. Modified by Pat Hall. # # 960323: created from photdiff.cl # 960325: added normalization option # 960326: truncate output to 159 characters so IRAF can handle it # 960327: fixed bugs relating to 159-char IRAF limit by using awk not IRAF # 960411: added option to just replot old results w/o changing or redoing them # 960716: added option to use aperture corrections if desired procedure photscale (photfile,prefix,suffix) string photfile {prompt="Photometry data file from photcheck"} string prefix {prompt="Prefix for output file(s)"} string suffix {prompt="Suffix for output file(s)"} bool apcor {no, prompt="Use aperture corrections?"} string apfile {no, prompt="Aperture correction file (coadded image first)"} bool display {yes, prompt="Automatically display lightcurve (needs STSDAS)?"} bool results {no, prompt="Output computed scales and weights?", mode="q"} bool newref {no, prompt="Select new reference image?", mode="q"} int refimagenum {min=1,prompt="Number of new reference image", mode="q"} bool replace {no, prompt="Replace a point with average of others?", mode="q"} int newpoint {min=1,prompt="Image number of point to replace", mode="q"} string avgpoints {prompt="Points to avg. for replacement (enter as `1,2')", mode="q"} string reenter {prompt="Re-enter points (enter as `1,2')", mode="q"} bool normal {no, prompt="Normalize scales to a certain image?", mode="q"} int normimagenum {min=1,prompt="Number of normalization image", mode="q"} struct *outdat begin string phfile,outp # tmp. working versions of input/output files string phiirsdir # directory containing PHIIRS scripts string igicommands, filename, tmpout, tmpfile, ssuffix, s1, s2, s3 string aavgpoints, tmpstart, tmpmid, tmpend, pphotfile, s4, s5, tmpawk string aapfile real ut, scale, serr, delta, derr, value1, error1, value2, error2 real xmin, xmax, ymin, ymax, valuemag, errormag, error0, value0 real xplotmin, xplotmax, yplotmin, yplotmax real normvalue, normserr, normdelta, normderr int x, y, z, rrefimagenum, nnewpoint, nnormimagenum, point1, point2 bool rresults, nnewref, rreplace, iterate, nnormal, normed, refereed bool justplot, aapcor # Get query parameters. pphotfile = photfile phfile = mktemp(pphotfile) copy(pphotfile,phfile) tmpout = prefix outp = mktemp(tmpout) ssuffix = suffix aapcor = apcor if(aapcor)aapfile=apfile # Check for presence of output files justplot=no if(access(tmpout//".photscales"//ssuffix)){ beep print("Output file "//tmpout//".photscales"//ssuffix//" already exists.") print ("No new files will be created; only plotting will be done.") justplot=yes } # Check for presence of filecalc task (in CTIO package) if(!deftask("filecalc")){ print ("Task `filecalc' is not loaded. Please load and restart task.") return } # Check for presence of the photscale.awk & photscale2.awk scripts in PHIIRS # source code directory. If either are not present, return error message. phiirsdir = osfn("phiirs$") if ((!access(phiirsdir//"photscale.awk")) || (!access(phiirsdir//"photscale2.awk"))) { print ("ERROR: Cannot access "//phiirsdir//"$photscale.awk or photscale2.awk!") return } # MAIN LOOP # Set up loop to allow repeated iterations using different reference images print ("Beginning...") iterate=yes nnewref=no rreplace=no nnormal=no normed=no refereed=no while(iterate){ # NEW REFERENCE IMAGE if(nnewref){ # If new reference image, what image number? refereed=yes rrefimagenum=refimagenum # Get that reference image's data and insert it as the first line w/awk tmpawk=mktemp("tmpawk") tmpfile=mktemp("tmpfile") print ("NR == "//rrefimagenum+1//", NR == "//rrefimagenum+1//" {print $0}", >> tmpawk) awk ("-f",tmpawk,phfile,>> tmpfile) del(tmpawk,ver-) tmpawk=mktemp("tmpawk") print ("NR != 1, NR != 1 {print $0}", >> tmpawk) awk ("-f",tmpawk,phfile,>> tmpfile) del(tmpawk,ver-) # Use awk script to calculate photometric scalings between frames. if(!aapcor){ awk ("-f",phiirsdir//"photscale.awk",tmpfile,>"_tmp."//outp) # If aperture corrections... } else { join(aapfile, tmpfile, maxch=9999, ver-, >> tmpfile//"2") awk ("-f",phiirsdir//"photscale2.awk",tmpfile//"2",>"_tmp."//outp) del(tmpfile//"2", ver-) } # Truncate output to 159 characters so IRAF can handle it. Lines are formatted # such that no mag,err pair should be cut off in the middle via this truncation tmpawk=mktemp("tmpawk") print ("{print (substr($0,1,159))}", >> tmpawk) awk ("-f",tmpawk,"_tmp."//outp,> outp) del("_tmp."//outp,ver-) del(tmpawk,ver-) del(phfile,ver-) rename(tmpfile,phfile) } else { # If first time through, calculate photometric scalings between frames. if(!rreplace && !nnormal){ del(outp,ver-,>&"dev$null") if(!aapcor){ awk ("-f",phiirsdir//"photscale.awk",phfile,>"_tmp."//outp) # If aperture corrections... } else { join(aapfile, phfile, maxch=9999, ver-, >> phfile//"2") awk ("-f",phiirsdir//"photscale2.awk",phfile//"2",>"_tmp."//outp) del(phfile//"2", ver-) } # Truncate output to 159 characters so IRAF can handle it. Lines are formatted # such that no mag,err pair should be cut off in the middle via this truncation tmpawk=mktemp("tmpawk") print ("{print (substr($0,1,159))}", >> tmpawk) awk ("-f",tmpawk,"_tmp."//outp,> outp) del("_tmp."//outp,ver-) del(tmpawk,ver-) } } # If display==yes, check to see if stsdas.graphics.stplot is loaded, and if # not, load it, then call stsdas.graphics.stplot.igi to display light curve. if (display) { if (!defpac("stsdas")) stsdas if (!defpac("graphics")) graphics if (!defpac("stplot")) stplot xplotmin = 0. xplotmax = 1. ymin = 1.E20 ymax = -1.E20 outdat = outp del("_plot."//outp, ver-, >& "dev$null") # First, scan data values to determine plot limits. Skip first line. if (fscan(outdat,filename) == EOF) error (0,"No lines in file ",outdat) while (fscan(outdat,filename,ut,delta,derr,scale,serr) != EOF) { xplotmax = xplotmax + 1. if(delta!=INDEF && derr!=INDEF){ ymin = min(ymin,delta-derr) ymax = max(ymax,delta+derr) } else { if(delta!=INDEF) { derr=99.999 } else { delta=0. derr=99.999 } } print(filename//" ",ut,delta,derr,scale,serr, >> "_plot."//outp) } yplotmin = ymin - 0.2 * (ymax-ymin) yplotmax = ymax + 0.2 * (ymax-ymin) # Now open temporary file and create igi command macro. igicommands = mktemp("plotdiff") print ("limits ",xplotmin,xplotmax,yplotmin,yplotmax, >igicommands) print ("box", >>igicommands) print ("xlabel image number", >>igicommands) print ("ylabel \gDm: reference - image", >>igicommands) print ("title Relative magnitude differences: ", tmpout//".photscales"//ssuffix, >>igicommands) print ("ltype 1", >>igicommands) print ("relocate ",xplotmin," 0.0 ", >>igicommands) print ("draw ",xplotmax," 0.0 ", >>igicommands) print ("ltype 0", >>igicommands) print ("data _plot."//outp, >>igicommands) # print ("data ",outp, >>igicommands) # print ("lines 2 1000 ", >>igicommands) print ("lines 1 1000 ", >>igicommands) print ("xcolumn 2", >>igicommands) print ("xevaluate r", >>igicommands) print ("ycolumn 3", >>igicommands) print ("ecol 4", >>igicommands) print ("ptype 4 0", >>igicommands) print ("points", >>igicommands) print ("error 2", >>igicommands) print ("error 4", >>igicommands) # Execute igi with command macro, exit, then bring up graphics cursor to # allow user to snapshot if desired. igi (initcmd="input "//igicommands//" ; end", >"dev$null") =gcur delete (igicommands,ver-) delete ("_plot."//outp,ver-,>&"dev$null") } # default: do not iterate, choose new reference image, or replace point(s) iterate=no nnewref=no nnormal=no rreplace=no # New reference image? if(!justplot)nnewref=newref if(nnewref){ iterate=yes } else { # # POINT REPLACEMENT # Replace a point? if(!justplot)rreplace=replace if(rreplace){ iterate=yes # Which point? nnewpoint=newpoint # Replace with average of what two points? (enter as 1,2) aavgpoints=avgpoints #if no , "re-enter (enter as 1,2):" while(stridx(",",aavgpoints)==0){ aavgpoints=reenter } point1=int(substr(aavgpoints,1,stridx(",",aavgpoints)-1)) point2=int(substr(aavgpoints,stridx(",",aavgpoints)+1,strlen(aavgpoints))) # Extract the value of point1 w/awk tmpawk=mktemp("tmpawk") tmpfile=mktemp("tmpfile") print("NR == "//point1+1//", NR == "//point1+1//" {print $0}",>> tmpawk) awk ("-f",tmpawk,outp,>> tmpfile) del(tmpawk,ver-) outdat=tmpfile while(fscan(outdat,filename,ut,delta,derr,scale,serr) != EOF) { value1=scale error1=serr } del(tmpfile,ver-,>&"dev$null") # Extract the value of point2 w/awk tmpawk=mktemp("tmpawk") tmpfile=mktemp("tmpfile") print("NR == "//point2+1//", NR == "//point2+1//" {print $0}",>> tmpawk) awk ("-f",tmpawk,outp,>> tmpfile) del(tmpawk,ver-) outdat=tmpfile while(fscan(outdat,filename,ut,delta,derr,scale,serr) != EOF) { value2=scale error2=serr } del(tmpfile,ver-,>&"dev$null") # Calculate the new point value0=0.5*(value1+value2) error0=sqrt(error1*error1+error2*error2) valuemag=-2.5*log10(value0) errormag=(2.5*error0)/(log(10.0)*value0) # Put in file w/awk, leaving out individ. star dm values to denote replacement tmpawk=mktemp("tmpawk") tmpstart=mktemp("tmpstart") tmpmid=mktemp("tmpmid") tmpend=mktemp("tmpend") tmpfile=mktemp("tmpfile") print("NR == 1, NR == "//nnewpoint//" {print $0}",>> tmpawk) awk ("-f",tmpawk,outp,>> tmpstart) del(tmpawk,ver-) tmpawk=mktemp("tmpawk") print("NR >= "//nnewpoint+2//" {print $0}",>> tmpawk) awk ("-f",tmpawk,outp,>> tmpend) del(tmpawk,ver-) tmpawk=mktemp("tmpawk") print("NR == "//nnewpoint+1//" {print $0}",>> tmpawk) awk ("-f",tmpawk,outp,>> tmpfile) del(tmpawk,ver-) outdat=tmpfile while(fscan(outdat,filename,ut,delta,derr,scale,serr) != EOF) { print(filename//" "//ut//" "//valuemag//" "//errormag//" "//value0//" "//error0, >> tmpmid) } del(outp, ver-) concat(tmpstart//","//tmpmid//","//tmpend, outp) del(tmpfile,ver-,>&"dev$null") del(tmpstart,ver-,>&"dev$null") del(tmpmid,ver-,>&"dev$null") del(tmpend,ver-,>&"dev$null") # End of loop for point replacement } else { # NORMALIZATION # Normalize scales? if(!justplot)nnormal=normal if(nnormal){ normed=yes iterate=yes # Normalize with what image? nnormimagenum=normimagenum # Extract the scaling value of nnormimagenum tmpawk=mktemp("tmpawk") tmpfile=mktemp("tmpfile") print("NR == "//nnormimagenum+1//", NR == "//nnormimagenum+1//" {print $0}",>> tmpawk) awk ("-f",tmpawk,outp,>> tmpfile) del(tmpawk,ver-) outdat=tmpfile while(fscan(outdat,filename,ut,delta,derr,scale,serr) != EOF) { normvalue=scale normdelta=delta } del(tmpfile,ver-,>&"dev$null") # Normalize all scales and errors by scaling value of nnormimagenum if(access(tmpout//".photold"//ssuffix))del(tmpout//".photold"//ssuffix,ver-) rename (outp,tmpout//".photold"//ssuffix) outdat=tmpout//".photold"//ssuffix while(fscan(outdat,s2,s3,delta,derr,scale,serr) != EOF) { # If delta, scale, and error are all defined, print normalized values of all if(delta!=INDEF && scale!=INDEF && serr!=INDEF){ # s1="one" # print(s1,delta,derr,scale,serr) print(s2//" "//s3//" "//delta-normdelta//" "//derr//" "//scale/normvalue//" "//serr/normvalue, >> outp) } else { # s1="two" # print(s1,delta,derr,scale,serr) # Set up strings containing values of delta and derr if(delta==INDEF){s4="INDEF"} else{s4=str(delta-normdelta)} if(derr==INDEF){s5="INDEF"} else{s5=str(derr)} # If only scale error is undefined, print INDEF value for it if(scale!=INDEF){ print(s2//" "//s3//" "//s4//" "//s5//" "//scale/normvalue//" INDEF", >> outp) # If both scale and scale error are undefined, print INDEF value for both } else { print(s2//" "//s3//" "//s4//" "//s5//" INDEF INDEF", >> outp) } } } # End of loop for normalization } # End of loop for no point replacement } # End of loop for no new reference image } # End of loop for a given reference image outdat="" } # Output scales and weights? if(!justplot){ rename(outp,tmpout//".photscales"//ssuffix) if(refereed){rename(phfile,tmpout//".photfile"//ssuffix)} else{del(phfile,ver-)} rresults=results if(rresults){ fields(tmpout//".photscales"//ssuffix, 5, lines="2-10000", >> tmpout//".scales"//ssuffix) filecalc(tmpout//".photscales"//ssuffix, "1/($6*$6)", lines="2-10000", >> tmpout//".weights"//ssuffix) } print("File "//tmpout//".photscales"//ssuffix//" was created") if(rresults){ print("along with "//tmpout//".scales"//ssuffix//" and "//tmpout//".weights"//ssuffix) print("(either or both of which can be used to re-ircoadd the images)") } if(refereed){ print("along with "//tmpout//".photfile"//ssuffix//" (which is a copy of") print(pphotfile//" except with a new reference image)") } if(normed){ print("along with "//tmpout//".photold"//ssuffix//" (which contains pre-normalization") print("scales and individual star magnitude differences)") } } else { del(outp,ver-,>&"dev$null") del(phfile,ver-,>&"dev$null") } beep end phat_alone/src/sctv.cl100644 1332 567 2336 6503624116 14272 0ustar hallast_hyeeprocedure sctv(image, frame) # Display an image with display range scaled to full range of image values # # 931123: modified to include more optional display parameters. -- MD # 950216: switch from min,max=0,1 to =min,max in image # 970506: modified to avoid IRAFV2.10 bug with some *.pl and minmax string image {prompt="Mask image to be displayed"} int frame {min=1,max=4,prompt="Frame buffer for image display"} bool fill {no,prompt="Scale image to fit display window?"} real xcenter {0.5,prompt="display window horizontal center"} real ycenter {0.5,prompt="display window vertical center"} real xsize {1.,prompt="display window horizontal size"} real ysize {1.,prompt="display window horizontal size"} real xmag {1.,prompt="display window horizontal magnification"} real ymag {1.,prompt="display window horizontal magnification"} begin real maxv, minv # replaced next line due to bug for *.pl files with large pos or neg values #minmax (image,force+,update-,ver-); maxv=real(minmax.maxval); minv=real(minmax.minval) imstat (image,fields="min,max",format-) | scan (minv,maxv) display (image,frame,zsc-,zra-,z1=minv,z2=maxv,fill=fill,xcenter=xcenter,ycenter=ycenter,xsize=xsize,ysize=ysize,xmag=xmag,ymag=ymag,ztrans="linear",order=0) end phat_alone/src/sigmanorm.cl100644 1332 567 3553 6503624117 15312 0ustar hallast_hyee# sigmanorm.cl -- normalize image by the square root of its exposure map # # Renormalizes mosaic image produced by DIMSUM by the square root of # the exposure map to produce an image which should have uniform rms # pixel-to-pixel noise across the entire exposed area. # # 930726: created by Mark Dickinson # 940106: Modified to allow user to specify name of normalization image. # 960328: added addition of header comments to output image # 960405: changed default normimage suffix from "exp" to "em" procedure sigmanorm(image) string image {prompt="Name of image to renormalize"} string normimage {"",prompt="Normalization image (default is root//em)"} string prefix {"norm", prompt="Prefix for renormalized image"} # bool undo {no,prompt="Undo (invert) normalization step?"} begin string img # equals image string ext # equals extension string nimg # normalization image real maxexp # peak exposure time # Get query parameter. img = image # Strip off filename extension. fileroot (img,validim+) img = fileroot.root ext = fileroot.extension if(ext!="")ext="."//ext # Check to see if normimage is null; if so, exposure map is assumed to be # imageroot//"em"//ext if (normimage == "") { nimg = img//"em"//ext } else { nimg = normimage } # Calculate sqrt of exposure map and multiply into image with normalization # such that the maximum exposure time in the normalization image is 1. minmax(nimg,force+,update-,ver-) maxexp = minmax.maxval imarith(nimg,"/",maxexp,prefix//img//ext,ver-) imfunc(prefix//img,prefix//img,"sqrt",ver-) # if(undo){imarith(img,"/",prefix//img,prefix//img,pix="real",calc="real",ver-,noact-) # }else{ imarith(img,"*",prefix//img,prefix//img,pix="real",calc="real",ver-) if(deftask("addcomment")){ addcomment(prefix//img,"phiirs.sigmanorm:",ver-) addcomment(prefix//img,img//" normalized by "//normimage,ver-) } end phat_alone/src/trim.cl100644 1332 567 6434 6503624117 14272 0ustar hallast_hyee# trim -- create constant-rms image with a certain minimum exposure time # # This task takes an input image and exposure map and creates: # # "trim"//img trimmed image # "trim"//mask exposure map for trimmed image # "trim"//mask//"mask" exposed/unexposed area mask for trimmed image # stats files of trimmed image RMS values (from maskstat) # # 960710: created from batch routine dofocasprep.cl procedure trim(image,mask,stats) string image {prompt="Image (or image list) to trim"} string mask {prompt="Exposure map or list (default=image//em)"} string stats {prompt="File to contain trimmed image RMS values"} string out="trim" {prompt="Prefix for trimmed images"} real mingoodexp=0.36 {prompt="Minimum acceptable exptime (fraction of maximum)"} struct *list begin string img, exp, newexp, pprefix, trimlist, imglist, trimmask, explist string sstats, joinlist, checki, checke, ext real mmingoodexp bool doren img = image checki=substr(img,1,1) if(checki=="@"){ imglist=substr(img,2,strlen(img)) trimlist=imglist//"trim" } else { imglist=mktemp("imglist") trimlist=imglist//"trim" print (img, >> imglist) } exp = mask checke=substr(exp,1,1) if(checke=="@"){ explist=substr(exp,2,strlen(exp)) } else { explist=mktemp("explist") if(checke=="") { fileroot (img, validim+) print (fileroot.root//"em", >> explist) } else { print (exp, >> explist) } } sstats=stats pprefix=out if(pprefix=="")pprefix="trim" mmingoodexp=mingoodexp # join image and mask lists joinlist=mktemp("joinlist") join (imglist, explist, >> joinlist) list=joinlist while (fscan (list,img,exp) != EOF) { fileroot(img, validim+) img = fileroot.root fileroot(exp, validim+) exp = fileroot.root ext = fileroot.extension if(ext!="") ext="."//ext newexp = pprefix//fileroot.root # the core print ("Preparing exposure map...") minmax (exp, force+, update+, ver-) imar (exp, "/", minmax.maxval, newexp, ver-, noact-) imreplace (newexp, 0., lower=INDEF, upper=mmingoodexp) imreplace (newexp, 1., lower=mmingoodexp-0.01, upper=INDEF) addring (newexp, newexp, ngrow=5, badval=1) imar (exp, "*", newexp, newexp, ver-, noact-) print ("Normalizing image...") sigmanorm (img, normim=newexp, prefix=pprefix) print ("Getting statistics...") print (pprefix//img, >> trimlist) imcopy (newexp, pprefix//img//"mask"//ext, ver-) imreplace (pprefix//img//"mask"//ext, 1., lower=0.01, upper=INDEF) maskstat (pprefix//img, pprefix//img//"mask"//ext, goodv=1, iterstat+, ver-, >> sstats) } del (joinlist, ver-) if (checke!="@") del (explist, ver-) if (checki!="@") { del (imglist, ver-) del (trimlist, ver-) } else { print("Output trimmed images are listed in "//trimlist) } print("Output trimmed image statistics are listed in "//sstats) #imar cf1.coadd3em / 3879.999267578125 cf1.coadd3em2 #imreplace cf1.coadd3em2 0. lower=INDEF upper=0.4 #imreplace cf1.coadd3em2 1. lower=0.39 upper=INDEF #addring cf1.coadd3em2 cf1.coadd3em2 ngrow=5 badval=1 #imar cf1.coadd3em * cf1.coadd3em2 cf1.coadd3em2 #imar cf1.coadd3em2 / 3879.999267578125 cf1.coadd3em2 #sigmanorm cf1.coadd3 normim=cf1.coadd3em2 #imcopy cf1.coadd3em2.imh cf1.coadd3em3.imh #imreplace cf1.coadd3em3.imh 1. lower=0.10 upper=INDEF #imren normcf1.coadd3.imh cf1 #maskstat cf1.imh cf1.coadd3em3.imh goodv=1 iterstat+ ver- >> stats beep end phat_alone/src/untrim.cl100644 1332 567 2566 6503624120 14631 0ustar hallast_hyee# untrim.cl -- script to produce true output magnitudes for objects detected # on a variable-exposure-time mosaic. # # Following two lines produce a list of the objects' INTEGER x,y # coordinates and their total COUNTS from FOCAS catalogs. # #filter H < image.cat > imagetmp.cat #catlist x y Li < imagetmp.cat >> untrim.image #catlist x y Ltotal < imagetmp.cat >> untrim.image # # Insert 1sig/arsec rms cts or 3sig limit cts in next line # imdel untrim.image*.imh ver- imar imagemask * 999 untrim.imagetmp.imh # list="untrim.image" while (fscan (list, i, j, z) !=EOF) { imdel ("tmp.imh", ver-, >& "dev$null") imar("imagemask["//i//":"//i//","//j//":"//j//"]", "*", z, "tmp.imh") imcopy ("tmp.imh", "untrim.imagetmp.imh["//i//":"//i//","//j//":"//j//"]") imdel ("tmp.imh", ver-, >& "dev$null") } minmax imagenorm force+ imar("imagenorm", "/", minmax.maxval, "imagenormtmp", ver+, noact-) # # Following two lines are optional. # #imar imagenormtmp + 0.03 imagenormtmp #imreplace imagenormtmp 1. lower=1. upper=INDEF # # Insert zeropoint for image in next line # imcalc untrim.imagetmp.imh,imagenormtmp untrim.image.imh "999-2.5*log10(im1 / (sqrt(im2)))" imdel imagenormtmp ver- imdel untrim.imagetmp.imh ver- # list="untrim.image" while (fscan (list, i, j, z) !=EOF) { imstat("untrim.image.imh["//i//":"//i//","//j//":"//j//"]", fields="mean", format-, >> "untrim.image.truemags") } beep phat_alone/src/irtfcoadd_4.p100644 1332 567 566 6427031100 15307 0ustar hallast_hyee#!/usr/local/bin/perl # cycle thru contents of file(s) given on command line using <> $iter=0; while (<>) { # skip blank lines or lines with # as first non-whitespace character next if (/^\s+$/ or /^#/ or /^\s+#/); if($iter==0) { ($mag2) = split " "; } else { ($one) = split " "; $out=$one/$mag2; printf "%9.7f\n", $out; } $iter=1; } phat_alone/src/irtfcoadd_5.p100644 1332 567 441 6427031100 15300 0ustar hallast_hyee#!/usr/local/bin/perl -w # cycle thru contents of file(s) given on command line using <> while (<>) { # skip blank lines or lines with # as first non-whitespace character next if (/^\s+$/ or /^#/ or /^\s+#/); ($one, $two) = split " "; $out=$two*$one; print "$out\n"; } phat_alone/src/irtfshift_0.p100644 1332 567 1016 6427031100 15355 0ustar hallast_hyee#!/usr/local/bin/perl # cycle thru contents of file(s) given on command line using <> $iter=0; while (<>) { # skip blank lines or lines with # as first non-whitespace character next if (/^\s+$/ or /^#/ or /^\s+#/); if($iter==0) { ($xxshiftold, $xshiftnew, $yyshiftold, $yshiftnew) = split " "; } else { ($one, $two, $three, $four) = split " "; $outone=$xxshiftold+(-1*$xshiftnew+$two); $outtwo=$yyshiftold+(-1*$yshiftnew+$four); printf "%8.2f%8.2f\n", $outone, $outtwo; } $iter=1; } phat_alone/src/irtfshift_1.p100644 1332 567 543 6427031100 15342 0ustar hallast_hyee#!/usr/local/bin/perl -w # cycle thru contents of file(s) given on command line using <> while (<>) { # skip blank lines or lines with # as first non-whitespace character next if (/^\s+$/ or /^#/ or /^\s+#/); ($one, $two, $three, $four) = split " "; $outone=$three-$one; $outtwo=$four-$two; printf "%6.2f%6.2f\n", $outone, $outtwo; } phat_alone/src/irtfshift_2.p100644 1332 567 443 6427031100 15342 0ustar hallast_hyee#!/usr/local/bin/perl -w # cycle thru contents of file(s) given on command line using <> while (<>) { # skip blank lines or lines with # as first non-whitespace character next if (/^\s+$/ or /^#/ or /^\s+#/); ($one, $two) = split " "; printf "%4.0f%4.0f\n", $one, $two; }