コード例 #1
0
ファイル: Fits2D.cpp プロジェクト: Asubayo/freeture
bool Fits2D::readStringKeyword(string keyword, string &value){

    char *ptr = NULL;

    int status = 0;

    fitsfile *fptr;

    const char * filename;

    char v[40];

    filename = mFitsPath.c_str();


    if(fits_open_file(&fptr, filename, READONLY, &status)){

        printerror(status);
        return false;

    }

    char * key = new char[keyword.length()+1];
    strcpy(key,keyword.c_str());

    if(fits_read_key(fptr, TSTRING, key, v, NULL, &status)){


        printerror(status);
        delete key;
        return false;

    }

    value = string(v);

    delete key;

    if(fits_close_file(fptr, &status)){

        printerror(status);
        return false;

    }

    return true;
}
コード例 #2
0
ファイル: substract8.c プロジェクト: thatking/CToupcam
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);
			

			fits_read_img(fptr,TBYTE,1,nelements,NULL,*image, &anynul, &status);
			fits_close_file(fptr, &status);
			return status;
		  }
     }
     return -1;		
}
コード例 #3
0
	int focus_quality(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 */

		std::sort(values.begin(), values.end(), std::greater<double>());
		return values[FOCUS_INDEX];
	}
コード例 #4
0
ファイル: fits.c プロジェクト: lajus/monetinr
str
FITStest(int *res, str *fname)
{
	fitsfile *fptr;       /* pointer to the FITS file, defined in fitsio.h */
	str msg = MAL_SUCCEED;
	int status = 0, hdutype;

	*res = 0;
	if (fits_open_file(&fptr, *fname, READONLY, &status))
		msg = createException(MAL, "fits.test", "Missing FITS file %s", *fname);
	else {
		fits_movabs_hdu(fptr, 2, &hdutype, &status);
		*res = hdutype;
		fits_close_file(fptr, &status);
	}

	return msg;
}
コード例 #5
0
int showkey(char *filename, char *keyword)
{
/*
	function showkey displays keyword and value

	if keyword is COMMENT or HISTORY, it displays all respective lines.

*/


	fitsfile *fptr;         /* FITS file pointer, defined in fitsio.h */
	char card[FLEN_CARD];
	int status = 0, nkeys, i;   /*  CFITSIO status value MUST be initialized to zero!  */

	if (!fits_open_file(&fptr, filename, READONLY, &status))
	{
		for (i=0; i<FLEN_CARD; i++) 
			keyword[i]=toupper(keyword[i]);
		if ( !strcmp(keyword, "COMMENT") || !strcmp(keyword, "HISTORY")) {
			fits_get_hdrspace(fptr, &nkeys, NULL, &status); /* get # of keywords */
			for (i = 1; i <= nkeys; i++) { /* Read and print each keywords */
				if (fits_read_record(fptr, i, card, &status))
					break;
				if ( !strncmp(card, keyword, 7) )
					printf("%s\n", card);
			}
		}
		else {
			if (fits_read_card(fptr, keyword, card, &status))
			{
				printf("Keyword does not exist\n");
				status = 0;  /* reset status after error */
			}
			else 
				printf("%s\n",card);
		}
		fits_close_file(fptr, &status);
	}    /* open_file */

	/* if error occured, print out error message */
	if (status) fits_report_error(stderr, status);
	return(status);
}
コード例 #6
0
ファイル: ipixcorr_utils.c プロジェクト: nfourmanoit/TIPS
/**
 * Function: get_SPC_opened
 * The function opens an existing SPC file and returns the pointer
 * to it.
 * As of now, the mode of opening it is automatically READWRITE.
 * Later on a differentiation using the free parameter "mode"
 * might be added  to generalize the function.
 *
 * Parameters:
 * @param SPCname - name of the SPC file
 * @param mode    - mode to open it (not yet used)
 *
 * Returns:
 * @return SPC_ptr - pointer to the opened fits file
 *
 */
fitsfile *
get_SPC_opened(char SPCname[], int mode)
{
    fitsfile *SPC_ptr;
    int f_status=0;

  // Open the OPET file for reading/writing
  fits_open_file (&SPC_ptr, SPCname, READWRITE, &f_status);
  if (f_status)
    {
      ffrprt (stdout, f_status);
      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		   "aXe_INTPIXCORR: Could not open file: %s\n",
		   SPCname);
    }

  // return the pointer to the fits file
  return SPC_ptr;
}
コード例 #7
0
void readheader( char *filename )

     /**********************************************************************/
     /* Print out all the header keywords in all extensions of a FITS file */
     /**********************************************************************/
{
  fitsfile *fptr;       /* pointer to the FITS file, defined in fitsio.h */

  int status, nkeys, keypos, hdutype, ii, jj;
  char card[FLEN_CARD];   /* standard string lengths defined in fitsioc.h */

  status = 0;

  if ( fits_open_file(&fptr, filename, READONLY, &status) ) 
    printerror( status, __LINE__ );

  /* attempt to move to next HDU, until we get an EOF error */
  for (ii = 1; !(fits_movabs_hdu(fptr, ii, &hdutype, &status) ); ii++) 
    {
      /* get no. of keywords */
      if (fits_get_hdrpos(fptr, &nkeys, &keypos, &status) )
	printerror( status, __LINE__ );

      printf("Header listing for HDU #%d:\n", ii);
      for (jj = 1; jj <= nkeys; jj++)  {
	if ( fits_read_record(fptr, jj, card, &status) )
	  printerror( status, __LINE__ );

	printf("%s\n", card); /* print the keyword card */
      }
      printf("END\n\n");  /* terminate listing with END */
    }

  if (status == END_OF_FILE)   /* status values are defined in fitsioc.h */
    status = 0;              /* got the expected EOF error; reset = 0  */
  else
    printerror( status, __LINE__ );     /* got an unexpected error                */

  if ( fits_close_file(fptr, &status) )
    printerror( status, __LINE__ );

  return;
}
コード例 #8
0
/**
 * Function: get_num_extensions
 * The function determines the number of extensions in
 * the fits file. Here the primary extension does not count.
 *
 * Parameters:
 * @param  spectral_models_file - pathname to the spectral models file
 *
 * Returns:
 * @return n_models              - the number of spectral models
 */
