Exemplo n.º 1
0
image_t	*readimage(const char *filename) {
	char	errmsg[80];
	image_t	*image = NULL;
	// open the FITS file
	int	status = 0;
	fitsfile	*fits = NULL;
	if (fits_open_file(&fits, filename, READONLY, &status)) {
		fits_get_errstatus(status, errmsg);
		fprintf(stderr, "cannot read fits file %s: %s\n",
			filename, errmsg);
		return NULL;
	}

	// find dimensions of pixel array
	int	igt;
	int	naxis;
	long	naxes[3];
	if (fits_get_img_param(fits, 3, &igt, &naxis, naxes, &status)) {
		fits_get_errstatus(status, errmsg);
		fprintf(stderr, "cannot read fits file info: %s\n", errmsg);
		goto bad;
	}
	image = (image_t *)malloc(sizeof(image_t));
	image->width = naxes[0];
	image->height = naxes[1];

	// read the pixel data
	long	npixels = image->width * image->height;
	image->data = (double *)malloc(npixels * sizeof(double));
	long	firstpixel[3] = { 1, 1, 1 };
	if (fits_read_pix(fits, TDOUBLE, firstpixel, npixels, NULL, image->data,
		NULL, &status)) {
		fits_get_errstatus(status, errmsg);
		fprintf(stderr, "cannot read pixel data: %s\n", errmsg);
		goto 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;
	}

	// return the image
	return image;
bad:
	if (image) {
		if (image->data) {
			free(image->data);
		}
		free(image);
	}
	if (fits) {
		fits_close_file(fits, &status);
	}
	return NULL;
}
Exemplo n.º 2
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);
}
Exemplo n.º 3
0
int read_and_process(char* path)
{
	fitsfile *fptr;    
    int status = 0;
    unsigned int bitpix, naxis;
    long naxes[3];
    long nelements;
    int anynul;
    unsigned char* image;
    
	if (!fits_open_file(&fptr, path, READONLY, &status))
    {
		if (!fits_get_img_param(fptr, 2, &bitpix, &naxis, naxes, &status) )
        {
			if (naxis != 3){
				printf("Not a 3D fits\n");
				return -1;
			}
			
			if (bitpix != 8){
				printf("Process only 8 bit fits\n");
				return -1;
			}
			
			printf("bitpix=%d naxes=%d width=%ld height=%ld\n",bitpix,naxis,naxes[0],naxes[1]);
			nelements = naxes[0]*naxes[1];
			if (width==0 && height==0){
				width = naxes[0];
				height = naxes[1];
			} else {
				if (width != naxes[0] || height != naxes[1]){
					printf("naxes error: %ldx%ld instead of %ldx%ld\n",naxes[0],naxes[1],width,height);
					return -1;
				}
			}
			
			image = malloc(sizeof(unsigned char)*nelements);
			
			fits_read_img(fptr,TBYTE,1,nelements,NULL,image, &anynul, &status);
			write_fits("red.fits",image);
			fits_read_img(fptr,TBYTE,nelements +1,nelements,NULL,image, &anynul, &status);
			write_fits("green.fits",image);
			fits_read_img(fptr,TBYTE,2* nelements +1,nelements,NULL,image, &anynul, &status);
			write_fits("blue.fits",image);
			fits_close_file(fptr, &status);
			
			free(image);
						
			return status;
	
		  }
     }
     return -1;		
}
Exemplo n.º 4
0
double get_average(std::string filename) {
	fitsfile *fptr;   /* FITS file pointer, defined in fitsio.h */
	int status = 0;   /* CFITSIO status value MUST be initialized to zero! */
	int bitpix, naxis, ii;
	long naxes[2] = {1,1}, fpixel[2] = {1,1};
	double *pixels;

	std::vector<double> values; //stores the values of all pixels in image

	if (!fits_open_file(&fptr, filename.c_str(), READONLY, &status))
	{
		if (!fits_get_img_param(fptr, 2, &bitpix, &naxis, naxes, &status) )
		{
			if (naxis > 2 || naxis == 0)
				printf("Error: only 1D or 2D images are supported\n");
			else
			{
				/* get memory for 1 row */
				pixels = (double *) malloc(naxes[0] * sizeof(double));

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

				/* loop over all the rows in the image, top to bottom */
				for (fpixel[1] = naxes[1]; fpixel[1] >= 1; fpixel[1]--)
				{
					if (fits_read_pix(fptr, TDOUBLE, fpixel, naxes[0], NULL,
							pixels, NULL, &status) )  /* read row of pixels */
						break;  /* jump out of loop on error */
					for (ii = 0; ii < naxes[0]; ii++) {
						values.push_back(pixels[ii]);
					}
				}
				free(pixels);
			}
		}
		fits_close_file(fptr, &status);
	}

	if (status) fits_report_error(stderr, status); /* print any error message */

	//report average of values
	double sum = 0;
	for (int i=0; i < values.size(); i++)
		sum += values[i];
	return sum/values.size();
}
Exemplo n.º 5
0
int read_fits(char* path, unsigned char** image)
{
	fitsfile *fptr;    
    int status = 0;
    unsigned int bitpix, naxis;
    long naxes[2];
    long nelements;
    int anynul;
	if (!fits_open_file(&fptr, path, READONLY, &status))
    {
		if (!fits_get_img_param(fptr, 2, &bitpix, &naxis, naxes, &status) )
        {
			printf("bitpix=%d naxes=%d width=%ld height=%ld\n",bitpix,naxis,naxes[0],naxes[1]);
			nelements = naxes[0]*naxes[1];
			if (width==0 && height==0){
				width = naxes[0];
				height = naxes[1];
			} else {
				if (width != naxes[0] || height != naxes[1]){
					printf("naxes error: %ldx%ld instead of %ldx%ld\n",naxes[0],naxes[1],width,height);
					return -1;
				}
			}
			
			if (naxis != 2){
				printf("Process only 2D fits\n");
				fits_close_file(fptr, &status); 
				return -1;
			}

			if (bitpix != 8){
				printf("Process only 8 bit fits\n");
				fits_close_file(fptr, &status); 
				return -1;
			}
			
			*image = malloc(sizeof(unsigned char)*nelements);
			
			if (bitpix == 8){
				fits_read_img(fptr,TBYTE,1,nelements,NULL,*image, &anynul, &status);
				fits_close_file(fptr, &status);
				if (status != 0) printf("status = %d\n",status);
				return status;
			} 
			
		  }
     }
     return -1;		
}
Exemplo n.º 6
0
/* Load dimension params from fits file */
int cyclic_load_params(fitsfile *f, struct cyclic_work *w, int *status) {

    int bitpix, naxis; 
    long naxes[4];

    fits_get_img_param(f, 4, &bitpix, &naxis, naxes, status);
    if (naxis!=4) { return(-1); }

    w->nphase = naxes[0];
    w->npol = naxes[1];
    w->nchan = naxes[2];

    w->nlag = 0;
    w->nharm = 0;

    return(*status);
}
void InputFileFITS::_readImage(Image<T>& buff, int type)
{
	int status = 0;
	if(!isOpened())
		throwException("Error in InputFileFITS::readImage() ", status);

	int bitpix;
	int naxis;
	const int MAXDIM = 3;
	long naxes[MAXDIM];
	fits_get_img_param(infptr, MAXDIM,  &bitpix, &naxis, naxes, &status);
	if(!isOpened())
		throwException("Error in InputFileFITS::readImage() ", status);


	long fpixel[MAXDIM];
	long nelements = 1;
	for(int dim=0; dim<naxis; dim++)
	{
		fpixel[dim] = 1;
		nelements *= naxes[dim];
	}

	long nulval = 0;
	int anynul;

	buff.data.resize(nelements);
	fits_read_pix(infptr, type, fpixel, nelements, &nulval, &buff.data[0], &anynul, &status);
	if(!isOpened())
		throwException("Error in InputFileFITS::readImage() ", status);

	buff.dim = naxis;

	buff.sizes.resize(0);
	for(int i=0; i<naxis; i++)
		buff.sizes.push_back(naxes[i]);
}
Exemplo n.º 8
0
int main(int argc, char **argv)
{

    int i, iarg, nPix, anynul, status, mask;
    char help[4096];

    fitsfile *iPtr;
    int iBitpix, iNaxis;
    long iNaxes[MAXDIM];
    float *iRData=NULL;

    fitsfile *mPtr;
    int mBitpix, mNaxis;
    long mNaxes[MAXDIM];
    int *mRData=NULL;

    char  *inim=NULL, *maskim=NULL, *outim=NULL;
    float fillVal=D_FILLVAL;

    /* START */
    status  = 0;
    mask    = D_MASK;
    fillVal = D_FILLVAL;

    sprintf(help, "Usage : maskim [options]\n");
    sprintf(help, "%sRequired options:\n", help);
    sprintf(help, "%s   [-inim fitsfile]  : input image\n", help);
    sprintf(help, "%s   [-maskim fitsfile]: corresponding mask image\n", help);
    sprintf(help, "%s   [-outim fitsfile] : output masked image\n\n", help);
    sprintf(help, "%sOptions:\n", help);
    sprintf(help, "%s   [-fi fillval]    : Value of filled pixels (%.3f)\n", help, fillVal);
    sprintf(help, "%s   [-mask hex]      : Mask for bad pixels (0x%x)\n", help, mask);

    /* read in command options. j counts # of required args given */
    for (iarg=1; iarg < argc; iarg++) {
        if (argv[iarg][0]=='-') {
            if (strcasecmp(argv[iarg]+1,"inim")==0) {
                inim = argv[++iarg];
            } else if (strcasecmp(argv[iarg]+1,"maskim")==0) {
                maskim = argv[++iarg];
            } else if (strcasecmp(argv[iarg]+1,"outim")==0) {
                outim = argv[++iarg];
            } else if (strcasecmp(argv[iarg]+1,"fi")==0) {
                sscanf(argv[++iarg], "%f", &fillVal);
            } else if (strcasecmp(argv[iarg]+1,"mask")==0) {
                sscanf(argv[++iarg], "%d", &mask);
            } else {
                fprintf(stderr, "Unknown option : %s\n", argv[iarg]);
                exit(1);
            }
        } else {
            fprintf(stderr, "Unexpected string encountered on command line : %s\n", argv[iarg]);
            exit(1);
        }
    }
    /* read in command options */
    if (argc < 2) {
        fprintf(stderr, "%s\n", help);
        exit(1);
    }

    /* insanity checking */
    if ( !(inim) ) {
        fprintf(stderr, "FATAL ERROR inim is required command line option\n");
        exit(1);
    }
    if ( !(maskim) ) {
        fprintf(stderr, "FATAL ERROR maskim is required command line option\n");
        exit(1);
    }
    if ( !(outim) ) {
        fprintf(stderr, "FATAL ERROR outim is required command line option\n");
        exit(1);
    }

    /* open up, get bitpix, # dimensions, image size */
    if ( fits_open_file(&iPtr, inim, 0, &status) ||
            fits_get_img_param(iPtr, 2, &iBitpix, &iNaxis, iNaxes, &status) ) {
        printError(status);
    }
    if ( fits_open_file(&mPtr, maskim, 0, &status) ||
            fits_get_img_param(mPtr, 2, &mBitpix, &mNaxis, mNaxes, &status) ) {
        printError(status);
    }

    assert(iNaxes[0] == mNaxes[0]);
    assert(iNaxes[1] == mNaxes[1]);

    nPix = iNaxes[0]*iNaxes[1];

    iRData = (float *)realloc(iRData, nPix*sizeof(float));
    mRData = (int *)realloc(mRData, nPix*sizeof(int));
    if (iRData == NULL || mRData == NULL) {
        fprintf(stderr, "Cannot Allocate Standard Data Arrays\n");
        exit (1);
    }
    memset(iRData,   0.0, nPix*sizeof(float));
    memset(mRData,   0x0, nPix*sizeof(int));

    if (fits_read_img(iPtr, TFLOAT, 1, nPix, 0, iRData, &anynul, &status) ||
            fits_read_img(mPtr, TINT,   1, nPix, 0, mRData, &anynul, &status) ||
            fits_close_file(mPtr, &status))
        printError(status);

    /* do the masking */
    for (i = nPix; i--; )
        if (mRData[i] & mask)
            iRData[i] = fillVal;

    /* reuse mptr and help */
    sprintf(help, "!%s", outim);
    if (fits_create_template(&mPtr, help, inim, &status) ||
            fits_write_img(mPtr, TFLOAT, 1, nPix, iRData, &status) ||
            fits_close_file(mPtr, &status) ||
            fits_close_file(iPtr, &status))
        printError(status);

    free(iRData);
    free(mRData);

    return 0;
}
Exemplo n.º 9
0
int main(int argc, char *argv[])
{
    fitsfile *infptr, *outfptr;   /* FITS file pointers defined in fitsio.h */
    int status = 0, ii = 1, iteration = 0, single = 0, hdupos;
    int hdutype, bitpix, bytepix, naxis = 0, nkeys, datatype = 0, anynul;
    long naxes[9] = {1, 1, 1, 1, 1, 1, 1, 1, 1};
    long first, totpix = 0, npix;
    double *array, bscale = 1.0, bzero = 0.0, nulval = 0.;
    char card[81];

    if (argc != 3)
    {
 printf("\n");
 printf("Usage:  imcopy inputImage outputImage[compress]\n");
 printf("\n");
 printf("Copy an input image to an output image, optionally compressing\n");
 printf("or uncompressing the image in the process.  If the [compress]\n");
 printf("qualifier is appended to the output file name then the input image\n");
 printf("will be compressed using the tile-compressed format.  In this format,\n");
 printf("the image is divided into rectangular tiles and each tile of pixels\n");
 printf("is compressed and stored in a variable-length row of a binary table.\n");
 printf("If the [compress] qualifier is omitted, and the input image is\n");
 printf("in tile-compressed format, then the output image will be uncompressed.\n");
 printf("\n");
 printf("If an extension name or number is appended to the input file name, \n");
 printf("enclosed in square brackets, then only that single extension will be\n");
 printf("copied to the output file.  Otherwise, every extension in the input file\n");
 printf("will be processed in turn and copied to the output file.\n");
 printf("\n");
 printf("Examples:\n");
 printf("\n");
 printf("1)  imcopy image.fit 'cimage.fit[compress]'\n");
 printf("\n");
 printf("    This compresses the input image using the default parameters, i.e.,\n");
 printf("    using the Rice compression algorithm and using row by row tiles.\n");
 printf("\n");
 printf("2)  imcopy cimage.fit image2.fit\n");
 printf("\n");
 printf("    This uncompress the image created in the first example.\n");
 printf("    image2.fit should be identical to image.fit if the image\n");
 printf("    has an integer datatype.  There will be small differences\n");
 printf("    in the pixel values if it is a floating point image.\n");
 printf("\n");
 printf("3)  imcopy image.fit 'cimage.fit[compress GZIP 100,100;4]'\n");
 printf("\n");
 printf("    This compresses the input image using the following parameters:\n");
 printf("         GZIP compression algorithm;\n");
 printf("         100 X 100 pixel compression tiles;\n");
 printf("         noise_bits = 4 (only used with floating point images)\n");
 printf("\n");
 printf("The full syntax of the compression qualifier is:\n");
 printf("    [compress ALGORITHM TDIM1,TDIM2,...; NOISE_BITS]\n");
 printf("where the allowed ALGORITHM values are Rice, GZIP, PLIO, \n");
 printf("and TDIMn is the size of the compression tile in each dimension,\n");
 printf("and NOISE_BITS = 1, 2, 3, or 4 and controls the amount of noise\n");
 printf("suppression when compressing floating point images. \n");
 printf("\n");
 printf("Note that it may be necessary to enclose the file names\n");
 printf("in single quote characters on the Unix command line.\n");
      return(0);
    }

    /* Open the input file and create output file */
    fits_open_file(&infptr, argv[1], READONLY, &status);
    fits_create_file(&outfptr, argv[2], &status);

    if (status != 0) {    
        fits_report_error(stderr, status);
        return(status);
    }

    fits_get_hdu_num(infptr, &hdupos);  /* Get the current HDU position */

    /* Copy only a single HDU if a specific extension was given */ 
    if (hdupos != 1 || strchr(argv[1], '[')) single = 1;

    for (; !status; hdupos++)  /* Main loop through each extension */
    {

      fits_get_hdu_type(infptr, &hdutype, &status);

      if (hdutype == IMAGE_HDU) {

          /* get image dimensions and total number of pixels in image */
          for (ii = 0; ii < 9; ii++)
              naxes[ii] = 1;

          fits_get_img_param(infptr, 9, &bitpix, &naxis, naxes, &status);

          totpix = naxes[0] * naxes[1] * naxes[2] * naxes[3] * naxes[4]
             * naxes[5] * naxes[6] * naxes[7] * naxes[8];
      }

      if (hdutype != IMAGE_HDU || naxis == 0 || totpix == 0) { 

          /* just copy tables and null images */
          fits_copy_hdu(infptr, outfptr, 0, &status);

      } else {

          /* Explicitly create new image, to support compression */
          fits_create_img(outfptr, bitpix, naxis, naxes, &status);
          if (status) {
                 fits_report_error(stderr, status);
                 return(status);
          }
	  	    
          /* copy all the user keywords (not the structural keywords) */
          fits_get_hdrspace(infptr, &nkeys, NULL, &status); 

          for (ii = 1; ii <= nkeys; ii++) {
              fits_read_record(infptr, ii, card, &status);
              if (fits_get_keyclass(card) > TYP_CMPRS_KEY)
                  fits_write_record(outfptr, card, &status);
          }

          switch(bitpix) {
              case BYTE_IMG:
                  datatype = TBYTE;
                  break;
              case SHORT_IMG:
                  datatype = TSHORT;
                  break;
              case LONG_IMG:
                  datatype = TINT;
                  break;
              case FLOAT_IMG:
                  datatype = TFLOAT;
                  break;
              case DOUBLE_IMG:
                  datatype = TDOUBLE;
                  break;
          }

          bytepix = abs(bitpix) / 8;

          npix = totpix;
          iteration = 0;

          /* try to allocate memory for the entire image */
          /* use double type to force memory alignment */
          array = (double *) calloc(npix, bytepix);

          /* if allocation failed, divide size by 2 and try again */
          while (!array && iteration < 10)  {
              iteration++;
              npix = npix / 2;
              array = (double *) calloc(npix, bytepix);
          }

          if (!array)  {
              printf("Memory allocation error\n");
              return(0);
          }

          /* turn off any scaling so that we copy the raw pixel values */
          fits_set_bscale(infptr,  bscale, bzero, &status);
          fits_set_bscale(outfptr, bscale, bzero, &status);

          first = 1;
          while (totpix > 0 && !status)
          {
             /* read all or part of image then write it back to the output file */
             fits_read_img(infptr, datatype, first, npix, 
                     &nulval, array, &anynul, &status);

             fits_write_img(outfptr, datatype, first, npix, array, &status);
             totpix = totpix - npix;
             first  = first  + npix;
          }
          free(array);
      }

      if (single) break;  /* quit if only copying a single HDU */
      fits_movrel_hdu(infptr, 1, NULL, &status);  /* try to move to next HDU */
    }

    if (status == END_OF_FILE)  status = 0; /* Reset after normal error */

    fits_close_file(outfptr,  &status);
    fits_close_file(infptr, &status);

    /* if error occurred, print out error message */
    if (status)
       fits_report_error(stderr, status);
    return(status);
}
Exemplo n.º 10
0
std::vector<ImportDescriptor*> FitsImporter::getImportDescriptors(const std::string& fname)
{
   std::string filename = fname;
   std::vector<std::vector<std::string> >& errors = mErrors[fname];
   std::vector<std::vector<std::string> >& warnings = mWarnings[fname];
   errors.clear();
   warnings.clear();
   int status=0;
   std::vector<ImportDescriptor*> descriptors;

   FitsFileResource pFile(filename);
   if (!pFile.isValid())
   {
      errors.resize(1);
      errors[0].push_back(pFile.getStatus());
      RETURN_DESCRIPTORS;
   }

   int hduCnt = 0;
   int specificHdu = 0;
   int hdu = 1;
   if (!splitFilename(filename, hduCnt, specificHdu, hdu, pFile, errors, warnings))
   {
      RETURN_DESCRIPTORS;
   }
   errors.resize(hduCnt+1);
   warnings.resize(hduCnt+1);

   for(; hdu <= hduCnt; ++hdu)
   {
      std::string datasetName = filename + "[" + StringUtilities::toDisplayString(hdu) + "]";
      int hduType;
      CHECK_FITS(fits_movabs_hdu(pFile, hdu, &hduType, &status), hdu, false, continue);
      ImportDescriptorResource pImportDescriptor(static_cast<ImportDescriptor*>(NULL));
      FactoryResource<DynamicObject> pMetadata;
      VERIFYRV(pMetadata.get() != NULL, descriptors);
      { // scope
         std::vector<std::string> comments;
         char pCard[81];
         char pValue[81];
         char pComment[81];
         int nkeys = 0;
         CHECK_FITS(fits_get_hdrspace(pFile, &nkeys, NULL, &status), hdu, true, ;);
         for(int keyidx = 1; keyidx <= nkeys; ++keyidx)
         {
            CHECK_FITS(fits_read_keyn(pFile, keyidx, pCard, pValue, pComment, &status), hdu, true, continue);
            std::string name = StringUtilities::stripWhitespace(std::string(pCard));
            std::string val = StringUtilities::stripWhitespace(std::string(pValue));
            std::string comment = StringUtilities::stripWhitespace(std::string(pComment));
            if (!val.empty())
            {
               pMetadata->setAttributeByPath("FITS/" + name, val);
            }
            else if (!comment.empty())
            {
               comments.push_back(comment);
            }
         }
         if (!comments.empty())
         {
            // ideally, this would add a multi-line string but Opticks doesn't display this properly
            // pMetadata->setAttributeByPath("FITS/COMMENT", StringUtilities::join(comments, "\n"));
            for(unsigned int idx = 0; idx < comments.size(); ++idx)
            {
               pMetadata->setAttributeByPath("FITS/COMMENT/" + StringUtilities::toDisplayString(idx), comments[idx]);
            }
         }
      }
      switch(hduType)
      {
      case IMAGE_HDU:
      {
         pImportDescriptor = ImportDescriptorResource(datasetName, TypeConverter::toString<RasterElement>());
         VERIFYRV(pImportDescriptor.get() != NULL, descriptors);

         EncodingType fileEncoding;
         InterleaveFormatType interleave(BSQ);
         unsigned int rows=0;
         unsigned int cols=0;
         unsigned int bands=1;

         int bitpix;
         int naxis;
         long axes[3];
         CHECK_FITS(fits_get_img_param(pFile, 3, &bitpix, &naxis, axes, &status), hdu, false, continue);
         switch(bitpix)
         {
         case BYTE_IMG:
            fileEncoding = INT1UBYTE;
            break;
         case SHORT_IMG:
            fileEncoding = INT2SBYTES;
            break;
         case LONG_IMG:
            fileEncoding = INT4SBYTES;
            break;
         case FLOAT_IMG:
            fileEncoding = FLT4BYTES;
            break;
         case DOUBLE_IMG:
            fileEncoding = FLT8BYTES;
            break;
         default:
            warnings[hdu].push_back("Unsupported BITPIX value " + StringUtilities::toDisplayString(bitpix) + ".");
            continue;
         }
         EncodingType dataEncoding = checkForOverflow(fileEncoding, pMetadata.get(), hdu, errors, warnings);
         if (naxis == 1)
         {
            // 1-D data is a signature
            pImportDescriptor = ImportDescriptorResource(datasetName, TypeConverter::toString<Signature>());
            pMetadata->setAttributeByPath(METADATA_SIG_ENCODING, dataEncoding);
            pMetadata->setAttributeByPath(METADATA_SIG_LENGTH, axes[0]);

            RasterUtilities::generateAndSetFileDescriptor(pImportDescriptor->getDataDescriptor(), filename,
               StringUtilities::toDisplayString(hdu), BIG_ENDIAN_ORDER);

            // add units
            SignatureDataDescriptor* pSigDd =
               dynamic_cast<SignatureDataDescriptor*>(pImportDescriptor->getDataDescriptor());
            if (pSigDd != NULL)
            {
               FactoryResource<Units> pUnits;
               pUnits->setUnitName("Custom");
               pUnits->setUnitType(CUSTOM_UNIT);
               pSigDd->setUnits("Reflectance", pUnits.get());
            }

            break; // leave switch()
         }
         else if (naxis == 2)
         {
            cols = axes[0];
            rows = axes[1];
         }
         else if (naxis == 3)
         {
            cols = axes[0];
            rows = axes[1];
            bands = axes[2];
         }
         else
         {
            errors[hdu].push_back(StringUtilities::toDisplayString(naxis) + " axis data not supported.");
         }

         RasterDataDescriptor* pDataDesc = RasterUtilities::generateRasterDataDescriptor(
            datasetName, NULL, rows, cols, bands, interleave, dataEncoding, IN_MEMORY);
         pImportDescriptor->setDataDescriptor(pDataDesc);
         if (specificHdu == 0 && hdu == 1 && naxis == 2 && (axes[0] <= 5 || axes[1] <= 5))
         {
            // use 5 as this is a good top end for the number of astronomical band pass filters
            // in general usage. this is not in a spec anywhere and is derived from various sample
            // FITS files for different astronomical instruments.
            //
            // There's a good chance this is really a spectrum. (0th HDU)
            // We'll create an import descriptor for the spectrum version of this
            // And disable the raster descriptor by default
            pImportDescriptor->setImported(false);
            ImportDescriptorResource pSigDesc(datasetName, TypeConverter::toString<SignatureLibrary>());
            DynamicObject* pSigMetadata = pSigDesc->getDataDescriptor()->getMetadata();
            pSigMetadata->merge(pMetadata.get());
            std::vector<double> centerWavelengths;
            unsigned int cnt = (axes[0] <= 5) ? axes[1] : axes[0];
            double startVal = StringUtilities::fromDisplayString<double>(
               dv_cast<std::string>(pMetadata->getAttributeByPath("FITS/MINWAVE"), "0.0"));
            double endVal = StringUtilities::fromDisplayString<double>(
               dv_cast<std::string>(pMetadata->getAttributeByPath("FITS/MAXWAVE"), "0.0"));
            double incr = (endVal == 0.0) ? 1.0 : ((endVal - startVal) / static_cast<double>(cnt));
            centerWavelengths.reserve(cnt);
            for (unsigned int idx = 0; idx < cnt; idx++)
            {
               centerWavelengths.push_back(startVal + (idx * incr));
            }
            pSigMetadata->setAttributeByPath(CENTER_WAVELENGTHS_METADATA_PATH, centerWavelengths);

            // Units
            std::string unitsName = dv_cast<std::string>(pMetadata->getAttributeByPath("FITS/BUNIT"), std::string());
            if (!unitsName.empty())
            {
               FactoryResource<Units> units;
               units->setUnitName(unitsName);
               units->setUnitType(RADIANCE);
               SignatureDataDescriptor* pSigDd =
                  dynamic_cast<SignatureDataDescriptor*>(pSigDesc->getDataDescriptor());
               if (pSigDd != NULL)
               {
                  pSigDd->setUnits("Reflectance", units.get());
               }
            }

            RasterUtilities::generateAndSetFileDescriptor(pSigDesc->getDataDescriptor(),
               filename, StringUtilities::toDisplayString(hdu), BIG_ENDIAN_ORDER);

            // If units are not available, set custom units into the data descriptor so that the user can
            // modify them - this must occur after the call to RasterUtilities::generateAndSetFileDescriptor()
            // so that the file descriptor will still display no defined units
            if (unitsName.empty())
            {
               FactoryResource<Units> units;
               units->setUnitName("Custom");
               units->setUnitType(CUSTOM_UNIT);
               SignatureDataDescriptor* pSigDd = dynamic_cast<SignatureDataDescriptor*>(pSigDesc->getDataDescriptor());
               if (pSigDd != NULL)
               {
                  pSigDd->setUnits("Reflectance", units.get());
               }
            }

            descriptors.push_back(pSigDesc.release());
         }

         RasterFileDescriptor* pFileDescriptor = dynamic_cast<RasterFileDescriptor*>(
            RasterUtilities::generateAndSetFileDescriptor(pDataDesc, filename,
            StringUtilities::toDisplayString(hdu), BIG_ENDIAN_ORDER));
         if (pFileDescriptor != NULL)
         {
            unsigned int bitsPerElement = RasterUtilities::bytesInEncoding(fileEncoding) * 8;
            pFileDescriptor->setBitsPerElement(bitsPerElement);
         }

         break; // leave switch()
      }
      case ASCII_TBL:
      case BINARY_TBL:
         warnings[hdu].push_back("Tables not supported. [HDU " + StringUtilities::toDisplayString(hdu) + "]");
         continue;
      default:
         warnings[hdu].push_back("HDU " + StringUtilities::toDisplayString(hdu) + " is an unknown type.");
         continue;
      }

      pImportDescriptor->getDataDescriptor()->setMetadata(pMetadata.release());
      pImportDescriptor->setImported(errors[hdu].empty());
      descriptors.push_back(pImportDescriptor.release());
   }
Exemplo n.º 11
0
void readFITS(const std::string& fitsname, cv::Mat& cvImage)
{
  fitsfile *fptr = nullptr;
  int status(0);
  char err_text[100];
  //READONLY, READWRITE

  fits_open_file(&fptr, fitsname.c_str(), READONLY, &status);
  if (status)
  {
    fits_report_error(stdout, status);
    fits_get_errstatus(status,err_text);
    fptr = nullptr;
    std::cout << "readFITS: Unable to open the fits file." << std::endl;
    throw  CustomException("readFITS: Unable to open the fits file.");
  }

  //turn off scaling so we read the raw pixel value
  double bscale_ = 1.0, bzero_ = 0.0;
  fits_set_bscale(fptr,  bscale_, bzero_, &status);
  int bitpix, naxis;
  int maxdim(3);
  long naxes[] = {1,1, 1};

  fits_get_img_param(fptr, maxdim,  &bitpix, &naxis, naxes, &status);
  if (status)
  {
    fits_report_error(stdout, status);
    fits_get_errstatus(status,err_text);
    fptr = nullptr;
    std::cout << "readFITS: Unable to get params from FITS." << std::endl;
    throw  CustomException("readFITS: Unable to get params from FITS.");
  }
  
  if(naxis == 2)
  {
    //  TBYTE, TSBYTE, TSHORT, TUSHORT, TINT, TUINT, TLONG, TLONGLONG, TULONG, TFLOAT, TDOUBLE
    long fpixel[] = {1, 1};
    long lpixel[] = {naxes[0], naxes[1]};
    long inc[] = {1, 1};
    long nelements = naxes[0] * naxes[1];
    double *array = new double[nelements];

    fits_read_subset(fptr, TDOUBLE, fpixel, lpixel, inc, nullptr,  array, nullptr, &status);
    if (status)
    {
      fits_report_error(stdout, status);
      fits_get_errstatus(status,err_text);
      fptr = nullptr;
      delete[] array;
      throw  CustomException("readFITS: Unable to read the fits file.");
    }

    //it seems cfitsio interprets image axes in the oppsite way of opencv
    cvImage = cv::Mat(naxes[1], naxes[0], cv::DataType<double>::type, array);

    fits_close_file(fptr, &status);
    if (status)
    {
      fits_report_error(stdout, status);
      fits_get_errstatus(status,err_text);
      fptr = nullptr;
      delete[] array;
      throw  CustomException("readFITS: Cannot close fits file.");
    } 
  }
  
  if(naxis == 3)
  {
     //  TBYTE, TSBYTE, TSHORT, TUSHORT, TINT, TUINT, TLONG, TLONGLONG, TULONG, TFLOAT, TDOUBLE
    long layer = 29;   //Only consider the first layer
    long fpixel[] = {1, 1, layer};
    long lpixel[] = {naxes[0], naxes[1], layer};
    long inc[] = {1, 1, 1};
    long nelements = naxes[0] * naxes[1];
    double *array = new double[nelements];

    fits_read_subset(fptr, TDOUBLE, fpixel, lpixel, inc, nullptr,  array, nullptr, &status);
    if (status)
    {
      fits_report_error(stdout, status);
      fits_get_errstatus(status,err_text);
      fptr = nullptr;
      delete[] array;
      throw  CustomException("readFITS: Unable to read the fits file.");
    }

    //it seems cfitsio interprets image axes in the oppsite way of opencv
    cvImage = cv::Mat(naxes[1], naxes[0], cv::DataType<double>::type, array);

    fits_close_file(fptr, &status);
    if (status)
    {
      fits_report_error(stdout, status);
      fits_get_errstatus(status,err_text);
      fptr = nullptr;
      delete[] array;
      throw  CustomException("readFITS: Cannot close fits file.");
    } 
  }
}
Exemplo n.º 12
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;
}
Exemplo n.º 13
0
bool FITSImage::loadFITS ( const QString &inFilename, QProgressDialog *progress )
{
    int status=0, nulval=0, anynull=0;
    long fpixel[2], nelements, naxes[2];
    char error_status[512];

    qDeleteAll(starCenters);
    starCenters.clear();

    if (mode == FITS_NORMAL && progress)
    {
        progress->setLabelText(i18n("Please hold while loading FITS file..."));
        progress->setWindowTitle(i18n("Loading FITS"));
    }

    if (mode == FITS_NORMAL && progress)
        progress->setValue(30);

    if (fptr)
    {

        fits_close_file(fptr, &status);

        if (tempFile)
            QFile::remove(filename);
    }

    filename = inFilename;

    if (filename.contains("/tmp/"))
        tempFile = true;
    else
        tempFile = false;

    filename.remove("file://");


    if (fits_open_image(&fptr, filename.toAscii(), READONLY, &status))
    {
        fits_report_error(stderr, status);
        fits_get_errstatus(status, error_status);
        if (progress)
            KMessageBox::error(0, i18n("Could not open file %1 (fits_get_img_param). Error %2", filename, QString::fromUtf8(error_status)), i18n("FITS Open"));
        return false;
    }


    if (mode == FITS_NORMAL && progress)
        if (progress->wasCanceled())
            return false;

    if (mode == FITS_NORMAL && progress)
        progress->setValue(40);


    if (fits_get_img_param(fptr, 2, &(stats.bitpix), &(stats.ndim), naxes, &status))
    {
        fits_report_error(stderr, status);
        fits_get_errstatus(status, error_status);

        if (progress)
            KMessageBox::error(0, i18n("FITS file open error (fits_get_img_param): %1", QString::fromUtf8(error_status)), i18n("FITS Open"));
        return false;
    }

    if (stats.ndim < 2)
    {
        if (progress)
            KMessageBox::error(0, i18n("1D FITS images are not supported in KStars."), i18n("FITS Open"));
        return false;
    }


    if (fits_get_img_type(fptr, &data_type, &status))
    {
        fits_report_error(stderr, status);
        fits_get_errstatus(status, error_status);

        if (progress)
            KMessageBox::error(0, i18n("FITS file open error (fits_get_img_type): %1", QString::fromUtf8(error_status)), i18n("FITS Open"));
        return false;
    }

    if (mode == FITS_NORMAL && progress)
        if (progress->wasCanceled())
            return false;

    if (mode == FITS_NORMAL && progress)
        progress->setValue(60);

    stats.dim[0] = naxes[0];
    stats.dim[1] = naxes[1];

    delete (image_buffer);
    image_buffer = NULL;

    image_buffer = new float[stats.dim[0] * stats.dim[1]];

    if (image_buffer == NULL)
    {
        qDebug() << "Not enough memory for image_buffer";
        return false;
    }
    if (mode == FITS_NORMAL && progress)
    {
        if (progress->wasCanceled())
        {
        delete (image_buffer);
        return false;
        }
    }

    if (mode == FITS_NORMAL && progress)
        progress->setValue(70);

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

    qApp->processEvents();

    if (fits_read_2d_flt(fptr, 0, nulval, naxes[0], naxes[0], naxes[1], image_buffer, &anynull, &status))
    {
        fprintf(stderr, "fits_read_pix error\n");
        fits_report_error(stderr, status);
        return false;
    }

    if (mode == FITS_NORMAL && progress)
    {
        if (progress->wasCanceled())
        {
            delete (image_buffer);
            return false;
        }
    }

    calculateStats();

    if (mode == FITS_NORMAL && progress)
        progress->setValue(80);

    //currentWidth  = stats.dim[0];
   // currentHeight = stats.dim[1];

    qApp->processEvents();

    if (mode == FITS_NORMAL)
    {
        checkWCS();

        if (progress)
            progress->setValue(90);
    }

    if (mode == FITS_NORMAL && progress)
    {
        if (progress->wasCanceled())
        {
            delete (image_buffer);
            return false;
        }
    }

    if (mode == FITS_NORMAL && progress)
        progress->setValue(100);

    starsSearched = false;

    return true;

}
Exemplo n.º 14
0
int main(int argc, char *argv[])
{
  fitsfile *fptr = 0;         /* FITS file pointer, defined in fitsio.h */
  char keyname[FLEN_KEYWORD], colname[FLEN_VALUE], coltype[FLEN_VALUE];
  int status = 0;   /* CFITSIO status value MUST be initialized to zero! */
  int single = 0, hdupos = 0, hdutype = 0, bitpix = 0, naxis = 0, ncols = 0, ii = 0;
  long naxes[10], nrows = 0;

  int printhelp = (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0));

  if (printhelp || argc != 2) {
    fprintf(stderr, "Usage:  %s filename[ext] \n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "List the structure of a single extension, or, if ext is \n");
    fprintf(stderr, "not given, list the structure of the entire FITS file.  \n");
    fprintf(stderr, "\n");
    fprintf(stderr, "Note that it may be necessary to enclose the input file\n");
    fprintf(stderr, "name in single quote characters on the Unix command line.\n");
    return (0);
  }

  FILE *fout = popen(PAGER, "w");
  if (fout == NULL) {
    fprintf(stderr, "Could not execute '%s'\n", PAGER);
    return (1);
  }

  if (!fits_open_file(&fptr, argv[1], READONLY, &status)) {
    fits_get_hdu_num(fptr, &hdupos);  /* Get the current HDU position */

    /* List only a single structure if a specific extension was given */
    if (strchr(argv[1], '[') || strchr(argv[1], '+')) {
      single++;
    }

    for (; !status; hdupos++) { /* Main loop for each HDU */
      fits_get_hdu_type(fptr, &hdutype, &status);  /* Get the HDU type */

      fprintf(fout, "\nHDU #%d  ", hdupos);
      if (hdutype == IMAGE_HDU) { /* primary array or image HDU */
        fits_get_img_param(fptr, 10, &bitpix, &naxis, naxes, &status);

        fprintf(fout, "Array:  NAXIS = %d,  BITPIX = %d\n", naxis, bitpix);
        for (ii = 0; ii < naxis; ii++) {
          fprintf(fout, "   NAXIS%d = %ld\n",ii+1, naxes[ii]);
        }
      } else { /* a table HDU */
        fits_get_num_rows(fptr, &nrows, &status);
        fits_get_num_cols(fptr, &ncols, &status);

        if (hdutype == ASCII_TBL) {
          fprintf(fout, "ASCII Table:  ");
        } else {
          fprintf(fout, "Binary Table:  ");
        }

        fprintf(fout, "%d columns x %ld rows\n", ncols, nrows);
        fprintf(fout, " COL NAME             FORMAT\n");

        for (ii = 1; ii <= ncols; ii++) {
          fits_make_keyn("TTYPE", ii, keyname, &status); /* make keyword */
          fits_read_key(fptr, TSTRING, keyname, colname, NULL, &status);
          fits_make_keyn("TFORM", ii, keyname, &status); /* make keyword */
          fits_read_key(fptr, TSTRING, keyname, coltype, NULL, &status);

          fprintf(fout, " %3d %-16s %-16s\n", ii, colname, coltype);
        }
      }

      if (single) {
        break;  /* quit if only listing a single HDU */
      }

      fits_movrel_hdu(fptr, 1, NULL, &status);  /* try move to next ext */
    }

    if (status == END_OF_FILE) {
      status = 0;  /* Reset normal error */
    }
    fits_close_file(fptr, &status);
  }

  pclose(fout);

  if (status) {
    fits_report_error(stderr, status);  /* print any error message */
  }
  return (status);
}
Exemplo n.º 15
0
int read_kpvt(
      char *input_file_name,
      char *aux_file,
      int verbose_flag,
      int minmax_flag)
{

   int status = 0;

   /*
    * If the Compiler macro FITS is not defined, that means the makefile
    * determined that libcfitsio.a was not available.  Instead of shutting down
    * the entire converter Lets just disable any read routines thatt depend on
    * the FITS library
    *
    */

#ifdef FITS

   extern int linear_minmax_search(float *, int, float *, float *);

   fitsfile *fits_filePtr;
   char header_buffer[FLEN_CARD ];

   float operand1;

   int i, j;
   int number_of_fits_header_keys;
   int number_of_fits_hdus;
   int hdu_type;
   int bit_pix;
   long naxes[10];
   int maxdim = 10;
   long fpixel[10];
   float missing_val = 256*256*256;
   int anynul;
   float net_flux_2d_static[180][360];
   float net_flux_2d_static_flat[64800];
   float total_flux_2d_static[180][360];
   float total_flux_2d_static_flat[64800];
   float weights_2d_static[180][360];
   float weights_2d_static_flat[64800];

   /** open fits file **/

   fits_open_file( &fits_filePtr, input_file_name, READONLY, &status);

   /** get number_of_fits_header_keys **/

   fits_get_hdrspace(fits_filePtr, &number_of_fits_header_keys, NULL, &status);

   /** get the number of hdu's in the current file **/

   fits_get_num_hdus(fits_filePtr, &number_of_fits_hdus, &status);

   printf("FITS File: %s has %d hdu's\n", input_file_name, number_of_fits_hdus);

   /** for every hdu **/

   for (i=0; i<number_of_fits_hdus; i++)
   {
      /** select hdu by number **/

      fits_movabs_hdu(fits_filePtr, number_of_fits_hdus, &hdu_type, &status);

      /** there are three type of hdu's
       * IMAGE_HDU
       * ACSII_TBL
       * BINARY_TBL
       * ********************************/

      if (hdu_type == IMAGE_HDU)
      {
         printf("Current HDU Type is IMAGE\n");

         /*** get general info about the current image file ***/

         fits_get_img_param(
               fits_filePtr,
               maxdim,
               &bit_pix,
               &naxis,
               naxes,
               &status);

         printf("bitpix = %d\nnaxis = %d\n", bit_pix, naxis);

         if (DEBUG_FLAG)
         {
            for (i = 0; i<naxis; i++)
               printf("naxis[%d] = %ld\n", i, naxes[i]);
         }

         naxis1 = naxes[0];
         naxis2 = naxes[1];

         number_of_elements = naxis1 * naxis2;

         /** dynamically allocate space for the image grid **/

         carrington_longitiude = malloc(naxis1 * sizeof(float));
         carrington_sine_latitude = malloc(naxis2 * sizeof(float));

         /** dynamically allocate space for the flat variable arrays **/

         net_flux = malloc(number_of_elements * sizeof(float));
         total_flux = malloc(number_of_elements * sizeof(float));
         weights = malloc(number_of_elements * sizeof(float));

         /** manually insert sequential grid values from 1 - naxes[*] **/

         operand1 = 2.0 / naxis2;
         if (DEBUG_FLAG)
         {
            printf(
                  "\n\n\n\n\n\nWTF: operand1 = %f\nnaxis2 = %d\n",
                  operand1,
                  naxis2);
         }

         for (i=0; i < naxis2; i++)
         {

            /** convert to sine latidude **/
            /*
             carrington_sine_latitude[i] = i+1;
             */
            carrington_sine_latitude[i] = (-1.0)
                  + (operand1 * ( (i + 1 ) - .5 ) );

            if (DEBUG_FLAG)
               printf("%d deg = %f\n", i+1, carrington_sine_latitude[i]);

         }

         for (i=0; i < naxis1; i++)
         {
            carrington_longitiude[i] = i+1;

            if (DEBUG_FLAG)
               printf("%d deg = %f deg\n", i+1, carrington_longitiude[i]);
         }

         /** print position values **/

         for (i=0; i<naxis2; i+=30)
         {
            for (j=0; j<naxis1; j+=30)
            {
               if (DEBUG_FLAG)
               {
                  printf(
                        "position[%f][%f]\n",
                        carrington_sine_latitude[i],
                        carrington_longitiude[j]);
               }
            }
         }

         /** print c_lon values **/

         for (i=0; i<naxis1; i++)
         {

            if( DEBUG_FLAG ) printf("c_lon[%d] = %f  ", i, carrington_longitiude[i]);

         }

         /** print c_sine_lat values **/

         for (i=0; i<naxis2; i++)
         {

            if( DEBUG_FLAG ) printf("c_sine_lat[%d] = %f  ", i, carrington_sine_latitude[i]);

         }

         /** dynamically allocate memory for the three image slices that we
          * expect - we must reverse the majority since the fits api expects
          * array[column][row] **/

         net_flux_2d = malloc(naxis1 * sizeof(float *));
         for (i=0; i< naxis1; i++)
         {
            net_flux_2d[i] = malloc(naxis2 * sizeof(float));
         }

         total_flux_2d = malloc(naxis2 * sizeof(float *));
         for (i=0; i< naxis2; i++)
         {
            total_flux_2d[i] = malloc(naxis1 * sizeof(float));
         }

         weights_2d = malloc(naxis2 * sizeof(float *));
         for (i=0; i< naxis2; i++)
         {
            weights_2d[i] = malloc(naxis1 * sizeof(float));
         }

         /*** read in the image data ***/

         /** this is the starting point for the read - slice one - net flux **/

         fpixel[0] = fpixel[1] = fpixel[2]= 1;
         if( DEBUG_FLAG ) printf(
               "\nfpixel[0] = %ld\nfpixel[1] = %ld\nfpixel[2] = %ld\nnumber_of_elements = %ld\n\n",
               fpixel[0],
               fpixel[1],
               fpixel[2],
               number_of_elements);
         /*
          fits_read_pix( fits_filePtr, TFLOAT, fpixel, number_of_elements,
          &missing_val, *net_flux_2d, &anynul, &status );
          */
         fits_read_pix(
               fits_filePtr,
               TFLOAT,
               fpixel,
               number_of_elements,
               &missing_val,
               net_flux_2d_static,
               &anynul,
               &status);

         /** this is the starting point for the read - slice two - total flux */

         fpixel[2] = 2;
         if( DEBUG_FLAG )  printf(
               "fpixel[0] = %ld\nfpixel[1] = %ld\nfpixel[2] = %ld\nnumber_of_elements = %ld\n\n",
               fpixel[0],
               fpixel[1],
               fpixel[2],
               number_of_elements);
         /*
          * fits_read_pix( fits_filePtr, TFLOAT, fpixel, number_of_elements,
          * &missing_val, *total_flux_2d, &anynul, &status );
          *
          */

         fits_read_pix(
               fits_filePtr,
               TFLOAT,
               fpixel,
               number_of_elements,
               &missing_val,
               total_flux_2d_static,
               &anynul,
               &status);

         /** this is the starting point for the read - slice three - weights **/

         fpixel[2] = 3;
         if( DEBUG_FLAG )printf(
               "fpixel[0] = %ld\nfpixel[1] = %ld\nfpixel[2] = %ld\nnumber_of_elements = %ld\n\n",
               fpixel[0],
               fpixel[1],
               fpixel[2],
               number_of_elements);
         /*
          * fits_read_pix( fits_filePtr, TFLOAT, fpixel, number_of_elements,
          * &missing_val, *weights_2d, &anynul, &status );
          *
          */

         fits_read_pix(
               fits_filePtr,
               TFLOAT,
               fpixel,
               number_of_elements,
               &missing_val,
               weights_2d_static,
               &anynul,
               &status);

         /** flatten out arrays **/

         for (i=0; i<naxis2; i++)
         {
            for (j=0; j<naxis1; j++)
            {
               /*
                net_flux[ i * naxis1 + j] = net_flux_2d_static[i][j];
                total_flux[ i * naxis1 + j] = total_flux_2d[i][j];
                weights[ i * naxis1 + j] = weights_2d[i][j];
                */
               net_flux[ i * naxis1 + j] = net_flux_2d_static[i][j];
               total_flux[ i * naxis1 + j] = total_flux_2d_static[i][j];
               weights[ i * naxis1 + j] = weights_2d_static[i][j];

            }
         }

         /*** DEBUG PRINT OUT OF VALUES ***/

         /*
          for( i=0;i<naxis2;i+=20)
          {
          for( j=0;j<naxis1;j+=20)
          {

          printf( "net_flux[%d][%d] = %f\n", i,j, net_flux[i * naxis1 + j] );
          printf( "net_flux_2d[%d][%d] = %f\n", i,j, net_flux_2d[i][j] );
          printf( "net_flux_2d_static[%d][%d] = %f\n", i,j, net_flux_2d_static[i][j] );
          printf( "net_flux_2d_static_flat[%d][%d] = %f\n", i,j, net_flux_2d_static_flat[i * naxis1 + j] );
          printf( "total_flux[%d][%d] = %f\n", i,j, total_flux[i * naxis1 + j] );
          printf( "total_flux_2d[%d][%d] = %f\n", i,j, total_flux_2d[i][j] );
          printf( "weights[%d][%d] = %f\n", i,j, weights[i * naxis1 + j] );
          printf( "weights_2d[%d][%d] = %f\n\n", i,j, weights_2d[i][j] );


          }
          }
          */

      }
      else if (hdu_type == ASCII_TBL)
      {
         printf("Current HDU Type is ACSII TABLE\n");
      }
      else if (hdu_type == BINARY_TBL)
      {
         printf("Current HDU Type is BINARY TABLE\n");
      }

      /*** get the header info for the current hdu ***/

      for (i = 0; i < number_of_fits_header_keys; i++)
      {
         fits_read_record(fits_filePtr, i, header_buffer, &status);
         printf("%s\n", header_buffer);
      }

   }

   /** close fits file **/

   fits_close_file(fits_filePtr, &status);

   if (status)
   {
      fits_report_error( stderr, status);
   }

   /*
    * calcluate actual min/max values for each ariable unless -nominmax flag was
    * specified
    *
    */

   /** add more error handling for each linear_minmax_search function call **/

   /*** if -nominmax option was NOT specified ***/

   if ( !minmax_flag)
   {

      if (verbose_flag)
      {
         printf("\ncalculating actual minimum & maximum values for each variable ...\n");
      }

      if (verbose_flag)
      {
         printf("%-25s%-25s%-25s\n", "", "min", "max");
      }

      linear_minmax_search(
            carrington_longitiude,
            naxis1,
            &carrington_longitiude_actual_min,
            &carrington_longitiude_actual_max);
      if (verbose_flag)
      {
         printf(
               "%-25s%-25g%-25g\n",
               "c_lon",
               carrington_longitiude_actual_min,
               carrington_longitiude_actual_max);
      }

      linear_minmax_search(
            carrington_sine_latitude,
            naxis2,
            &carrington_sine_latitude_actual_min,
            &carrington_sine_latitude_actual_max);
      if (verbose_flag)
      {
         printf(
               "%-25s%-25g%-25g\n",
               "c_sine_lat",
               carrington_sine_latitude_actual_min,
               carrington_sine_latitude_actual_max);
      }

      linear_minmax_search(
            net_flux,
            number_of_elements,
            &net_flux_actual_min,
            &net_flux_actual_max);
      if (verbose_flag)
      {
         printf(
               "%-25s%-25g%-25g\n",
               "net_flux",
               net_flux_actual_min,
               net_flux_actual_max);
      }

      linear_minmax_search(
            total_flux,
            number_of_elements,
            &total_flux_actual_min,
            &total_flux_actual_max);
      if (verbose_flag)
      {
         printf(
               "%-25s%-25g%-25g\n",
               "total_flux",
               total_flux_actual_min,
               total_flux_actual_max);
      }

      linear_minmax_search(
            weights,
            number_of_elements,
            &weights_actual_min,
            &weights_actual_max);
      if (verbose_flag)
      {
         printf(
               "%-25s%-25g%-25g\n",
               "weights",
               weights_actual_min,
               weights_actual_max);
      }

   }

#endif

#ifndef FITS
   printf("\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
   printf("!! WARNING: from %s line [%d]. Conversion Software was not compiled and linked with netCDF libraries ( libcfitsio.a ).  No .fts FITS files will be ingested... \n", __FILE__, __LINE__ );
   return EXIT_FAILURE;
#endif

   return status;

}
Exemplo n.º 16
0
Arquivo: data.c Projeto: glenco/lensed
void read_fits(const char* filename, int datatype, size_t* width, size_t* height, void** image)
{
    int status = 0;
    
    // the FITS file
    fitsfile* fptr;
    
    // metadata
    int bitpix;
    int naxis;
    long naxes[2];
    
    // total number of pixels
    long npix;
    
    // reading offset
    long fpixel[2] = { 1, 1 };
    
    // size of output image pixels
    size_t spix = 0;
    
    // open FITS file
    fits_open_image(&fptr, filename, READONLY, &status);
    if(status)
        fits_error(filename, status);
    
    // get metadata
    fits_get_img_param(fptr, 2, &bitpix, &naxis, naxes, &status);
    if(status)
        fits_error(filename, status);
    
    // check dimension of image
    if(naxis != 2)
        errorf(filename, 0, "file has %d axes (should be 2)", naxis);
    
    // set dimensions
    *width = naxes[0];
    *height = naxes[1];
    
    // size of output pixels
    switch(datatype)
    {
        case TINT:
            spix = sizeof(int);
            break;
            
        case TFLOAT:
            spix = sizeof(float);
            break;
            
        case TDOUBLE:
            spix = sizeof(double);
            break;
            
        default:
            error("read_fits(): datatype %d not implemented", datatype);
    }
    
    // create array for pixels
    npix = naxes[0]*naxes[1];
    *image = malloc(npix*spix);
    if(!*image)
        errori(NULL);
    
    // read pixels into array
    fits_read_pix(fptr, datatype, fpixel, npix, NULL, *image, NULL, &status);
    if(status)
        fits_error(filename, status);
    
    // close file again
    fits_close_file(fptr, &status);
    if(status)
        fits_error(filename, status);
}
Exemplo n.º 17
0
int main(int argc, char *argv[])
{
  fitsfile *fptr = 0;   /* FITS file pointer, defined in fitsio.h */
  int status = 0;   /* CFITSIO status value MUST be initialized to zero! */
  int bitpix = 0, naxis = 0, ii = 0, d = 0;
  long naxes[9] = {1,1,1,1,1,1,1,1,1}, fpixel[9] = {1,1,1,1,1,1,1,1,1};
  double *pixels = 0;
  char format[20], hdformat[20];

  int printhelp = (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0));

  if (printhelp || argc != 2) {
    fprintf(stderr, "Usage:  %s filename[ext][section filter] \n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "List the the pixel values in a FITS array \n");
    fprintf(stderr, "\n");
    fprintf(stderr, "Example: \n");
    fprintf(stderr, "  %s array.fits                    - list the whole array\n", argv[0]);
    fprintf(stderr, "  %s array.fits[100:110,400:410]   - list a section\n", argv[0]);
    fprintf(stderr, "  %s table.fits[2][bin (x,y) = 32] - list the pixels in\n", argv[0]);
    fprintf(stderr, "         an array constructed from a 2D histogram of X and Y\n");
    fprintf(stderr, "         columns in a table with a binning factor = 32\n");
    return (0);
  }

  FILE *fout = popen(PAGER, "w");
  if (fout == NULL) {
    fprintf(stderr, "Could not execute '%s'\n", PAGER);
    return (1);
  }

  if (!fits_open_file(&fptr, argv[1], READONLY, &status)) {
    if (!fits_get_img_param(fptr, 9, &bitpix, &naxis, naxes, &status)) {
      if (naxis > 9 || naxis == 0) {
        fprintf(stderr, "Error: only 1- to 9-dimensional arrays are supported\n");
      } else {
        /* get memory for 1 row */
        pixels = (double *) malloc(naxes[0] * sizeof(double));

        if (pixels == NULL) {
          fprintf(stderr, "Memory allocation error\n");
          return (1);
        }

        if (bitpix > 0) {  /* set the default output format string */
          strcpy(hdformat, "   %7d");
          strcpy(format,   "   %7.0g");
        } else {
          strcpy(hdformat, "   %15d");
          strcpy(format,   "   %15.5g");
        }

        if (naxis > 2) {  /* label higher dimensions */
          fprintf(fout, "#");
          for (d = naxis - 1; d > 0; d--) {
            fprintf(fout, "%1iD ", d+1);
          }
          fprintf(fout, "\n");
        }

        /* loop over all the rows in the array */
        for (fpixel[8] = 1; fpixel[8] <= naxes[8]; fpixel[8]++) {
          for (fpixel[7] = 1; fpixel[7] <= naxes[7]; fpixel[7]++) {
            for (fpixel[6] = 1; fpixel[6] <= naxes[6]; fpixel[6]++) {
              for (fpixel[5] = 1; fpixel[5] <= naxes[5]; fpixel[5]++) {
                for (fpixel[4] = 1; fpixel[4] <= naxes[4]; fpixel[4]++) {
                  for (fpixel[3] = 1; fpixel[3] <= naxes[3]; fpixel[3]++) {
                    for (fpixel[2] = 1; fpixel[2] <= naxes[2]; fpixel[2]++) {
                      for (fpixel[1] = 1; fpixel[1] <= naxes[1]; fpixel[1]++) {
                        if (fits_read_pix(fptr, TDOUBLE, fpixel, naxes[0], NULL,
                                          pixels, NULL, &status)) { /* read row of pixels */
                          break;  /* jump out of loop on error */
                        }

                        if (naxis > 2) {  /* print higher dimensions */
                          fprintf(fout, " ");
                          for (d = naxis - 1; d > 0; d--) {
                            fprintf(fout, "% 2li ", fpixel[d]);
                          }
                        }
                        for (ii = 0; ii < naxes[0]; ii++) {
                          fprintf(fout, format, pixels[ii]);  /* print each value  */
                        }
                        fprintf(fout, "\n");                    /* terminate line */
                      }
                    }
                  }
                }
              }
            }
          }
        }
        free(pixels);
      }
    }
    fits_close_file(fptr, &status);
  }

  pclose(fout);

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