Esempio n. 1
0
int append_profile(const char *fname, int ispec, struct profile_phase *pp) {
    int status=0;
    fitsfile *fptr;
    fits_open_file(&fptr, fname, READWRITE, &status);
    fits_movnam_hdu(fptr, IMAGE_HDU, "PROFILE", 0, &status);
    int naxis;
    long naxes[2];
    fits_get_img_dim(fptr, &naxis, &status);
    if (naxis!=2) { 
        fits_close_file(fptr, &status);
        return(-1); 
    }
    fits_get_img_size(fptr, 2, naxes, &status);
    if (naxes[0]!=pp->nphase || naxes[1]<ispec) {
        fits_close_file(fptr, &status);
        return(-2);
    }
    naxes[0] = 1;
    naxes[1] = ispec;
    fits_write_pix(fptr, TFLOAT, naxes, pp->nphase, pp->data, &status);
    fits_close_file(fptr, &status);
    if (status) {
        fprintf(stderr, "Error in append_profile:\n");
        fits_report_error(stderr, status);
        return(-1);
    }
    return(0);
}
Esempio n. 2
0
static int
vips_fits_write( VipsRegion *region, VipsRect *area, void *a )
{
	VipsFits *fits = (VipsFits *) a;
	VipsImage *image = fits->image;
	int es = VIPS_IMAGE_SIZEOF_ELEMENT( image );
	int ps = VIPS_IMAGE_SIZEOF_PEL( image );

	int status;
	int y, b, x, k;

	status = 0;

	VIPS_DEBUG_MSG( "vips_fits_write: "
		"writing left = %d, top = %d, width = %d, height = %d\n", 
		area->left, area->top, area->width, area->height );

	/* We need to write a band at a time. We can't bandsplit in vips,
	 * since vips_sink_disc() can't loop over many images at once, sadly.
	 */

	for( y = 0; y < area->height; y++ ) {
		VipsPel *p = VIPS_REGION_ADDR( region, 
			area->left, area->top + y );

		for( b = 0; b < image->Bands; b++ ) {
			VipsPel *p1, *q;
			long fpixel[3];

			p1 = p + b * es;
			q = fits->buffer;

			for( x = 0; x < area->width; x++ ) {
				for( k = 0; k < es; k++ ) 
					q[k] = p1[k];
				
				q += es;
				p1 += ps;
			}

			fpixel[0] = area->left + 1;
			fpixel[1] = area->top + y + 1;
			fpixel[2] = b + 1;

			/* No need to lock, write functions are single-threaded.
			 */

			if( fits_write_pix( fits->fptr, fits->datatype, 
				fpixel, area->width, fits->buffer, 
				&status ) ) {
				vips_fits_error( status );
				return( -1 );
			}
		}
	}

	return( 0 );
}
static void write_pixels(oskar_Mem* data, const char* filename,
        int width, int height, int num_planes, int i_plane, int* status)
{
    long naxes[3], firstpix[3], num_pix;
    int dims_ok = 0;
    fitsfile* f = 0;
    if (*status) return;
    if (oskar_file_exists(filename))
    {
        int naxis = 0, imagetype = 0;
        fits_open_file(&f, filename, READWRITE, status);
        fits_get_img_param(f, 3, &imagetype, &naxis, naxes, status);
        if (naxis == 3 &&
                naxes[0] == width &&
                naxes[1] == height &&
                naxes[2] == num_planes)
        {
            dims_ok = 1;
        }
        else
        {
            *status = 0;
            fits_close_file(f, status);
            remove(filename);
            f = 0;
        }
    }
    if (!dims_ok)
    {
        naxes[0] = width;
        naxes[1] = height;
        naxes[2] = num_planes;
        fits_create_file(&f, filename, status);
        fits_create_img(f, oskar_mem_is_double(data) ? DOUBLE_IMG : FLOAT_IMG,
                3, naxes, status);
    }
    if (*status || !f)
    {
        if (f) fits_close_file(f, status);
        *status = OSKAR_ERR_FILE_IO;
        return;
    }
    num_pix = width * height;
    firstpix[0] = 1;
    firstpix[1] = 1;
    firstpix[2] = 1 + i_plane;
    if (i_plane < 0)
    {
        firstpix[2] = 1;
        num_pix *= num_planes;
    }
    fits_write_pix(f, oskar_mem_is_double(data) ? TDOUBLE : TFLOAT,
            firstpix, num_pix, oskar_mem_void(data), status);
    fits_close_file(f, status);
}
Esempio n. 4
0
void write_plane(oskar_Imager* h, oskar_Mem* plane,
        int t, int c, int p, int* status)
{
    int datatype, num_pixels;
    long firstpix[4];
    if (*status) return;
    if (!h->fits_file[p]) return;
    datatype = (oskar_mem_is_double(plane) ? TDOUBLE : TFLOAT);
    firstpix[0] = 1;
    firstpix[1] = 1;
    firstpix[2] = 1 + c;
    firstpix[3] = 1 + t;
    num_pixels = h->image_size * h->image_size;
    fits_write_pix(h->fits_file[p], datatype, firstpix, num_pixels,
            oskar_mem_void(plane), status);
}
Esempio n. 5
0
int write2Dfits(char *fname, double *f, int pwidth, int pheight)
{
  /*  write out image as a fits file */

  fitsfile *afptr;
  int status = 0;
  int anaxis;
  long anaxes[2], fpixel[2]={1,1};
  int bitpix;
  int size;

  bitpix = -32;
  anaxis = 2;
  anaxes[0] = pwidth;
  anaxes[1] = pheight;

  size = anaxes[0]*anaxes[1];

  fits_create_file(&afptr, fname, &status);
  fits_create_img(afptr, bitpix, anaxis, anaxes, &status);

  if (status) {
    fits_report_error(stderr, status); /* print error message */
    return(status);
  }

  /* write all data into image array */
  if (fits_write_pix(afptr, TDOUBLE, fpixel, size, f, &status) )
    {
      printf(" error reading pixel data \n");
      exit (2);
    }

  /* close the fits file */

  fits_close_file(afptr, &status);

  if (status) {
    fits_report_error(stderr, status); /* print error message */
    exit(2);
  }

  return 0;

}
Esempio n. 6
0
void	writeimage(const image_t *image, const char *filename) {
	if (debug) {
		fprintf(stderr, "%s:%d: writing image %s\n", __FILE__, __LINE__,
			filename);
	}
	char	errmsg[80];
	int	status = 0;
	fitsfile	*fits = NULL;
	if (fits_create_file(&fits, filename, &status)) {
		fits_get_errstatus(status, errmsg);
		fprintf(stderr, "cannot create fits file %s: %s\n",
			filename, errmsg);
		return;
	}

	// find dimensions of pixel array
	int	naxis = 2;
	long	naxes[2] = { image->width, image->height };
	if (fits_create_img(fits, DOUBLE_IMG, naxis, naxes, &status)) {
		fits_get_errstatus(status, errmsg);
		fprintf(stderr, "cannot create image: %s\n", errmsg);
		goto bad;
	}

	// read the pixel data
	long	npixels = image->width * image->height;
	long	firstpixel[3] = { 1, 1, 1 };
	if (fits_write_pix(fits, TDOUBLE, firstpixel, npixels,
			image->data, &status)) {
		fits_get_errstatus(status, errmsg);
		fprintf(stderr, "cannot write pixel data: %s\n", errmsg);
	}

bad:
	// close the file
	if (fits_close_file(fits, &status)) {
		fits_get_errstatus(status, errmsg);
		fprintf(stderr, "cannot close fits file %s: %s\n",
			filename, errmsg);
		goto bad;
	}
}
Esempio n. 7
0
int	WriteFITS(unsigned short *buffer, int cols, int rows, char *filename) {
#ifdef HAVE_FITSIO_H
	int	status = 0;
	fitsfile	*fits;
	unlink(filename);
	fits_create_file(&fits, filename, &status);
	if (status) {
		std::cerr << "cannot create file " << filename << std::endl;
		return -1;
	}
	long	naxes[2] = { cols, rows };
	fits_create_img(fits, SHORT_IMG, 2, naxes, &status);
	long	fpixel[2] = { 1, 1 };
	fits_write_pix(fits, TUSHORT, fpixel, cols * rows, buffer, &status);
	fits_close_file(fits, &status);
#else
	std::cerr << "FITS not supported" << std::endl;
	return -1;
#endif
}
Esempio n. 8
0
int append_filter(const char *fname, int ispec, int imjd, double fmjd, 
        struct filter_freq *hf) {
    int status=0;
    fitsfile *fptr;
    fits_open_file(&fptr, fname, READWRITE, &status);
    fits_movabs_hdu(fptr, 1, NULL, &status);
    int naxis;
    long naxes[3];
    fits_get_img_dim(fptr, &naxis, &status);
    if (naxis!=3) { 
        fits_close_file(fptr, &status);
        return(-1); 
    }
    fits_get_img_size(fptr, 3, naxes, &status);
    if (naxes[0]!=2 || naxes[1]!=hf->nchan || naxes[2]<ispec) {
        fits_close_file(fptr, &status);
        return(-2);
    }
    int imjd0;
    double fmjd0;
    fits_read_key(fptr, TINT, "IMJD", &imjd0, NULL, &status);
    fits_read_key(fptr, TDOUBLE, "FMJD", &fmjd0, NULL, &status);
    double toffs = (double)(imjd-imjd0) + (fmjd-fmjd0);
    toffs *= 86400.0;
    char key[80];
    sprintf(key, "DT%5.5d", ispec);
    fits_write_key(fptr, TDOUBLE, key, &toffs, "[s]", &status);
    naxes[0] = naxes[1] = 1;
    naxes[2] = ispec;
    fits_write_pix(fptr, TFLOAT, naxes, 2*hf->nchan, 
            (float *)hf->data, &status);
    fits_close_file(fptr, &status);
    if (status) {
        fprintf(stderr, "Error in append_filter:\n");
        fits_report_error(stderr, status);
        return(-1);
    }
    return(0);
}
Esempio n. 9
0
File: data.c Progetto: glenco/lensed
void write_fits(fitsfile* fptr, int datatype, size_t width, size_t height,
                size_t num, void** images, const char* names[], int* status)
{
    // total number of pixels
    long npix = width*height;
    
    // dimensions
    int naxis = 2;
    long naxes[2] = { width, height };
    
    // writing offset
    long fpixel[2] = { 1, 1 };
    
    // write primary HDU
    fits_create_img(fptr, SHORT_IMG, 0, NULL, status);
    
    // record file origin
    fits_write_key(fptr, TSTRING, "ORIGIN", "Lensed " LENSED_VERSION, "FITS file originator", status);
    fits_write_comment(fptr, "for more information, see http://glenco.github.io/lensed/", status);
    
    // record the date of FITS creation
    fits_write_date(fptr, status);
    
    // write images
    for(size_t n = 0; n < num; ++n)
    {
        // create image extension
        fits_create_img(fptr, FLOAT_IMG, naxis, naxes, status);
        
        // write pixels
        fits_write_pix(fptr, datatype, fpixel, npix, images[n], status);
        
        // give extension name
        if(names && names[n])
            fits_write_key(fptr, TSTRING, "EXTNAME", (void*)names[n], "extension name", status);
    }
}
Esempio n. 10
0
int FITSImage::saveFITS( const QString &newFilename )
{
    int status=0;
    long fpixel[2], nelements;
    fitsfile *new_fptr;

    nelements = stats.dim[0] * stats.dim[1];
    fpixel[0] = 1;
    fpixel[1] = 1;


    /* Create a new File, overwriting existing*/
    if (fits_create_file(&new_fptr, newFilename.toAscii(), &status))
    {
        fits_report_error(stderr, status);
        return status;
    }

    /* Copy ALL contents */
    if (fits_copy_file(fptr, new_fptr, 1, 1, 1, &status))
    {
        fits_report_error(stderr, status);
        return status;
    }

    /* close current file */
    if (fits_close_file(fptr, &status))
    {
        fits_report_error(stderr, status);
        return status;
    }

    if (tempFile)
    {
        QFile::remove(filename);
        tempFile = false;
    }

    filename = newFilename;

    fptr = new_fptr;

    /* Write Data */
    if (fits_write_pix(fptr, TFLOAT, fpixel, nelements, image_buffer, &status))
    {
        fits_report_error(stderr, status);
        return status;
    }

    /* Write keywords */

    // Minimum
    if (fits_update_key(fptr, TDOUBLE, "DATAMIN", &(stats.min), "Minimum value", &status))
    {
        fits_report_error(stderr, status);
        return status;
    }

    // Maximum
    if (fits_update_key(fptr, TDOUBLE, "DATAMAX", &(stats.max), "Maximum value", &status))
    {
        fits_report_error(stderr, status);
        return status;
    }

    // ISO Date
    if (fits_write_date(fptr, &status))
    {
        fits_report_error(stderr, status);
        return status;
    }

    QString history = QString("Modified by KStars on %1").arg(QDateTime::currentDateTime().toString("yyyy-MM-ddThh:mm:ss"));
    // History
    if (fits_write_history(fptr, history.toAscii(), &status))
    {
        fits_report_error(stderr, status);
        return status;
    }

    return status;
}
Esempio n. 11
0
int generateMedianPlane (char *cubepath, char *impath, int iplane,
    int nplane_in, int *startplane, int *endplane, char *errmsg)
{
    struct stat     buf;
    struct FitsHdr  hdr;

    char   str[1024];
    char   cmd[1024];
    
    int    bitpix;
    int    istatus;
    
    int    nhdu, hdutype, hdunum;

    
    long    nelements;
    
    int    naxis3;
    int    l;
    int    i;
    int    j;
    int    jj;

    int    nullcnt;
    
    int    splane;
    int    eplane;
    int    nplane;
    
    
    int    indx;
    int    indx1;
    int    indx2;

    int    npixel;
    int    midpoint; 

    long   fpixel[4];
    long   fpixelo[4];

    double *fitscubebuf;
    double *outbuf;
    double *fitsbuf1d;
    double *wavebuf;


    fitsfile  *infptr;
    fitsfile  *outfptr;

    
    int    debugfile = 1;


/*
     Make a NaN value to use setting blank pixels
*/

    union
    {
        double d;
        char   c[8];
    }
    value;

    double nan;

    for(i=0; i<8; ++i)
        value.c[i] = 255;

    nan = value.d;


    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "\nEnter generateMedianPlane: cubepath= [%s]\n", 
            cubepath);
        fprintf (fp_debug, "impath= [%s]\n", impath);
        fprintf (fp_debug, "iplane= [%d]\n", iplane);
        fprintf (fp_debug, "nplane_in= [%d]\n", nplane_in);
        fflush (fp_debug);
    }

    nplane = nplane_in;

    splane = iplane - nplane/2;
    eplane = splane + nplane - 1;

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "splane= [%d] eplane= [%d]\n", splane, eplane);
        fflush (fp_debug);
    }


/*
    Open input fits cube 
*/
    istatus = 0;
    if (fits_open_file (&infptr, cubepath, READONLY, &istatus)) {

        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
            fprintf (fp_debug, "istatus= [%d]\n", istatus);
            fflush (fp_debug);
        }

        sprintf (errmsg, "Failed to open FITS file [%s]\n", cubepath);
        return (-1);
    } 


    hdunum = 1; 
    nhdu = 0;
    istatus = 0;
    istatus = fits_get_num_hdus (infptr, &nhdu, &istatus);
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, 
            "returned fits_get_hdu_num: istatus= [%d] nhdu= [%d]\n",
            istatus, nhdu);
        fflush (fp_debug);
    }

    if (hdunum > nhdu) {

        sprintf (errmsg, "fname [%s] doesn't contain any HDU", cubepath);
        return (-1);
    }


/*
    Read fits keywords from the first HDU
*/
    hdutype = 0;
    istatus = 0;
    istatus = fits_movabs_hdu (infptr, hdunum, &hdutype, &istatus);

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, 
            "returned fits_movabs_hdu: istatus= [%d] hdutype= [%d]\n",
            istatus, hdutype);
        fflush (fp_debug);
    }

/*
    Read fits keywords
*/
    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "simple", str, (char *)NULL, 
        &istatus);
    
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword SIMPLE not found in fits header");
        return (-1);
    }
   
    if ((strcmp (str, "T") != 0) && (strcmp (str, "F") != 0)) {
        sprintf (errmsg, "keyword SIMPLE must be T or F");
        return (-1);
    }

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "bitpix", str, (char *)NULL, 
        &istatus);
    
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword BITPIX not found in fits header");
        return (-1);
    }
  
    istatus = str2Integer (str, &bitpix, errmsg);
    if (istatus != 0) {
        sprintf (errmsg, "keyword BITPIX must be an integer");
        return (-1);
    }

    if ((bitpix != 8) &&
        (bitpix != 16) &&
        (bitpix != 32) &&
        (bitpix != 64) &&
        (bitpix != -32) &&
        (bitpix != -64)) {
        
        sprintf (errmsg, 
            "keyword BITPIX value must be 8, 16, 32, 64, -32, -64");
        return (-1);
    }

    hdr.bitpix = bitpix;

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis", str, (char *)NULL, 
        &istatus);
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis not found in fits header");
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }
    istatus = str2Integer (str, &hdr.naxis, errmsg);
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis to integer");
        return (-1);
    }
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "naxis= [%d]\n", hdr.naxis);
        fflush (fp_debug);
    }


    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis1", str, (char *)NULL, 
        &istatus);
        
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", istatus);
        fflush (fp_debug);
    }
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis1 not found in fits header");
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }

    istatus = str2Integer (str, &hdr.ns, errmsg);
    
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis1 string to integer");
        return (-1);
    }
    hdr.naxes[0] = hdr.ns;

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis2", str, 
        (char *)NULL, &istatus);
        
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", istatus);
        fflush (fp_debug);
    }
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis2 not found in fits header");
        return (-1);
    }
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }

    istatus = str2Integer (str, &hdr.nl, errmsg);
    
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis2 string to integer");
        return (-1);
    }
    hdr.naxes[1] = hdr.nl;

    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "ns= [%d] nl= [%d]\n", hdr.ns, hdr.nl);
        fflush (fp_debug);
    }

    hdr.nplane = 1;

    if (hdr.naxis > 2) {
    
        istatus = 0;
        istatus = fits_read_key (infptr, TSTRING, "naxis3", str, 
            (char *)NULL, &istatus);
        
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
            fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", 
                istatus);
            fflush (fp_debug);
        }
        
        if (istatus == KEY_NO_EXIST) {
            sprintf (errmsg, "keyword naxis3 not found in fits header");
            return (-1);
        }
    
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
            fprintf (fp_debug, "str= [%s]\n", str);
            fflush (fp_debug);
        }

        istatus = str2Integer (str, &hdr.naxes[2], errmsg);
    
        if (istatus < 0) {
            sprintf (errmsg, "Failed to convert naxis3 string to integer");
            return (-1);
        }
        hdr.nplane = hdr.naxes[2];
    
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
            fprintf (fp_debug, "naxes[2]= [%d]\n", hdr.naxes[2]);
            fflush (fp_debug);
        }
    }
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "hdr.nplane= [%d]\n", hdr.nplane);
        fflush (fp_debug);
    }


    if (splane < 1)
        splane = 1;
    
    if (eplane > hdr.nplane)
        eplane = hdr.nplane;

    nplane = eplane - splane + 1;

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "hdr.nplane= [%d]\n", hdr.nplane);
        fprintf (fp_debug, "splane= [%d] eplane= [%d]\n", splane, eplane);
        fprintf (fp_debug, "nplane= [%d]\n", nplane);
        fflush (fp_debug);
    }