int
get_num_extensions(const char spectral_models_file[])
{
  int n_ext=0;
  int n_models=0;
  int i;
  int f_status=0;


  fitsfile *s_models;

  // open the fits file
  // report any error
  fits_open_file (&s_models, spectral_models_file, READONLY, &f_status);
  if (f_status)
    {
      ffrprt (stderr, f_status);
      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		   "aXe_PETCONT: " "Could not open file: %s",
		   spectral_models_file);
    }

  // do until a fits error occurs
  while (!f_status)
    {
      // move one extension forward
      fits_movrel_hdu (s_models, 1, NULL, &f_status);

      // count up
      n_ext++;
    }
  
  // close the fits file
  fits_close_file (s_models, &f_status);

  // the zeroth extension
  // does nnot count!!
  n_models = n_ext - 1;
  
  // return the 
  return n_models;
}
コード例 #9
0
FitsReader& FitsReader::operator=(const FitsReader& rhs)
{
	_filename = rhs._filename;
	_imgWidth = rhs._imgWidth;
	_imgHeight = rhs._imgHeight;
	_nFrequencies = rhs._nFrequencies;
	_phaseCentreRA = rhs._phaseCentreRA;
	_phaseCentreDec = rhs._phaseCentreDec;
	_pixelSizeX = rhs._pixelSizeX;
	_pixelSizeY = rhs._pixelSizeY;
	_phaseCentreDL = rhs._phaseCentreDL;
	_phaseCentreDM = rhs._phaseCentreDM;
	_frequency = rhs._frequency;
	_bandwidth = rhs._bandwidth;
	_dateObs = rhs._dateObs;
	_hasBeam = rhs._hasBeam;
	_beamMajorAxisRad = rhs._beamMajorAxisRad;
	_beamMinorAxisRad = rhs._beamMinorAxisRad;
	_beamPositionAngle = rhs._beamPositionAngle;
	_polarization = rhs._polarization;
	_unit = rhs._unit;
	_telescopeName = rhs._telescopeName;
	_observer = rhs._observer;
	_objectName = rhs._objectName;
	_origin = rhs._origin;
	_originComment = rhs._originComment;
	_history = rhs._history;
	
	int status = 0;
	fits_close_file(_fitsPtr, &status);
	checkStatus(status, _filename);
	
	fits_open_file(&_fitsPtr, _filename.c_str(), READONLY, &status);
	checkStatus(status, _filename);
	
	// Move to first HDU
	int hduType;
	fits_movabs_hdu(_fitsPtr, 1, &hduType, &status);
	checkStatus(status, _filename);
	if(hduType != IMAGE_HDU) throw std::runtime_error("First HDU is not an image");
	return *this;
}
コード例 #10
0
ファイル: cfitsio_verify.c プロジェクト: 278261631/astropy
int main(int argc, char *argv[])
{
	fitsfile *fptr;
	int i, j, status, dataok, hduok, hdunum, hdutype;
	char *hdustr, *datastr;

	for (i=1; i<argc; i++) {

		fits_open_file(&fptr, argv[i], READONLY, &status);
		if (status) { 
			fits_report_error(stderr, status);
			exit(-1); 
		}

		fits_get_num_hdus(fptr, &hdunum, &status);
		if (status) { 
			fprintf(stderr, "Bad get_num_hdus status for '%s' = %d", 
				argv[i], status);
			exit(-1); 
		}

		for (j=0; j<hdunum; j++) {
			fits_movabs_hdu(fptr, hdunum, &hdutype, &status);
			if (status) { 
				fprintf(stderr, "Bad movabs status for '%s[%d]' = %d.", 
					argv[i], j, status);
				exit(-1);
			}
			fits_verify_chksum(fptr, &dataok, &hduok, &status);
			if (status) { 
				fprintf(stderr, "Bad verify status for '%s[%d]' = %d.", 
					argv[i], j, status);
				exit(-1);
			}
			datastr = verify_status(dataok);
			hdustr = verify_status(hduok);
			printf("Verifying '%s[%d]'  data='%s'   hdu='%s'.\n",
			       argv[i], j, datastr, hdustr);
		}
	}
}
コード例 #11
0
ファイル: fitsutils.c プロジェクト: sfabbro/allphot
fitsfile* fits_init(char *filename, int iomode, int *nrelhdu, int *status) {
  *status = 0;
  fitsfile *fptr;
  if (fits_open_file(&fptr, filename, iomode, status)) {
    fits_print_error(*status);
    return 0;
  }

  /* Get the current HDU position and number of HDUs*/
  int hdupos, nhdu;
  fits_get_hdu_num (fptr, &hdupos);
  fits_get_num_hdus(fptr, &nhdu, status);

  /* will process only a single header if a specific extension was given, 
     otherwise all HDUs */ 
  if  (hdupos != 1 || strchr(filename, '[') || nhdu == 1) 
    *nrelhdu = 0;
  else *nrelhdu = nhdu-hdupos;

  return fptr;
}
コード例 #12
0
ファイル: fits.c プロジェクト: f7753/monetdb
str FITSdirpat(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci)
{
	str msg = MAL_SUCCEED;
	str dir = *getArgReference_str(stk, pci, 1);
	str pat = *getArgReference_str(stk, pci, 2);
	fitsfile *fptr;
	char *s;
	int status = 0;
	glob_t globbuf;
	char fulldirectory[BUFSIZ];
	size_t j = 0;

	(void)mb;
	globbuf.gl_offs = 0;
	snprintf(fulldirectory, BUFSIZ, "%s%s", dir, pat);
	glob(fulldirectory, GLOB_DOOFFS, NULL, &globbuf);

	/*	fprintf(stderr,"#fulldir: %s \nSize: %lu\n",fulldirectory, globbuf.gl_pathc);*/

	if (globbuf.gl_pathc == 0)
		throw(MAL, "listdir", "Couldn't open the directory or there are no files that match the pattern");

	for (j = 0; j < globbuf.gl_pathc; j++) {
		char stmt[BUFSIZ];
		char fname[BUFSIZ];

		s = stmt;
		snprintf(fname, BUFSIZ, "%s", globbuf.gl_pathv[j]);
		status = 0;
		fits_open_file(&fptr, fname, READONLY, &status);
		if (status == 0) {
			snprintf(stmt, BUFSIZ, ATTACHDIR, fname);
			msg = SQLstatementIntern(cntxt, &s, "fits.listofdirpat", TRUE, FALSE, NULL);
			fits_close_file(fptr, &status);
			break;
		}
	}

	return msg;
}
コード例 #13
0
// Function which determines if file is of type spSpec, spPlate
int SDSS_filetype(char *infile, int *nspec){
	// return value:
	// 0 = spSpec
	// 1 = spPlate
	// 2 = spec
	int val = 0;
	int hdunum_exp = 0;

	fitsfile *infits;
	int status = 0, hdunum = 0;
	//printf("Name of File: %s\n", infile);
	fits_open_file(&infits, infile, READONLY, &status);
	fits_get_num_hdus(infits, &hdunum, &status);
	//printf("HDUNumber: %i\n\n", hdunum);


	// Number of HDUs not necessarily 9. In some cases might be different
	if( strstr(infile, "spSpec") != NULL ){
		val = 0;
		hdunum_exp = 7;
		//if(hdunum != hdunum_exp) warnmsg("Number of HDUs is not %d as expected from spSpec", hdunum_exp);
	}
	if( strstr(infile, "spPlate") != NULL ){
		val = 1;
		hdunum_exp = 9;
		//if(hdunum != hdunum_exp) warnmsg("Number of HDUs is not %d as expected from spPlate", hdunum_exp);
		fits_read_key(infits, TINT, "NAXIS2", nspec, NULL, &status);
	}
	if( strstr(infile, "spec-") != NULL ){
		val = 2;
		hdunum_exp = 14;
		//if(hdunum != hdunum_exp) warnmsg("Number of HDUs is not %d as expected from spec", hdunum_exp);
	}

	// report Error. TODO: Decide if want to use errormsg instead.
	fits_close_file(infits, &status);
	fits_report_error(stderr, status);

	return val;
}
コード例 #14
0
ファイル: Fits2D.cpp プロジェクト: Asubayo/freeture
bool Fits2D::readDoubleKeyword(string keyword, double &value){

    char *ptr = NULL;

    int status = 0;

    fitsfile *fptr;

    const char * filename;

    filename = mFitsPath.c_str();

    if(fits_open_file(&fptr, filename, READONLY, &status)){

        printerror(status);
        return false;
    }

    char * key = new char[keyword.length()+1];
    strcpy(key,keyword.c_str());

    if(fits_read_key(fptr, TDOUBLE, key, &value, NULL, &status)){

        printerror(status);
        delete key;
        return false;
    }

    delete key;

    if(fits_close_file(fptr, &status)){

        printerror(status);
        return false;

    }

    return true;
}
コード例 #15
0
ファイル: cfitsio-test.c プロジェクト: AmatCoder/mxe
int main(int argc, char *argv[])
{
    (void)argc;

    fitsfile *fptr;
    char card[FLEN_CARD];
    int status = 0,  nkeys, ii;  /* MUST initialize status */

    fits_open_file(&fptr, argv[1], READONLY, &status);
    fits_get_hdrspace(fptr, &nkeys, NULL, &status);

    for (ii = 1; ii <= nkeys; ii++)  {
      fits_read_record(fptr, ii, card, &status); /* read keyword */
      printf("%s\n", card);
    }
    printf("END\n\n");  /* terminate listing with END */
    fits_close_file(fptr, &status);

    if (status)          /* print any error messages */
        fits_report_error(stderr, status);
    return(status);
}
コード例 #16
0
ファイル: read_fits.c プロジェクト: linan7788626/my_libs
//----------------------------------------------------------------------------------
double *read_data_fits(char *source_fits,long nx,long ny) {

    fitsfile *fptr_in;
    int status, anynull;
    long fpixel,npixels;

    double nullval;
    status = 0;

    fits_open_file(&fptr_in, source_fits, READONLY, &status);

    npixels  = nx*ny;
    fpixel	 = 1;
    nullval  = 0;

    double *source_map = (double *)malloc(npixels*sizeof(double));
    fits_read_img(fptr_in, TDOUBLE, fpixel, npixels, &nullval,source_map, &anynull, &status);
    fits_close_file(fptr_in, &status);

    //printf("%ld %ld %ld\n", i,j,npixels);
    return source_map;
}
コード例 #17
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);
}
コード例 #18
0
void ClienteQtFits::leerFits()
{
    fitsfile *fptr;
    float nullval, pline[2048];
    int status = 0, anynull=0;
    long fpixel = 1;
    char filename[] = "/home/ievivas/Desarrollo/obs401.qnx3.ccd2.n110.fits";

    if (fits_open_file(&fptr, filename, READONLY, &status))
        printerror(status);

    for (int i=0; i<512; i++)
    {
        if ( fits_read_img(fptr, TFLOAT, fpixel, 2048, &nullval, pline, &anynull, &status) )
                   printerror( status );
        for (int j=0; j<2048; j++)
        {
            matrix(i, j) = quint16(pline[j]);
        }
        fpixel = fpixel + 2100;
        std::cout << 512 - i << std::endl;
    }
}
コード例 #19
0
ファイル: iter_b.c プロジェクト: Asubayo/freeture
/*
  This program illustrates how to use the CFITSIO iterator function.
  It simply prints out the values in a character string and a logical
  type column in a table, and toggles the value in the logical column
  so that T -> F and F -> T.
*/
main()
{
    extern str_iter(); /* external work function is passed to the iterator */
    fitsfile *fptr;
    iteratorCol cols[2];
    int n_cols;
    long rows_per_loop, offset;
    int status = 0;
    char filename[]  = "iter_b.fit";     /* name of rate FITS file */

    /* open the file and move to the correct extension */
    fits_open_file(&fptr, filename, READWRITE, &status);
    fits_movnam_hdu(fptr, BINARY_TBL, "iter_test", 0, &status);

    /* define input column structure members for the iterator function */
    n_cols  = 2;   /* number of columns */

    /* define input column structure members for the iterator function */
    fits_iter_set_by_name(&cols[0], fptr, "Avalue", TSTRING,  InputOutputCol);
    fits_iter_set_by_name(&cols[1], fptr, "Lvalue", TLOGICAL, InputOutputCol);

    rows_per_loop = 0;  /* use default optimum number of rows */
    offset = 0;         /* process all the rows */

    /* apply the  function to each row of the table */
    printf("Calling iterator function...%d\n", status);

    fits_iterate_data(n_cols, cols, offset, rows_per_loop,
                      str_iter, 0L, &status);

    fits_close_file(fptr, &status);      /* all done */

    if (status)
       fits_report_error(stderr, status); /* print out error messages */

    return(status);
}
コード例 #20
0
ファイル: psrfits.c プロジェクト: nextgen-astrodata/presto
int is_PSRFITS(char *filename)
// Return 1 if the file described by filename is a PSRFITS file
// Return 0 otherwise.                                         
{
    fitsfile *fptr;
    int status=0;
    char ctmp[80], comment[120];
    
    // Read the primary HDU
    fits_open_file(&fptr, filename, READONLY, &status);
    if (status) return 0;
    
    // Make the easy check first
    fits_read_key(fptr, TSTRING, "FITSTYPE", ctmp, comment, &status);
    if (status || strcmp(ctmp, "PSRFITS")) return 0;

    // See if the data are search-mode
    fits_read_key(fptr, TSTRING, "OBS_MODE", ctmp, comment, &status);
    if (status || (strcmp(ctmp, "SEARCH") && 
                   strcmp(ctmp, "SRCH"))) return 0;

    fits_close_file(fptr, &status);
    return 1;  // it is search-mode  PSRFITS
}
コード例 #21
0
void
avtFITSFileFormat::Initialize(avtDatabaseMetaData *md)
{
    const char *mName = "avtFITSFileFormat::Initialize: ";

    if(fits == 0)
    {
        debug4 << mName << "Opening " << filename << endl;
        int status = 0;
        if(fits_open_file(&fits, filename, 0, &status))
        {
            PrintError(status);
            EXCEPTION1(InvalidFilesException, filename);
        }

        char card[FLEN_CARD], tmp[100];
        std::string fileComment;
        int hdutype = 0;

        // Iterate over the HDU's
        for(int hdu = 1; !(fits_movabs_hdu(fits, hdu, &hdutype, &status)); hdu++) 
        {
            debug4 << mName << "Looking at HDU " << hdu << endl;

            // Get no. of keywords
            int nkeys = 0, keypos = 0;
            if(fits_get_hdrpos(fits, &nkeys, &keypos, &status))
                PrintError(status);

            if(hdutype == IMAGE_HDU)
            {
                debug4 << mName << "HDU " << hdu << " contains an image" << endl;
                //int status2 = 0;
                char value[FLEN_VALUE];
                std::string objname, bunit, xlabel, ylabel, zlabel;

                // Try and get the key value for BUNIT
                if(GetKeywordValue("BUNIT", value))
                {
                    bunit = std::string(value);
                    debug4 << "\tBUNIT=" << value << endl;
                }

                // Try and get the key value for OBJECT
                if(GetKeywordValue("OBJECT", value))
                {
                    objname = std::string(value);
                    debug4 << "\tOBJECT=" << value << endl;
                }
#if 0
//
// Re-enable these someday when we read the mesh coordinates from the file
// and use them to construct a sensible mesh.
//
                // Try and get the key value for CTYPE1
                if(GetKeywordValue("CTYPE1", value))
                {
                    xlabel = std::string(value);
                    debug4 << "\tCTYPE1=" << value << endl;
                }

                // Try and get the key value for CTYPE2
                if(GetKeywordValue("CTYPE2", value))
                {
                    ylabel = std::string(value);
                    debug4 << "\tCTYPE2=" << value << endl;
                }

                // Try and get the key value for CTYPE3
                if(GetKeywordValue("CTYPE3", value))
                {
                    zlabel = std::string(value);
                    debug4 << "\tCTYPE3=" << value << endl;
                }
#endif
                // Use the keywords to create a comment.
                SNPRINTF(tmp, 100, "Header listing for HDU #%d:\n", hdu);
                fileComment += tmp;
                for(int jj = 1; jj <= nkeys; jj++)
                {
                    if(fits_read_record(fits, jj, card, &status))
                        PrintError(status);
                    std::string cs(card);
                    fileComment += cs;
                    if(cs.size() > 0 && cs[cs.size()-1] != '\n')
                        fileComment += "\n";
                }
                fileComment += "\n\n";

                //
                // Get the image's dimensions.
                //
                int ndims = 0;
                if(fits_get_img_dim(fits, &ndims, &status))
                    PrintError(status);
                debug4 << mName << "Num dimensions: " << ndims << ", status=" << status << endl;
                long *dims = new long[ndims];
                if(fits_get_img_size(fits, ndims, dims, &status))
                    PrintError(status);
                if(ndims == 0)
                {
                    debug4 << mName << "The image has no dimensions. Skip it." << endl;
                    continue;
                }

                //
                // Create a mesh name for the image.
                //
                intVector mdims;
                std::string meshName("image");
                debug4 << mName << "Image dimensions: ";
                bool dimensionsNonZero = false;
                for(int i = 0; i < ndims; ++i)
                {
                    char num[20];
                    if(i > 0)
                        SNPRINTF(num, 20, "x%d", (int)dims[i]);
                    else
                        SNPRINTF(num, 20, "%d", (int)dims[i]);
                    meshName += num;
                    mdims.push_back((int)dims[i]);
                    dimensionsNonZero |= (dims[i] != 0);
                    debug4 << dims[i] << ", ";
                }
                debug4 << endl;
                if(!dimensionsNonZero)
                {
                    debug4 << mName << "All dimensions were zero. skip." << endl;
                    continue;
                }
                if(ndims == 1 && objname != "")
                    meshName = objname;
                if(meshDimensions.find(meshName) == meshDimensions.end())
                {
                    meshDimensions[meshName] = mdims;

                    // Create metadata if necessary.
                    if(md != 0)
                    {
                        if(ndims == 1)
                        {
                            debug4 << mName << "Adding a curve called "
                                   << meshName.c_str() << " for HDU "
                                   << hdu << endl;

                            avtCurveMetaData *cmd = new avtCurveMetaData;
                            cmd->name = meshName;
                            if(xlabel != "")
                                cmd->xLabel = xlabel;
                            if(ylabel != "")
                                cmd->yLabel = ylabel;
                            md->Add(cmd);

                            // Do this because we use GetVar to read the data
                            // that we use to create the curve.
                            varToHDU[meshName] = hdu;
                            varToMesh[meshName] = meshName;
                        }
                        else
                        {
                            int sdims, tdims;
                            int nrealdims = (ndims <= 3) ? ndims : 3;
#define VECTOR_SUPPORT
#ifdef VECTOR_SUPPORT
                            if(nrealdims == 3 && dims[2] == 3)
                                nrealdims = 2;
#endif
                            sdims = tdims = nrealdims;

                            debug4 << mName << "Adding a " << sdims
                                   << " dimensional mesh called "
                                   << meshName.c_str() << " for HDU "
                                   << hdu << endl;

                            avtMeshMetaData *mmd = new avtMeshMetaData(
                                meshName, 1, 1, 1, 0, sdims, tdims,
                                AVT_RECTILINEAR_MESH);
                            if(xlabel != "")
                                mmd->xLabel = xlabel;
                            if(ylabel != "")
                                mmd->yLabel = ylabel;
                            if(zlabel != "")
                                mmd->zLabel = zlabel;

                            md->Add(mmd);
                        }
                    }
                }

                //
                // Create a name for the variable at this HDU
                //
                if(ndims > 1)
                {
                    char varname[100];
                    SNPRINTF(varname, 100, "hdu%d", hdu);
                    std::string vName(varname);
                    if(objname != "")
                        vName = objname;
                    varToHDU[vName] = hdu;
                    varToMesh[vName] = meshName;

                    // Create metadata if necessary
                    if(md != 0)
                    {
#ifdef VECTOR_SUPPORT
                        // Limit the dimensions to 3.
                        int ncomps = 1;
                        int nrealdims = (ndims <= 3) ? ndims : 3;
                        if(nrealdims == 3 && dims[2] == 3)
                            ncomps = 3;

                        if(ncomps == 1)
                        {
#endif
                            debug4 << mName << "Adding a scalar called "
                                   << vName.c_str() << " for HDU "
                                   << hdu << endl;
                            // Add the scalar metadata
                            avtScalarMetaData *smd = new avtScalarMetaData(
                                vName, meshName, AVT_ZONECENT);
                            smd->hasUnits = bunit != "";
                            smd->units = bunit;
                            md->Add(smd);
#ifdef VECTOR_SUPPORT
                        }
                        else
                        {
                            debug4 << mName << "Adding a color vector called "
                                   << vName.c_str() << " for HDU "
                                   << hdu << endl;

                            // Add the vector metadata
                            avtVectorMetaData *vmd = new avtVectorMetaData(
                                vName, meshName, AVT_ZONECENT, 4);
//                          vmd->hasUnits = true;
//                          vmd->units = 
                            md->Add(vmd);
                        }
#endif
                    }
                }

                delete [] dims;
            }
            else if(hdutype == ASCII_TBL)
            {
                debug4 << mName << "HDU " << hdu
                       << " contains an ascii table" << endl;
            }
            else if(hdutype == BINARY_TBL)
            {
                debug4 << mName << "HDU " << hdu
                       << " contains a binary table" << endl;

                // Use the keywords to create a comment.
                SNPRINTF(tmp, 100, "Header listing for HDU #%d:\n", hdu);
                debug4 << tmp;
                for(int jj = 1; jj <= nkeys; jj++)
                {
                    if(fits_read_record(fits, jj, card, &status))
                        PrintError(status);
                    std::string cs(card);
                    if(cs.size() > 0 && cs[cs.size()-1] != '\n')
                        cs += "\n";
                    debug4 << "\t" << cs.c_str();
                }
            }
        }

        if(md != 0)
            md->SetDatabaseComment(fileComment);
    }
}
コード例 #22
0
ファイル: eventlist.c プロジェクト: Chandra-MARX/marx
/* This function is called with (cosx,cosy,cosz) denoting the unit vector
 * in marx spacecraft coordinates that corresponds to the desired
 * location of the optical axis.  This will place a source at this
 * position on axis (Duhh!).  To simulate an event file as-is, the user
 * should use the nominal ra and dec as given in the event file for the
 * source position.
 */