/*
    malloc arrays for reading data
*/
    fitscubebuf  
    = (double *)malloc(hdr.ns*hdr.nl*nplane*sizeof(double));
    
    outbuf  = (double *)malloc(hdr.ns*hdr.nl*sizeof(double));
    
    wavebuf  = (double *)malloc(nplane*sizeof(double));
    
    fitsbuf1d  = (double *)malloc(hdr.ns*sizeof(double));

    nelements = hdr.ns;

    npixel = hdr.ns*hdr.nl;
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "npixel= [%d]\n", npixel);
        fflush (fp_debug);
    }


/*
    Read cube data to fitscubebuf
*/
    fpixel[0] = 1;
    fpixel[3] = 1;
    
    indx = 0;
    for (l=splane; l<=eplane; l++)
    {
       
        indx2 = hdr.nl*hdr.ns*(l-splane); 

        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
            fprintf (fp_debug, "l= [%d]\n", l);
            fflush (fp_debug);
        }


        fpixel[1] = 1;
        fpixel[2] = l;
        
        for (j=0; j<hdr.nl; j++)
        {
            indx1 = hdr.ns*j; 

            if (fits_read_pix (infptr, TDOUBLE, fpixel, nelements, &nan,
                fitsbuf1d, &nullcnt, &istatus)) {
                break;
            }

            for (i=0; i<nelements; i++) {
                
                fitscubebuf[indx2+indx1+i] = fitsbuf1d[i];
                
                if ((debugfile) && (fp_debug != (FILE *)NULL)) {
                    
                    if ((i == 30) && (j == 25)) {
                        fprintf (fp_debug, "i=[%d] j=[%d] l=[%d] pixel=[%lf]\n",
                            i, j, l, fitscubebuf[indx2+indx1+i]);
                        fflush (fp_debug);
                    }
                }


            }

            fpixel[1]++;
        }
   }

/*
    istatus = 0;
    if (fits_close_file (infptr, &istatus)) {
        sprintf (errmsg, "Failed to close cubepath [%s]\n", cubepath);
        return (-1); 
    }
*/


/*
    Extract wave axis and compute median values
*/
    midpoint = nplane / 2;
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "midpint= [%d]\n", midpoint);
        fflush (fp_debug);
    }

    for (j=0; j<hdr.nl; j++) {
        
        indx1 = hdr.ns*j;

        for (i=0; i<hdr.ns; i++) {
        
            for (l=0; l<nplane; l++) {
                
                indx = npixel*l + indx1 + i;

                wavebuf[l] = fitscubebuf[indx];
                    
                if ((debugfile) && (fp_debug != (FILE *)NULL)) {
                    
                    if ((i == 30) && (j == 25)) {
                        fprintf (fp_debug, "i=[%d] j=[%d] l=[%d] pixel=[%lf]\n",
                            i, j, l, wavebuf[l]);
                        fflush (fp_debug);
                    }
                }
            }

            sort (wavebuf, nplane);
                
            if ((debugfile) && (fp_debug != (FILE *)NULL)) {
                    
                
                if ((i == 30) && (j == 25)) {
                    
                    fprintf (fp_debug, "after qsort\n");
                    for (l=0; l<nplane; l++) {
                        fprintf (fp_debug, "l=[%d] pixel=[%lf]\n", 
                            l, wavebuf[l]);
                    }
                    fflush (fp_debug);
                }
            }

            outbuf[indx1+i] = wavebuf[midpoint];
            
            if ((debugfile) && (fp_debug != (FILE *)NULL)) {
                if ((i == 30) && (j == 25)) {
                    fprintf (fp_debug, "outbuf= [%lf]\n", outbuf[indx1+i]);
                    fflush (fp_debug);
                }
            }

        }
    }



/*
    Create output fits file
*/
    istatus = stat (impath, &buf);
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "impath exists? : istatus= [%d]\n", istatus);
        fflush (fp_debug); 
    }

    if (istatus >= 0) {
        sprintf (cmd, "unlink %s", impath);
        istatus = system (cmd);
    }        


    istatus = 0;
    if (fits_create_file (&outfptr, impath, &istatus)) {
            
        sprintf (errmsg, "Failed to create output fitsfile [%s]\n", 
            impath);
        
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
            fprintf (fp_debug, "err: [%s]\n", errmsg);
            fflush (fp_debug);
        }
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "outptr created\n");
        fflush (fp_debug);
    }


/* 
    Copy input fits header to output fitsfile
*/
    istatus = 0;
    if (fits_copy_header (infptr, outfptr, &istatus)) {

        strcpy (errmsg, "Failed to copy fitshdr\n");
        
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
            fprintf (fp_debug, "err: [%s]\n", errmsg);
            fflush (fp_debug);
        }
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "header copied\n");
        fflush (fp_debug);
    }



/*
    Update header keyword NAXIS3
*/
    naxis3 = 1;
    istatus = 0;
    if (fits_update_key_lng(outfptr, "NAXIS3", naxis3, (char *)NULL, 
        &istatus)) {
        
        strcpy (errmsg, "Failed to update keyword NAXIS3\n");
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "naxis3 updated\n");
        fflush (fp_debug);
    }


/*
    Write to output fitsfile
*/
    nelements = hdr.ns;
    fpixelo[0] = 1;
    fpixelo[1] = 1;
    fpixelo[2] = 1;
    fpixelo[3] = 1;
       
    for (j=0; j<hdr.nl; j++) {
    
        jj = hdr.ns*j;
        for (i=0; i<hdr.ns; i++) {
                
            fitsbuf1d[i] = outbuf[jj+i];
        }

        if (fits_write_pix (outfptr, TDOUBLE, fpixelo, nelements,
             (void *)fitsbuf1d, &istatus)) {

            sprintf (errmsg, "fits write error: l= [%d] j= [%d]\n", l, j);
            return (-1);
        }

        fpixelo[1]++;
    }

        
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "here2\n");
        fflush (fp_debug);
    }


    istatus = 0;
    if (fits_close_file (infptr, &istatus)) {
        sprintf (errmsg, "Failed to close cubepath [%s]\n", cubepath);
        return (-1); 
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "here3\n");
        fflush (fp_debug);
    }


    istatus = 0;
    if (fits_close_file (outfptr, &istatus)) {
        sprintf (errmsg, "Failed to close impath [%s]\n", impath);
        return (-1); 
    }

    *startplane = splane;
    *endplane = eplane;


    return (0);
}
Esempio n. 12
0
/* does the actual write of the file */
static void file_write_rays2fits(long fileNum, long firstTask, long lastTask, MPI_Comm fileComm)
{
  const char *ttype[] = 
    { "nest", "ra", "dec", "A00", "A01", "A10", "A11"
#ifdef OUTPUTRAYDEFLECTIONS
      , "alpha0", "alpha1"
#endif
#ifdef OUTPUTPHI
      , "phi"
#endif
    };
  
  const char *tform[] = 
    { "K", "D", "D", "D", "D", "D", "D"
#ifdef OUTPUTRAYDEFLECTIONS
      , "D", "D"
#endif
#ifdef OUTPUTPHI
      , "D"
#endif
    };
  
  char name[MAX_FILENAME];
  char bangname[MAX_FILENAME];
  long NumRaysInFile,i,j;
  long *NumRaysInPeanoCell,*StartRaysInPeanoCell,peano;
  
  fitsfile *fptr;
  int status = 0;
  int naxis = 1;
  long naxes[1],fpixel[1];
  LONGLONG nrows;
  int tfields,colnum;
  long k,chunkInd,firstInd,lastInd,NumRaysInChunkBase,NumRaysInChunk,NumChunks;
  LONGLONG firstrow,firstelem,nelements;
  double *darr;
  long *larr;
  char *buff;
  double ra,dec;
  
  long nwc=0,NtotToRecv,nw=0,nwg=0,rpeano,rowloc;
  MPI_Status mpistatus;
  double t0 = 0.0;
  
  sprintf(name,"%s/%s%04ld.%04ld",rayTraceData.OutputPath,rayTraceData.RayOutputName,rayTraceData.CurrentPlaneNum,fileNum);
  sprintf(bangname,"!%s",name);
  
  /* build fits table layout*/
  tfields = 7;
#ifdef OUTPUTRAYDEFLECTIONS
  tfields += 2;
#endif
#ifdef OUTPUTPHI
  tfields += 1;
#endif
  
  /* build file layout*/
  NumRaysInPeanoCell = (long*)malloc(sizeof(long)*NbundleCells);
  assert(NumRaysInPeanoCell != NULL);
  StartRaysInPeanoCell = (long*)malloc(sizeof(long)*NbundleCells);
  assert(StartRaysInPeanoCell != NULL);
  for(i=0;i<NbundleCells;++i)
    StartRaysInPeanoCell[i] = 0;
  for(i=0;i<NbundleCells;++i)
    {
      if(ISSETBITFLAG(bundleCells[i].active,PRIMARY_BUNDLECELL))
	{
	  peano = nest2peano(bundleCells[i].nest,rayTraceData.bundleOrder);
	  StartRaysInPeanoCell[peano] = bundleCells[i].Nrays;
	  nwc += bundleCells[i].Nrays;
	}
    }
  MPI_Allreduce(StartRaysInPeanoCell,NumRaysInPeanoCell,(int) NbundleCells,MPI_LONG,MPI_SUM,fileComm);
  j = 0;
  for(i=0;i<NbundleCells;++i)
    {
      StartRaysInPeanoCell[i] = j;
      j += NumRaysInPeanoCell[i];
    }
  NumRaysInFile = j;
  
  /* make the file and write header info */
  if(ThisTask == firstTask)
    {
      t0 = -MPI_Wtime();
      
      remove(name);
      
      fits_create_file(&fptr,bangname,&status);
      if(status)
        fits_report_error(stderr,status);
      
      naxes[0] = 2l*NbundleCells;
      fits_create_img(fptr,LONGLONG_IMG,naxis,naxes,&status);
      if(status)
        fits_report_error(stderr,status);
      
      fpixel[0] = 0+1;
      fits_write_pix(fptr,TLONG,fpixel,(LONGLONG) (NbundleCells),NumRaysInPeanoCell,&status);
      if(status)
        fits_report_error(stderr,status);
      
      fpixel[0] = NbundleCells+1;
      fits_write_pix(fptr,TLONG,fpixel,(LONGLONG) (NbundleCells),StartRaysInPeanoCell,&status);
      if(status)
        fits_report_error(stderr,status);
      
      fits_write_key(fptr,TLONG,"NumFiles",&(rayTraceData.NumRayOutputFiles),"number of files that rays are split into",&status);
      if(status)
        fits_report_error(stderr,status);
      
      fits_write_key(fptr,TLONG,"PeanoCellHEALPixOrder",&(rayTraceData.bundleOrder),"HEALPix order of peano indexed cells rays are organized into",&status);
      if(status)
        fits_report_error(stderr,status);
      
      fits_write_key(fptr,TLONG,"RayHEALPixOrder",&(rayTraceData.rayOrder),"HEALPix order of ray grid",&status);
      if(status)
        fits_report_error(stderr,status);
      
      nrows = (LONGLONG) (NumRaysInFile);
      fits_create_tbl(fptr,BINARY_TBL,nrows,tfields,ttype,tform,NULL,"Rays",&status);
      if(status)
        fits_report_error(stderr,status);
      
      fits_get_rowsize(fptr,&NumRaysInChunkBase,&status);
      if(status)
	fits_report_error(stderr,status);
    }
  
  MPI_Bcast(&NumRaysInChunkBase,1,MPI_LONG,0,fileComm);
  if(sizeof(long) > sizeof(double))
    buff = (char*)malloc(sizeof(long)*NumRaysInChunkBase);
  else
    buff = (char*)malloc(sizeof(double)*NumRaysInChunkBase);
  assert(buff != NULL);
  darr = (double*) buff;
  larr = (long*) buff;
  
  for(i=firstTask;i<=lastTask;++i)
    {
      if(ThisTask == i)
	{
#ifdef DEBUG
#if DEBUG_LEVEL > 0
	  fprintf(stderr,"%d: fileNum = %ld, first,last = %ld|%ld\n",ThisTask,fileNum,firstTask,lastTask);
#endif
#endif
	  if(ThisTask != firstTask)
	    MPI_Send(&nwc,1,MPI_LONG,(int) firstTask,TAG_RAYIO_TOTNUM,MPI_COMM_WORLD);
	  
	  for(rpeano=0;rpeano<NrestrictedPeanoInd;++rpeano)
            {
              j = bundleCellsRestrictedPeanoInd2Nest[rpeano];
              
	      if(ISSETBITFLAG(bundleCells[j].active,PRIMARY_BUNDLECELL))
		{
		  peano = nest2peano(bundleCells[j].nest,rayTraceData.bundleOrder);
		  
		  assert(NumRaysInPeanoCell[peano] == ((1l) << (2*(rayTraceData.rayOrder-rayTraceData.bundleOrder))));
		  assert((StartRaysInPeanoCell[peano] - 
			  ((StartRaysInPeanoCell[peano])/(((1l) << (2*(rayTraceData.rayOrder-rayTraceData.bundleOrder)))))
			  *(((1l) << (2*(rayTraceData.rayOrder-rayTraceData.bundleOrder))))) == 0);
		  
		  NumChunks = NumRaysInPeanoCell[peano]/NumRaysInChunkBase;
		  if(NumChunks*NumRaysInChunkBase < NumRaysInPeanoCell[peano])
		    NumChunks += 1;
		  
		  firstrow = (LONGLONG) (StartRaysInPeanoCell[peano]) + (LONGLONG) 1;
		  firstelem = 1;
		  for(chunkInd=0;chunkInd<NumChunks;++chunkInd)
		    {
		      firstInd = chunkInd*NumRaysInChunkBase;
		      lastInd = (chunkInd+1)*NumRaysInChunkBase-1;
		      if(lastInd >= NumRaysInPeanoCell[peano]-1)
			lastInd = NumRaysInPeanoCell[peano]-1;
		      NumRaysInChunk = lastInd - firstInd + 1;
		      
		      nelements = (LONGLONG) NumRaysInChunk;
		      nw += NumRaysInChunk;
		      
		      if(ThisTask != firstTask)
			{
			  rowloc = firstrow;
			  MPI_Send(&rowloc,1,MPI_LONG,(int) firstTask,TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD);
			  MPI_Send(&NumRaysInChunk,1,MPI_LONG,(int) firstTask,TAG_RAYIO_NUMCHUNK,MPI_COMM_WORLD);
			  colnum = TAG_RAYIO_CHUNKDATA+1;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    larr[k-firstInd] = bundleCells[j].rays[k].nest;
			  MPI_Ssend(larr,(int) NumRaysInChunk,MPI_LONG,(int) firstTask,colnum,MPI_COMM_WORLD);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    {
			      vec2radec(bundleCells[j].rays[k].n,&ra,&dec);
			      darr[k-firstInd] = ra;
			    }
			  MPI_Ssend(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) firstTask,colnum,MPI_COMM_WORLD);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    {
			      vec2radec(bundleCells[j].rays[k].n,&ra,&dec);
			      darr[k-firstInd] = dec;
			    }
			  MPI_Ssend(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) firstTask,colnum,MPI_COMM_WORLD);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].A[2*0+0];
			  MPI_Ssend(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) firstTask,colnum,MPI_COMM_WORLD);
                          ++colnum;
			  			  
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].A[2*0+1];
			  MPI_Ssend(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) firstTask,colnum,MPI_COMM_WORLD);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].A[2*1+0];
			  MPI_Ssend(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) firstTask,colnum,MPI_COMM_WORLD);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].A[2*1+1];
			  MPI_Ssend(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) firstTask,colnum,MPI_COMM_WORLD);
			  ++colnum;
			  
#ifdef OUTPUTRAYDEFLECTIONS
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].alpha[0];
			  MPI_Ssend(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) firstTask,colnum,MPI_COMM_WORLD);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].alpha[1];
			  MPI_Ssend(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) firstTask,colnum,MPI_COMM_WORLD);
			  ++colnum;