int user_open_source (char **argv, int argc, double area,
		      double cosx, double cosy, double cosz)
{
   char *file, *extname;
   fitsfile *f;
   int status = 0;
   double want_ra, want_dec;
   char *spectral_file, *ra_str, *dec_str;

   file = spectral_file = ra_str = dec_str = NULL;

   switch (argc)
     {
      default:
	return usage ();

      case 4:
	ra_str = argv[2];
	dec_str = argv[3];
	if (1 != sscanf (ra_str, "%lf", &want_ra))
	  return usage ();

	if (1 != sscanf (dec_str, "%lf", &want_dec))
	  return usage ();

	want_ra *= PI/180;
	want_dec *= PI/180;

	/* drop */

      case 2:
	file = argv[0];
	spectral_file = argv[1];
	break;
     }

   extname = "EVENTS";

   (void) fits_open_file (&f, file, READONLY, &status);
   if (status)
     {
	fprintf (stderr, "Unable to open fits file %s\n", file);
	dump_fits_error (status);
	return -1;
     }

   if (0 != fits_movnam_hdu (f, BINARY_TBL, extname, 1, &status))
     {
	dump_fits_error (status);
	close_file (f);
	return -1;
     }

   if ((-1 == get_col_num (f, "X", &X_Col_Num))
       || (-1 == get_col_num (f, "Y", &Y_Col_Num))
       || (-1 == get_col_num (f, "EXPNO", &Expno_Col_Num))
       || (-1 == get_col_num (f, "PI", &Pi_Col_Num)))
     {
	close_file (f);
	return -1;
     }

   if ((-1 == read_wcs_info (f, X_Col_Num, &X_CrVal, &X_CrPix, &X_CDelt))
      || (-1 == read_wcs_info (f, Y_Col_Num, &Y_CrVal, &Y_CrPix, &Y_CDelt)))
     {
	close_file (f);
	return -1;
     }

   if ((-1 == read_key_double (f, "RA_NOM", &Nominal_Ra))
       || (-1 == read_key_double (f, "DEC_NOM", &Nominal_Dec))
       || (-1 == read_key_double (f, "ROLL_NOM", &Nominal_Roll))
       || (-1 == read_key_double (f, "TSTART", &TStart)))
     {
	close_file (f);
	return -1;
     }
   Nominal_Ra *= PI/180.0;
   Nominal_Dec *= PI/180.0;
   Nominal_Roll *= PI/180.0;

   Nominal_Pointing = JDMv_spherical_to_vector (1.0, PI/2 - Nominal_Dec, Nominal_Ra);

   Marx_Pointing.x = -cosx;
   Marx_Pointing.y = -cosy;
   Marx_Pointing.z = -cosz;

   if (ra_str == NULL)
     want_ra = Nominal_Ra;

   if (dec_str == NULL)
     want_dec = Nominal_Dec;

   setup_rotations (want_ra, want_dec);

   if (-1 == init_spectral_bins (spectral_file))
     {
	close_file (f);
	return -1;
     }

   Events_Ptr = f;
   return 0;
}
コード例 #23
0
int main(int argc, char *argv []) {

        if(populate_env_variable(REF_ERROR_CODES_FILE, "L2_ERROR_CODES_FILE")) {

                printf("\nUnable to populate [REF_ERROR_CODES_FILE] variable with corresponding environment variable. Routine will proceed without error handling\n");

        }

        if (argc != 7) {

                if(populate_env_variable(SPE_BLURB_FILE, "L2_SPE_BLURB_FILE")) {

                        RETURN_FLAG = 1;

                } else {

                        print_file(SPE_BLURB_FILE);

                }

                write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -1, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);

                return 1;

        } else {
                // ***********************************************************************
                // Redefine routine input parameters
                
                char *input_f                           = strdup(argv[1]);              
                char *method                            = strdup(argv[2]); 
                char *ss_method                         = strdup(argv[3]); 
                double target_half_aperture_px          = strtod(argv[4], NULL); 
                int sky_window_half_aperture_px         = strtol(argv[5], NULL, 0);   
                char *output_f                          = strdup(argv[6]);                    
                
                // ***********************************************************************
                // Open input file (ARG 1), get parameters and perform any data format 
                // checks

                fitsfile *input_f_ptr;

                int input_f_maxdim = 2, input_f_status = 0, input_f_bitpix, input_f_naxis;
                long input_f_naxes [2] = {1,1};

                if(!fits_open_file(&input_f_ptr, input_f, IMG_READ_ACCURACY, &input_f_status)) {

                        if(!populate_img_parameters(input_f, input_f_ptr, input_f_maxdim, &input_f_bitpix, &input_f_naxis, input_f_naxes, &input_f_status, "INPUT FRAME")) {

                                if (input_f_naxis != 2) {       // any data format checks here

                                        write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -2, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);

                                        free(input_f);
                                        free(output_f);
                                        free(method);
                                        free(ss_method);
                                        if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

                                        return 1;
        
                                }

                        } else { 

                                write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -3, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                                fits_report_error(stdout, input_f_status); 

                                free(input_f);
                                free(output_f);                                
                                free(method);
                                free(ss_method);
                                if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

                                return 1; 

                        }

                } else { 

                        write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -4, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                        fits_report_error(stdout, input_f_status); 

                        free(input_f);
                        free(output_f);                        
                        free(method);
                        free(ss_method);
                        
                        return 1; 

                }
                
                // ***********************************************************************
                // Set the range limits

                int cut_x [2] = {1, input_f_naxes[0]};
                int cut_y [2] = {1, input_f_naxes[1]};

                // ***********************************************************************
                // Set parameters used when reading data from input file (ARG 1)

                long fpixel [2] = {cut_x[0], cut_y[0]};
                long nxelements = (cut_x[1] - cut_x[0]) + 1;
                long nyelements = (cut_y[1] - cut_y[0]) + 1;

                // ***********************************************************************
                // Create arrays to store pixel values from input fits file (ARG 1)

                double input_f_pixels [nxelements];
                
                // ***********************************************************************
                // Get input fits file (ARG 1) values and store in 2D array

                int ii;

                double input_frame_values [nyelements][nxelements];
                memset(input_frame_values, 0, sizeof(double)*nxelements*nyelements);
                for (fpixel[1] = cut_y[0]; fpixel[1] <= cut_y[1]; fpixel[1]++) {

                        memset(input_f_pixels, 0, sizeof(double)*nxelements);

                        if(!fits_read_pix(input_f_ptr, TDOUBLE, fpixel, nxelements, NULL, input_f_pixels, NULL, &input_f_status)) {

                                for (ii=0; ii<nxelements; ii++) {
                                        input_frame_values[fpixel[1]-1][ii] = input_f_pixels[ii];
                                }

                        } else { 

                                write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -5, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                                fits_report_error(stdout, input_f_status); 

                                free(input_f);  
                                free(output_f);  
                                free(method);
                                free(ss_method);                                
                                if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 

                                return 1; 

                        }

                }
                
                // ***********************************************************************
                // Open [SPFIND_OUTPUTF_PEAKS_FILE] input file
        
                FILE *inputfile;
        
                if (!check_file_exists(SPFIND_OUTPUTF_PEAKS_FILE)) { 

                        inputfile = fopen(SPFIND_OUTPUTF_PEAKS_FILE , "r");

                } else {

                        write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -6, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);

                        return 1;

                }

                // ***********************************************************************
                // Find some [SPFIND_OUTPUTF_PEAKS_FILE] input file details

                char input_string [150];
                
                int row_count = 0;
                while(!feof(inputfile)) {
                        memset(input_string, '\0', sizeof(char)*150);
                        fgets(input_string, 150, inputfile);
                        if (strtol(&input_string[0], NULL, 0) > 0) {            // check the line begins with a positive number (usable)
                                row_count++;
                        }
                }
                
                rewind(inputfile);
                
                // ***********************************************************************
                // Store [SPFIND_OUTPUTF_PEAKS_FILE] data               
                
                double x_coords[row_count];
                memset(x_coords, 0, sizeof(double)*(row_count));

                double y_coords[row_count];
                memset(y_coords, 0, sizeof(double)*(row_count));

                double coord_x, coord_y;
                int idx = 0;
                while(!feof(inputfile)) {
                        memset(input_string, '\0', sizeof(char)*150);
                        fgets(input_string, 150, inputfile);    
                        if (strtol(&input_string[0], NULL, 0) > 0) {            // check the line begins with a positive number (usable)
                                sscanf(input_string, "%lf\t%lf\n", &coord_x, &coord_y);
                                x_coords[idx] = coord_x;
                                y_coords[idx] = coord_y;
                                idx++;
                        }
                }            
        
                double output_frame_values[nxelements];
                memset(output_frame_values, 0, sizeof(double)*nxelements);     
                
                // ***********************************************************************
                // EXTRACTION
                               
                if (strcmp(method, "simple") == 0) {
                    // ***********************************************************************
                    // PARTIAL PIXEL APERTURE

                    int ii, jj;

                    double y;    
                    
                    y = y_coords[0];                            // should only be one bin in [SPFIND_OUTPUTF_PEAKS_FILE] data file
     
                    double this_col_value;
                    for (ii=0; ii<nxelements; ii++) {   
                      
                        this_col_value = 0.;
                        
                        // ***********************************************************************
                        // Does [y] violate the img boundaries?

                        if ((y + target_half_aperture_px > nyelements) || (y - target_half_aperture_px <= 0)) {

                            write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -7, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                            fits_report_error(stdout, input_f_status); 

                            free(input_f);
                            free(output_f);  
                            free(method);
                            free(ss_method);
                            
                            if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 
                            fclose(inputfile);

                            return 1;

                        }

                        // ***********************************************************************
                        // Extract flux within aperture

                        double y_low, y_high;

                        y_low = y-target_half_aperture_px-0.5;
                        y_high = y+target_half_aperture_px+0.5;                   

                        int y_low_floor, y_high_floor;
        
                        y_low_floor = floor(y-target_half_aperture_px-0.5);            // 0.5 as taking (half_ap*2) + 1 as total aperture
                        y_high_floor = floor(y+target_half_aperture_px+0.5);
                                            
                        for (jj=y_low_floor; jj<=y_high_floor; jj++) {
                         
                            if (jj == y_low_floor) {                        // outside pixel where partial flux needs to be taken into account
                                  

                                double partial_fraction_of_bin = (y_low_floor + 1) - y_low;
                                this_col_value += partial_fraction_of_bin * input_frame_values[jj][ii];
                                
                            } else if (jj == y_high_floor) {                // outside pixel where partial flux needs to be taken into account
                                  
                                double partial_fraction_of_bin = y_high - y_high_floor;
                                this_col_value += partial_fraction_of_bin * input_frame_values[jj][ii];
                                
                            } else {
                              
                                this_col_value += input_frame_values[jj][ii]; 
                                    
                            }
                        }   
                        
                        output_frame_values[ii] = this_col_value;
                        
                    }    
                } else {
                  
                    write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -8, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                    fits_report_error(stdout, input_f_status); 

                    free(input_f);
                    free(output_f);
                    free(method);
                    free(ss_method);
                    
                    if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status);  
                    fclose(inputfile);
                    
                    return 1;
                    
                }
                
                // ***********************************************************************
                // SKY SUBTRACTION
                
                if (strcmp(ss_method, "none") == 0) {
                } else if (strcmp(ss_method, "median") == 0) {

                    // ***********************************************************************
                    // MEDIAN SUBTRACTION             
                    int ii, jj;

                    double y;    
                    
                    y = y_coords[0];                            // should only be one bin in [SPFIND_OUTPUTF_PEAKS_FILE] data file
     
                    double this_col_value;
                    
                    for (ii=0; ii<nxelements; ii++) {          
                        this_col_value = 0.;
                        
                        // ***********************************************************************
                        // Does [y] violate the img boundaries?

                        if ((y + target_half_aperture_px + sky_window_half_aperture_px > nyelements) || (y - target_half_aperture_px - sky_window_half_aperture_px <= 0)) {

                            write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -9, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                            fits_report_error(stdout, input_f_status); 

                            free(input_f);
                            free(output_f);  
                            free(method);
                            free(ss_method);
                            
                            if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 
                            fclose(inputfile);

                            return 1;

                        }
                        
                        // ***********************************************************************
                        // Find pixels for sky aperture

                        int ap_lower_lo, ap_lower_hi, ap_upper_lo, ap_upper_hi; 
                        
                        ap_lower_lo = floor(y-target_half_aperture_px-0.5) - sky_window_half_aperture_px - 1;
                        ap_lower_hi = floor(y-target_half_aperture_px-0.5) - 1;
                        ap_upper_lo = floor(y+target_half_aperture_px+0.5) + 1;
                        ap_upper_hi = floor(y+target_half_aperture_px+0.5) + sky_window_half_aperture_px + 1;
                        
                        int n_ap_values = (ap_lower_hi-ap_lower_lo) + (ap_upper_hi-ap_upper_lo) + 2;
                        
                        double ap_values[n_ap_values];
                             
                        int idx = 0;
 
                        
                        for (jj=ap_lower_lo; jj<=ap_lower_hi; jj++) {
                          
                            ap_values[idx] = input_frame_values[jj][ii]; 
                            idx++;
                                    
                        }  
                        
                        for (jj=ap_upper_lo; jj<=ap_upper_hi; jj++) {
                          
                            ap_values[idx] = input_frame_values[jj][ii]; 
                            idx++;
                                    
                        }  
                        
                        // DEBUG
                        /*for (jj=0; jj<idx; jj++) 
                          printf("%f,", ap_values[jj]);
                        
                        printf("\n");
                        
                        for (jj=0; jj<idx; jj++) 
                          printf("%d,", jj);
                        
                        printf("\n");*/ 
                        
                        // Take median
                        double ap_values_sorted [n_ap_values];
                        memcpy(ap_values_sorted, ap_values, sizeof(double)*n_ap_values);

                        gsl_sort(ap_values_sorted, 1, (ap_lower_hi-ap_lower_lo) + (ap_upper_hi-ap_upper_lo) + 2);
                        double ap_values_median = gsl_stats_median_from_sorted_data(ap_values_sorted, 1, n_ap_values);     
                        
                        this_col_value = ap_values_median * ((target_half_aperture_px*2) + 1);    // need to scale up to target extraction aperture size
                        
                        output_frame_values[ii] -= this_col_value;              

                    }
                  
                } else {
                  
                    write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -10, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                    fits_report_error(stdout, input_f_status); 

                    free(input_f);
                    free(output_f);
                    free(method);
                    free(ss_method);
                    
                    if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status);  
                    fclose(inputfile);
                    
                    return 1;
                    
                }
                
                // ***********************************************************************
                // Set output frame parameters

                fitsfile *output_f_ptr;
        
                int output_f_status = 0;
                long output_f_naxes [2] = {nxelements, 1};
        
                long output_f_fpixel = 1;

                // ***********************************************************************
                // Create and write [output_frame_values] to output file (ARG 6)
        
                if (!fits_create_file(&output_f_ptr, output_f, &output_f_status)) {
        
                        if (!fits_create_img(output_f_ptr, INTERMEDIATE_IMG_ACCURACY[0], 2, output_f_naxes, &output_f_status)) {

                                if (!fits_write_img(output_f_ptr, INTERMEDIATE_IMG_ACCURACY[1], output_f_fpixel, nxelements, output_frame_values, &output_f_status)) {

                                } else { 

                                        write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -11, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                                        fits_report_error(stdout, output_f_status); 

                                        free(input_f);
                                        free(output_f);
                                        free(method);
                                        free(ss_method);
                                        
                                        if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 
                                        if(fits_close_file(output_f_ptr, &output_f_status)) fits_report_error (stdout, output_f_status);
                                        fclose(inputfile);

                                        return 1; 

                                }

                        } else {

                                write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -12, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                                fits_report_error(stdout, output_f_status); 

                                free(input_f);
                                free(output_f);
                                free(method);
                                free(ss_method);
                                
                                if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 
                                if(fits_close_file(output_f_ptr, &output_f_status)) fits_report_error (stdout, output_f_status);
                                fclose(inputfile);

                                return 1; 

                        }

                } else {

                        write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -13, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                        fits_report_error(stdout, output_f_status); 

                        free(input_f);
                        free(output_f);
                        free(method);
                        if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); 
                        fclose(inputfile);

                        return 1; 

                }                
                
                // ***********************************************************************
                // Free arrays on heap

                free(input_f);
                free(output_f);
                free(method);  
                free(ss_method);
                
                // ***********************************************************************
                // Close input file (ARG 1) and output file (ARG 6)          
                
                if(fits_close_file(input_f_ptr, &input_f_status)) { 

                        write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -14, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                        fits_report_error (stdout, input_f_status); 

                        return 1; 

                }     
               
                if(fits_close_file(output_f_ptr, &output_f_status)) { 

                        write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -15, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                        fits_report_error (stdout, output_f_status); 

                        return 1; 

                }  
                
                if (fclose(inputfile)) {
                        write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATTR", -16, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);
                        return 1; 
                } 
                
                // Write success to [ERROR_CODES_FILE]

                write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", RETURN_FLAG, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS);

                return 0;

        }

}
コード例 #24
0
ファイル: aXe_PET2SPC.c プロジェクト: nfourmanoit/TIPS
int
main (int argc, char *argv[])
{
  char *opt;

  char grism_file[MAXCHAR];
  char grism_file_path[MAXCHAR];

  char aper_file[MAXCHAR];
  char aper_file_path[MAXCHAR];

  char obj_PET_file[MAXCHAR];
  char obj_PET_file_path[MAXCHAR];

  char bck_PET_file[MAXCHAR];
  char bck_PET_file_path[MAXCHAR];

  char conf_file[MAXCHAR];
  char conf_file_path[MAXCHAR];

  char SPC_file[MAXCHAR];
  char SPC_file_path[MAXCHAR];

  char SPC_opt_file[MAXCHAR];
  char SPC_opt_file_path[MAXCHAR];

  char WHT_file[MAXCHAR];
  char WHT_file_path[MAXCHAR];

  char label[MAXCHAR];

  int i, index, dobck = 0, noflux = 1;

  object **oblist;

  FITScards      *cards;

  ap_pixel *obj_PET = NULL, *bck_PET = NULL;

  observation *obs;

  //tracestruct *trace;
  aperture_conf *conf;

  spectrum *obj_spec = NULL, *bck_spec = NULL, *sobj_spec = NULL;
  spectrum *resp;
  response_function *resp_func;
  calib_function *wl_calibration;

  fitsfile *OPET_ptr, *BPET_ptr;
  int f_status = 0;

  fitsfile *SPC_ptr, *SPC_opt_ptr, *WHT_ptr;

  gsl_matrix *weights;
  drzstamp     *modvar;

  int obj_aperID, obj_beamID, objindex;
  int bck_aperID, bck_beamID;

  char table[MAXCHAR], table_path[MAXCHAR];
  //char comment[FLEN_COMMENT];
  int empty;
  int drizzle;
  int quant_cont=0;
  int opt_weights=0;
  int for_grism=0;
  int smooth_conv=0;

  d_point smooth_params;

  double exptime;
  double sky_cps;

  drzstamp_dim  dimension;
  gsl_matrix *coverage;

  if (((argc < 3))
      || (opt = get_online_option ("help", argc, argv)))
    {
      fprintf (stdout,
	       "ST-ECF European Coordinating Facility\n"
	       "Copyright (C) 2002 Martin Kuemmel\n"
	       "aXe_PET2SPC Version %s:\n"
	       "             aXe task that produces 1-D, binned spectra using information\n"
	       "             contained in a OPET and a BPET. A 1-D spectrum is generated\n"
	       "             for each beam in each of both the OPET and the BPET files\n"
	       "             The binned background spectra of each beam (order) is then\n"
	       "             subtraced from the corresponding spectra form the OPET. Th\ne"
	       "             background subtraction (and reading a BPET altogether can be\n"
	       "             avoided by using the -noBPET option\n"
	       "             An SPC file, a multi-extension FITS file containing binned\n"
	       "             spectra is produced. Each extension (named after the beam ID,\n"
	       "             e.g. 11B for aperture (object) 11,beam (order) B) contains the\n"
	       "             following columns:\n"
	       "\n"
	       "              LAMBDA      ; the wavelength (in A)\n"
	       "              TCOUNT      ; the total number of counts (in DN)\n"
	       "              TERROR      ; the error in TERRORS (in DN)\n"
	       "              BCOUNT      ; the estimated number of counts from the\n"
	       "                            background (in DN)\n"
	       "              BERROR      ; the error in BCOUNTS (in DN)\n"
	       "              COUNT       ; the estimated number of counts from the\n"
	       "                            object (in DN)\n"
	       "              ERROR       ; the error in COUNTS (in DN)\n"
	       "              FLUX        ; the estimated flux (in erg/s/cm^2/A)\n"
	       "              FERROR      ; the error in FLUX (in erg/s/cm^s/A)\n"
	       "              WEIGHT      ; weight (in pixels)\n"
	       "\n"
	       "             Input FITS mages are looked for in $AXE_IMAGE_PATH\n"
	       "             aXe config file is looked for in $AXE_CONFIG_PATH\n"
	       "             All outputs are writen to $AXE_OUTPUT_PATH\n"
	       "\n"
	       "Usage:\n"
	       "     aXe_PET2SPC [g/prism image filename] [aXe config file name] [options]\n"
	       "\n"
	       "Options:\n"
	       "             -noBPET         - to disable the use of a BPET file\n"
	       "             -noflux         - to disable the flux calibration\n"
	       "             -drz            - use $AXE_DRIZZLE_PATH to locate the grism-, OAF-\n"
	       "                             - and PET-files instead of $AXE_IMAGE/OUTPUT_PATH\n"
	       "             -in_AF=[string] - overwrite the default input Aperture File name\n"
	       "             -OPET=[string]  - overwrite the default input Object PET file name\n"
	       "             -BPET=[string]  - overwrite the default input Background PET\n"
	       "                               file name\n"
	       "             -out_SPC=[string] - overwrite the default output SPC file name\n"
	       "\n"
	       "Example:\n"
	       "       ./aXe_PET2SPC slim_grism.fits SLIM.conf.A.0\n"
	       "\n",RELEASE);
      exit (1);
    }

  // make a general opening statement
  fprintf (stdout, "aXe_PET2SPC: Starting...\n");

  // get the name of the flt-file
  index = 0;
  strcpy (grism_file, argv[++index]);
  if ((opt = get_online_option ("drz", argc, argv)))
    {
      build_path (AXE_DRIZZLE_PATH, grism_file, grism_file_path);
      drizzle=1;
    }
  else
    {
      build_path (AXE_IMAGE_PATH, grism_file, grism_file_path);
      drizzle=0;
    }

  // get the name of the configuration file
  strcpy (conf_file, argv[++index]);
  build_path (AXE_CONFIG_PATH, conf_file, conf_file_path);

  // load the configuration file
  conf = get_aperture_descriptor (conf_file_path);

  // Determine where the various extensions are in the FITS file
  get_extension_numbers(grism_file_path, conf,conf->optkey1,conf->optval1);


  // Build aperture file name
  replace_file_extension (grism_file, aper_file, ".fits",
			  ".OAF", conf->science_numext);
  if (drizzle)
    build_path (AXE_DRIZZLE_PATH, aper_file, aper_file_path);
  else
    build_path (AXE_OUTPUT_PATH, aper_file, aper_file_path);

  // Build object PET file name
  replace_file_extension (grism_file, obj_PET_file, ".fits",
			  ".PET.fits", conf->science_numext);
  // make the total filename
  if (drizzle)
    build_path (AXE_DRIZZLE_PATH, obj_PET_file, obj_PET_file_path);
  else
    build_path (AXE_OUTPUT_PATH, obj_PET_file, obj_PET_file_path);


  // Build background PET file name
  replace_file_extension (grism_file, bck_PET_file, ".fits",
			  ".BCK.PET.fits", conf->science_numext);

  // make the total filename
  if (drizzle)
    build_path (AXE_DRIZZLE_PATH, bck_PET_file, bck_PET_file_path);
  else
    build_path (AXE_OUTPUT_PATH, bck_PET_file, bck_PET_file_path);

  // make a non-standard AF name if necessary
  if ((opt = get_online_option ("in_AF", argc, argv)))
    {
      strcpy(aper_file,opt);
      strcpy(aper_file_path,opt);
    }

  // make a non-standard PET name if necessary
  if ((opt = get_online_option ("OPET", argc, argv)))
    {
      strcpy(obj_PET_file,opt);
      strcpy(obj_PET_file_path,opt);
    }

  // make a non-standard BPET name if necessary
  if ((opt = get_online_option ("BPET", argc, argv)))
    {
      strcpy(bck_PET_file,opt);
      strcpy(bck_PET_file_path,opt);
    }

  // set the flagg for no background subtraction
  if ((opt = get_online_option ("noBPET",argc,argv)))
    {
      dobck = 0;
      strcpy(bck_PET_file,"None");
      strcpy(bck_PET_file_path, "None");
    }
  else
    {
      dobck = 1;
    }

  // set the flagg for flux
  if ((opt = get_online_option ("noflux",argc,argv)))
    noflux = 1;
  else
    noflux = 0;

  // check for the weights flagg,
  // set the file name if the flagg is set
  if ((opt = get_online_option ("opt_weights",argc,argv)))
    opt_weights = 1;
  else
    opt_weights = 0;

  // read the trigger for smoothing the sensitivity
  if ((opt = get_online_option ("smooth_conv",argc,argv)))
    smooth_conv = 1;
  else
    smooth_conv = 0;

  if ((opt = get_online_option ("out_SPC", argc, argv)))
    {
      strcpy (SPC_file, opt);
      strcpy (SPC_file_path, opt);

      if (opt_weights)
	{
	  replace_file_extension (SPC_file, SPC_opt_file, ".fits",
			      "_opt.SPC.fits", -1);
	  replace_file_extension (SPC_file_path, SPC_opt_file_path, ".fits",
			      "_opt.SPC.fits", -1);
	  replace_file_extension (SPC_opt_file, WHT_file, ".SPC.fits",
				  ".WHT.fits", -1);
	  replace_file_extension (SPC_opt_file_path, WHT_file_path, ".SPC.fits",
				  ".WHT.fits", -1);
	}
    }
  else
    {
      replace_file_extension (obj_PET_file, SPC_file, ".PET.fits",
			      ".SPC.fits", -1);
      if (drizzle)
	build_path (AXE_DRIZZLE_PATH, SPC_file, SPC_file_path);
      else
	build_path (AXE_OUTPUT_PATH, SPC_file, SPC_file_path);

      if (opt_weights)
	{
	  replace_file_extension (obj_PET_file, SPC_opt_file, ".PET.fits",
				  "_opt.SPC.fits", -1);
	  replace_file_extension (SPC_opt_file, WHT_file, ".SPC.fits",
				  ".WHT.fits", -1);
	  if (drizzle)
	    {
	      build_path (AXE_DRIZZLE_PATH, SPC_opt_file, SPC_opt_file_path);
	      build_path (AXE_DRIZZLE_PATH, WHT_file, WHT_file_path);
	    }
	  else
	    {
	      build_path (AXE_OUTPUT_PATH, SPC_opt_file, SPC_opt_file_path);
	      build_path (AXE_OUTPUT_PATH, WHT_file, WHT_file_path);
	    }
	}
    }

  // check the configuration file for the smoothin keywords
  if (!check_conf_for_smoothing(conf, smooth_conv))
    aXe_message(aXe_M_FATAL, __FILE__, __LINE__,
        "aXe_PET2SP: Either the configuration file %s does not contain\n"
        "the necessary keywords for the smoothing (POBJSIZE, SMFACTOR),\n"
        "or one of these keywords has an unreasonable value < 0.0!\n",
        conf_file_path);


  // give feedback onto the screen:
  // report on input and output
  // and also on specific parameter
  fprintf (stdout, "aXe_PET2SPC: Input configuration file name:   %s\n",
	   conf_file_path);
  fprintf (stdout, "aXe_PET2SPC: Input Object Aperture file name: %s\n",
	   aper_file_path);
  fprintf (stdout, "aXe_PET2SPC: Input Object PET file name:      %s\n",
	   obj_PET_file_path);
  if (dobck)
    fprintf (stdout, "aXe_PET2SPC: Input Background PET file name:  %s\n",
	     bck_PET_file_path);
  fprintf (stdout, "aXe_PET2SPC: Output SPC file name:            %s\n",
	   SPC_file_path);
  if (opt_weights)
    {
      fprintf (stdout, "aXe_PET2SPC: Computing optimal weights.\n");
      fprintf (stdout, "aXe_PET2SPC: Optimized SPC file name:         %s\n",
	       SPC_opt_file_path);
      fprintf (stdout, "aXe_PET2SPC: Output WHT file name:            %s\n",
	       WHT_file_path);
    }
  if (!noflux)
    {
      fprintf (stdout, "aXe_PET2SPC: Performing flux calibration.\n");
      if (smooth_conv)
	fprintf (stdout, "aXe_PET2SPC: Using smoothed sensitivity curves.\n");
    }
  fprintf (stdout, "\n\n");

  //
  // try to get the descriptor 'exptime' from the 'sci'-extension
  //
  exptime = (double)get_float_from_keyword(grism_file_path, conf->science_numext, conf->exptimekey);
  if (isnan(exptime))
    exptime = (double)get_float_from_keyword(grism_file_path, 1, conf->exptimekey);
  if (isnan(exptime))
    exptime = 1.0;

  //
  // try to get the descriptor 'SKY_CPS' from the 'sci'-extension
  //
  sky_cps = (double)get_float_from_keyword(grism_file_path, conf->science_numext, "SKY_CPS");
  if (isnan(sky_cps))
    sky_cps = 0.0;


  //  Open the OPET file for reading
  fits_open_file (&OPET_ptr, obj_PET_file_path, READONLY, &f_status);
  if (f_status)
    {
      ffrprt (stderr, f_status);
      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		   "aXe_PET2SPC: Could not open file: %s\n",
		   obj_PET_file_path);
    }

  // check whether the contamination is quantitative
  quant_cont = check_quantitative_contamination(OPET_ptr);

  if (opt_weights && !quant_cont)
    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		 "aXe_PET2SPC: The optimal extractions needs quantitative contamination! "
		 " Please re-run aXe with Gauss or Fluxcube contamination!");

  obs = load_dummy_observation ();
  /* Loading the object list */
  fprintf (stdout, "aXe_PET2SPC: Loading object aperture list...");
  oblist = file_to_object_list_seq (aper_file_path, obs);
  fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist));

  if (dobck)
    {
      //  Open the file for reading
      fits_open_file (&BPET_ptr, bck_PET_file_path, READONLY, &f_status);
      if (f_status)
	{
	  ffrprt (stderr, f_status);
	  aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		       "aXe_PET2SP: Could not open file: %s\n",
		       bck_PET_file_path);
	}
    }


  /* Copy the header info from the grism image */
  SPC_ptr = create_SPC_opened (SPC_file_path,1);
  cards = get_FITS_cards_opened(OPET_ptr);
  put_FITS_cards_opened(SPC_ptr, cards);
  free_FITScards(cards);

  if (opt_weights)
    {
      cards = get_FITS_cards_opened(OPET_ptr);

      // open the WHT file and add the header keywords
      WHT_ptr = create_FITSimage_opened (WHT_file_path, 1);
      put_FITS_cards_opened(WHT_ptr, cards);

      // open the opt_SPC and add the header keywords
      SPC_opt_ptr = create_SPC_opened (SPC_opt_file_path,1);
      put_FITS_cards_opened(SPC_opt_ptr, cards);

      // delete the header keywords
      free_FITScards(cards);
    }

  // do something only if there
  // exist valid objects
  i = 0;
  if (oblist!=NULL)
    {

      // turn until the end of the PET is reached
      while (1)
	{
	  empty=0;

	  // Get the PET for this object
	  obj_PET = get_ALL_from_next_in_PET(OPET_ptr, &obj_aperID, &obj_beamID);

	  // load the background PET if requested
	  if (dobck)
	    {
	      bck_PET = get_ALL_from_next_in_PET(BPET_ptr, &bck_aperID, &bck_beamID);
	      if ((bck_aperID!=obj_aperID)||(bck_beamID!=obj_beamID))
		aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
			     "Background PET and Object PET extensions are not"
			     " in the same order and cannot be combined.\n");
	    }

	  // end of PET reached: the break condition
	  if ((obj_aperID==-1) && (obj_beamID==-1))
	    break;

	  // signal an empty PET
	  if (obj_PET==NULL)
	    empty=1;

	  // give feedback to the screen
	  fprintf (stdout, "aXe_PET2SPC: BEAM %d; %d%c\n", i, obj_aperID, BEAM(obj_beamID));fflush(stdout);

	  // identify the object which matches the PET
	  objindex =  find_object_in_object_list(oblist,obj_aperID);

	  // look whether we are for grisms or prisms
	  for_grism = check_for_grism (conf_file_path, obj_beamID);
	  wl_calibration  = get_calfunc_for_beam(oblist[objindex]->beams[obj_beamID], for_grism, conf_file_path, conf);

	  // compute the object spectrum
	  obj_spec = bin_naive (obj_PET, oblist[objindex]->beams[obj_beamID].width,
				oblist[objindex]->beams[obj_beamID].orient,	quant_cont);

	  // check for the existence of a background PET
	  if (dobck)
	    {
	      // compute the background spectrum
	      bck_spec = bin_naive (bck_PET,
				    oblist[objindex]->beams[bck_beamID].width,
				    oblist[objindex]->beams[bck_beamID].orient, quant_cont);
	    }
	  else
	    {
	      // create a dummy background spectrum
	      bck_spec = empty_counts_spectrum_copy(obj_spec);
	    }


	  // subtract the background spectrum from the
	  // object (or forground) spectrum
	  sobj_spec = subtract_spectra (obj_spec, bck_spec);

	  if(!noflux)
	    {
	      get_troughput_table_name(conf_file_path,
				       oblist[objindex]->beams[obj_beamID].ID,
				       table);
	      if (strcmp(table,"None"))
		{
		  build_path (AXE_CONFIG_PATH, table, table_path);
		  resp=get_response_function_from_FITS(table_path,2);
		  resp_func = create_response_function(table_path);
		  if (resp->spec_len <2)
		    {
		      aXe_message (aXe_M_WARN1, __FILE__, __LINE__,
				   "Throughput table %s contains only %d"
				   " values. No sensitivity curve was applied.\n",
				   table_path,resp->spec_len);
		    }
		  else
		    {
		      fprintf(stdout,"aXe_PET2SPC: Applying sensitivity contained in %s\n",table_path);
		      smooth_params = get_smooth_pars_for_beam(conf, smooth_conv, oblist[objindex]->beams[obj_beamID]);
		      if (smooth_params.x > 0.0)
		        {
		          // apply a smoothed flux conversion
			  apply_smoothed_response(wl_calibration, for_grism, quant_cont, resp_func, smooth_params, sobj_spec);
			}
		      else
			{
			  // apply a normal flux conversion
			  apply_response_function(sobj_spec,resp, quant_cont);
			}
		    }
		  // free the memory of the
		  // response functions
		  free_spectrum(resp);
		  free_response_function(resp_func);
		}
	    }
	  if (empty!=1)
	    {
	      add_spectra_to_SPC_opened (SPC_ptr, obj_spec, bck_spec,
					 sobj_spec, oblist[objindex]->ID, oblist[objindex]->beams[obj_beamID].ID);


	      /* Copy header from OPET extension into this SPC extension */
	      cards = get_FITS_cards_opened(OPET_ptr);
	      put_FITS_cards_opened(SPC_ptr,cards);
	      free_FITScards(cards);

	    }

	  free_spectrum (bck_spec);
	  free_spectrum (sobj_spec);
	  free_spectrum (obj_spec);


	  if (opt_weights)
	    {
	      // get the dimension in trace length
	      // and crossdispersion
	      dimension = get_all_dims(obj_PET, bck_PET,
				       oblist[objindex]->beams[obj_beamID], dobck);

	      // check for empty PET
	      if (!dimension.resolution)
		{
		  // create dummies in case of empty PET's
		  weights = get_default_weight();
		  modvar  = get_default_modvar();
		}
	      else
		{
		  // prepare the PET's by computing the inverse variance.
		  // Also the trace distances are shifted by 0.5
		  // to get a sampling comparable to the unweighted
		  // extraction
		  prepare_inv_variance(obj_PET, bck_PET, dobck, conf, exptime, sky_cps, 0.0);

		  // compute the inverse variance and the profile
		  // image in the trace distance - crossdispersion plane
		  modvar = compute_modvar(obj_PET, oblist[objindex]->beams[obj_beamID], dimension);

		  // compute the optimal weights
		  weights = comp_allweight(modvar);

		}

	      if (dimension.resolution && empty != 1)
		{
		  sprintf (label, "WHT_%d%c", obj_aperID, BEAM (obj_beamID));
		  gsl_to_FITSimage_opened (weights, WHT_ptr ,0,label);

		  // make and store the default header
		  cards = beam_to_FITScards(oblist[objindex],obj_beamID);
		  put_FITS_cards_opened(WHT_ptr,cards);
		  free_FITScards(cards);
		}

	      // create the optimal weighted
	      // foreground spectrum
	      obj_spec = bin_optimal (obj_PET,oblist[objindex]->beams[obj_beamID],
				      quant_cont, weights, dimension, coverage);



	      // check for the presence of a background PET
	      if (dobck)
		{
		  // create the optimal weighted
		  // background spectrum
		  bck_spec = bin_optimal (bck_PET,oblist[objindex]->beams[obj_beamID],
					  quant_cont, weights, dimension, coverage);
		}
	      else
		{
		  // make a dummy background spectrum
		  bck_spec = empty_counts_spectrum_copy(obj_spec);
		}

	      // release memory
	      gsl_matrix_free(weights);
	      free_drzstamp(modvar);


	  // subtract the background spectrum from the
	  // object (or forground) spectrum
	  sobj_spec = subtract_spectra (obj_spec, bck_spec);

	  if(!noflux)
	    {
	      get_troughput_table_name(conf_file_path,
				       oblist[objindex]->beams[obj_beamID].ID,
				       table);
	    if (strcmp(table,"None"))
	      {
		build_path (AXE_CONFIG_PATH, table, table_path);
		resp=get_response_function_from_FITS(table_path,2);
		resp_func = create_response_function(table_path);
		if (resp->spec_len <2)
		  {
		    aXe_message (aXe_M_WARN1, __FILE__, __LINE__,
				 "Throughput table %s contains only %d"
				 " values. No sensitivity curve was applied.\n",
				 table_path,resp->spec_len);
		  }
		else
		  {
		    fprintf(stdout,"aXe_PET2SPC: Applying sensitivity contained in %s\n",table_path);
		    smooth_params = get_smooth_pars_for_beam(conf, smooth_conv, oblist[objindex]->beams[obj_beamID]);
                    if (smooth_params.x > 0.0)
                      {
                        apply_smoothed_response(wl_calibration, for_grism, quant_cont, resp_func, smooth_params, sobj_spec);
                      }
		    else
		      {
			apply_response_function(sobj_spec,resp, quant_cont);
		      }
		  }
		// free the memory
		free_spectrum(resp);
		free_response_function(resp_func);
	      }
	    }
	  if (empty!=1)
	    {
	      add_spectra_to_SPC_opened (SPC_opt_ptr, obj_spec, bck_spec,
					 sobj_spec, oblist[objindex]->ID, oblist[objindex]->beams[obj_beamID].ID);


	      /* Copy header from OPET extension into this SPC extension */
	      cards = get_FITS_cards_opened(OPET_ptr);
	      put_FITS_cards_opened(SPC_opt_ptr,cards);
	      free_FITScards(cards);

	    }

	  free_spectrum (bck_spec);
	  free_spectrum (sobj_spec);
	  free_spectrum (obj_spec);
	    }

	  // free memory
	  free_calib (wl_calibration);
	  if (bck_PET!=NULL)
	    free (bck_PET);
	  if (obj_PET!=NULL)
	    free (obj_PET);
	  i++;
        }
    }

  fits_close_file (SPC_ptr, &f_status);
  if (f_status)
    {
      ffrprt (stderr, f_status);
      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		   "aXe_PET2SPC: " "Error closing SPC: %s\n",
		   SPC_file_path);
    }

  if (opt_weights)
    {
      fits_close_file (WHT_ptr, &f_status);
      if (f_status)
	{
	  ffrprt (stderr, f_status);
	  aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		       "aXe_PET2SPC: " "Error closing WHT: %s\n",
		       WHT_file_path);
	}
      fits_close_file (SPC_opt_ptr, &f_status);
      if (f_status)
	{
	  ffrprt (stderr, f_status);
	  aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
		       "aXe_PET2SPC: " "Error closing PSC: %s\n",
		       SPC_opt_file_path);
	}
    }

  if (oblist!=NULL)
    free_oblist (oblist);

  fprintf (stdout, "aXe_PET2SPC: Done...\n");
  exit (0);
}
コード例 #25
0
ファイル: psrfits.c プロジェクト: nextgen-astrodata/presto
void read_PSRFITS_files(struct spectra_info *s)
// Read and convert PSRFITS information from a group of files 
// and place the resulting info into a spectra_info structure.
{
    int IMJD, SMJD, itmp, ii, status = 0;
    double OFFS, dtmp;
    long double MJDf;
    char ctmp[80], comment[120];
    
    s->datatype = PSRFITS;
    s->fitsfiles = (fitsfile **)malloc(sizeof(fitsfile *) * s->num_files);
    s->start_subint = gen_ivect(s->num_files);
    s->num_subint = gen_ivect(s->num_files);
    s->start_spec = (long long *)malloc(sizeof(long long) * s->num_files);
    s->num_spec = (long long *)malloc(sizeof(long long) * s->num_files);
    s->num_pad = (long long *)malloc(sizeof(long long) * s->num_files);
    s->start_MJD = (long double *)malloc(sizeof(long double) * s->num_files);
    s->N = 0;
    s->num_beams = 1;
    s->get_rawblock = &get_PSRFITS_rawblock;
    s->offset_to_spectra = &offset_to_PSRFITS_spectra;

    // By default, don't flip the band.  But don't change
    // the input value if it is aleady set to flip the band always
    if (s->apply_flipband==-1) s->apply_flipband = 0;

    // Step through the other files
    for (ii = 0 ; ii < s->num_files ; ii++) {

        // Is the file a PSRFITS file?
        if (!is_PSRFITS(s->filenames[ii])) {
            fprintf(stderr, 
                    "\nError!  File '%s' does not appear to be PSRFITS!\n", 
                    s->filenames[ii]);
            exit(1);
        }
        
        // Open the PSRFITS file
        fits_open_file(&(s->fitsfiles[ii]), s->filenames[ii], READONLY, &status);

        // Is the data in search mode?
        fits_read_key(s->fitsfiles[ii], TSTRING, "OBS_MODE", ctmp, comment, &status);
        // Quick fix for Parkes DFB data (SRCH?  why????)...
        if (strcmp("SRCH", ctmp)==0) {
            strncpy(ctmp, "SEARCH", 40);
        }
        if (strcmp(ctmp, "SEARCH")) {
            fprintf(stderr, 
                    "\nError!  File '%s' does not contain SEARCH-mode data!\n", 
                    s->filenames[ii]);
            exit(1);
        }

        // Now get the stuff we need from the primary HDU header
        fits_read_key(s->fitsfiles[ii], TSTRING, "TELESCOP", ctmp, comment, &status); \
        // Quick fix for MockSpec data...
        if (strcmp("ARECIBO 305m", ctmp)==0) {
            strncpy(ctmp, "Arecibo", 40);
        }
        // Quick fix for Parkes DFB data...
        {
            char newctmp[80];

            // Copy ctmp first since strlower() is in-place
            strcpy(newctmp, ctmp);
            if (strcmp("parkes", strlower(remove_whitespace(newctmp)))==0) {
                strncpy(ctmp, "Parkes", 40);
            }
        }
        if (status) {
            printf("Error %d reading key %s\n", status, "TELESCOP");
            if (ii==0) s->telescope[0]='\0';
            if (status==KEY_NO_EXIST) status=0;
        } else {
            if (ii==0) strncpy(s->telescope, ctmp, 40);
            else if (strcmp(s->telescope, ctmp)!=0)
                printf("Warning!:  %s values don't match for files 0 and %d!\n",
                       "TELESCOP", ii);
        }

        get_hdr_string("OBSERVER", s->observer);
        get_hdr_string("SRC_NAME", s->source);
        get_hdr_string("FRONTEND", s->frontend);
        get_hdr_string("BACKEND", s->backend);
        get_hdr_string("PROJID", s->project_id);
        get_hdr_string("DATE-OBS", s->date_obs);
        get_hdr_string("FD_POLN", s->poln_type);
        get_hdr_string("RA", s->ra_str);
        get_hdr_string("DEC", s->dec_str);
        get_hdr_double("OBSFREQ", s->fctr);
        get_hdr_int("OBSNCHAN", s->orig_num_chan);
        get_hdr_double("OBSBW", s->orig_df);
        //get_hdr_double("CHAN_DM", s->chan_dm);
        get_hdr_double("BMIN", s->beam_FWHM);

        /* This is likely not in earlier versions of PSRFITS so */
        /* treat it a bit differently                           */
        fits_read_key(s->fitsfiles[ii], TDOUBLE, "CHAN_DM", 
                      &(s->chan_dm), comment, &status);
        if (status==KEY_NO_EXIST) {
            status = 0;
            s->chan_dm = 0.0;
        }

        // Don't use the macros unless you are using the struct!
        fits_read_key(s->fitsfiles[ii], TINT, "STT_IMJD", &IMJD, comment, &status);
        s->start_MJD[ii] = (long double) IMJD;
        fits_read_key(s->fitsfiles[ii], TINT, "STT_SMJD", &SMJD, comment, &status);
        fits_read_key(s->fitsfiles[ii], TDOUBLE, "STT_OFFS", &OFFS, comment, &status);
        s->start_MJD[ii] += ((long double) SMJD + (long double) OFFS) / SECPERDAY;

        // Are we tracking?
        fits_read_key(s->fitsfiles[ii], TSTRING, "TRK_MODE", ctmp, comment, &status);
        itmp = (strcmp("TRACK", ctmp)==0) ? 1 : 0;
        if (ii==0) s->tracking = itmp;
        else if (s->tracking != itmp)
            printf("Warning!:  TRK_MODE values don't match for files 0 and %d!\n", ii);

        // Now switch to the SUBINT HDU header
        fits_movnam_hdu(s->fitsfiles[ii], BINARY_TBL, "SUBINT", 0, &status);
        get_hdr_double("TBIN", s->dt);
        get_hdr_int("NCHAN", s->num_channels);
        get_hdr_int("NPOL", s->num_polns);
        get_hdr_string("POL_TYPE", s->poln_order);
        fits_read_key(s->fitsfiles[ii], TINT, "NCHNOFFS", &itmp, comment, &status);
        if (itmp > 0)
            printf("Warning!:  First freq channel is not 0 in file %d!\n", ii);
        get_hdr_int("NSBLK", s->spectra_per_subint);
        get_hdr_int("NBITS", s->bits_per_sample);
        fits_read_key(s->fitsfiles[ii], TINT, "NAXIS2", 
                      &(s->num_subint[ii]), comment, &status);
        fits_read_key(s->fitsfiles[ii], TINT, "NSUBOFFS", 
                      &(s->start_subint[ii]), comment, &status);
        s->time_per_subint = s->dt * s->spectra_per_subint;

        /* This is likely not in earlier versions of PSRFITS so */
        /* treat it a bit differently                           */
        fits_read_key(s->fitsfiles[ii], TFLOAT, "ZERO_OFF", 
                      &(s->zero_offset), comment, &status);
        if (status==KEY_NO_EXIST) {
            status = 0;
            s->zero_offset = 0.0;
        }
        s->zero_offset = fabs(s->zero_offset);

        // Get the time offset column info and the offset for the 1st row
        {
            double offs_sub;
            int colnum, anynull, numrows;

            // Identify the OFFS_SUB column number
            fits_get_colnum(s->fitsfiles[ii], 0, "OFFS_SUB", &colnum, &status);
            if (status==COL_NOT_FOUND) {
                printf("Warning!:  Can't find the OFFS_SUB column!\n");
                status = 0; // Reset status
            } else {
                if (ii==0) {
                    s->offs_sub_col = colnum;
                } else if (colnum != s->offs_sub_col) {
                    printf("Warning!:  OFFS_SUB column changes between files!\n");
                }
            }

            // Read the OFFS_SUB column value for the 1st row
            fits_read_col(s->fitsfiles[ii], TDOUBLE,
                          s->offs_sub_col, 1L, 1L, 1L,
                          0, &offs_sub, &anynull, &status);

            numrows = (int)((offs_sub - 0.5 * s->time_per_subint) /
                            s->time_per_subint + 1e-7);
            // Check to see if any rows have been deleted or are missing
            if (numrows > s->start_subint[ii]) {
                printf("Warning: NSUBOFFS reports %d previous rows\n"
                       "         but OFFS_SUB implies %d.  Using OFFS_SUB.\n"
                       "         Will likely be able to correct for this.\n",
                       s->start_subint[ii], numrows);
            }
            s->start_subint[ii] = numrows;
        }

        // This is the MJD offset based on the starting subint number
        MJDf = (s->time_per_subint * s->start_subint[ii]) / SECPERDAY;
        // The start_MJD values should always be correct
        s->start_MJD[ii] += MJDf;

        // Compute the starting spectra from the times
        MJDf = s->start_MJD[ii] - s->start_MJD[0];
        if (MJDf < 0.0) {
            fprintf(stderr, "Error!: File %d seems to be from before file 0!\n", ii); 
            exit(1);
        }
        s->start_spec[ii] = (long long)(MJDf * SECPERDAY / s->dt + 0.5);

        // Now pull stuff from the other columns
        {
            float ftmp;
            long repeat, width;
            int colnum, anynull;
            
            // Identify the data column and the data type
            fits_get_colnum(s->fitsfiles[ii], 0, "DATA", &colnum, &status);
            if (status==COL_NOT_FOUND) {
                printf("Warning!:  Can't find the DATA column!\n");
                status = 0; // Reset status
            } else {
                if (ii==0) {
                    s->data_col = colnum;
                    fits_get_coltype(s->fitsfiles[ii], colnum, &(s->FITS_typecode), 
                                     &repeat, &width, &status);
                } else if (colnum != s->data_col) {
                    printf("Warning!:  DATA column changes between files!\n");
                }
            }
            
            // Telescope azimuth
            fits_get_colnum(s->fitsfiles[ii], 0, "TEL_AZ", &colnum, &status);
            if (status==COL_NOT_FOUND) {
                s->azimuth = 0.0;
                status = 0; // Reset status
            } else {
                fits_read_col(s->fitsfiles[ii], TFLOAT, colnum, 
                              1L, 1L, 1L, 0, &ftmp, &anynull, &status);
                if (ii==0) s->azimuth = (double) ftmp;
            }
            
            // Telescope zenith angle
            fits_get_colnum(s->fitsfiles[ii], 0, "TEL_ZEN", &colnum, &status);
            if (status==COL_NOT_FOUND) {
                s->zenith_ang = 0.0;
                status = 0; // Reset status
            } else {
                fits_read_col(s->fitsfiles[ii], TFLOAT, colnum, 
                              1L, 1L, 1L, 0, &ftmp, &anynull, &status);
                if (ii==0) s->zenith_ang = (double) ftmp;
            }
            
            // Observing frequencies
            fits_get_colnum(s->fitsfiles[ii], 0, "DAT_FREQ", &colnum, &status);
            if (status==COL_NOT_FOUND) {
                printf("Warning!:  Can't find the channel freq column!\n");
                status = 0; // Reset status
            } else {
                int jj;
                float *freqs = (float *)malloc(sizeof(float) * s->num_channels);
                fits_read_col(s->fitsfiles[ii], TFLOAT, colnum, 1L, 1L, 
                              s->num_channels, 0, freqs, &anynull, &status);
                
                if (ii==0) {
                    s->df = freqs[1]-freqs[0];
                    s->lo_freq = freqs[0];
                    s->hi_freq = freqs[s->num_channels-1];
                    // Now check that the channel spacing is the same throughout
                    for (jj = 0 ; jj < s->num_channels - 1 ; jj++) {
                        ftmp = freqs[jj+1] - freqs[jj];
                        if (fabs(ftmp - s->df) > 1e-7)
                            printf("Warning!:  Channel spacing changes in file %d!\n", ii);
                    }
                } else {
                    ftmp = fabs(s->df-(freqs[1]-freqs[0]));
                    if (ftmp > 1e-7)
                        printf("Warning!:  Channel spacing changes between files!\n");
                    ftmp = fabs(s->lo_freq-freqs[0]);
                    if (ftmp > 1e-7)
                        printf("Warning!:  Low channel changes between files!\n");
                    ftmp = fabs(s->hi_freq-freqs[s->num_channels-1]);
                    if (ftmp > 1e-7)
                        printf("Warning!:  High channel changes between files!\n");
                }
                free(freqs);
            }
            
            // Data weights
            fits_get_colnum(s->fitsfiles[ii], 0, "DAT_WTS", &colnum, &status);
            if (status==COL_NOT_FOUND) {
                printf("Warning!:  Can't find the channel weights!\n");
                status = 0; // Reset status
            } else {
                if (s->apply_weight < 0) { // Use the data to decide
                    int jj;
                    if (ii==0) {
                        s->dat_wts_col = colnum;
                    } else if (colnum != s->dat_wts_col) {
                        printf("Warning!:  DAT_WTS column changes between files!\n");
                    }
                    float *fvec = (float *)malloc(sizeof(float) * s->num_channels);
                    fits_read_col(s->fitsfiles[ii], TFLOAT, s->dat_wts_col, 1L, 1L, 
                                  s->num_channels, 0, fvec, &anynull, &status);
                    for (jj = 0 ; jj < s->num_channels ; jj++) {
                        // If the weights are not 1, apply them
                        if (fvec[jj] != 1.0) {
                            s->apply_weight = 1;
                            break;
                        }
                    }
                    free(fvec);
                }
                if (s->apply_weight < 0) s->apply_weight = 0;  // not needed
            }
            
            // Data offsets
            fits_get_colnum(s->fitsfiles[ii], 0, "DAT_OFFS", &colnum, &status);
            if (status==COL_NOT_FOUND) {
                printf("Warning!:  Can't find the channel offsets!\n");
                status = 0; // Reset status
            } else {
                if (s->apply_offset < 0) { // Use the data to decide
                    int jj;
                    if (ii==0) {
                        s->dat_offs_col = colnum;
                    } else if (colnum != s->dat_offs_col) {
                        printf("Warning!:  DAT_OFFS column changes between files!\n");
                    }
                    float *fvec = (float *)malloc(sizeof(float) * 
                                                  s->num_channels * s->num_polns);
                    fits_read_col(s->fitsfiles[ii], TFLOAT, s->dat_offs_col, 1L, 1L, 
                                  s->num_channels * s->num_polns, 
                                  0, fvec, &anynull, &status);
                    for (jj = 0 ; jj < s->num_channels * s->num_polns ; jj++) {
                        // If the offsets are not 0, apply them
                        if (fvec[jj] != 0.0) {
                            s->apply_offset = 1;
                            break;
                        }
                    }
                    free(fvec);
                }
                if (s->apply_offset < 0) s->apply_offset = 0; // not needed
            }
            
            // Data scalings
            fits_get_colnum(s->fitsfiles[ii], 0, "DAT_SCL", &colnum, &status);
            if (status==COL_NOT_FOUND) {
                printf("Warning!:  Can't find the channel scalings!\n");
                status = 0; // Reset status
            } else {
                if (s->apply_scale < 0) { // Use the data to decide
                    int jj;
                    if (ii==0) {
                        s->dat_scl_col = colnum;
                    } else if (colnum != s->dat_scl_col) {
                        printf("Warning!:  DAT_SCL column changes between files!\n");
                    }
                    float *fvec = (float *)malloc(sizeof(float) * 
                                                  s->num_channels * s->num_polns);
                    fits_read_col(s->fitsfiles[ii], TFLOAT, colnum, 1L, 1L, 
                                  s->num_channels * s->num_polns, 
                                  0, fvec, &anynull, &status);
                    for (jj = 0 ; jj < s->num_channels * s->num_polns ; jj++) {
                        // If the scales are not 1, apply them
                        if (fvec[jj] != 1.0) {
                            s->apply_scale = 1;
                            break;
                        }
                    }
                    free(fvec);
                }
                if (s->apply_scale < 0) s->apply_scale = 0; // not needed
            }
        }
        
        // Compute the samples per file and the amount of padding
        // that the _previous_ file has
        s->num_pad[ii] = 0;
        s->num_spec[ii] = s->spectra_per_subint * s->num_subint[ii];
        if (ii > 0) {
            if (s->start_spec[ii] > s->N) { // Need padding
                s->num_pad[ii-1] = s->start_spec[ii] - s->N;
                s->N += s->num_pad[ii-1];
            }
        }
        s->N += s->num_spec[ii];
    }

    // Convert the position strings into degrees
    {
        int d, h, m;
        double sec;
        ra_dec_from_string(s->ra_str, &h, &m, &sec);
        s->ra2000 = hms2rad(h, m, sec) * RADTODEG;
        ra_dec_from_string(s->dec_str, &d, &m, &sec);
        s->dec2000 = dms2rad(d, m, sec) * RADTODEG;
    }

    // Are the polarizations summed?
    if ((strncmp("AA+BB", s->poln_order, 5)==0) ||
        (strncmp("INTEN", s->poln_order, 5)==0))
        s->summed_polns = 1;
    else
        s->summed_polns = 0;

    // Calculate some others
    s->T = s->N * s->dt;
    s->orig_df /= (double) s->orig_num_chan;
    s->samples_per_spectra = s->num_polns * s->num_channels;
    // Note:  the following is the number of bytes that will be in
    //        the returned array from CFITSIO.
    //        CFITSIO turns bits into bytes when FITS_typecode=1
    //        and we turn 2-bits or 4-bits into bytes if bits_per_sample < 8
    if (s->bits_per_sample < 8)
        s->bytes_per_spectra = s->samples_per_spectra;
    else
        s->bytes_per_spectra = (s->bits_per_sample * s->samples_per_spectra) / 8;
    s->samples_per_subint = s->samples_per_spectra * s->spectra_per_subint;
    s->bytes_per_subint = s->bytes_per_spectra * s->spectra_per_subint;
    
    // Flip the band?
    if (s->hi_freq < s->lo_freq) {
        float ftmp = s->hi_freq;
        s->hi_freq = s->lo_freq;
        s->lo_freq = ftmp;
        s->df *= -1.0;
        s->apply_flipband = 1;
    }
    // Compute the bandwidth
    s->BW = s->num_channels * s->df;

    // Flip the bytes for Parkes FB_1BIT data
    if (s->bits_per_sample==1 &&
        strcmp(s->telescope, "Parkes")==0 &&
        strcmp(s->backend, "FB_1BIT")==0) {
        printf("Flipping bit ordering since Parkes FB_1BIT data.\n");
        s->flip_bytes = 1;
    } else {
        s->flip_bytes = 0;
    }

    // Allocate the buffers
    cdatabuffer = gen_bvect(s->bytes_per_subint);
    // Following is twice as big because we use it as a ringbuffer too
    fdatabuffer = gen_fvect(2 * s->spectra_per_subint * s->num_channels);
    s->padvals = gen_fvect(s->num_channels);
    for (ii = 0 ; ii < s->num_channels ; ii++)
        s->padvals[ii] = 0.0;
    offsets = gen_fvect(s->num_channels * s->num_polns);
    scales = gen_fvect(s->num_channels * s->num_polns);
    weights = gen_fvect(s->num_channels);
    // Initialize these if we won't be reading them from the file
    if (s->apply_offset==0) 
        for (ii = 0 ; ii < s->num_channels * s->num_polns ; ii++)
            offsets[ii] = 0.0;
    if (s->apply_scale==0)
        for (ii = 0 ; ii < s->num_channels * s->num_polns ; ii++)
            scales[ii] = 1.0;
    if (s->apply_weight==0)
        for (ii = 0 ; ii < s->num_channels ; ii++)
            weights[ii] = 1.0;
}
コード例 #26
0
ファイル: tpih2.c プロジェクト: kapteyn-astro/kapteyn
int main()