#endif
#ifdef OUTPUTPHI
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].phi;
			  MPI_Ssend(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) firstTask,colnum,MPI_COMM_WORLD);
			  ++colnum;
#endif
			  firstrow += nelements;
			}
		      else
			{
			  colnum = 1;
			  for(k=firstInd;k<=lastInd;++k)
			    larr[k-firstInd] = bundleCells[j].rays[k].nest;
			  fits_write_col(fptr,TLONG,colnum,firstrow,firstelem,nelements,larr,&status);
			  if(status)
			    fits_report_error(stderr,status);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    {
			      vec2radec(bundleCells[j].rays[k].n,&ra,&dec);
			      darr[k-firstInd] = ra;
			    }
			  fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
			  if(status)
			    fits_report_error(stderr,status);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    {
			      vec2radec(bundleCells[j].rays[k].n,&ra,&dec);
			      darr[k-firstInd] = dec;
			    }
			  fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
			  if(status)
			    fits_report_error(stderr,status);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].A[2*0+0];
			  fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
			  if(status)
			    fits_report_error(stderr,status);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].A[2*0+1];
			  fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
			  if(status)
			    fits_report_error(stderr,status);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].A[2*1+0];
			  fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
			  if(status)
			    fits_report_error(stderr,status);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].A[2*1+1];
			  fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
			  if(status)
			    fits_report_error(stderr,status);
			  ++colnum;
			  
#ifdef OUTPUTRAYDEFLECTIONS
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].alpha[0];
			  fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
			  if(status)
			    fits_report_error(stderr,status);
			  ++colnum;
			  
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].alpha[1];
			  fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
			  if(status)
			    fits_report_error(stderr,status);
			  ++colnum;
#endif
#ifdef OUTPUTPHI
			  for(k=firstInd;k<=lastInd;++k)
			    darr[k-firstInd] = bundleCells[j].rays[k].phi;
			  fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
			  if(status)
			    fits_report_error(stderr,status);
			  ++colnum;
#endif
			  firstrow += nelements;
			}
		    }// for(chunkInd=0;chunkInd<NumChunks;++chunkInd)
		} //if(ISSETBITFLAG(bundleCells[j].active,PRIMARY_BUNDLECELL)).
	    } //for(j=0;j<NbundleCells;++j)
	} //if(ThisTask == i)
      
      if(i != firstTask && ThisTask == firstTask)
	{
	  MPI_Recv(&NtotToRecv,1,MPI_LONG,(int) i,TAG_RAYIO_TOTNUM,MPI_COMM_WORLD,&mpistatus);
	  
	  firstelem = 1;
	  while(NtotToRecv > 0)
	    {
	      MPI_Recv(&rowloc,1,MPI_LONG,(int) i,TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD,&mpistatus);
	      MPI_Recv(&NumRaysInChunk,1,MPI_LONG,(int) i,TAG_RAYIO_NUMCHUNK,MPI_COMM_WORLD,&mpistatus);
	      firstrow = (LONGLONG) (rowloc);
	      nelements = (LONGLONG) NumRaysInChunk;
	      colnum = 1;
	      
	      MPI_Recv(larr,(int) NumRaysInChunk,MPI_LONG,(int) i,colnum+TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD,&mpistatus);
	      fits_write_col(fptr,TLONG,colnum,firstrow,firstelem,nelements,larr,&status);
	      if(status)
		fits_report_error(stderr,status);
	      ++colnum;
	      
	      MPI_Recv(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) i,colnum+TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD,&mpistatus);
	      fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
	      if(status)
		fits_report_error(stderr,status);
	      ++colnum;
	      
	      MPI_Recv(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) i,colnum+TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD,&mpistatus);
	      fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
	      if(status)
		fits_report_error(stderr,status);
	      ++colnum;
	      
	      MPI_Recv(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) i,colnum+TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD,&mpistatus);
	      fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
	      if(status)
		fits_report_error(stderr,status);
	      ++colnum;
	      
	      MPI_Recv(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) i,colnum+TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD,&mpistatus);
	      fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
	      if(status)
		fits_report_error(stderr,status);
	      ++colnum;
	      
	      MPI_Recv(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) i,colnum+TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD,&mpistatus);
	      fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
	      if(status)
		fits_report_error(stderr,status);
	      ++colnum;
	      
	      MPI_Recv(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) i,colnum+TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD,&mpistatus);
	      fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
	      if(status)
		fits_report_error(stderr,status);
	      ++colnum;
	      
#ifdef OUTPUTRAYDEFLECTIONS
	      MPI_Recv(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) i,colnum+TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD,&mpistatus);
	      fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
	      if(status)
		fits_report_error(stderr,status);
	      ++colnum;
	      
	      MPI_Recv(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) i,colnum+TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD,&mpistatus);
	      fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
	      if(status)
		fits_report_error(stderr,status);
	      ++colnum;
#endif
#ifdef OUTPUTPHI
	      MPI_Recv(darr,(int) NumRaysInChunk,MPI_DOUBLE,(int) i,colnum+TAG_RAYIO_CHUNKDATA,MPI_COMM_WORLD,&mpistatus);
	      fits_write_col(fptr,TDOUBLE,colnum,firstrow,firstelem,nelements,darr,&status);
	      if(status)
		fits_report_error(stderr,status);
	      ++colnum;
#endif
	      	      
	      nwg += NumRaysInChunk;
              NtotToRecv -= NumRaysInChunk;
	    }
	}
      
      //////////////////////////////
      MPI_Barrier(fileComm);
      //////////////////////////////
    }
  
  if(ThisTask == firstTask)
    {
      fits_close_file(fptr,&status);
      if(status)
	fits_report_error(stderr,status);
      
      t0 += MPI_Wtime();

#ifdef DEBUG      
      fprintf(stderr,"writing %ld rays to file '%s' took %g seconds.\n",NumRaysInFile,name,t0);
#endif
      
      assert(nwg == NumRaysInFile-nw); //error check # of rays recvd
    }
  
  //error check # of rays written
  MPI_Allreduce(&nw,&nwg,1,MPI_LONG,MPI_SUM,fileComm);
  assert(nw == nwc);
  assert(nwg == NumRaysInFile);
  
  //clean up and close files for this task
  free(buff);
  free(StartRaysInPeanoCell);
  free(NumRaysInPeanoCell);
}
Esempio n. 13
0
void GuiderOneStar::SaveStarFITS()
{
    double StarX = m_star.X;
    double StarY = m_star.Y;
    usImage *pImage = CurrentImage();
    usImage tmpimg;

    tmpimg.Init(60,60);
    int start_x = ROUND(StarX)-30;
    int start_y = ROUND(StarY)-30;
    if ((start_x + 60) > pImage->Size.GetWidth())
        start_x = pImage->Size.GetWidth() - 60;
    if ((start_y + 60) > pImage->Size.GetHeight())
        start_y = pImage->Size.GetHeight() - 60;
    int x,y, width;
    width = pImage->Size.GetWidth();
    unsigned short *usptr = tmpimg.ImageData;
    for (y=0; y<60; y++)
        for (x=0; x<60; x++, usptr++)
            *usptr = *(pImage->ImageData + (y+start_y)*width + (x+start_x));

    wxString fname = Debug.GetLogDir() + PATHSEPSTR + "PHD_GuideStar" + wxDateTime::Now().Format(_T("_%j_%H%M%S")) + ".fit";

    fitsfile *fptr;  // FITS file pointer
    int status = 0;  // CFITSIO status value MUST be initialized to zero!
    long fpixel[3] = {1,1,1};
    long fsize[3];
    char keyname[9]; // was 9
    char keycomment[100];
    char keystring[100];
    int output_format=USHORT_IMG;

    fsize[0] = 60;
    fsize[1] = 60;
    fsize[2] = 0;
    PHD_fits_create_file(&fptr, fname, false, &status);
    if (!status)
    {
        fits_create_img(fptr,output_format, 2, fsize, &status);

        time_t now;
        struct tm *timestruct;
        time(&now);
        timestruct=gmtime(&now);
        sprintf(keyname,"DATE");
        sprintf(keycomment,"UTC date that FITS file was created");
        sprintf(keystring,"%.4d-%.2d-%.2d %.2d:%.2d:%.2d",timestruct->tm_year+1900,timestruct->tm_mon+1,timestruct->tm_mday,timestruct->tm_hour,timestruct->tm_min,timestruct->tm_sec);
        if (!status) fits_write_key(fptr, TSTRING, keyname, keystring, keycomment, &status);

        sprintf(keyname,"DATE-OBS");
        sprintf(keycomment,"YYYY-MM-DDThh:mm:ss observation start, UT");
        sprintf(keystring,"%s", (const char *) pImage->GetImgStartTime().c_str());
        if (!status) fits_write_key(fptr, TSTRING, keyname, keystring, keycomment, &status);

        sprintf(keyname,"EXPOSURE");
        sprintf(keycomment,"Exposure time [s]");
        float dur = (float) pImage->ImgExpDur / 1000.0;
        if (!status) fits_write_key(fptr, TFLOAT, keyname, &dur, keycomment, &status);

        unsigned int tmp = 1;
        sprintf(keyname,"XBINNING");
        sprintf(keycomment,"Camera binning mode");
        fits_write_key(fptr, TUINT, keyname, &tmp, keycomment, &status);
        sprintf(keyname,"YBINNING");
        sprintf(keycomment,"Camera binning mode");
        fits_write_key(fptr, TUINT, keyname, &tmp, keycomment, &status);

        sprintf(keyname,"XORGSUB");
        sprintf(keycomment,"Subframe x position in binned pixels");
        tmp = start_x;
        fits_write_key(fptr, TINT, keyname, &tmp, keycomment, &status);
        sprintf(keyname,"YORGSUB");
        sprintf(keycomment,"Subframe y position in binned pixels");
        tmp = start_y;
        fits_write_key(fptr, TINT, keyname, &tmp, keycomment, &status);

        if (!status) fits_write_pix(fptr,TUSHORT,fpixel,tmpimg.NPixels,tmpimg.ImageData,&status);

    }
    PHD_fits_close_file(fptr);
}
Esempio n. 14
0
TEST(imager, grid_sum)
{
    int status = 0, type = OSKAR_DOUBLE;
    int size = 2048, grid_size = size * size;

    // Create and set up the imager.
    oskar_Imager* im = oskar_imager_create(type, &status);
    oskar_imager_set_grid_kernel(im, "pillbox", 1, 1, &status);
    oskar_imager_set_fov(im, 5.0);
    oskar_imager_set_size(im, size, &status);
    oskar_Mem* grid = oskar_mem_create(type | OSKAR_COMPLEX, OSKAR_CPU,
            grid_size, &status);
    ASSERT_EQ(0, status);

    // Create visibility data.
    int num_vis = 10000;
    oskar_Mem* uu = oskar_mem_create(type, OSKAR_CPU, num_vis, &status);
    oskar_Mem* vv = oskar_mem_create(type, OSKAR_CPU, num_vis, &status);
    oskar_Mem* ww = oskar_mem_create(type, OSKAR_CPU, num_vis, &status);
    oskar_Mem* vis = oskar_mem_create(type | OSKAR_COMPLEX, OSKAR_CPU, num_vis,
            &status);
    oskar_Mem* weight = oskar_mem_create(type, OSKAR_CPU, num_vis, &status);
    oskar_mem_random_gaussian(uu, 0, 1, 2, 3, 100.0, &status);
    oskar_mem_random_gaussian(vv, 4, 5, 6, 7, 100.0, &status);
    oskar_mem_set_value_real(vis, 1.0, 0, num_vis, &status);
    oskar_mem_set_value_real(weight, 1.0, 0, num_vis, &status);

    // Grid visibility data.
    double plane_norm = 0.0;
    oskar_imager_update_plane(im, num_vis, uu, vv, ww, vis, weight, grid,
            &plane_norm, 0, &status);
    ASSERT_DOUBLE_EQ((double)num_vis, plane_norm);

    // Sum the grid.
    double2* t = oskar_mem_double2(grid, &status);
    double sum = 0.0;
    for (int i = 0; i < grid_size; i++) sum += t[i].x;
    ASSERT_DOUBLE_EQ((double)num_vis, sum);

    // Finalise the image.
    oskar_imager_finalise_plane(im, grid, plane_norm, &status);
    ASSERT_EQ(0, status);

#ifdef WRITE_FITS
    // Get the real part only.
    if (oskar_mem_precision(grid) == OSKAR_DOUBLE)
    {
        double *t = oskar_mem_double(grid, &status);
        for (int j = 0; j < grid_size; ++j) t[j] = t[2 * j];
    }
    else
    {
        float *t = oskar_mem_float(grid, &status);
        for (int j = 0; j < grid_size; ++j) t[j] = t[2 * j];
    }

    // Save the real part.
    fitsfile* f;
    long naxes[2] = {size, size}, firstpix[2] = {1, 1};
    fits_create_file(&f, "test_imager_grid_sum.fits", &status);
    fits_create_img(f, (type == OSKAR_DOUBLE ? DOUBLE_IMG : FLOAT_IMG),
            2, naxes, &status);
    fits_write_pix(f, (type == OSKAR_DOUBLE ? TDOUBLE : TFLOAT),
            firstpix, grid_size, oskar_mem_void(grid), &status);
    fits_close_file(f, &status);
#endif

    // Clean up.
    oskar_imager_free(im, &status);
    oskar_mem_free(uu, &status);
    oskar_mem_free(vv, &status);
    oskar_mem_free(ww, &status);
    oskar_mem_free(vis, &status);
    oskar_mem_free(weight, &status);
    oskar_mem_free(grid, &status);
}
Esempio n. 15
0
int main(int argc, char **argv)
{
   int       i, j, countRange, countNaN, status;
   int       haveMinMax, haveVal, writeOutput;
   long      fpixel[4], nelements;
   double   *inbuffer;
   double    NaNvalue;

   double    minblank, maxblank;
   double   *outbuffer;

   char     *end;


   /************************************************/
   /* Make a NaN value to use setting blank pixels */
   /************************************************/

   union
   {
      double d;
      char   c[8];
   }
   value;

   double nan;

   for(i=0; i<8; ++i)
      value.c[i] = 255;

   nan = value.d;


   /***************************************/
   /* Process the command-line parameters */
   /***************************************/

   fstatus = stdout;

   debug   = 0;
   haveVal = 0;

   writeOutput = 1;

   for(i=0; i<argc; ++i)
   {
      if(strcmp(argv[i], "-d") == 0)
      {
	 if(i+1 >= argc)
	 {
	    printf("[struct stat=\"ERROR\", msg=\"No debug level given\"]\n");
	    exit(1);
	 }

	 debug = strtol(argv[i+1], &end, 0);

	 if(end - argv[i+1] < strlen(argv[i+1]))
	 {
	    printf("[struct stat=\"ERROR\", msg=\"Debug level string is invalid: '%s'\"]\n", argv[i+1]);
	    exit(1);
	 }

	 if(debug < 0)
	 {
	    printf("[struct stat=\"ERROR\", msg=\"Debug level value cannot be negative\"]\n");
	    exit(1);
	 }

	 argv += 2;
	 argc -= 2;
      }

      if(strcmp(argv[i], "-v") == 0)
      {
	 if(i+1 >= argc)
	 {
	    printf("[struct stat=\"ERROR\", msg=\"No value given for NaN conversion\"]\n");
	    exit(1);
	 }

	 NaNvalue = strtod(argv[i+1], &end);

	 if(end - argv[i+1] < strlen(argv[i+1]))
	 {
	    printf("[struct stat=\"ERROR\", msg=\"NaN conversion value string is invalid: '%s'\"]\n", argv[i+1]);
	    exit(1);
	 }

	 haveVal = 1;

	 argv += 2;
	 argc -= 2;
      }
   }
   
   if (argc < 3) 
   {
      printf ("[struct stat=\"ERROR\", msg=\"Usage: %s [-d level][-v NaN-value] in.fits out.fits [minblank maxblank] (output file name '-' means no file)\"]\n", argv[0]);
      exit(1);
   }

   strcpy(input_file,  argv[1]);

   if(input_file[0] == '-')
   {
      printf ("[struct stat=\"ERROR\", msg=\"Invalid input file '%s'\"]\n", input_file);
      exit(1);
   }

   strcpy(output_file, argv[2]);

   if(output_file[0] == '-')
      writeOutput = 0;


   haveMinMax = 0;

   minblank = -2;
   maxblank =  2;

   if(argc > 3)
   {
      haveMinMax = 1;

      minblank = strtod(argv[3], &end);

      if(end < argv[3] + strlen(argv[3]))
      {
	 printf ("[struct stat=\"ERROR\", msg=\"min blank value string is not a number\"]\n");
	 exit(1);
      }

      maxblank = strtod(argv[4], &end);

      if(end < argv[4] + strlen(argv[4]))
      {
	 printf ("[struct stat=\"ERROR\", msg=\"max blank value string is not a number\"]\n");
	 exit(1);
      }
   }

   if(debug >= 1)
   {
      printf("input_file       = [%s]\n", input_file);
      printf("output_file      = [%s]\n", output_file);
      printf("minblank         = %-g\n",  minblank);
      printf("maxblank         = %-g\n",  maxblank);
      fflush(stdout);
   }


   /************************/
   /* Read the input image */
   /************************/

   time(&currtime);
   start = currtime;

   readFits(input_file);

   if(debug >= 1)
   {
      printf("input.naxes[0]       =  %ld\n",   input.naxes[0]);
      printf("input.naxes[1]       =  %ld\n",   input.naxes[1]);
      printf("input.crpix1         =  %-g\n",   input.crpix1);
      printf("input.crpix2         =  %-g\n",   input.crpix2);

      fflush(stdout);
   }

   output.naxes[0] = input.naxes[0];
   output.naxes[1] = input.naxes[1];
   output.crpix1   = input.crpix1;
   output.crpix2   = input.crpix2;


   if(writeOutput)
   {
      /********************************/
      /* Create the output FITS files */
      /********************************/

      remove(output_file);               

      status = 0;
      if(fits_create_file(&output.fptr, output_file, &status)) 
	 printFitsError(status);           

      if(debug >= 1)
      {
	 printf("\nFITS output file created (not yet populated)\n"); 
	 fflush(stdout);
      }


      /********************************/
      /* Copy all the header keywords */
      /* from the input to the output */
      /********************************/

      if(fits_copy_header(input.fptr, output.fptr, &status))
	 printFitsError(status);           

      if(debug >= 1)
      {
	 printf("Header keywords copied to FITS output file\n\n"); 
	 fflush(stdout);
      }


      /***************************/
      /* Modify BITPIX to be -64 */
      /***************************/

      if(fits_update_key_lng(output.fptr, "BITPIX", -64,
			     (char *)NULL, &status))
	 printFitsError(status);
   }


   /*****************************************************/ 
   /* Allocate memory for the input/output image pixels */ 
   /* (same size as the input image)                    */ 
   /*****************************************************/ 

   outbuffer = (double *)malloc(output.naxes[0] * sizeof(double));

   if(debug >= 1)
   {
      printf("%ld bytes allocated for row of output image pixels\n", 
	 output.naxes[0] * sizeof(double));
      fflush(stdout);
   }

   inbuffer = (double *)malloc(input.naxes[0] * sizeof(double));

   if(debug >= 1)
   {
      printf("%ld bytes allocated for row of input image pixels\n", 
	 input.naxes[0] * sizeof(double));
      fflush(stdout);
   }


   /*****************************/
   /* Loop over the input lines */
   /*****************************/

   fpixel[0] = 1;
   fpixel[1] = 1;
   fpixel[2] = 1;
   fpixel[3] = 1;

   nelements = input.naxes[0];

   status = 0;

   countRange = 0;
   countNaN   = 0;

   for (j=0; j<input.naxes[1]; ++j)
   {
      if(debug >= 2)
      {
	 if(debug >= 3)
	    printf("\n");

	 printf("\rProcessing input row %5d [So far rangeCount=%d, nanCount=%d]",
	    j, countRange, countNaN);

	 if(debug >= 3)
	    printf("\n");

	 fflush(stdout);
      }

      for (i=0; i<output.naxes[0]; ++i)
	 outbuffer[i] = 0.;


      /***********************************/
      /* Read a line from the input file */
      /***********************************/

      if(fits_read_pix(input.fptr, TDOUBLE, fpixel, nelements, NULL,
		       inbuffer, NULL, &status))
	 printFitsError(status);
      

      /************************/
      /* For each input pixel */
      /************************/

      for (i=0; i<input.naxes[0]; ++i)
      {
	 if(mNaN(inbuffer[i]) && haveVal) 
         {
            ++countNaN;

	    outbuffer[i] = NaNvalue;

            if(debug >= 3)
            {
	       printf("pixel[%d][%d] converted to %-g\n", j, i, NaNvalue);
	       fflush(stdout);
	    }
         }

	 else if(haveMinMax
	      && inbuffer[i] >= minblank 
	      && inbuffer[i] <= maxblank)
	 {
            ++countRange;

            if(haveVal) 
	    {
	       ++countNaN;

	       outbuffer[i] = NaNvalue;

               if(debug >= 3)
               {
	          printf("pixel[%d][%d] converted to NaN -> %-g\n", j, i, NaNvalue);
	          fflush(stdout);
	       }
	    }
            else
	    {
	       outbuffer[i] = nan;

               if(debug >= 3)
               {
	          printf("pixel[%d][%d] converted to NaN\n", j, i);
	          fflush(stdout);
	       }
	    }
	 }
	 else
	    outbuffer[i] = inbuffer[i];
      }


      /***************************/
      /* Write the output buffer */
      /***************************/

      if(writeOutput)
      {
	 if (fits_write_pix(output.fptr, TDOUBLE, fpixel, nelements, 
			    outbuffer, &status))
	    printFitsError(status);
      }

      ++fpixel[1];
   }


   if(debug >= 1)
   {
      time(&currtime);
      printf("\nDone copying data (%d seconds)\n", 
	 (int)(currtime - start));
      fflush(stdout);
   }


   /************************/
   /* Close the FITS files */
   /************************/

   if(fits_close_file(input.fptr, &status))
      printFitsError(status);

   if(writeOutput)
   {
      if(fits_close_file(output.fptr, &status))
	 printFitsError(status);           
   }

   if(debug >= 1)
   {
      time(&currtime);
      printf("Done (%d seconds total)\n", (int)(currtime - start));
      fflush(stdout);
   }

   free(inbuffer);
   free(outbuffer);

   printf("[struct stat=\"OK\", rangeCount=%d, nanCount=%d]\n", countRange, countNaN);
   fflush(stdout);

   exit(0);
}
Esempio n. 16
0
int main(int argc, char **argv)
{
    int       i, j, c, ifile, status;
    long      fpixel[4], nelements;
    int       nullcnt;
    int       imin, jmin, haveMinMax;
    int       imax, jmax;
    int       istart, iend, ilength;
    int       jstart, jend, jlength;
    double   *buffer, *abuffer;
    double    datamin, datamax;
    double    areamin, areamax;

    int       narea1, narea2;
    double    avearea1, avearea2;
    double    maxarea1, maxarea2;

    double    pixel_value;

    double  **data;
    double  **area;

    char      template_file[MAXSTR];
    char      line         [MAXSTR];

    char      infile[2][MAXSTR];
    char      inarea[2][MAXSTR];


    /*************************************************/
    /* Initialize output FITS basic image parameters */
    /*************************************************/

    int  bitpix = DOUBLE_IMG;
    long naxis  = 2;


    /************************************************/
    /* Make a NaN value to use setting blank pixels */
    /************************************************/

    union
    {
        double d;
        char   c[8];
    }
    value;

    double nan;

    for(i=0; i<8; ++i)
        value.c[i] = 255;

    nan = value.d;



    /***************************************/
    /* Process the command-line parameters */
    /***************************************/

    debug   = 0;
    noAreas = 0;

    coverageLimit = 0.0001;

    opterr = 0;

    fstatus = stdout;

    while ((c = getopt(argc, argv, "nc:d:s:")) != EOF)
    {
        switch (c)
        {
        case 'n':
            noAreas = 1;
            break;

        case 'c':
            coverageLimit = atof(optarg);
            break;

        case 'd':
            debug = debugCheck(optarg);
            break;

        case 's':
            if((fstatus = fopen(optarg, "w+")) == (FILE *)NULL)
            {
                printf("[struct stat=\"ERROR\", msg=\"Cannot open status file: %s\"]\n",
                       optarg);
                exit(1);
            }
            break;

        default:
            printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-d level] [-n(o-areas)] [-s statusfile] in1.fits in2.fits out.fits hdr.template\"]\n", argv[0]);
            exit(1);
            break;
        }
    }

    if (argc - optind < 4)
    {
        printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-d level] [-n(o-areas)] [-s statusfile] in1.fits in2.fits out.fits hdr.template\"]\n", argv[0]);
        exit(1);
    }

    strcpy(input_file1,   argv[optind]);
    strcpy(input_file2,   argv[optind + 1]);
    strcpy(output_file,   argv[optind + 2]);
    strcpy(template_file, argv[optind + 3]);

    checkHdr(template_file, 1, 0);

    if(strlen(output_file) > 5 &&
            strncmp(output_file+strlen(output_file)-5, ".fits", 5) == 0)
        output_file[strlen(output_file)-5] = '\0';

    strcpy(output_area_file, output_file);
    strcat(output_file,  ".fits");
    strcat(output_area_file, "_area.fits");

    if(debug >= 1)
    {
        printf("input_file1      = [%s]\n", input_file1);
        printf("input_file2      = [%s]\n", input_file2);
        printf("output_file      = [%s]\n", output_file);
        printf("output_area_file = [%s]\n", output_area_file);
        printf("template_file    = [%s]\n", template_file);
        fflush(stdout);
    }


    /****************************/
    /* Get the input file names */
    /****************************/

    if(strlen(input_file1) > 5
            && strcmp(input_file1+strlen(input_file1)-5, ".fits") == 0)
    {
        strcpy(line, input_file1);

        line[strlen(line)-5] = '\0';

        strcpy(infile[0], line);
        strcat(infile[0],  ".fits");
        strcpy(inarea[0], line);
        strcat(inarea[0], "_area.fits");
    }
    else
    {
        strcpy(infile[0], input_file1);
        strcat(infile[0],  ".fits");
        strcpy(inarea[0], input_file1);
        strcat(inarea[0], "_area.fits");
    }


    if(strlen(input_file2) > 5
            && strcmp(input_file2+strlen(input_file2)-5, ".fits") == 0)
    {
        strcpy(line, input_file2);

        line[strlen(line)-5] = '\0';

        strcpy(infile[1], line);
        strcat(infile[1],  ".fits");
        strcpy(inarea[1], line);
        strcat(inarea[1], "_area.fits");
    }
    else
    {
        strcpy(infile[1], input_file2);
        strcat(infile[1],  ".fits");
        strcpy(inarea[1], input_file2);
        strcat(inarea[1], "_area.fits");
    }

    if(debug >= 1)
    {
        printf("\ninput files:\n\n");

        printf("   [%s][%s]\n", infile[0], inarea[0]);
        printf("   [%s][%s]\n", infile[1], inarea[1]);

        printf("\n");
    }


    /*************************************************/
    /* Process the output header template to get the */
    /* image size, coordinate system and projection  */
    /*************************************************/

    readTemplate(template_file);

    if(debug >= 1)
    {
        printf("output.naxes[0] =  %ld\n", output.naxes[0]);
        printf("output.naxes[1] =  %ld\n", output.naxes[1]);
        printf("output.crpix1   =  %-g\n", output.crpix1);
        printf("output.crpix2   =  %-g\n", output.crpix2);
        fflush(stdout);
    }


    /*****************************************************/
    /* We open the two input files briefly to get enough */
    /* information to determine the region of overlap    */
    /* (for memory allocation purposes)                  */
    /*****************************************************/

    readFits(infile[0], inarea[0]);

    imin = output.crpix1 - input.crpix1;
    jmin = output.crpix2 - input.crpix2;

    imax = imin + input.naxes[0];
    jmax = jmin + input.naxes[1];

    istart = imin;
    iend   = imax;

    jstart = jmin;
    jend   = jmax;

    if(debug >= 1)
    {
        printf("\nFile 1:\n");
        printf("input.naxes[0]       =  %ld\n",   input.naxes[0]);
        printf("input.naxes[1]       =  %ld\n",   input.naxes[1]);
        printf("input.crpix1         =  %-g\n",   input.crpix1);
        printf("input.crpix2         =  %-g\n",   input.crpix2);
        printf("imin                 =  %d\n",    imin);
        printf("imax                 =  %d\n",    imax);
        printf("jmin                 =  %d\n",    jmin);
        printf("jmax                 =  %d\n\n",  jmax);
        printf("istart               =  %d\n",    istart);
        printf("iend                 =  %d\n",    iend);
        printf("jstart               =  %d\n",    jstart);
        printf("jend                 =  %d\n",    jend);

        fflush(stdout);
    }

    status = 0;

    if(fits_close_file(input.fptr, &status))
        printFitsError(status);

    if(!noAreas)
    {
        if(fits_close_file(input_area.fptr, &status))
            printFitsError(status);
    }

    readFits(infile[1], inarea[1]);

    imin = output.crpix1 - input.crpix1;
    jmin = output.crpix2 - input.crpix2;

    imax = imin + input.naxes[0];
    jmax = jmin + input.naxes[1];

    if(debug >= 1)
    {
        printf("\nFile 2:\n");
        printf("input.naxes[0]       =  %ld\n",   input.naxes[0]);
        printf("input.naxes[1]       =  %ld\n",   input.naxes[1]);
        printf("input.crpix1         =  %-g\n",   input.crpix1);
        printf("input.crpix2         =  %-g\n",   input.crpix2);
        printf("imin                 =  %d\n",    imin);
        printf("imax                 =  %d\n",    imax);
        printf("jmin                 =  %d\n",    jmin);
        printf("jmax                 =  %d\n",    jmax);
        printf("istart               =  %d\n\n",  istart);
        printf("iend                 =  %d\n",    iend);
        printf("jstart               =  %d\n",    jstart);
        printf("jend                 =  %d\n",    jend);
        printf("\n");

        fflush(stdout);
    }

    if(imin > istart) istart = imin;
    if(imax < iend  ) iend   = imax;

    if(jmin > jstart) jstart = jmin;
    if(jmax < jend  ) jend   = jmax;

    if(istart < 0) istart = 0;
    if(jstart < 0) jstart = 0;

    if(iend > output.naxes[0]-1) iend = output.naxes[0]-1;
    if(jend > output.naxes[1]-1) jend = output.naxes[1]-1;

    ilength = iend - istart + 1;
    jlength = jend - jstart + 1;

    if(debug >= 1)
    {
        printf("\nComposite:\n");
        printf("input.naxes[0]       =  %ld\n",   input.naxes[0]);
        printf("input.naxes[1]       =  %ld\n",   input.naxes[1]);
        printf("input.crpix1         =  %-g\n",   input.crpix1);
        printf("input.crpix2         =  %-g\n",   input.crpix2);
        printf("istart               =  %d\n",    istart);
        printf("iend                 =  %d\n",    iend);
        printf("jstart               =  %d\n",    jstart);
        printf("jend                 =  %d\n",    jend);
        printf("ilength              =  %d\n",    ilength);
        printf("jlength              =  %d\n",    jlength);
        printf("\n");

        fflush(stdout);
    }

    if(fits_close_file(input.fptr, &status))
        printFitsError(status);

    if(!noAreas)
    {
        if(fits_close_file(input_area.fptr, &status))
            printFitsError(status);
    }

    /*********************/
    /* Check for overlap */
    /*********************/

    if(ilength <= 0 || jlength <= 0)
        printError("Images don't overlap");


    /***********************************************/
    /* Allocate memory for the output image pixels */
    /***********************************************/

    data = (double **)malloc(jlength * sizeof(double *));

    for(j=0; j<jlength; ++j)
        data[j] = (double *)malloc(ilength * sizeof(double));

    if(debug >= 1)
    {
        printf("%d bytes allocated for image pixels\n",
               ilength * jlength * sizeof(double));
        fflush(stdout);
    }


    /****************************/
    /* Initialize data to zeros */
    /****************************/

    for (j=0; j<jlength; ++j)
    {
        for (i=0; i<ilength; ++i)
        {
            data[j][i] = 0.;
        }
    }


    /**********************************************/
    /* Allocate memory for the output pixel areas */
    /**********************************************/

    area = (double **)malloc(jlength * sizeof(double *));

    for(j=0; j<jlength; ++j)
        area[j] = (double *)malloc(ilength * sizeof(double));

    if(debug >= 1)
    {
        printf("%d bytes allocated for pixel areas\n",
               ilength * jlength * sizeof(double));
        fflush(stdout);
    }


    /****************************/
    /* Initialize area to zeros */
    /****************************/

    for (j=0; j<jlength; ++j)
    {
        for (i=0; i<ilength; ++i)
        {
            area[j][i] = 0.;
        }
    }


    /***************************/
    /* For the two input files */
    /***************************/

    time(&currtime);
    start = currtime;

    avearea1 = 0.;
    avearea2 = 0.;
    maxarea1 = 0.;
    maxarea2 = 0.;
    narea1   = 0.;
    narea2   = 0.;

    for(ifile=0; ifile<2; ++ifile)
    {
        /************************/
        /* Read the input image */
        /************************/

        readFits(infile[ifile], inarea[ifile]);

        imin = output.crpix1 - input.crpix1;
        jmin = output.crpix2 - input.crpix2;

        if(debug >= 1)
        {
            printf("\nflux file            =  %s\n",  infile[ifile]);
            printf("input.naxes[0]       =  %ld\n",   input.naxes[0]);
            printf("input.naxes[1]       =  %ld\n",   input.naxes[1]);
            printf("input.crpix1         =  %-g\n",   input.crpix1);
            printf("input.crpix2         =  %-g\n",   input.crpix2);
            printf("\narea file            =  %s\n",  inarea[ifile]);
            printf("input_area.naxes[0]  =  %ld\n",   input.naxes[0]);
            printf("input_area.naxes[1]  =  %ld\n",   input.naxes[1]);
            printf("input_area.crpix1    =  %-g\n",   input.crpix1);
            printf("input_area.crpix2    =  %-g\n",   input.crpix2);
            printf("\nimin                 =  %d\n",  imin);
            printf("jmin                 =  %d\n\n",  jmin);

            fflush(stdout);
        }


        /**********************************************************/
        /* Create the output array by processing the input pixels */
        /**********************************************************/

        buffer  = (double *)malloc(input.naxes[0] * sizeof(double));
        abuffer = (double *)malloc(input.naxes[0] * sizeof(double));

        fpixel[0] = 1;
        fpixel[1] = 1;
        fpixel[2] = 1;
        fpixel[3] = 1;

        nelements = input.naxes[0];

        status = 0;


        /*****************************/
        /* Loop over the input lines */
        /*****************************/

        for (j=0; j<input.naxes[1]; ++j)
        {
            if(debug >= 2)
            {
                printf("\rProcessing input row %5d  ", j);
                fflush(stdout);
            }


            /***********************************/
            /* Read a line from the input file */
            /***********************************/

            if(fits_read_pix(input.fptr, TDOUBLE, fpixel, nelements, NULL,
                             buffer, &nullcnt, &status))
                printFitsError(status);


            if(noAreas)
            {
                for(i=0; i<input.naxes[0]; ++i)
                    abuffer[i] = 1.;
            }
            else
            {
                if(fits_read_pix(input_area.fptr, TDOUBLE, fpixel, nelements, NULL,
                                 abuffer, &nullcnt, &status))
                    printFitsError(status);
            }

            ++fpixel[1];


            /************************/
            /* For each input pixel */
            /************************/

            for (i=0; i<input.naxes[0]; ++i)
            {
                pixel_value = buffer[i] * abuffer[i];

                if(debug >= 4)
                {
                    printf("input: line %5d / pixel %5d, value = %10.2e (%10.2e) [array: %5d %5d]\n",
                           j, i, buffer[i], abuffer[i], j+jmin-jstart, i+imin-istart);
                    fflush(stdout);
                }

                if(i+imin < istart) continue;
                if(j+jmin < jstart) continue;

                if(i+imin >= iend) continue;
                if(j+jmin >= jend) continue;

                if(debug >= 3)
                {
                    printf("keep: line %5d / pixel %5d, value = %10.2e (%10.2e) [array: %5d %5d]\n",
                           j, i, buffer[i], abuffer[i], j+jmin-jstart, i+imin-istart);
                    fflush(stdout);
                }

                if(ifile == 0)
                {
                    if(mNaN(buffer[i])
                            || abuffer[i] <= 0.)
                    {
                        if(debug >= 5)
                        {
                            printf("First file. Setting data to NaN and area to zero.\n");
                            fflush(stdout);
                        }

                        data[j+jmin-jstart][i+imin-istart] = nan;
                        area[j+jmin-jstart][i+imin-istart] = 0.;

                        if(debug >= 5)
                        {
                            printf("done.\n");
                            fflush(stdout);
                        }

                        continue;
                    }
                    else
                    {
                        if(debug >= 5)
                        {
                            printf("First file. Setting data to pixel value.\n");
                            fflush(stdout);
                        }

                        data[j+jmin-jstart][i+imin-istart] = pixel_value;
                        area[j+jmin-jstart][i+imin-istart] = abuffer[i];

                        ++narea1;
                        avearea1 += abuffer[i];

                        if(abuffer[i] > maxarea1)
                            maxarea1 = abuffer[i];

                        if(debug >= 5)
                        {
                            printf("done.\n");
                            fflush(stdout);
                        }

                    }
                }
                else
                {
                    if(mNaN(buffer[i])
                            || abuffer[i] <= 0.
                            || data[j+jmin-jstart][i+imin-istart] == nan
                            || area[j+jmin-jstart][i+imin-istart] == 0.)
                    {
                        if(debug >= 5)
                        {
                            printf("Second file. One or the other value is NaN (or zero area).\n");
                            fflush(stdout);
                        }

                        data[j+jmin-jstart][i+imin-istart] = nan;
                        area[j+jmin-jstart][i+imin-istart] = 0.;

                        continue;
                    }
                    else
                    {
                        if(debug >= 5)
                        {
                            printf("Second file. Subtracting pixel value.\n");
                            fflush(stdout);
                        }

                        data[j+jmin-jstart][i+imin-istart] -= pixel_value;
                        area[j+jmin-jstart][i+imin-istart] += abuffer[i];

                        ++narea2;
                        avearea2 += abuffer[i];

                        if(abuffer[i] > maxarea2)
                            maxarea2 = abuffer[i];

                        if(debug >= 5)
                        {
                            printf("done.\n");
                            fflush(stdout);
                        }
                    }
                }
            }
        }

        free(buffer);
        free(abuffer);

        if(fits_close_file(input.fptr, &status))
            printFitsError(status);

        if(!noAreas)
        {
            if(fits_close_file(input_area.fptr, &status))
                printFitsError(status);
        }
    }

    if(debug >= 1)
    {
        time(&currtime);
        printf("\nDone reading data (%.0f seconds)\n",
               (double)(currtime - start));
        fflush(stdout);
    }


    /************************************/
    /* Anly keep those pixels that were */
    /* covered twice reasonably fully   */
    /************************************/

    avearea1 = avearea1/narea1;
    avearea2 = avearea2/narea2;

    areamax = maxarea1 + maxarea2;

    if(debug >= 2)
    {
        printf("\npixel areas: %-g + %-g = %-g\n\n", avearea1, avearea2, areamax);
        fflush(stdout);
    }

    for (j=0; j<jlength; ++j)
    {
        for (i=0; i<ilength; ++i)
        {
            if(mNaN(area[j][i]) || area[j][i] == 0.)
            {
                data[j][i] = 0.;
                area[j][i] = 0.;
            }
            else
            {
                if(fabs(area[j][i] - areamax)/areamax > coverageLimit)
                {
                    data[j][i] = 0.;
                    area[j][i] = 0.;
                }
            }
        }
    }


    /*********************************/
    /* Normalize image data based on */
    /* total area added to pixel     */
    /*********************************/

    haveMinMax = 0;

    datamax = 0.,
    datamin = 0.;
    areamin = 0.;
    areamax = 0.;

    imin = 99999;
    imax = 0;

    jmin = 99999;
    jmax = 0;

    for (j=0; j<jlength; ++j)
    {
        for (i=0; i<ilength; ++i)
        {
            if(area[j][i] > 0.)
            {
                data[j][i] = 2. * data[j][i] / area[j][i];

                if(!haveMinMax)
                {
                    datamin = data[j][i];
                    datamax = data[j][i];
                    areamin = area[j][i];
                    areamax = area[j][i];

                    haveMinMax = 1;
                }

                if(data[j][i] < datamin) datamin = data[j][i];
                if(data[j][i] > datamax) datamax = data[j][i];
                if(area[j][i] < areamin) areamin = area[j][i];
                if(area[j][i] > areamax) areamax = area[j][i];

                if(j < jmin) jmin = j;
                if(j > jmax) jmax = j;
                if(i < imin) imin = i;
                if(i > imax) imax = i;
            }
            else
            {
                data[j][i] = nan;
                area[j][i] = 0.;
            }
        }
    }

    imin += istart;
    jmin += jstart;

    imax += istart;
    jmax += jstart;

    if(debug >= 1)
    {
        printf("Data min = %-g\n", datamin);
        printf("Data max = %-g\n", datamax);
        printf("Area min = %-g\n", areamin);
        printf("Area max = %-g\n\n", areamax);
        printf("j min    = %d\n", jmin);
        printf("j max    = %d\n", jmax);
        printf("i min    = %d\n", imin);
        printf("i max    = %d\n", imax);
    }

    if(jmin > jmax || imin > imax)
        printError("All pixels are blank.");


    /********************************/
    /* Create the output FITS files */
    /********************************/

    remove(output_file);
    remove(output_area_file);

    if(fits_create_file(&output.fptr, output_file, &status))
        printFitsError(status);

    if(fits_create_file(&output_area.fptr, output_area_file, &status))
        printFitsError(status);


    /*********************************************************/
    /* Create the FITS image.  All the required keywords are */
    /* handled automatically.                                */
    /*********************************************************/

    if (fits_create_img(output.fptr, bitpix, naxis, output.naxes, &status))
        printFitsError(status);

    if(debug >= 1)
    {
        printf("\nFITS data image created (not yet populated)\n");
        fflush(stdout);
    }

    if (fits_create_img(output_area.fptr, bitpix, naxis, output_area.naxes, &status))
        printFitsError(status);

    if(debug >= 1)
    {
        printf("FITS area image created (not yet populated)\n");
        fflush(stdout);
    }


    /****************************************/
    /* Set FITS header from a template file */
    /****************************************/

    if(fits_write_key_template(output.fptr, template_file, &status))
        printFitsError(status);

    if(debug >= 1)
    {
        printf("Template keywords written to FITS data image\n");
        fflush(stdout);
    }

    if(fits_write_key_template(output_area.fptr, template_file, &status))
        printFitsError(status);

    if(debug >= 1)
    {
        printf("Template keywords written to FITS area image\n\n");
        fflush(stdout);
    }


    /***************************/
    /* Modify BITPIX to be -64 */
    /***************************/

    if(fits_update_key_lng(output.fptr, "BITPIX", -64,
                           (char *)NULL, &status))
        printFitsError(status);

    if(fits_update_key_lng(output_area.fptr, "BITPIX", -64,
                           (char *)NULL, &status))
        printFitsError(status);


    /***************************************************/
    /* Update NAXIS, NAXIS1, NAXIS2, CRPIX1 and CRPIX2 */
    /***************************************************/

    if(fits_update_key_lng(output.fptr, "NAXIS", 2,
                           (char *)NULL, &status))
        printFitsError(status);

    if(fits_update_key_lng(output.fptr, "NAXIS1", imax-imin+1,
                           (char *)NULL, &status))
        printFitsError(status);

    if(fits_update_key_lng(output.fptr, "NAXIS2", jmax-jmin+1,
                           (char *)NULL, &status))
        printFitsError(status);

    if(fits_update_key_dbl(output.fptr, "CRPIX1", output.crpix1-imin, -14,
                           (char *)NULL, &status))
        printFitsError(status);

    if(fits_update_key_dbl(output.fptr, "CRPIX2", output.crpix2-jmin, -14,
                           (char *)NULL, &status))
        printFitsError(status);

    if(fits_update_key_lng(output_area.fptr, "NAXIS", 2,
                           (char *)NULL, &status))
        printFitsError(status);

    if(fits_update_key_lng(output_area.fptr, "NAXIS1", imax-imin+1,
                           (char *)NULL, &status))
        printFitsError(status);

    if(fits_update_key_lng(output_area.fptr, "NAXIS2", jmax-jmin+1,
                           (char *)NULL, &status))
        printFitsError(status);

    if(fits_update_key_dbl(output_area.fptr, "CRPIX1", output.crpix1-imin, -14,
                           (char *)NULL, &status))
        printFitsError(status);

    if(fits_update_key_dbl(output_area.fptr, "CRPIX2", output.crpix2-jmin, -14,
                           (char *)NULL, &status))
        printFitsError(status);

    if(debug >= 1)
    {
        printf("Template keywords BITPIX, CRPIX, and NAXIS updated\n");
        fflush(stdout);
    }


    /************************/
    /* Write the image data */
    /************************/

    fpixel[0] = 1;
    fpixel[1] = 1;
    nelements = imax - imin + 1;

    for(j=jmin; j<=jmax; ++j)
    {
        if (fits_write_pix(output.fptr, TDOUBLE, fpixel, nelements,
                           (void *)(&data[j-jstart][imin-istart]), &status))
            printFitsError(status);

        ++fpixel[1];
    }

    free(data[0]);

    if(debug >= 1)
    {
        printf("Data written to FITS data image\n");
        fflush(stdout);
    }


    /***********************/
    /* Write the area data */
    /***********************/

    fpixel[0] = 1;
    fpixel[1] = 1;
    nelements = imax - imin + 1;

    for(j=jmin; j<=jmax; ++j)
    {
        if (fits_write_pix(output_area.fptr, TDOUBLE, fpixel, nelements,
                           (void *)(&area[j-jstart][imin-istart]), &status))
            printFitsError(status);

        ++fpixel[1];
    }

    free(area[0]);

    if(debug >= 1)
    {
        printf("Data written to FITS area image\n\n");
        fflush(stdout);
    }


    /***********************/
    /* Close the FITS file */
    /***********************/

    if(fits_close_file(output.fptr, &status))
        printFitsError(status);

    if(debug >= 1)
    {
        printf("FITS data image finalized\n");
        fflush(stdout);
    }

    if(fits_close_file(output_area.fptr, &status))
        printFitsError(status);

    if(debug >= 1)
    {
        printf("FITS area image finalized\n\n");
        fflush(stdout);
    }

    if(debug >= 1)
    {
        time(&currtime);
        printf("Done (%.0f seconds total)\n", (double)(currtime - start));
        fflush(stdout);
    }

    fprintf(fstatus, "[struct stat=\"OK\"]\n");
    fflush(stdout);

    exit(0);
}
Esempio n. 17
0
struct mShrinkReturn *mShrink(char *input_file, int hduin, char *output_file, double shrinkFactor, int fixedSize, int debug)
{
   int       i, j, ii, jj, status, bufrow,  split;
   int       ibuffer, jbuffer, ifactor, nbuf, nullcnt, k, l, imin, imax, jmin, jmax;
   long      fpixel[4], fpixelo[4], nelements, nelementso;
   double    obegin, oend;
   double   *colfact, *rowfact;
   double   *buffer;
   double    xfactor, flux, area;