{
  char infile[] = "pih.fits";
  char devtyp[16], idents[3][80], nlcprm[1], opt[2];
  int  c0[] = {-1, -1, -1, -1, -1, -1, -1};
  int  i, ic, gcode[2], naxis[2], nkeyrec, nreject, nwcs, relax, status;
  float  blc[2], trc[2];
  double cache[257][4], grid1[1], grid2[1], nldprm[1];
  struct wcsprm *wcs;
  nlfunc_t pgwcsl_;
#if defined HAVE_CFITSIO && defined DO_CFITSIO
  char *header;
  fitsfile *fptr;
#else
  char keyrec[81], header[28801];
  int  gotend, j, k;
  FILE *fptr;
#endif


  /* Set line buffering in case stdout is redirected to a file, otherwise
   * stdout and stderr messages will be jumbled (stderr is unbuffered). */
  setvbuf(stdout, NULL, _IOLBF, 0);

  printf("Testing WCSLIB parser for FITS image headers (tpih2.c)\n"
         "------------------------------------------------------\n\n");

  /* Read in the FITS header, excluding COMMENT and HISTORY keyrecords. */
#if defined HAVE_CFITSIO && defined DO_CFITSIO
  status = 0;

  if (fits_open_file(&fptr, infile, READONLY, &status)) {
    fits_report_error(stderr, status);
    return 1;
  }

  if (fits_hdr2str(fptr, 1, NULL, 0, &header, &nkeyrec, &status)) {
    fits_report_error(stderr, status);
    return 1;
  }

  fits_close_file(fptr, &status);
#else
  if ((fptr = fopen(infile, "r")) == 0x0) {
    printf("ERROR opening %s\n", infile);
    return 1;
  }

  k = 0;
  nkeyrec = 0;
  gotend = 0;
  for (j = 0; j < 10; j++) {
    for (i = 0; i < 36; i++) {
      if (fgets(keyrec, 81, fptr) == 0) {
        break;
      }

      if (strncmp(keyrec, "        ", 8) == 0) continue;
      if (strncmp(keyrec, "COMMENT ", 8) == 0) continue;
      if (strncmp(keyrec, "HISTORY ", 8) == 0) continue;

      strncpy(header+k, keyrec, 80);
      k += 80;
      nkeyrec++;

      if (strncmp(keyrec, "END     ", 8) == 0) {
        /* An END keyrecord was read, but read the rest of the block. */
        gotend = 1;
      }
    }

    if (gotend) break;
  }
  fclose(fptr);
#endif

  fprintf(stderr, "Found %d non-comment header keyrecords.\n", nkeyrec);

  relax = WCSHDR_all;
  if ((status = wcspih(header, nkeyrec, relax, 2, &nreject, &nwcs, &wcs))) {
    fprintf(stderr, "wcspih ERROR %d: %s.\n", status, wcs_errmsg[status]);
  }
#if defined HAVE_CFITSIO && defined DO_CFITSIO
  free(header);
#endif

  /* Plot setup. */
  naxis[0] = 1024;
  naxis[1] = 1024;

  blc[0] = 0.5f;
  blc[1] = 0.5f;
  trc[0] = naxis[0] + 0.5f;
  trc[1] = naxis[1] + 0.5f;

  strcpy(devtyp, "/XWINDOW");
  cpgbeg(0, devtyp, 1, 1);
  cpgvstd();

  cpgwnad(0.0f, 1.0f, 0.0f, 1.0f);
  cpgask(1);
  cpgpage();

  /* Annotation. */
  strcpy(idents[0], "Right ascension");
  strcpy(idents[1], "Declination");

  opt[0] = 'G';
  opt[1] = 'E';

  /* Compact lettering. */
  cpgsch(0.8f);

  /* Draw full grid lines. */
  cpgsci(1);
  gcode[0] = 2;
  gcode[1] = 2;
  grid1[0] = 0.0;
  grid2[0] = 0.0;

  for (i = 0; i < nwcs; i++) {
    if ((status = wcsset(wcs+i))) {
      fprintf(stderr, "wcsset ERROR %d: %s.\n", status, wcs_errmsg[status]);
      continue;
    }

    /* Get WCSNAME out of the wcsprm struct. */
    strcpy(idents[2], (wcs+i)->wcsname);
    printf("\n%s\n", idents[2]);

    /* Draw the celestial grid.  The grid density is set for each world */
    /* coordinate by specifying LABDEN = 1224. */
    ic = -1;
    cpgsbox(blc, trc, idents, opt, 0, 1224, c0, gcode, 0.0, 0, grid1, 0,
      grid2, 0, pgwcsl_, 1, WCSLEN, 1, nlcprm, (int *)(wcs+i), nldprm, 256,
      &ic, cache, &status);

    /* Draw the frame. */
    cpgbox("BC", 0.0f, 0, "BC", 0.0f, 0);

    cpgpage();
  }

  status = wcsvfree(&nwcs, &wcs);

  return 0;
}
コード例 #27
0
ファイル: test-read.c プロジェクト: esheldon/misc
int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr,"test-read filename ext\n");
        exit(EXIT_FAILURE);
    }
    fitsfile* fits=NULL;
    struct image *image=NULL;

    const char *fname=argv[1];
    int ext = atoi(argv[2]);

    fprintf(stderr,"reading ext %d from %s\n",ext,fname);

    int status=0;
    if (fits_open_file(&fits, fname, READONLY, &status)) {
        fits_report_error(stderr, status);
        exit(EXIT_FAILURE);
    }

    int hdutype=0;
    if (fits_movabs_hdu(fits, ext+1, &hdutype, &status)) {
        fits_report_error(stderr, status);
        exit(EXIT_FAILURE);
    }


    int maxdim=CFITSIO_MAX_ARRAY_DIMS;
    LONGLONG dims[CFITSIO_MAX_ARRAY_DIMS];
    int bitpix=0, ndims=0;
    if (fits_get_img_paramll(fits, maxdim, &bitpix, &ndims, dims, &status)) {
        fits_report_error(stderr, status);
        exit(EXIT_FAILURE);
    }
    if (ndims != 2) {
        fprintf(stderr,"expected ndims=2, got %d\n", ndims);
        goto _test_read_bail;
    }
    // dims reversed
    fprintf(stderr,"dims: [%lld,%lld]\n", dims[1], dims[2]);

    // note dims are reversed
    image=image_new(dims[1], dims[0]);
    long npix=dims[1]*dims[0];
    long fpixel[2]={1,1};
    if (fits_read_pix(fits, TDOUBLE, fpixel, npix,
                      NULL,image->rows[0], NULL, &status)) {
        fits_report_error(stderr, status);
        exit(EXIT_FAILURE);
    }

    size_t row=0,col=0;

    row=10; col=13;
    fprintf(stderr,"im[%ld,%ld]: %.16g\n",row,col,IM_GET(image,row,col));
    row=10; col=10;
    fprintf(stderr,"im[%ld,%ld]: %.16g\n",row,col,IM_GET(image,row,col));
    row=18; col=24;
    fprintf(stderr,"im[%ld,%ld]: %.16g\n",row,col,IM_GET(image,row,col));