   double   *outdata;
   double  **indata;

   struct mShrinkReturn *returnStruct;


   /************************************************/
   /* Make a NaN value to use setting blank pixels */
   /************************************************/

   union
   {
      double d;
      char   c[8];
   }
   value;

   double nan;

   for(i=0; i<8; ++i)
      value.c[i] = 255;

   nan = value.d;



   /*******************************/
   /* Initialize return structure */
   /**n****************************/

   returnStruct = (struct mShrinkReturn *)malloc(sizeof(struct mShrinkReturn));

   bzero((void *)returnStruct, sizeof(returnStruct));


   returnStruct->status = 1;

   strcpy(returnStruct->msg, "");


   /***************************************/
   /* Process the command-line parameters */
   /***************************************/

   time(&currtime);
   start = currtime;

   hdu = hduin;

   xfactor = shrinkFactor;
   
   if(!fixedSize)
   {
      ifactor = ceil(xfactor);

      if((double)ifactor < xfactor)
         xfactor += 2;
   }

   if(xfactor <= 0)
   {
      if(fixedSize)
         mShrink_printError("Requested image size must be positive");
      else
         mShrink_printError("Shrink factor must be positive");

      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(debug >= 1)
   {
      printf("input_file       = [%s]\n", input_file);
      printf("output_file      = [%s]\n", output_file);
      printf("xfactor          = %-g\n",  xfactor);
      printf("ifactor          = %d\n",   ifactor);
      fflush(stdout);
   }


   /************************/
   /* Read the input image */
   /************************/

   if(mShrink_readFits(input_file))
   {
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }


   // Error if we are trying to shrink to less than one pixel

   if(!fixedSize
   && (   shrinkFactor > input.naxes[0]
       || shrinkFactor > input.naxes[1]))
   {
      mShrink_printError("Trying to shrink image to smaller than one pixel");
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }


   if(debug >= 1)
   {
      printf("\nflux file            =  %s\n",  input_file);
      printf("input.bitpix         =  %ld\n",   input.bitpix);
      printf("input.naxes[0]       =  %ld\n",   input.naxes[0]);
      printf("input.naxes[1]       =  %ld\n",   input.naxes[1]);

      if(haveCtype)   printf("input.ctype1         =  %s\n",    input.ctype1);
      if(haveCtype)   printf("input.typel2         =  %s\n",    input.ctype2);
      if(haveCrval)   printf("input.crval1         =  %-g\n",   input.crval1);
      if(haveCrval)   printf("input.crval2         =  %-g\n",   input.crval2);
      if(haveCrpix)   printf("input.crpix1         =  %-g\n",   input.crpix1);
      if(haveCrpix)   printf("input.crpix2         =  %-g\n",   input.crpix2);
      if(haveCnpix)   printf("input.cnpix1         =  %-g\n",   input.cnpix1);
      if(haveCnpix)   printf("input.cnpix2         =  %-g\n",   input.cnpix2);
      if(havePixelsz) printf("input.xpixelsz       =  %-g\n",   input.xpixelsz);
      if(havePixelsz) printf("input.ypixelsz       =  %-g\n",   input.ypixelsz);
      if(havePP)      printf("input.ppo3           =  %-g\n",   input.ppo3);
      if(havePP)      printf("input.ppo6           =  %-g\n",   input.ppo6);
      if(haveCdelt)   printf("input.cdelt1         =  %-g\n",   input.cdelt1);
      if(haveCdelt)   printf("input.cdelt2         =  %-g\n",   input.cdelt2);
      if(haveCrota2)  printf("input.crota2         =  %-g\n",   input.crota2);
      if(haveCD11)    printf("input.cd11           =  %-g\n",   input.cd11);
      if(haveCD12)    printf("input.cd12           =  %-g\n",   input.cd12);
      if(haveCD21)    printf("input.cd21           =  %-g\n",   input.cd21);
      if(haveCD22)    printf("input.cd22           =  %-g\n",   input.cd22);
      if(havePC11)    printf("input.pc11           =  %-g\n",   input.pc11);
      if(havePC12)    printf("input.pc12           =  %-g\n",   input.pc12);
      if(havePC21)    printf("input.pc21           =  %-g\n",   input.pc21);
      if(havePC22)    printf("input.pc22           =  %-g\n",   input.pc22);
      if(haveEpoch)   printf("input.epoch          =  %-g\n",   input.epoch);
      if(haveEquinox) printf("input.equinox        =  %-g\n",   input.equinox);
      if(haveBunit)   printf("input.bunit          =  %s\n",    input.bunit);
      if(haveBlank)   printf("input.blank          =  %ld\n",   input.blank);
      printf("\n");

      fflush(stdout);
   }


   /***********************************************/
   /* If we are going for a fixed size, the scale */
   /* factor needs to be computed.                */
   /***********************************************/

   if(fixedSize)
   {
      if(input.naxes[0] > input.naxes[1])
         xfactor = (double)input.naxes[0]/(int)xfactor;
      else
         xfactor = (double)input.naxes[1]/(int)xfactor;

      ifactor = ceil(xfactor);

      if((double)ifactor < xfactor)
         xfactor += 2;

      if(debug >= 1)
      {
         printf("xfactor         -> %-g\n",  xfactor);
         printf("ifactor         -> %d\n",   ifactor);
         fflush(stdout);
      }
   }

   /***********************************************/
   /* Compute all the parameters for the shrunken */
   /* output file.                                */
   /***********************************************/

   output.naxes[0] = floor((double)input.naxes[0]/xfactor);
   output.naxes[1] = floor((double)input.naxes[1]/xfactor);
   
   if(debug >= 1)
   {
      printf("output.naxes[0] = %ld\n",  output.naxes[0]);
      printf("output.naxes[1] = %ld\n",  output.naxes[1]);
      fflush(stdout);
   }

   strcpy(output.ctype1, input.ctype1);
   strcpy(output.ctype2, input.ctype2);

   output.crval1   = input.crval1;
   output.crval2   = input.crval2;
   output.crpix1   = (input.crpix1-0.5)/xfactor + 0.5;
   output.crpix2   = (input.crpix2-0.5)/xfactor + 0.5;
   output.cdelt1   = input.cdelt1*xfactor;
   output.cdelt2   = input.cdelt2*xfactor;
   output.crota2   = input.crota2;
   output.cd11     = input.cd11*xfactor;
   output.cd12     = input.cd12*xfactor;
   output.cd21     = input.cd21*xfactor;
   output.cd22     = input.cd22*xfactor;
   output.pc11     = input.pc11;
   output.pc12     = input.pc12;
   output.pc21     = input.pc21;
   output.pc22     = input.pc22;
   output.epoch    = input.epoch;
   output.equinox  = input.equinox;

   strcpy(output.bunit, input.bunit);

   if(haveCnpix)
   {
      input.crpix1    = input.ppo3 / input.xpixelsz - input.cnpix1 + 0.5; 
      input.crpix2    = input.ppo6 / input.ypixelsz - input.cnpix2 + 0.5; 

      output.crpix1   = (input.crpix1-0.5)/xfactor + 0.5;
      output.crpix2   = (input.crpix2-0.5)/xfactor + 0.5;

      output.xpixelsz = input.xpixelsz * xfactor;
      output.ypixelsz = input.ypixelsz * xfactor;

      output.cnpix1   = input.ppo3 / output.xpixelsz - output.crpix1 + 0.5;
      output.cnpix2   = input.ppo6 / output.ypixelsz - output.crpix2 + 0.5;
   }


   /********************************/
   /* Create the output FITS files */
   /********************************/

   status = 0;

   remove(output_file);               

   if(fits_create_file(&output.fptr, output_file, &status)) 
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }


   /******************************************************/
   /* Create the FITS image.  Copy over the whole header */
   /******************************************************/

   if(fits_copy_header(input.fptr, output.fptr, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(debug >= 1)
   {
      printf("\nFITS header copied to output\n"); 
      fflush(stdout);
   }


   /************************************/
   /* Reset all the WCS header kewords */
   /************************************/

   if(fits_update_key_lng(output.fptr, "NAXIS", 2,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(fits_update_key_lng(output.fptr, "NAXIS1", output.naxes[0],
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(fits_update_key_lng(output.fptr, "NAXIS2", output.naxes[1],
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveBunit && fits_update_key_str(output.fptr, "BUNIT", output.bunit,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveBlank && fits_update_key_lng(output.fptr, "BLANK", output.blank,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCtype && fits_update_key_str(output.fptr, "CTYPE1", output.ctype1,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCtype && fits_update_key_str(output.fptr, "CTYPE2", output.ctype2,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCrval && fits_update_key_dbl(output.fptr, "CRVAL1", output.crval1, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCrval && fits_update_key_dbl(output.fptr, "CRVAL2", output.crval2, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCrpix && fits_update_key_dbl(output.fptr, "CRPIX1", output.crpix1, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCrpix && fits_update_key_dbl(output.fptr, "CRPIX2", output.crpix2, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCnpix && fits_update_key_dbl(output.fptr, "CNPIX1", output.cnpix1, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCnpix && fits_update_key_dbl(output.fptr, "CNPIX2", output.cnpix2, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(havePixelsz && fits_update_key_dbl(output.fptr, "XPIXELSZ", output.xpixelsz, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(havePixelsz && fits_update_key_dbl(output.fptr, "YPIXELSZ", output.ypixelsz, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCdelt && fits_update_key_dbl(output.fptr, "CDELT1", output.cdelt1, -14,
                                     (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCdelt && fits_update_key_dbl(output.fptr, "CDELT2", output.cdelt2, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCrota2 && fits_update_key_dbl(output.fptr, "CROTA2", output.crota2, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCD11 && fits_update_key_dbl(output.fptr, "CD1_1", output.cd11, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCD12 && fits_update_key_dbl(output.fptr, "CD1_2", output.cd12, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCD21 && fits_update_key_dbl(output.fptr, "CD2_1", output.cd21, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveCD22 && fits_update_key_dbl(output.fptr, "CD2_2", output.cd22, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(havePC11 && fits_update_key_dbl(output.fptr, "PC1_1", output.pc11, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(havePC12 && fits_update_key_dbl(output.fptr, "PC1_2", output.pc12, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(havePC21 && fits_update_key_dbl(output.fptr, "PC2_1", output.pc21, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(havePC22 && fits_update_key_dbl(output.fptr, "PC2_2", output.pc22, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveEpoch && fits_update_key_dbl(output.fptr, "EPOCH", output.epoch, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(haveEquinox && fits_update_key_dbl(output.fptr, "EQUINOX", output.equinox, -14,
                                  (char *)NULL, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }


   if(debug >= 1)
   {
      printf("Output header keywords set\n\n");
      fflush(stdout);
   }



   /***********************************************/ 
   /* Allocate memory for a line of output pixels */ 
   /***********************************************/ 

   outdata = (double *)malloc(output.naxes[0] * sizeof(double));


   /*************************************************************************/ 
   /* We could probably come up with logic that would work for both scale   */
   /* factors of less than one and greater than one but the it would be too */
   /* hard to follow.  Instead, we put in a big switch here to deal with    */
   /* the two cases separately.                                             */
   /*************************************************************************/ 

   if(xfactor < 1.)
   {
      /************************************************/ 
      /* Allocate memory for "ifactor" lines of input */ 
      /************************************************/ 

      nbuf = 2;

      indata = (double **)malloc(nbuf * sizeof(double *));

      for(j=0; j<nbuf; ++j)
         indata[j] = (double *)malloc((input.naxes[0]+1) * sizeof(double));


      /**********************************************************/
      /* Create the output array by processing the input pixels */
      /**********************************************************/

      ibuffer = 0;

      buffer  = (double *)malloc(input.naxes[0] * sizeof(double));
      colfact = (double *)malloc(nbuf * sizeof(double));
      rowfact = (double *)malloc(nbuf * sizeof(double));

      fpixel[0] = 1;
      fpixel[1] = 1;
      fpixel[2] = 1;
      fpixel[3] = 1;

      fpixelo[0] = 1;
      fpixelo[1] = 1;

      nelements = input.naxes[0];

      status = 0;


      /******************************/
      /* Loop over the output lines */
      /******************************/

      split = 0;

      for(l=0; l<output.naxes[1]; ++l)
      {
         obegin = (fpixelo[1] - 1.) * xfactor;
         oend   =  fpixelo[1] * xfactor;

         if(floor(oend) == oend)
            oend = obegin;

         if(debug >= 2)
         {
            printf("OUTPUT row %d: obegin = %.2f -> oend = %.3f\n\n", l, obegin, oend);
            fflush(stdout);
         }

         rowfact[0] = 1.;
         rowfact[1] = 0.;


         /******************************************/
         /* If we have gone over into the next row */
         /******************************************/

         if(l == 0 || (int)oend > (int)obegin)
         {
            rowfact[0] = 1.;
            rowfact[1] = 0.;

            if(l > 0)
            {
               split = 1;

               jbuffer = (ibuffer + 1) % nbuf;

               rowfact[1] = (oend - (int)(fpixelo[1] * xfactor))/xfactor;
               rowfact[0] = 1. - rowfact[1];
            }
            else
            {
               jbuffer = 0;
            }

            if(debug >= 2)
            {
               printf("Reading input image row %5ld  (ibuffer %d)\n", fpixel[1], jbuffer);
               fflush(stdout);
            }

            if(debug >= 2)
            {
               printf("Rowfact:  %-g %-g\n", rowfact[0], rowfact[1]);
               fflush(stdout);
            }


            /***********************************/
            /* Read a line from the input file */
            /***********************************/

            if(fpixel[1] <= input.naxes[1])
            {
               if(fits_read_pix(input.fptr, TDOUBLE, fpixel, nelements, &nan,
                                buffer, &nullcnt, &status))
               {
                  mShrink_printFitsError(status);
                  strcpy(returnStruct->msg, montage_msgstr);
                  return returnStruct;
               }
            }
            
            ++fpixel[1];


            /************************/
            /* For each input pixel */
            /************************/

            indata[jbuffer][input.naxes[0]] = nan;

            for (i=0; i<input.naxes[0]; ++i)
            {
               indata[jbuffer][i] = buffer[i];

               if(debug >= 4)
               {
                  printf("input: line %5ld / pixel %5d: indata[%d][%d] = %10.3e\n",
                     fpixel[1]-2, i, jbuffer, i, indata[jbuffer][i]);
                  fflush(stdout);
               }
            }

            if(debug >= 4)
            {
               printf("---\n");
               fflush(stdout);
            }
         }


         /*************************************/
         /* Write out the next line of output */
         /*************************************/

         nelementso = output.naxes[0];

         for(k=0; k<nelementso; ++k)
         {
            /* When "expanding" we never need to use more than two   */
            /* pixels in more than two rows.  The row factors were   */
            /* computed above and the column factors will be compute */
            /* here as we go.                                        */

            outdata[k] = nan;

            colfact[0] = 1.;
            colfact[1] = 0.;

            obegin =  (double)k     * xfactor;
            oend   = ((double)k+1.) * xfactor;

            if(floor(oend) == oend)
               oend = obegin;

            imin = (int)obegin;

            if((int)oend > (int)obegin)
            {
               colfact[1] = (oend - (int)(((double)k+1.) * xfactor))/xfactor;
               colfact[0] = 1. - colfact[1];
            }

            flux = 0;
            area = 0;

            for(jj=0; jj<2; ++jj)
            {
               if(rowfact[jj] == 0.)
                  continue;

               for(ii=0; ii<2; ++ii)
               {
                  bufrow = (ibuffer + jj) % nbuf;

                  if(!mNaN(indata[bufrow][imin+ii]) && colfact[ii] > 0.)
                  {
                     flux += indata[bufrow][imin+ii] * colfact[ii] * rowfact[jj];
                     area += colfact[ii] * rowfact[jj];

                     if(debug >= 3)
                     {
                        printf("output[%d][%d] -> %10.2e (area: %10.2e) (using indata[%d][%d] = %10.2e, colfact[%d] = %5.3f, rowfact[%d] = %5.3f)\n", 
                           l, k, flux, area,
                           bufrow, imin+ii, indata[bufrow][imin+ii], 
                           imin+ii, colfact[ii],
                           jj, rowfact[jj]);

                        fflush(stdout);
                     }
                  }
               }
            }

            if(area > 0.)
               outdata[k] = flux/area;
            else
               outdata[k] = nan;

            if(debug >= 3)
            {
               printf("\nflux[%d] = %-g / area = %-g --> outdata[%d] = %-g\n",
                  k, flux, area, k, outdata[k]);
               
               printf("---\n");
               fflush(stdout);
            }
         }

         if(fpixelo[1] <= output.naxes[1])
         {
            if(debug >= 2)
            {
               printf("\nWRITE output image row %5ld\n===========================================\n", fpixelo[1]);
               fflush(stdout);
            }

            if (fits_write_pix(output.fptr, TDOUBLE, fpixelo, nelementso, 
                               (void *)(outdata), &status))
            {
               mShrink_printFitsError(status);
               strcpy(returnStruct->msg, montage_msgstr);
               return returnStruct;
            }
         }

         ++fpixelo[1];

         if(split)
         {
            ibuffer = jbuffer;
            split = 0;
         }


         /***************************************************************/
         /* Special case:  The expansion factor is integral and we have */
         /* gotten to the point where we need the next line.            */
         /***************************************************************/

         oend   =  fpixelo[1] * xfactor;

         if(fpixel[1] <= input.naxes[1] && floor(oend) == oend)
         {
            if(debug >= 2)
            {
               printf("Reading input image row %5ld  (ibuffer %d)\n", fpixel[1], jbuffer);
               fflush(stdout);
            }

            if(fits_read_pix(input.fptr, TDOUBLE, fpixel, nelements, &nan,
                             buffer, &nullcnt, &status))
            {
               mShrink_printFitsError(status);
               strcpy(returnStruct->msg, montage_msgstr);
               return returnStruct;
            }
            
            ++fpixel[1];

            indata[jbuffer][input.naxes[0]] = nan;

            for (i=0; i<input.naxes[0]; ++i)
            {
               indata[jbuffer][i] = buffer[i];

               if(debug >= 4)
               {
                  printf("input: line %5ld / pixel %5d: indata[%d][%d] = %10.3e\n",
                     fpixel[1]-2, i, jbuffer, i, indata[jbuffer][i]);
                  fflush(stdout);
               }
            }

            if(debug >= 4)
            {
               printf("---\n");
               fflush(stdout);
            }
         }
      }
   }
   else
   {
      /************************************************/ 
      /* Allocate memory for "ifactor" lines of input */ 
      /************************************************/ 

      nbuf = ifactor + 1;

      indata = (double **)malloc(nbuf * sizeof(double *));

      for(j=0; j<nbuf; ++j)
         indata[j] = (double *)malloc(input.naxes[0] * sizeof(double));



      /**********************************************************/
      /* Create the output array by processing the input pixels */
      /**********************************************************/

      ibuffer = 0;

      buffer  = (double *)malloc(input.naxes[0] * sizeof(double));
      colfact = (double *)malloc(input.naxes[0] * sizeof(double));
      rowfact = (double *)malloc(input.naxes[1] * sizeof(double));

      fpixel[0] = 1;
      fpixel[1] = 1;
      fpixel[2] = 1;
      fpixel[3] = 1;

      fpixelo[0] = 1;
      fpixelo[1] = 1;

      nelements = input.naxes[0];

      status = 0;


      /*****************************/
      /* Loop over the input lines */
      /*****************************/

      l = 0;

      obegin =  (double)l     * xfactor;
      oend   = ((double)l+1.) * xfactor;

      jmin = floor(obegin);
      jmax = ceil (oend);

      for(jj=jmin; jj<=jmax; ++jj)
      {
         rowfact[jj-jmin] = 1.;

              if(jj <= obegin && jj+1 <= oend) rowfact[jj-jmin] = jj+1. - obegin;
         else if(jj <= obegin && jj+1 >= oend) rowfact[jj-jmin] = oend - obegin;
         else if(jj >= obegin && jj+1 >= oend) rowfact[jj-jmin] = oend - jj;

         if(rowfact[jj-jmin] < 0.)
            rowfact[jj-jmin] = 0.;

         if(debug >= 4)
         {
            printf("rowfact[%d]  %-g\n", jj, rowfact[jj]);
            fflush(stdout);
         }
      }

      for (j=0; j<input.naxes[1]; ++j)
      {
         if(debug >= 2)
         {
            printf("Reading input image row %5ld  (ibuffer %d)\n", fpixel[1], ibuffer);
            fflush(stdout);
         }


         /***********************************/
         /* Read a line from the input file */
         /***********************************/

         if(fits_read_pix(input.fptr, TDOUBLE, fpixel, nelements, &nan,
                          buffer, &nullcnt, &status))
         {
            mShrink_printFitsError(status);
            strcpy(returnStruct->msg, montage_msgstr);
            return returnStruct;
         }
         
         ++fpixel[1];

         /************************/
         /* For each input pixel */
         /************************/

         for (i=0; i<input.naxes[0]; ++i)
         {
            indata[ibuffer][i] = buffer[i];

            if(debug >= 4)
            {
               printf("input: line %5d / pixel %5d: indata[%d][%d] = %10.2e\n",
                  j, i, ibuffer, i, indata[ibuffer][i]);
               fflush(stdout);
            }
         }

         if(debug >= 4)
         {
            printf("---\n");
            fflush(stdout);
         }


         /**************************************************/
         /* If we have enough for the next line of output, */
         /* compute and write it                           */
         /**************************************************/

         if(j == jmax || fpixel[1] == input.naxes[1])
         {
            nelementso = output.naxes[0];

            for(k=0; k<nelementso; ++k)
            {
               /* OK, we are trying to determine the correct flux   */
               /* for output pixel k in output line l.  We have all */
               /* the input lines we need (modulo looping back from */
               /* indata[ibuffer])                                  */

               outdata[k] = nan;

               obegin =  (double)k     * xfactor;
               oend   = ((double)k+1.) * xfactor;

               imin = floor(obegin);
               imax = ceil (oend);

               if(debug >= 3)
               {
                  printf("\nimin = %4d, imax = %4d, jmin = %4d, jmax = %4d\n", imin, imax, jmin, jmax);
                  fflush(stdout);
               }

               flux = 0;
               area = 0;

               for(ii=imin; ii<=imax; ++ii)
               {
                  colfact[ii-imin] = 1.;

                       if(ii <= obegin && ii+1 <= oend) colfact[ii-imin] = ii+1. - obegin;
                  else if(ii <= obegin && ii+1 >= oend) colfact[ii-imin] = oend - obegin;
                  else if(ii >= obegin && ii+1 >= oend) colfact[ii-imin] = oend - ii;

                  if(colfact[ii-imin] < 0.)
                     colfact[ii-imin] = 0.;
               }

               for(jj=jmin; jj<=jmax; ++jj)
               {
                  if(rowfact[jj-jmin] == 0.)
                     continue;

                  for(ii=imin; ii<=imax; ++ii)
                  {
                     bufrow = (ibuffer - jmax + jj + nbuf) % nbuf;

                     if(!mNaN(indata[bufrow][ii]) && colfact[ii-imin] > 0.)
                     {
                        flux += indata[bufrow][ii] * colfact[ii-imin] * rowfact[jj-jmin];
                        area += colfact[ii-imin] * rowfact[jj-jmin];

                        if(debug >= 3)
                        {
                           printf("output[%d][%d] -> %10.2e (area: %10.2e) (using indata[%d][%d] = %10.2e, colfact[%d-%d] = %5.3f, rowfact[%d-%d] = %5.3f)\n", 
                              l, k, flux, area,
                              bufrow, ii, indata[bufrow][ii], 
                              ii, imin, colfact[ii-imin],
                              jj, jmin, rowfact[jj-jmin]);

                           fflush(stdout);
                        }
                     }
                  }

                  if(debug >= 3)
                  {
                     printf("---\n");
                     fflush(stdout);
                  }
               }

               if(area > 0.)
                  outdata[k] = flux/area;
               else
                  outdata[k] = nan;

               if(debug >= 3)
               {
                  printf("\nflux = %-g / area = %-g --> outdata[%d] = %-g\n",
                     flux, area, k, outdata[k]);
                  
                  fflush(stdout);
               }
            }

            if(fpixelo[1] <= output.naxes[1])
            {
               if(debug >= 2)
               {
                  printf("\nWRITE output image row %5ld\n===========================================\n", fpixelo[1]);
                  fflush(stdout);
               }

               if (fits_write_pix(output.fptr, TDOUBLE, fpixelo, nelementso, 
                                  (void *)(outdata), &status))
               {
                  mShrink_printFitsError(status);
                  strcpy(returnStruct->msg, montage_msgstr);
                  return returnStruct;
               }
            }

            ++fpixelo[1];

            ++l;

            obegin =  (double)l     * xfactor;
            oend   = ((double)l+1.) * xfactor;

            jmin = floor(obegin);
            jmax = ceil (oend);

            for(jj=jmin; jj<=jmax; ++jj)
            {
               rowfact[jj-jmin] = 1.;

                    if(jj <= obegin && jj+1 <= oend) rowfact[jj-jmin] = jj+1. - obegin;
               else if(jj <= obegin && jj+1 >= oend) rowfact[jj-jmin] = oend - obegin;
               else if(jj >= obegin && jj+1 >= oend) rowfact[jj-jmin] = oend - jj;

               if(rowfact[jj-jmin] < 0.)
                  rowfact[jj-jmin] = 0.;

               if(debug >= 4)
               {
                  printf("rowfact[%d-%d] -> %-g\n", jj, jmin, rowfact[jj-jmin]);
                  fflush(stdout);
               }
            }
         }

         ibuffer = (ibuffer + 1) % nbuf;
      }
   }


   /*******************/
   /* Close the files */
   /*******************/

   if(fits_close_file(input.fptr, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(fits_close_file(output.fptr, &status))
   {
      mShrink_printFitsError(status);
      strcpy(returnStruct->msg, montage_msgstr);
      return returnStruct;
   }

   if(debug >= 1)
   {
      printf("FITS data image finalized\n"); 
      fflush(stdout);
   }

   time(&currtime);

   returnStruct->status = 0;

   sprintf(returnStruct->msg,  "time=%.0f",       (double)(currtime - start));
   sprintf(returnStruct->json, "{\"time\"=%.0f}", (double)(currtime - start));

   returnStruct->time = (double)(currtime - start);

   return returnStruct;
}
Esempio n. 18
0
int extractAvePlane (char *cubepath, char *impath, int iplane, int nplaneave,
    int *splaneave, int *eplaneave, char *errmsg)
{
    struct stat     buf;
    struct FitsHdr  hdr;

    char   str[1024];
    char   cmd[1024];
    
    int    bitpix;
    int    istatus;
    
    int    nhdu, hdutype, hdunum;

    int    nelements;
   
    int    naxis3;
    int    l;
    int    j;
    int    i;
    int    jj;
    int    nullcnt;

    int    splane;
    int    eplane;

    long   fpixel[4];
    long   fpixelo[4];

    double *fitsbuf;
    double *imbuff;
    
    fitsfile  *infptr;
    fitsfile  *outfptr;

    
    int    debugfile = 1;
    int    debugfile1 = 0;


/*
     Make a NaN value to use setting blank pixels
 */

    union
    {
        double d;
        char   c[8];
    }
    value;

    double nan;

    for(i=0; i<8; ++i)
        value.c[i] = 255;

    nan = value.d;


    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	fprintf (fp_debug, "\nEnter extractAvePlane: cubepath= [%s]\n", 
	    cubepath);
	fprintf (fp_debug, "iplane= [%d]\n", iplane);
	fprintf (fp_debug, "nplaneave= [%d]\n", nplaneave);
	fprintf (fp_debug, "impath= [%s]\n", impath);
        fflush (fp_debug);
    }

    splane = iplane - nplaneave/2;
    eplane = splane + nplaneave - 1;

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	fprintf (fp_debug, "splane= [%d] eplane= [%d]\n", splane, eplane);
        fflush (fp_debug);
    }

    istatus = 0;
    if (fits_open_file (&infptr, cubepath, READONLY, &istatus)) {

        if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	    fprintf (fp_debug, "istatus= [%d]\n", istatus);
            fflush (fp_debug);
	}

	sprintf (errmsg, "Failed to open FITS file [%s]\n", cubepath);
	return (-1);
    } 
   
    hdunum = 1; 
    nhdu = 0;
    istatus = 0;
    istatus = fits_get_num_hdus (infptr, &nhdu, &istatus);
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	fprintf (fp_debug, 
	    "returned fits_get_hdu_num: istatus= [%d] nhdu= [%d]\n",
	    istatus, nhdu);
        fflush (fp_debug);
    }

    if (hdunum > nhdu) {

        sprintf (errmsg, "fname [%s] doesn't contain any HDU", cubepath);
	return (-1);
    }


/*
    Read fits keywords from the first HDU
*/
    hdutype = 0;
    istatus = 0;
    istatus = fits_movabs_hdu (infptr, hdunum, &hdutype, &istatus);

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	fprintf (fp_debug, 
	    "returned fits_movabs_hdu: istatus= [%d] hdutype= [%d]\n",
	    istatus, hdutype);
        fflush (fp_debug);
    }

/*
    Read fits keywords
*/
    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "simple", str, (char *)NULL, 
        &istatus);
    
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword SIMPLE not found in fits header");
        return (-1);
    }
   
    if ((strcmp (str, "T") != 0) && (strcmp (str, "F") != 0)) {
        sprintf (errmsg, "keyword SIMPLE must be T or F");
        return (-1);
    }

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "bitpix", str, (char *)NULL, 
        &istatus);
    
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword BITPIX not found in fits header");
        return (-1);
    }
  
    istatus = str2Integer (str, &bitpix, errmsg);
    if (istatus != 0) {
        sprintf (errmsg, "keyword BITPIX must be an integer");
        return (-1);
    }

    if ((bitpix != 8) &&
        (bitpix != 16) &&
        (bitpix != 32) &&
        (bitpix != 64) &&
        (bitpix != -32) &&
        (bitpix != -64)) {
        
	sprintf (errmsg, 
	    "keyword BITPIX value must be 8, 16, 32, 64, -32, -64");
        return (-1);
    }

    hdr.bitpix = bitpix;

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis", str, (char *)NULL, 
        &istatus);
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis not found in fits header");
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }
    istatus = str2Integer (str, &hdr.naxis, errmsg);
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis to integer");
        return (-1);
    }
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "naxis= [%d]\n", hdr.naxis);
        fflush (fp_debug);
    }


    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis1", str, (char *)NULL, 
        &istatus);
        
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", istatus);
        fflush (fp_debug);
    }
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis1 not found in fits header");
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }

    istatus = str2Integer (str, &hdr.ns, errmsg);
    
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis1 string to integer");
        return (-1);
    }
    hdr.naxes[0] = hdr.ns;

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis2", str, 
        (char *)NULL, &istatus);
        
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", istatus);
        fflush (fp_debug);
    }
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis2 not found in fits header");
        return (-1);
    }
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }

    istatus = str2Integer (str, &hdr.nl, errmsg);
    
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis2 string to integer");
        return (-1);
    }
    hdr.naxes[1] = hdr.nl;

    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "ns= [%d] nl= [%d]\n", hdr.ns, hdr.nl);
        fflush (fp_debug);
    }

    hdr.nplane = 1;

    if (hdr.naxis > 2) {
    
        istatus = 0;
        istatus = fits_read_key (infptr, TSTRING, "naxis3", str, 
            (char *)NULL, &istatus);
        
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {

            fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", 
	        istatus);
            fflush (fp_debug);
        }
        
        if (istatus == KEY_NO_EXIST) {
            sprintf (errmsg, "keyword naxis3 not found in fits header");
            return (-1);
        }
    
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {

            fprintf (fp_debug, "str= [%s]\n", str);
            fflush (fp_debug);
        }

        istatus = str2Integer (str, &hdr.naxes[2], errmsg);
    
        if (istatus < 0) {
            sprintf (errmsg, "Failed to convert naxis3 string to integer");
            return (-1);
        }
        hdr.nplane = hdr.naxes[2];
    
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {

            fprintf (fp_debug, "naxes[2]= [%d]\n", hdr.naxes[2]);
            fflush (fp_debug);
        }
    }
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "nplane= [%d]\n", hdr.nplane);
        fflush (fp_debug);
    }


    istatus = stat (impath, &buf);
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "impath exists? : istatus= [%d]\n", istatus);
        fflush (fp_debug); 
    }

    if (istatus >= 0) {
        sprintf (cmd, "unlink %s", impath);
	istatus = system (cmd);
    }	

/*
    Create output fits file
*/
    istatus = 0;
    if (fits_create_file (&outfptr, impath, &istatus)) {
	    
        sprintf (errmsg, "Failed to create output fitsfile [%s]\n", impath);
        
	if ((debugfile) && (fp_debug != (FILE *)NULL)) {
            fprintf (fp_debug, "err: [%s]\n", errmsg);
	    fflush (fp_debug);
        }
	return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
	fprintf (fp_debug, "outptr created\n");
        fflush (fp_debug);
    }


/* 
    Copy input fits header to output fitsfile
*/
    istatus = 0;
    if (fits_copy_header (infptr, outfptr, &istatus)) {

        strcpy (errmsg, "Failed to copy fitshdr\n");
        
	if ((debugfile) && (fp_debug != (FILE *)NULL)) {
            fprintf (fp_debug, "err: [%s]\n", errmsg);
	    fflush (fp_debug);
        }
	return (-1);
    }

/*
    Update header keyword NAXIS3
*/
    naxis3 = 1;
    istatus = 0;
    if (fits_update_key_lng(outfptr, "NAXIS3", naxis3, (char *)NULL, 
        &istatus)) {
	
        strcpy (errmsg, "Failed to update keyword NAXIS3\n");
	return (-1);
    }

    istatus = 0;
    if (fits_close_file (infptr, &istatus)) {
        sprintf (errmsg, "Failed to close cubepath [%s]\n", cubepath);
        return (-1); 
    }
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
	        
	fprintf (fp_debug, "cubepath= [%s]\n", cubepath);
        fflush (fp_debug);
    }

    istatus = 0;
    if (fits_open_file (&infptr, cubepath, READONLY, &istatus)) {

        if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	    fprintf (fp_debug, "istatus= [%d]\n", istatus);
            fflush (fp_debug);
	}

	sprintf (errmsg, "Failed to open FITS file [%s]\n", cubepath);
	return (-1);
    } 
  
/*
    Create imbuff for average image
*/
    imbuff = (double *)malloc (hdr.ns*hdr.nl*sizeof(double));
    for (i=0; i<hdr.nl*hdr.ns; i++) {
        imbuff[i] = 0.;
    }


/*
    Read data from nth plane and write to output fitsfile
*/
    nelements = hdr.ns;
       
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	fprintf (fp_debug, "iplane= [%d]\n", iplane);
        fflush (fp_debug);
    }

    fitsbuf  = (double *)malloc(hdr.ns*sizeof(double));

    if (splane < 1)
        splane = 1;
    
    if (eplane > hdr.nplane)
        eplane = hdr.nplane;

    for (l=splane; l<=eplane; l++) { 
    
        fpixel[0] = 1;
        fpixel[1] = 1;
        fpixel[2] = l;
        fpixel[3] = 1;

        for (j=0; j<hdr.nl; j++) {

	    if (j == 0) {
	        if ((debugfile1) && (fp_debug != (FILE *)NULL)) {
	        
	            fprintf (fp_debug, "l= [%d] fpixel[2]= [%ld]\n", 
		        l, fpixel[2]);
                    fflush (fp_debug);
	        }
            }

	    if (fits_read_pix (infptr, TDOUBLE, fpixel, nelements, &nan,
                fitsbuf, &nullcnt, &istatus)) {
	        break;
	    }
            
	    if (j == 10) {
	        if ((debugfile1) && (fp_debug != (FILE *)NULL)) {
                    for (i=0; i<hdr.ns; i++) {
	                fprintf (fp_debug, "j= [%d] i= [%d] fitsbuf= [%lf]\n",
	                    j, i, fitsbuf[i]);
	                fprintf (fp_debug, "fitsbuf/nplaneave= [%lf]\n",
	                    fitsbuf[i]/nplaneave);
		    }
                    fflush (fp_debug);
	        }
            }         

/*
    Copy data to imbuff for plane averaging
*/
            jj = hdr.ns*j;
	    if ((debugfile1) && (fp_debug != (FILE *)NULL)) {
	        fprintf (fp_debug, "jj= [%d]\n", jj);
                fflush (fp_debug);
	    }
	        
            for (i=0; i<hdr.ns; i++) {
		imbuff[jj+i] += fitsbuf[i]/nplaneave; 
            }         
 
            if (j == 10) {
	        if ((debugfile1) && (fp_debug != (FILE *)NULL)) {
	        
                    for (i=0; i<hdr.ns; i++) {
	                fprintf (fp_debug, "j= [%d] i= [%d] imbuff= [%lf]\n",
	                    j, i, imbuff[jj+i]);
		    }
                    fflush (fp_debug);
	        }
            }         
            fpixel[1]++;
        }
    }

/*
    Write averaged image to output FITS file
*/
    fpixelo[0] = 1;
    fpixelo[1] = 1;
    fpixelo[2] = 1;
    fpixelo[3] = 1;
    
    for (j=0; j<hdr.nl; j++) {

        jj = hdr.ns*j;
        for (i=0; i<hdr.ns; i++) {
	    fitsbuf[i] = imbuff[jj+i]; 
        }
            
	if (j == 10) {
	    if ((debugfile1) && (fp_debug != (FILE *)NULL)) {
	        
                for (i=0; i<hdr.ns; i++) {
	            fprintf (fp_debug, "j= [%d] i= [%d] fitsbuf= [%lf]\n", 
		        j, i, fitsbuf[i]);
		}
                fflush (fp_debug);
	    }
        }         

        
	if (fits_write_pix (outfptr, TDOUBLE, fpixelo, nelements,
			 (void *)fitsbuf, &istatus)) {

            sprintf (errmsg, "fits write error: l= [%d]\n", l);
            return (-1);
        }

        fpixelo[1]++;
    }   


    istatus = 0;
    if (fits_close_file (infptr, &istatus)) {
        sprintf (errmsg, "Failed to close cubepath [%s]\n", cubepath);
        return (-1); 
    }
    
    istatus = 0;
    if (fits_close_file (outfptr, &istatus)) {
        sprintf (errmsg, "Failed to close impath [%s]\n", impath);
        return (-1); 
    }

    *splaneave = splane;
    *eplaneave = eplane;

    return (0);
}
Esempio n. 19
0
int write3Dmatrix_fits(char *outputname, double ***f, int numl, int yboxnum, int pwidth, int pheight)
{
  fitsfile *afptr;
  int status = 0;
  int atype, anaxis, check = 1;
  long anaxes[3], fpixel[3]={1,1,1};
  int i, n, bitpix, row, psfnum, psfnumx, psfnumy;
  float *psf, *psf3d;
  double sum;
  int psfsize, psfsize3d, dwidth, dfactor, maxboxno;
  int ix, iy, x, y, j, ij, npixels,k,k0;

  /*  write out matrix data as a fits file */

  if (pwidth<=0 || pheight <=0 || numl<=0 || yboxnum<=0)
    {
      fprintf (stderr," error in subimage dimensions or number \n");
      return 1;
    }

  bitpix = -32;
  anaxis = 3;
  anaxes[0] = pwidth;
  anaxes[1] = pheight;
  anaxes[2] = numl;

  psfsize = anaxes[0]*anaxes[1]*anaxes[2];
  psf3d = (float*)calloc(psfsize,sizeof(float));
  if (psf3d==NULL)
    {
      fprintf (stderr," error allocating memory for 3D psf in writepsf_fits \n");
      fprintf (stderr," memory requested = %d floats \n",psfsize3d);
      exit (2);
    }

  fits_create_file(&afptr, outputname, &status); 
  fits_create_img(afptr, bitpix, anaxis, anaxes, &status);

  if (status) {
    fits_report_error(stderr, status); /* print error message */
    return(status);
  }

  k=0;
  for (x=0; x<anaxes[2]; x++)
    {
      for (i=0;i<anaxes[0];i++) {
        for (y=0;y<anaxes[1];y++) {
          k++;
	  psf3d[k] = (float)f[x][y][i];
	}
      }
    }

  /* write all matrix data into image array */
  if (fits_write_pix(afptr, TFLOAT, fpixel, psfsize, psf3d, &status) )
    {
      printf(" error reading pixel data \n");
      exit (2);
    }

  /* close the fits file */

  fits_close_file(afptr, &status);

  if (status) {
    fits_report_error(stderr, status); /* print error message */
    return(status);
  }


  return (0);

}
Esempio n. 20
0
int main(int argc, char *argv[])
{
	fitsfile *afptr, *outfptr;  /* FITS file pointers */
	int status = 0;  /* CFITSIO status value MUST be initialized to zero! */
	int anaxis, check = 1, ii, op, keytype;
	long npixels = 1, firstpix[3] = {1,1,1}, ntodo;
	long anaxes[3] = {1,1,1};
	double *apix;
	double maxval, minval;
	char card[FLEN_CARD];

	if (argc != 5) { 
		printf("Usage: pruneimage image max min outimage \n");
		printf("\n");
		printf("Compiled from cfitsio v2.460\n");
		printf("\n");
		printf("Trim off the peaks and valley values of the image.\n");
		printf("\n");
		printf("outimage is of format BITPIX = -32\n");
		printf("\n");
		printf("Example: \n");
		printf("  pruneimage in.fit 1000 850 out.fits - sets all values above 1000 to 1000\n");
		printf("                                            and all values below 850 to 850.\n");
		return(0);
	}

	fits_open_file(&afptr, argv[1], READONLY, &status); /* open input images */
	fits_get_img_dim(afptr, &anaxis, &status);  /* read dimensions */
	fits_get_img_size(afptr, 3, anaxes, &status);

	if (status) {
		fits_report_error(stderr, status); /* print error message */
		return(status);
	}

	if (anaxis > 3) {
		printf("Error: images with > 3 dimensions are not supported\n");
		check = 0;
	}

	maxval = atof ( argv[2] );
	minval = atof ( argv[3] );

	/* create the new empty output file if the above checks are OK */
	if (check && !fits_create_file(&outfptr, argv[4], &status) )
	{
		/* copy all the header keywords from first image to new output file */
		fits_copy_header(afptr, outfptr, &status);

		/* change to floating point variable */
		fits_modify_key_lng (outfptr, "BITPIX", -32, "&", &status );

		fits_modify_key_flt (outfptr, "DATAMIN", minval, -10, "&", &status );
		fits_modify_key_flt (outfptr, "DATAMAX", maxval, -10, "&", &status );

		npixels = anaxes[0];  /* no. of pixels to read in each row */
		apix = (double *) malloc(npixels * sizeof(double)); /* mem for 1 row */

		if (apix == NULL) {
			printf("Memory allocation error\n");
			return(1);
		}

		/* loop over all planes of the cube (2D images have 1 plane) */
		for (firstpix[2] = 1; firstpix[2] <= anaxes[2]; firstpix[2]++)
		{
			/* loop over all rows of the plane */
			for (firstpix[1] = 1; firstpix[1] <= anaxes[1]; firstpix[1]++)
			{
				/* Read both images as doubles, regardless of actual datatype.  */
				/* Give starting pixel coordinate and no. of pixels to read.    */
				/* This version does not support undefined pixels in the image. */
				if (fits_read_pix(afptr, TDOUBLE, firstpix, npixels, NULL, apix,
					NULL, &status)  )
					break;   /* jump out of loop on error */



				for(ii=0; ii< npixels; ii++) {
					if ( apix[ii] > maxval )
						apix[ii] = maxval;
					else if ( apix[ii] < minval )
						apix[ii] = minval;
				}

				fits_write_pix(outfptr, TDOUBLE, firstpix, npixels,
					apix, &status); /* write new values to output image */
			}
		}    /* end of loop over planes */

		fits_close_file(outfptr, &status);
		free(apix);
	}

	fits_close_file(afptr, &status);
	 
	if (status) fits_report_error(stderr, status); /* print any error message */
		return(status);
}
Esempio n. 21
0
/* copy image section from input to putput, with binning */
int copyImageSection(fitsfile *ifptr, fitsfile *ofptr,
		     int *dims, double *cens, int bin, char *slice,
		     int *status)
{
  void *buf;
  char card[FLEN_CARD];
  char tbuf[SZ_LINE];
  int numkeys, nkey, bitpix, dtype;
  int start[2];
  int end[2];
  int naxis = 2;
  long nelements;
  long naxes[2];
  long fpixel[2] = {1,1};
  buf = getImageToArray(ifptr, dims, cens, bin, slice, start, end, &bitpix,
			status);
  if( !buf || *status ){
    fits_get_errstatus(*status, tbuf);
    fprintf(stderr, "ERROR: could not create section for output image: %s\n",
	    tbuf);
    return *status;
  }
  /* get image size and total number of elements */
  naxes[0] = (int)((end[0] - start[0] + 1) / bin);
  naxes[1] = (int)((end[1] - start[1] + 1) / bin);
  nelements = naxes[0] * naxes[1];
  /* convert bitpix to cfitio data type */
  switch(bitpix){
  case 8:
    dtype = TBYTE;
    break;
  case 16:
    dtype = TSHORT;
    break;
  case -16:
    dtype = TUSHORT;
    break;
  case 32:
    dtype = TINT;
    break;
  case 64:
    dtype = TLONGLONG;
    break;
  case -32:
    dtype = TFLOAT;
    break;
  case -64:
    dtype = TDOUBLE;
    break;
  default:
    fprintf(stderr, "ERROR: unknown data type for image section\n");
    return -1;
  }
  /* this code is modeled after cfitsio/cfileio.c/fits_copy_image_section() */
  fits_create_img(ofptr, bitpix, naxis, naxes, status);
  /* copy all other non-structural keywords from the input to output file */
  fits_get_hdrspace(ifptr, &numkeys, NULL, status);
  for(nkey=4; nkey<=numkeys; nkey++) {
    fits_read_record(ifptr, nkey, card, status);
    if (fits_get_keyclass(card) > TYP_CMPRS_KEY){
      /* write the record to the output file */
      fits_write_record(ofptr, card, status);
    }
  }
  if( *status > 0 ){
    fprintf(stderr,
	    "ERROR: can't copy header from input image to output section");
    return(*status);
  }
  /* write image to FITS file */
  fits_write_pix(ofptr, dtype, fpixel, nelements, buf, status);
  /* update LTM/TLV values in header */
  updateLTM(ifptr, ofptr,
	    (int)((end[0] + start[0]) / 2), (int)((end[1] + start[1]) / 2), 
	    (int)(end[0] - start[0] + 1), (int)(end[1] - start[1] + 1),
	    bin, 1);
  /* free up space */
  if( buf ){
    free(buf);
  }
  /* return status */
  return *status;
}
Esempio n. 22
0
int main(int argc, char *argv[])
{
	fitsfile *afptr, *outfptr;  /* FITS file pointers */
	int status = 0;  /* CFITSIO status value MUST be initialized to zero! */
	int anaxis, check = 1, keytype;
	long npixels = 1, firstpix[3] = {1,1,1};
	long anaxes[3] = {1,1,1};
	double *apix;
	char card[FLEN_CARD];

	if (argc != 3) { 
		printf("Usage: tofitsbp16 inimage outimage \n");
		printf("\n");
		printf("Compiled from cfitsio v2.460\n");
		printf("\n");
		printf("Converts a FITS from BITPIX = -32 to BITPIX = 16\n");
		printf("\n");
		printf("Example: \n");
		printf("  tofitsbp16 in.fit out.fits.\n");
		return(0);
	}

	fits_open_file(&afptr, argv[1], READONLY, &status); /* open input images */

	fits_get_img_dim(afptr, &anaxis, &status);  /* read dimensions */
	fits_get_img_size(afptr, 3, anaxes, &status);

	if (status) {
		fits_report_error(stderr, status); /* print error message */
		return(status);
	}

	/* create the new empty output file if the above checks are OK */
	if (check && !fits_create_file(&outfptr, argv[2], &status) )
	{
		/* copy all the header keywords from first image to new output file */
		fits_copy_header(afptr, outfptr, &status);

		/* change to 16 bit integer variable */
		fits_modify_key_lng (outfptr, "BITPIX", 16, "&", &status );

		npixels = anaxes[0];  /* no. of pixels to read in each row */
		apix = (double *) malloc(npixels * sizeof(double)); /* mem for 1 row */

		if (apix == NULL) {
			printf("Memory allocation error\n");
			return(1);
		}

		/* loop over all planes of the cube (2D images have 1 plane) */
		for (firstpix[2] = 1; firstpix[2] <= anaxes[2]; firstpix[2]++)
		{
			/* loop over all rows of the plane */
			for (firstpix[1] = 1; firstpix[1] <= anaxes[1]; firstpix[1]++)
			{
				/* Read both images as doubles, regardless of actual datatype.  */
				/* Give starting pixel coordinate and no. of pixels to read.    */
				/* This version does not support undefined pixels in the image. */
				if (fits_read_pix(afptr, TDOUBLE, firstpix, npixels, NULL, apix,
					NULL, &status)  )
					break;   /* jump out of loop on error */

				fits_write_pix(outfptr, TDOUBLE, firstpix, npixels,
					apix, &status); /* write new values to output image */
			}
		}    /* end of loop over planes */

		fits_close_file(outfptr, &status);
		free(apix);
	}

	fits_close_file(afptr, &status);
	 
	if (status) fits_report_error(stderr, status); /* print any error message */
		return(status);
}
Esempio n. 23
0
/* Function to write array to FITS file, and copy header info from other file */
void fitswrap_write2file(char *fileout, char *copyhdr, double **array, 
			  long write_size[2], int *status){
  
  /* Variable Declarations & Initializations */
  int k,naxis,bitpix;
  long fpixel[2],naxes[2],bzero;
  char buf_date[FLEN_VALUE],buf_time[FLEN_VALUE],*mod_comm;
  fitsfile *fitsfp,*hdrfp;
  time_t now;
  struct tm *ptr;
  *status = 0;

  /* Open file from which header will be copied */
  hdrfp = fitswrap_open_read(copyhdr, status);

  /* Check for output file -- create & open for write */
  if(access(fileout,F_OK) == 0)          // Check if output file exists
    remove(fileout);                     // If yes, remove it
  if(fits_create_file(&fitsfp, fileout, status)){
    fitswrap_catcherror(status);    // Send pointer not value
  }

  mod_comm = "Modified by fitswrap routine, TPEB.";
  /* Copy header from copyhdr FITS file. */
  fits_copy_header(hdrfp, fitsfp, status);  // Copy header from input FITS
  fits_get_img_param(hdrfp, 2 ,&bitpix, &naxis, naxes, status);
  fits_read_key(hdrfp, TLONG, "BZERO", &bzero, NULL, status);

  /* Check for needed updates */
    // Writing new FITS as double
    if(bitpix != DOUBLE_IMG){
      bitpix = DOUBLE_IMG;
      fits_update_key(fitsfp, TSHORT, "BITPIX", &bitpix, mod_comm, status);
    }
    
    // check for 'zero level' (needed for type long FITS headers)
    // NOTE: If input header does not contain this keyword (status = 202), 
    // skip update & reset CFITSIO status to zero.
    
    if(bzero != 0 || *status != 202){  
      bzero = 0;
      fits_update_key(fitsfp, TSHORT, "BZERO", &bzero, mod_comm, status);
    }
    *status = 0;                       // Reset Status
    
    // Check new axis lengths are correct
    if(naxes[0] != write_size[0])
      fits_update_key(fitsfp, TULONG,"NAXIS1",&write_size[0],mod_comm,status);
    if(naxes[1] != write_size[1])
      fits_update_key(fitsfp, TULONG,"NAXIS2",&write_size[1],mod_comm,status);
    
    
  /* Write array to file */
  fpixel[0] = 1;
  for(k=0; k < write_size[1]; k++){       // Loop over size[1] rows (i.e. y)
    fpixel[1] = k + 1; 
    if(fits_write_pix(fitsfp, TDOUBLE, fpixel, write_size[0], array[k], 
  		      status)){
      fits_report_error(stderr,*status);
      break;
    }
  }
  
  /* Add/modify keyword for date modified 'DATE-MOD' & 'TIME-MOD' */
  time(&now);
  ptr = localtime(&now);
  strftime(buf_date, FLEN_VALUE, "%Y-%m-%d", ptr);
  strftime(buf_time, FLEN_VALUE, "%H:%M:%S", ptr);
  fits_update_key(fitsfp, TSTRING, "DATE-MOD", buf_date, mod_comm, status);
  fits_update_key(fitsfp, TSTRING, "TIME-MOD", buf_time, NULL, status);
  
  /* Clean up */
  fits_close_file(fitsfp, status);
  fits_close_file(hdrfp,  status);
  
  /* Report any CFITSIO errors to stderr */
  if(!*status)
    fitswrap_catcherror(status);    // Send pointer not value
  
  return;
}
Esempio n. 24
0
void montage_copyData(fitsfile *infptr, fitsfile *outfptr, struct imageParams *params)
{
   long    fpixel[4], fpixelo[4];
   int     i, j, nullcnt;
   int     status = 0;
   double *buffer, refval;


   /*************************************************/
   /* Make a NaN value to use checking blank pixels */
   /*************************************************/

   union
   {
      double d;
      char   c[8];
   }
   value;

   double nan;

   for(i=0; i<8; ++i)
      value.c[i] = 255;

   nan = value.d;


   fpixel[0] = params->ibegin;
   fpixel[1] = params->jbegin;
   fpixel[2] = 1;
   fpixel[3] = 1;

   if(params->plane)
      fpixel[2] = params->plane;

   buffer  = (double *)malloc(params->nelements * sizeof(double));

   fpixelo[0] = 1;
   fpixelo[1] = 1;
   fpixelo[2] = 1;
   fpixelo[3] = 1;

   isflat = 1;

   refval = nan;

   for (j=params->jbegin; j<=params->jend; ++j)
   {
      if(debug >= 2)
      {
         printf("Processing input image row %5d\n", j);
         fflush(stdout);
      }

      if(fits_read_pix(infptr, TDOUBLE, fpixel, params->nelements, &nan,
                       buffer, &nullcnt, &status))
         montage_printFitsError(status);

      for(i=0; i<params->nelements; ++i)
      {
         if(!mNaN(buffer[i]))
         {
            if(mNaN(refval))
               refval = buffer[i];

            if(buffer[i] != refval)
               isflat = 0;
         }
      }

      if (fits_write_pix(outfptr, TDOUBLE, fpixelo, params->nelements,
                         (void *)buffer, &status))
         montage_printFitsError(status);

      ++fpixelo[1];
      ++fpixel [1];
   }


   free(buffer);

   if(isflat)
   {
      if(mNaN(refval))
         strcpy(content, "blank");
      else
         strcpy(content, "flat");
   }
   else
      strcpy(content, "normal");
}
Esempio n. 25
0
bool usImage::Save(const wxString& fname, const wxString& hdrNote) const
{
    bool bError = false;

    try
    {
        long fsize[3] = {
            (long)Size.GetWidth(),
            (long)Size.GetHeight(),
            0L,
        };
        long fpixel[3] = { 1, 1, 1 };

        fitsfile *fptr;  // FITS file pointer
        int status = 0;  // CFITSIO status value MUST be initialized to zero!

        PHD_fits_create_file(&fptr, fname, true, &status);
        fits_create_img(fptr, USHORT_IMG, 2, fsize, &status);

        FITSHdrWriter hdr(fptr, &status);

        float exposure = (float) ImgExpDur / 1000.0;
        hdr.write("EXPOSURE", exposure, "Exposure time in seconds");

        if (ImgStackCnt > 1)
            hdr.write("STACKCNT", (unsigned int) ImgStackCnt, "Stacked frame count");

        if (!hdrNote.IsEmpty())
            hdr.write("USERNOTE", static_cast<const char *>(hdrNote), 0);

        time_t now = wxDateTime::GetTimeNow();
        struct tm *timestruct = gmtime(&now);
        char buf[100];
        sprintf(buf, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d", timestruct->tm_year + 1900, timestruct->tm_mon + 1, timestruct->tm_mday, timestruct->tm_hour, timestruct->tm_min, timestruct->tm_sec);
        hdr.write("DATE", buf, "Time FITS file was created");

        hdr.write("DATE-OBS", GetImgStartTime().c_str(), "Time image was captured");
        hdr.write("CREATOR", wxString(APPNAME _T(" ") FULLVER).c_str(), "Capture software");
        if (pCamera)
        {
            hdr.write("INSTRUME", pCamera->Name.c_str(), "Instrument name");
            unsigned int b = pCamera->Binning;
            hdr.write("XBINNING", b, "Camera X Bin");
            hdr.write("YBINNING", b, "Camera Y Bin");
            hdr.write("CCDXBIN", b, "Camera X Bin");
            hdr.write("CCDYBIN", b, "Camera Y Bin");
            float sz = b * pCamera->PixelSize;
            hdr.write("XPIXSZ", sz, "pixel size in microns (with binning)");
            hdr.write("YPIXSZ", sz, "pixel size in microns (with binning)");
        }

        if (pPointingSource)
        {
            double ra, dec, st;
            pPointingSource->GetCoordinates(&ra, &dec, &st);
            hdr.write("RA", (float) (ra * 360.0 / 24.0), "Object Right Ascension in degrees");
            hdr.write("DEC", (float) dec, "Object Declination in degrees");

            {
                int h = (int) ra;
                ra -= h;
                ra *= 60.0;
                int m = (int) ra;
                ra -= m;
                ra *= 60.0;
                hdr.write("OBJCTRA", wxString::Format("%02d %02d %06.3f", h, m, ra).c_str(), "Object Right Ascension in hms");
            }

            {
                int sign = dec < 0.0 ? -1 : +1;
                dec *= sign;
                int d = (int) dec;
                dec -= d;
                dec *= 60.0;
                int m = (int) dec;
                dec -= m;
                dec *= 60.0;
                hdr.write("OBJCTDEC", wxString::Format("%c%d %02d %06.3f", sign < 0 ? '-' : '+', d, m, dec).c_str(), "Object Declination in dms");
            }
        }

        float sc = (float) pFrame->GetCameraPixelScale();
        hdr.write("SCALE", sc, "Image scale (arcsec / pixel)");
        hdr.write("PIXSCALE", sc, "Image scale (arcsec / pixel)");

        fits_write_pix(fptr, TUSHORT, fpixel, NPixels, ImageData, &status);

        PHD_fits_close_file(fptr);

        bError = status ? true : false;
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);
        bError = true;
    }

    return bError;
}