_test_read_bail:
    image=image_free(image);
    if (fits_close_file(fits, &status)) {
        fits_report_error(stderr, status);
        exit(EXIT_FAILURE);
    }
}
コード例 #28
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);
}
コード例 #29
0
ファイル: fits_table_merge.c プロジェクト: lscsoft/lalsuite
int main(int argc, char *argv[])
{
  fitsfile *infptr = 0, *outfptr = 0;  /* FITS file pointers */
  int status = 0;   /* CFITSIO status value MUST be initialized to zero! */
  int icol = 0, incols = 0, outcols = 0, intype = 0, outtype = 0, check = 1;
  long inrep = 0, outrep = 0, width = 0, inrows = 0, outrows = 0, ii = 0, jj = 0;
  unsigned char *buffer = 0;

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

  if (printhelp || argc != 3) {
    fprintf(stderr, "Usage:  %s infile1[ext][filter] outfile[ext]\n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "Merge 2 tables by copying all the rows from the 1st table\n");
    fprintf(stderr, "into the 2nd table.  The  2 tables must have identical\n");
    fprintf(stderr, "structure, with the same number of columns with the same\n");
    fprintf(stderr, "datatypes.  This program modifies the output file in place,\n");
    fprintf(stderr, "rather than creating a whole new output file.\n");
    fprintf(stderr, "\n");
    fprintf(stderr, "Examples: \n");
    fprintf(stderr, "\n");
    fprintf(stderr, "1. %s intab.fit+1 outtab.fit+2\n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "    merge the table in the 1st extension of intab.fit with\n");
    fprintf(stderr, "    the table in the 2nd extension of outtab.fit.\n");
    fprintf(stderr, "\n");
    fprintf(stderr, "2. %s 'intab.fit+1[PI > 45]' outab.fits+2\n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "    Same as the 1st example, except only rows that have a PI\n");
    fprintf(stderr, "    column value > 45 will be merged into the output table.\n");
    fprintf(stderr, "\n");
    return (0);
  }

  /* open both input and output files and perform validity checks */
  if (fits_open_file(&infptr,  argv[1], READONLY,  &status) ||
      fits_open_file(&outfptr, argv[2], READWRITE, &status)) {
    fprintf(stderr, " Couldn't open both files\n");
  }

  else if (fits_get_hdu_type(infptr,  &intype,  &status) ||
           fits_get_hdu_type(outfptr, &outtype, &status)) {
    fprintf(stderr, "couldn't get the type of HDU for the files\n");
  }

  else if (intype == IMAGE_HDU) {
    fprintf(stderr, "The input HDU is an image, not a table\n");
  }

  else if (outtype == IMAGE_HDU) {
    fprintf(stderr, "The output HDU is an image, not a table\n");
  }

  else if (outtype != intype) {
    fprintf(stderr, "Input and output HDUs are not the same type of table.\n");
  }

  else if (fits_get_num_cols(infptr,  &incols,  &status) ||
           fits_get_num_cols(outfptr, &outcols, &status)) {
    fprintf(stderr, "Couldn't get number of columns in the tables\n");
  }

  else if (incols != outcols) {
    fprintf(stderr, "Input and output HDUs don't have same # of columns.\n");
  }

  else if (fits_read_key(infptr, TLONG, "NAXIS1", &width, NULL, &status)) {
    fprintf(stderr, "Couldn't get width of input table\n");
  }

  else if (!(buffer = (unsigned char *) malloc(width))) {
    fprintf(stderr, "memory allocation error\n");
  }

  else if (fits_get_num_rows(infptr,  &inrows,  &status) ||
           fits_get_num_rows(outfptr, &outrows, &status)) {
    fprintf(stderr, "Couldn't get the number of rows in the tables\n");
  }

  else  {
    /* check that the corresponding columns have the same datatypes */
    for (icol = 1; icol <= incols; icol++) {
      fits_get_coltype(infptr,  icol, &intype,  &inrep,  NULL, &status);
      fits_get_coltype(outfptr, icol, &outtype, &outrep, NULL, &status);
      if (intype != outtype || inrep != outrep) {
        fprintf(stderr, "Column %d is not the same in both tables\n", icol);
        check = 0;
      }
    }

    if (check && !status) {
      /* insert 'inrows' empty rows at the end of the output table */
      fits_insert_rows(outfptr, outrows, inrows, &status);

      for (ii = 1, jj = outrows +1; ii <= inrows; ii++, jj++) {
        /* read row from input and write it to the output table */
        fits_read_tblbytes(infptr,  ii, 1, width, buffer, &status);
        fits_write_tblbytes(outfptr, jj, 1, width, buffer, &status);
        if (status) {
          break;  /* jump out of loop if error occurred */
        }
      }

      /* all done; now free memory and close files */
      fits_close_file(outfptr, &status);
      fits_close_file(infptr,  &status);
    }
  }

  if (buffer) {
    free(buffer);
  }

  if (status) {
    fits_report_error(stderr, status);  /* print any error message */
  }
  return (status);
}
コード例 #30
0
ファイル: tofitsbp16.c プロジェクト: jakewendt/my
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);
}