예제 #1
0
//----------------------------------------------------------
int write_hits_header(etfits_t * etf, int beampol, size_t nhits, size_t missed_pkts) {
//----------------------------------------------------------

#define TFIELDS 4
    int * status_p = &(etf->status);
    *status_p = 0;

    int tbltype                = BINARY_TBL;
    long long naxis2           = 0;
    //const int tfields          = 3;
    // TODO check chan types!
    const char *ttype[TFIELDS] = {"DETPOW  ", "MEANPOW ",  "COARCHAN", "FINECHAN"};
    const char *tform[TFIELDS] = {"1E",       "1E",        "1U",        "1V"};     // cfitsio format codes 
                             //     32-bit floats       16-bit unint   32-bit uint

    if(etf->integration_cnt == 0 && etf->beampol_cnt == 0) {
        // at start of file go to the template created HDU for this set of beampols
        if(! *status_p) fits_movnam_hdu(etf->fptr, BINARY_TBL, (char *)"ETHITS", 0, status_p);
    } else {
        // otherwise create new HDU for this set of beampols
        if(! *status_p) fits_create_tbl(etf->fptr, BINARY_TBL, 0, TFIELDS, (char **)&ttype, (char **)&tform, NULL, (char *)"ETHITS", status_p);
    }

    if(! *status_p) fits_update_key(etf->fptr, TINT,    "TIME",    &(etf->hits_hdr[beampol].time),    NULL, status_p);    
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "RA",      &(etf->hits_hdr[beampol].ra),      NULL, status_p);   
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "DEC",     &(etf->hits_hdr[beampol].dec),     NULL, status_p);   
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "BEAMPOL", &(etf->hits_hdr[beampol].beampol), NULL, status_p);   
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "NHITS",   &nhits,                            NULL, status_p);   
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "MISSEDPK",&missed_pkts,                      NULL, status_p);   

    if (*status_p) {
        hashpipe_error(__FUNCTION__, "Error writing hits header");
        fits_report_error(stderr, *status_p);
    }
}
예제 #2
0
// gotoFITSHDU: try to go to a reasonable HDU if the primary is useless
// we look for specified extensions and if not found, go to hdu #2
// this is how xray binary tables are imaged automatically
fitsfile *gotoFITSHDU(fitsfile *fptr, char *extlist, int *hdutype, int *status){
  int hdunum, naxis, thdutype, gotext;
  char *ext, *textlist;
  // if this is the primary array and it does not contain an image,
  // try to move to something more reasonble
  fits_get_hdu_num(fptr, &hdunum); *status = 0;
  fits_get_img_dim(fptr, &naxis, status); *status = 0;
  if( (hdunum == 1) && (naxis == 0) ){ 
    // look through the extension list
    if( extlist ){
      gotext = 0;
      textlist = (char *)strdup(extlist);
      for(ext=(char *)strtok(textlist, " "); ext != NULL; 
	  ext=(char *)strtok(NULL," ")){
	fits_movnam_hdu(fptr, ANY_HDU, ext, 0, status);
	if( *status == 0 ){
	  gotext = 1;
	  break;
	} else {
	  *status = 0;
	}
      }
      free(textlist);      
    }
    if( !gotext ){
      // if all else fails, move to extension #2 and hope for the best
      fits_movabs_hdu(fptr, 2, &thdutype, status);
    }
  }
  fits_get_hdu_type(fptr, hdutype, status);
  return fptr;
}
예제 #3
0
int append_profile(const char *fname, int ispec, struct profile_phase *pp) {
    int status=0;
    fitsfile *fptr;
    fits_open_file(&fptr, fname, READWRITE, &status);
    fits_movnam_hdu(fptr, IMAGE_HDU, "PROFILE", 0, &status);
    int naxis;
    long naxes[2];
    fits_get_img_dim(fptr, &naxis, &status);
    if (naxis!=2) { 
        fits_close_file(fptr, &status);
        return(-1); 
    }
    fits_get_img_size(fptr, 2, naxes, &status);
    if (naxes[0]!=pp->nphase || naxes[1]<ispec) {
        fits_close_file(fptr, &status);
        return(-2);
    }
    naxes[0] = 1;
    naxes[1] = ispec;
    fits_write_pix(fptr, TFLOAT, naxes, pp->nphase, pp->data, &status);
    fits_close_file(fptr, &status);
    if (status) {
        fprintf(stderr, "Error in append_profile:\n");
        fits_report_error(stderr, status);
        return(-1);
    }
    return(0);
}
예제 #4
0
int psrfits_remove_ephem(struct psrfits *pf) {
    // Delete the ephemeris table
    
    int *status = &(pf->status);

    // Save current HDU, move to polyco table
    int hdu;
    fits_get_hdu_num(pf->fptr, &hdu);
    fits_movnam_hdu(pf->fptr, BINARY_TBL, "PSREPHEM", 0, status);

    // Delete it
    fits_delete_hdu(pf->fptr, NULL, status);

    // Go to the SUBINT HDU
    fits_movnam_hdu(pf->fptr, BINARY_TBL, "SUBINT", 0, status);

    return *status;
}
예제 #5
0
int cfits_movnam_hdu (cfitsfile *fptr, const char *extname)
{
   int status = 0;

   (void) fits_movnam_hdu((fitsfile *) fptr, ANY_HDU, (char *)extname, 0, &status);
   cfits_report_error (status);

   if (status != 0) return -1;
   return 0;
}
예제 #6
0
int read_data(const char *filename,const char *extname, int colnum, long firstelem, long nelements, double *data)
{
    firstelem++; //from 0 to 1 based
    int status = 0, anynul;
    double doublenull = 0.;
    fitsfile *fptr;         
    fits_open_file(&fptr, filename, READONLY, &status);
    fits_movnam_hdu(fptr, BINARY_TBL, extname, 0, &status);
    fits_read_col(fptr, TDOUBLE, colnum, firstelem, 1, nelements, &doublenull, data, &anynul, &status);
    fits_close_file(fptr, &status);
    if (status)          /* print any error messages */
        fits_report_error(stderr, status);
    return(status);
}
예제 #7
0
파일: hdu.c 프로젝트: rforge/rfitsio
/* Wrapper to fits_movnam_hdu */
SEXP
cfitsio_movnam_hdu (SEXP fits_object,
		    SEXP hdu_type,
		    SEXP ext_name,
		    SEXP ext_ver)
{
    fits_file_t * fits = R_ExternalPtrAddr (fits_object);

    if (NULL != fits && NULL != fits->cfitsio_ptr)
    {
	fits_movnam_hdu (fits->cfitsio_ptr,
			 asInteger (hdu_type),
			 (char *) NM(ext_name),
			 hdu_type_from_name (ext_ver),
			 &(fits->status));

	return R_NilValue;
    }
    else
	return R_NilValue;
}
예제 #8
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);
}
예제 #9
0
파일: pfits.c 프로젝트: SixByNine/pfits
// Return the number of channels
int readBandpass(fitsfile *fp,float *bpass)
{
  int status=0;
  int samplesperbyte;
  long nrows;
  int colnum;
  int j,pol,subint;
  int initflag=0;
  float val=1;
  float nval = 0;
  long npts;
  int start,end;
  int i,anynul;
  float dat_offs,dat_scl;
  float freq,bw,chanbw;
  long nchan;
  int naxis;
  int typecode;
  long repeat,width;

  // Go to bandpass table
  fits_movnam_hdu(fp,BINARY_TBL,"BANDPASS",1,&status);
  if (status) {
    printf("Unable to move to bandpass table in FITS file\n");
    exit(1);
  }

  fits_get_colnum(fp,CASEINSEN,"DAT_OFFS",&colnum,&status);
  fits_read_col(fp,TFLOAT,colnum,1,1,1,&nval,&dat_offs,&anynul,&status);
  if (status){
    printf("Error in bandpass header 1\n");
    fits_report_error(stderr,status);
    exit(1);
  }
  fits_get_colnum(fp,CASEINSEN,"DAT_SCL",&colnum,&status);
  fits_read_col(fp,TFLOAT,colnum,1,1,1,&nval,&dat_scl,&anynul,&status);
  if (status){
    printf("Error in bandpass header\n");
    fits_report_error(stderr,status);
    exit(1);
    }

  fits_get_colnum(fp,CASEINSEN,"DATA",&colnum,&status);
  if (status){
    fits_report_error(stderr,status);
    exit(1);
  }
  fits_get_coltype(fp,colnum,&typecode,&repeat,&width,&status);
  nchan = (int)repeat-1; // Don't read the first channel
  printf("nc = %d, na = %d\n",(int)nchan,(int)naxis);
  for (i=1;i<(int)nchan;i++)
    {
      fits_read_col(fp,TFLOAT,colnum,1,i+1,1,&nval,&val,&anynul,&status);
      bpass[i-1] = val*dat_scl + dat_offs;
      if (status){
	fits_report_error(stderr,status);
	exit(1);
      }
    }
  fits_close_file(fp,&status);  
  return nchan;
}
예제 #10
0
int read_prof (subintegration *sub, pheader *header)
{  
	int i, j, k;
	fitsfile *fptr;       // pointer to the FITS file, defined in fitsio.h 
	int status;
	int colnum;
	double *data, *dat_offs, *dat_scl;

	data = (double *)malloc(sizeof(double)*header->nbin*header->nchan*header->npol);
	dat_offs = (double *)malloc(sizeof(double)*header->nchan*header->npol);
	dat_scl = (double *)malloc(sizeof(double)*header->nchan*header->npol);

	status = 0;

	// open psrfits
	if ( fits_open_file(&fptr, sub->fname, READONLY, &status) )          // open the file
	{
		printf( "error while openning file\n" );
	}

	// move to subint
	fits_movnam_hdu(fptr, BINARY_TBL, (char *)"SUBINT",0,&status);

	int frow;
	int felem;
	int nelem;
	int null;
	int anynull;

	/////////////////////////////////////////////////////////////////////////
	// read profile
	if ( fits_get_colnum(fptr, CASEINSEN, "DATA", &colnum, &status) )           // get the row number
	{
		printf( "error while getting the colnum number\n" );
	}

	frow = sub->indexSub;
	felem = 1;
	nelem = header->nbin*header->nchan*header->npol;
	null = 0;
	anynull = 0;

	//fits_read_col(fptr, TDOUBLE, colnum, frow, felem, nelem, &null, sub->p_multi, &anynull, &status);           // read the column
	fits_read_col(fptr, TDOUBLE, colnum, frow, felem, nelem, &null, data, &anynull, &status);           // read the column

	/////////////////////////////////////////////////////////////////////////////////////////////////////
	// read DAT_SCL
 
	if ( fits_get_colnum(fptr, CASEINSEN, "DAT_SCL", &colnum, &status) )           // get the colnum number
	{
		printf( "error while getting the colnum number\n" );
	}

	frow = sub->indexSub;
  felem = 1;
  nelem = header->nchan*header->npol;
  null = 0;
  anynull = 0;

	fits_read_col(fptr, TDOUBLE, colnum, frow, felem, nelem, &null, dat_scl, &anynull, &status);           // read the column

	/////////////////////////////////////////////////////////////////////////////////////////////////////
	// read DAT_OFFS
 
	if ( fits_get_colnum(fptr, CASEINSEN, "DAT_OFFS", &colnum, &status) )           // get the colnum number
	{
		printf( "error while getting the colnum number\n" );
	}

	frow = sub->indexSub;
  felem = 1;
  nelem = header->nchan*header->npol;
  null = 0;
  anynull = 0;

	fits_read_col(fptr, TDOUBLE, colnum, frow, felem, nelem, &null, dat_offs, &anynull, &status);           // read the column

	// close psrfits file
	if ( fits_close_file(fptr, &status) )
	{
		printf( " error while closing the file " );
	}

	//for (i = 0; i < header->nbin*header->nchan*header->npol; i++)
	//{
	//	printf ("%lf\n", sub->p_multi[i]);
	//}
	for (i = 0; i < header->npol; i++)
	{
		for (j = 0; j < header->nchan; j++)
		{
			for (k = 0; k < header->nbin; k++)
			{
				sub->p_multi[i*header->nchan*header->nbin + j*header->nbin + k] = data[i*header->nchan*header->nbin + j*header->nbin + k]*dat_scl[i*header->nchan + j] + dat_offs[i*header->nchan + j];
			}
		}
	}

	free (data);
	free (dat_scl);
	free (dat_offs);

	return 0;
}
예제 #11
0
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;
}
예제 #12
0
int main(int argc, char *argv[])
{

    static struct option long_opts[] = {
        {"start",  1, NULL, 's'},
        {"end",    1, NULL, 'e'},
	{0,0,0,0}
    };	

    fitsfile *infptr, *outfptr;   /* FITS file pointers defined in fitsio.h */
    int opt, opti;
    int i, status = 0, ii = 1, jj=1;       /* status must always be initialized = 0  */
    int lo_row, hi_row;
    unsigned char *buffer = 0;

    long nrows;
    int ncols;
    int tfields;
    long  pcount;
    char  extname[FLEN_VALUE];
    char  *ttype[NFIELDS_I];
    char  *tform[NFIELDS_I];
    char  *tunit[NFIELDS_I];
    char  *tcomm[NFIELDS_I];

    float start=0.0, end=1.0;
    while ((opt=getopt_long(argc,argv,"s:e:h",long_opts,&opti))!=-1) {
        switch (opt) {
	    case 's':
	        start = atof(optarg);
		break;
	    case 'e':
	        end = atof(optarg);
		break;
	    case 'h':
	    default:
	        usage();
		exit(0);
		break;
	}	

    }

    if (argc < 3)
    {
      usage();
      return(0);
    }

    //printf("> %s %s\n", argv[1], argv[2]);
    //printf("> %s %s\n", argv[optind], argv[2]);


   /* Allocate space for the table parameters and initialize */
   for (i=0; i<NFIELDS_I; i++)
   {
      ttype[i] = (char *) malloc(FLEN_VALUE*sizeof(char));
      tform[i] = (char *) malloc(FLEN_VALUE*sizeof(char));
      tunit[i] = (char *) malloc(FLEN_VALUE*sizeof(char));
      tcomm[i] = (char *) malloc(FLEN_CARD*sizeof(char));
      strcpy(ttype[i], " ");
   }


    /* Open the input file */
    if ( !fits_open_file(&infptr, argv[optind], READONLY, &status) )
    {
      /* Create the output file */
      if ( !fits_create_file(&outfptr, argv[optind+1], &status) )
      {
        /* Copy every HDU until we get an error */
        //while( !fits_movabs_hdu(infptr, ii++, NULL, &status) )
	
	/* Copy first HDU */
        fits_copy_hdu(infptr, outfptr, 0, &status);

	fits_movnam_hdu(infptr, BINARY_TBL, "SUBINT", 0, &status);

	fits_get_num_rows(infptr, &nrows, &status);
	printf("Number of rows = %ld\n", nrows);
	
	fits_get_num_cols(infptr, &ncols, &status);
	printf("Number of cols = %d\n", ncols);
		
	long width;
	fits_read_key(infptr, TLONG, "NAXIS1", &width, NULL, &status);
	printf("Width = %ld\n", width);
	buffer = (unsigned char *) malloc(width);
	
	/* Copy the fits header */
	fits_copy_header(infptr, outfptr, &status);

//#if 0
	/* Determine low and high row number ot copy */
	lo_row = 1 + start * nrows;
	hi_row = end * nrows;
	printf("lo_row=%d hi_row=%d\n", lo_row, hi_row);

	for (ii=lo_row, jj=1; ii<=hi_row; ii++, jj++) {
	    printf("\rRead %d/%ld", ii, nrows);
	    fits_read_tblbytes( infptr,  ii, 1, width, buffer, &status);

	    fits_write_tblbytes(outfptr, jj, 1, width, buffer, &status);
	}
	nrows = (hi_row-lo_row)+1;
	fits_update_key(outfptr, TLONG, "NAXIS2", &nrows, 0, &status);
	printf("\nDone\n");
//#endif
        /* Reset status after normal error */
        //if (status == END_OF_FILE) status = 0;

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

    /* if error occured, print out error message */
    if (status) fits_report_error(stderr, status);
    return(status);
}
예제 #13
0
파일: pfits.c 프로젝트: SixByNine/pfits
int writeData(fitsfile *fp,FILE *fout,dSet *data,long s1,long s2,float dm)
{
  long sub_1,samp_1;
  long sub_2,samp_2;
  int  s,r1,r2;
  int nsblk;
  int nchan = data->phead.nchan;
  int nbits = data->phead.nbits;
  int npol  = data->phead.npol;
  int samplesperbyte = 8/data->phead.nbits;
  float chanVal[nchan];
  long ipos=0;
  int status=0;
  int colnum;
  int initflag=0;
  unsigned char *cval;
  unsigned char nval = '0';
  int i,c,count=0,sa;
  unsigned char chVals[nchan];
  int smoothSamp=1;
  int sm;
  unsigned int t=0;
  unsigned int j;
  float tempVal;
  int nsampDM;
  float tDM;
  float bw = data->phead.bw; // MHz
  float f0 = data->phead.freq+fabs(data->phead.bw)/2.0; // MHz // Highest frequency
  float chanbw = data->phead.bw/data->phead.nchan;
  unsigned char *ring_s;
  unsigned char *ring_e;
  unsigned char *ring_pos;
  unsigned char *ring_last;
  unsigned int bitCount;
  int cdelay,k,l;
  float tdelay;
  unsigned int pos;
  unsigned int **cde_byte;
  unsigned char **cde_bit;
  unsigned int nchanbyte;

  nchanbyte = nchan/samplesperbyte;

  // Do we require smoothing?
  printf("At here: smoothSamp = %d\n",smoothSamp);
  nsblk = data->phead.nsblk;

  findPosSample(data,s1,&sub_1,&samp_1);
  findPosSample(data,s2,&sub_2,&samp_2);
  //  printf("Here with %d %d %d %d\n",sub_1,samp_1,sub_2,samp_2);
  // Go to the subint table

  fits_movnam_hdu(fp,BINARY_TBL,"SUBINT",1,&status);
  if (status) {
    printf("Unable to move to subint table in FITS file\n");
    exit(1);
  }
  fits_get_colnum(fp,CASEINSEN,"DATA",&colnum,&status);
  if (status) {
    printf("Unable to find data in the subint table in FITS file\n");
    exit(1);
  }
  // Number of extra samples required to process 
  // to de-disperse across the band
  tDM = fabs(4.15e-3*dm*(pow((f0)/1000.0,-2)-pow((f0-fabs(bw))/1000.0,-2)));
  nsampDM = ceil(tDM/data->phead.tsamp);


  cval = (unsigned char *)malloc(sizeof(unsigned char)*nchanbyte*npol*nsampDM);

  printf("Trying to allocate memory\n");
  cde_byte = (unsigned int **)malloc(sizeof(unsigned int *)*nsampDM);
  cde_bit  = (unsigned char **)malloc(sizeof(unsigned char *)*nsampDM);

  for (i=0;i<nsampDM;i++)
    {
      cde_byte[i] = (unsigned int *)malloc(sizeof(unsigned int)*nchan*npol*nsampDM);
      cde_bit[i] = (unsigned char *)malloc(sizeof(unsigned char)*nchan*npol*nsampDM);
    }
  printf("Allocated memory\n");

  // Now turn on the bits that correspond to the DM
  j=0;
  for (i=0;i<nchan;i++)
    {
      tdelay = 4.15e-3*dm*(pow(f0/1000.0,-2)-pow((f0-fabs(chanbw)*i)/1000.0,-2));
      cdelay = nint(-tdelay/data->phead.tsamp);
      //      printf("Have %g %d\n",tdelay,cdelay);
      for (j=0;j<nsampDM;j++)
	{
	  k = (int)((float)i/(float)samplesperbyte)+cdelay*nchanbyte+j*nchan/samplesperbyte;
	  if (k>(nsampDM)*nchanbyte)
	    k-=nsampDM*nchanbyte;
	  if (k>(nsampDM)*nchanbyte)
	    {
	      printf("ERROR\n");
	      exit(1);
	    }
	  cde_byte[j][i] = k;
	  cde_bit[j][i]  = i%8;
	}
    }

 printf("Ready\n");

  ring_s   = cval;
  ring_pos = cval;
  ring_e   = &cval[nchanbyte*npol*(nsampDM)];
     printf("Got here 2\n");
  // Should check if I'm running off the end of a subint
  s = sub_1;
  sa = samp_1;
  // Use a ring buffer to store the data
  // Fill it up
  count = 0;
  t=0;
  pos = 0;
  printf("Got here 3\n");
  fprintf(fout,"# %s %d %g %g\n",data->phead.source,data->phead.imjd,data->phead.freq,data->phead.tsamp);
  for (i=0;i<s2-s1-nsampDM;i++)
    {
      //            printf("i = %d, s = %d, sa = %d\n",i,s,sa);
      fits_read_col_byt(fp,colnum,s+1,(sa)*nchanbyte+1,nchanbyte,nval,ring_pos,&initflag,&status);
      sa++;
      
      if (i >= nsampDM-1)
	{
	  bitCount = 0;
	  //	  for (k=0;k<35;k++)
	    {
	      for (j=0;j<nchan;j++)
		{
		  //	      bitCount += extractBit(cval[cde_byte[t][j]],cde_bit[t][j]);
		  // ONLY 1-BIT DATA
		  bitCount += extractBit(cval[cde_byte[t][j]],j%8);
		  
		  //	      bitCount+=cde_byte[t][j]+cde_bit[t][j];
		}
	    }
	    fprintf(fout,"%d\n",bitCount);
	    t++;
	}
      
      ring_pos += nchanbyte*npol;
      if (ring_pos == ring_e)
	{
	  //	  printf("Got to end of ring buffer %d %d\n",i,nsampDM);
	  ring_pos = ring_s;
	  t=0;
	} 
      if (sa == nsblk)
 	{
 	  //	  printf("Running off the end of a block\n");
 	  s++;
 	  sa = 0;
 	} 
     }
  
  tempVal=0;
  //  printf("Got here\n");
  //  exit(1);
  if (status)
    {
      fits_report_error(stderr,status);
      exit(1);
    }
  
  
  //  printf("Complete %d %d\n",t,count);
  free(cval);
   for (i=0;i<nsampDM;i++)
     {
       free(cde_byte[i]);
       free(cde_bit[i]);
     }
   free(cde_byte);
   free(cde_bit);

   return count;
}
예제 #14
0
파일: pfits.c 프로젝트: SixByNine/pfits
int extractDataZeroDM(fitsfile *fp,dSet *data,long s1,long s2,float *mean,float *min,float *max,long maxVal,int *nsmooth)
{
  long sub_1,samp_1;
  long sub_2,samp_2;
  int  s,r1,r2;
  int nsblk;
  int nchan = data->phead.nchan;
  int nbits = data->phead.nbits;
  int npol  = data->phead.npol;
  int samplesperbyte = 8/data->phead.nbits;
  float chanVal[nchan];
  long ipos=0;
  int status=0;
  int colnum;
  int initflag=0;
  unsigned char *cval;
  unsigned char nval = '0';
  int i,c,count=0,sa;
  unsigned char chVals[nchan];
  int smoothSamp=1;
  int sm;
  int t=0;
  float tempVal;

  printf("Extract zeroDM smaplesperbyte = %d\n",samplesperbyte);
  // Do we require smoothing?
  if (s2 - s1 > maxVal)
    {
      smoothSamp = ceil((double)(s2-s1)/(double)maxVal);
      //      printf("smoothSamp = %d\n",smoothSamp);
    }

  nsblk = data->phead.nsblk;

  findPosSample(data,s1,&sub_1,&samp_1);
  findPosSample(data,s2,&sub_2,&samp_2);
  //  printf("Here with %d %d %d %d\n",sub_1,samp_1,sub_2,samp_2);
  // Go to the subint table

  fits_movnam_hdu(fp,BINARY_TBL,"SUBINT",1,&status);
  if (status) {
    printf("Unable to move to subint table in FITS file\n");
    exit(1);
  }
  fits_get_colnum(fp,CASEINSEN,"DATA",&colnum,&status);
  if (status) {
    printf("Unable to find data in the subint table in FITS file\n");
    exit(1);
  }
  cval = (unsigned char *)malloc(sizeof(unsigned char)*nsblk*nchan/samplesperbyte*npol);
  //  printf("Allocated memory\n");
  t=0;
  for (s=sub_1;s<=sub_2;s++)
    {
      //      printf("Loading sub: %d\n",s);
      if (s==sub_1)
	r1 = samp_1;
      else
	r1 = 0;
      if (s==sub_2)
	r2 = samp_2;
      else
	r2 = nsblk;
      //      printf("Reading from %d to %d\n",r1,r2);

      // Read nchan data points
      for (sa=r1;sa<r2;sa++)
	{
	  fits_read_col_byt(fp,colnum,s+1,sa*nchan/samplesperbyte+1,nchan/samplesperbyte,nval,cval,&initflag,&status);
	  if (status)
	    {
	      fits_report_error(stderr,status);
	      exit(1);
	    }
	  bytesToValues(samplesperbyte, nchan, cval, chVals);
	  tempVal = 0.0;
	  //	  val[count] = 0.0;
	  for (i=0;i<nchan;i++)
	    {
	      if (samplesperbyte==8)
		{
		  if (chVals[i]==0) tempVal += 0.5;
		  else tempVal -= 0.5;
		  //		  printf("Adding %d %d %d %d\n",s,sa,i,chVals[i]);

		}
	      else
		{
		  tempVal+=chVals[i];
		}
	    }
	  tempVal/=(float)nchan;
	  if (t==0)
	    {
	      mean[count] = min[count] = max[count] = tempVal;
	    }
	  else
	    {
	      if (min[count] > tempVal)
		min[count] = tempVal;
	      if (max[count] < tempVal)
		max[count] = tempVal;
	      mean[count] += tempVal;
	    }
	  t++;
	  if (t==smoothSamp)
	    {
	      mean[count]/=(double)smoothSamp;
	      count++;
	      t=0;
	    }
	}
    }
  //  printf("Complete %d %d\n",t,count);
  free(cval);
  *nsmooth = smoothSamp;
  if (count > maxVal)
    {
      printf("In pfits.c -- this should not have happened\n");
      printf("count = %d, maxVal = %d\n",(int)count,(int)maxVal);
      printf("s2-s1 = %d\n",(int)(s2-s1));
      printf("Exit ...\n");
      exit(1);
    }
  //  printf("Returning\n");
  return count;
}
예제 #15
0
int psrfits_create(struct psrfits *pf) {
    int itmp, *status;
    long long lltmp;
    long double ldtmp;
    double dtmp;
    char ctmp[40];
    struct hdrinfo *hdr;
    struct foldinfo *fld;

    hdr = &(pf->hdr);        // dereference the ptr to the header struct
    status = &(pf->status);  // dereference the ptr to the CFITSIO status
    fld = &(pf->fold);       // ptr to foldinfo struct

    // Figure out what mode this is 
    int mode=0;
    mode = psrfits_obs_mode(hdr->obs_mode);
    if (mode==fold) {
        if (hdr->onlyI)
            printf("Warning!  In folding mode and ONLY_I is set!\n");
        if (hdr->ds_time_fact > 1)
            printf("Warning!  In folding mode and DS_TIME is > 1!\n");
        if (hdr->ds_freq_fact > 1)
            printf("Warning!  In folding mode and DS_FREQ is > 1!\n");
    }

    // Initialize the key variables if needed
    if (pf->filenum == 0) {  // first time writing to the file
        pf->status = 0;
        pf->tot_rows = 0;
        pf->N = 0L;
        pf->T = 0.0;
        hdr->offset_subint = 0;
        pf->mode = 'w';

        // Create the output directory if needed
        char datadir[1024];
        strncpy(datadir, pf->basefilename, 1023);
        char *last_slash = strrchr(datadir, '/');
        if (last_slash!=NULL && last_slash!=datadir) {
            *last_slash = '\0';
            printf("Using directory '%s' for output.\n", datadir);
            char cmd[1024];
            sprintf(cmd, "mkdir -m 1777 -p %s", datadir);
            system(cmd);
        }
    }
    pf->filenum++;
    pf->rownum = 1;
    hdr->offset_subint = pf->tot_rows;

    // Update the filename - don't include filenum for fold mode
    // TODO : use rf/cf extensions for psr/cals?
    if (mode==fold && pf->multifile!=1)
        sprintf(pf->filename, "%s.fits", pf->basefilename);
    else
        sprintf(pf->filename, "%s_%04d.fits", pf->basefilename, pf->filenum);

    // Create basic FITS file from our template
    // Fold mode template has additional tables (polyco, ephem)
    char template_dir[1024];
    char template_file[1024];
#ifdef PSRFITS_TEMPLATE_DIR
    sprintf(template_dir, "%s", PSRFITS_TEMPLATE_DIR);
#else
    char *guppi_dir = getenv("GUPPI_DIR");
    if (guppi_dir==NULL) {
        fprintf(stderr, 
                "Error: GUPPI_DIR environment variable not set, exiting.\n");
        exit(1);
    }
    sprintf(template_dir, "%s/src", guppi_dir);
#endif
    printf("Opening file '%s' ", pf->filename);
    if (mode==search) { 
        printf("in search mode.\n");
        sprintf(template_file, "%s/%s", template_dir, PSRFITS_SEARCH_TEMPLATE);
    } else if (mode==fold) { 
        printf("in fold mode.\n");
        sprintf(template_file, "%s/%s", template_dir, PSRFITS_FOLD_TEMPLATE);
    }
    fits_create_template(&(pf->fptr), pf->filename, template_file, status);

    // Check to see if file was successfully created
    if (*status) {
        fprintf(stderr, "Error creating psrfits file from template.\n");
        fits_report_error(stderr, *status);
        exit(1);
    }

    // Go to the primary HDU
    fits_movabs_hdu(pf->fptr, 1, NULL, status);

    // Update the keywords that need it
    fits_get_system_time(ctmp, &itmp, status);
    // Note:  this is the date the file was _written_, not the obs start date
    fits_update_key(pf->fptr, TSTRING, "DATE", ctmp, NULL, status);
    fits_update_key(pf->fptr, TSTRING, "TELESCOP", hdr->telescope,NULL, status);
    fits_update_key(pf->fptr, TSTRING, "OBSERVER", hdr->observer, NULL, status);
    fits_update_key(pf->fptr, TSTRING, "PROJID", hdr->project_id, NULL, status);
    fits_update_key(pf->fptr, TSTRING, "FRONTEND", hdr->frontend, NULL, status);
    fits_update_key(pf->fptr, TSTRING, "BACKEND", hdr->backend, NULL, status);
    if (hdr->onlyI || hdr->summed_polns) {
        if (!hdr->onlyI && hdr->npol > 1) {
            printf("Warning!:  Can't have %d polarizations _and_ be summed!\n", 
                   hdr->npol);
        }
        itmp = 2;
        fits_update_key(pf->fptr, TINT, "NRCVR", &itmp, NULL, status);
    } else {
        if (hdr->npol > 2) { // Can't have more than 2 real polns (i.e. NRCVR)
            itmp = 2;
            fits_update_key(pf->fptr, TINT, "NRCVR", &itmp, NULL, status);
        } else {
            fits_update_key(pf->fptr, TINT, "NRCVR", &(hdr->npol), NULL, status);
        }
    }
    fits_update_key(pf->fptr, TSTRING, "FD_POLN", hdr->poln_type, NULL, status);
    fits_update_key(pf->fptr, TINT, "FD_HAND", &(hdr->fd_hand), NULL, status);
    fits_update_key(pf->fptr, TDOUBLE, "FD_SANG", &(hdr->fd_sang), NULL, status);
    fits_update_key(pf->fptr, TDOUBLE, "FD_XYPH", &(hdr->fd_xyph), NULL, status);
    fits_update_key(pf->fptr, TINT, "BE_PHASE", &(hdr->be_phase), NULL, status);
    fits_update_key(pf->fptr, TSTRING, "DATE-OBS", hdr->date_obs, NULL, status);
    if (mode==fold && !strcmp("CAL",hdr->obs_mode)) 
        fits_update_key(pf->fptr, TSTRING, "OBS_MODE", hdr->obs_mode, 
                NULL, status);
    fits_update_key(pf->fptr, TDOUBLE, "OBSFREQ", &(hdr->fctr), NULL, status);
    fits_update_key(pf->fptr, TDOUBLE, "OBSBW", &(hdr->BW), NULL, status);
    fits_update_key(pf->fptr, TINT, "OBSNCHAN", &(hdr->orig_nchan), NULL, status);
    fits_update_key(pf->fptr, TDOUBLE, "CHAN_DM", &(hdr->chan_dm), NULL, status);
    fits_update_key(pf->fptr, TSTRING, "SRC_NAME", hdr->source, NULL, status);
    if (!strcmp("UNKNOWN", hdr->track_mode)) {
        printf("Warning!:  Unknown telescope tracking mode!\n");
    }
    fits_update_key(pf->fptr, TSTRING, "TRK_MODE", hdr->track_mode, NULL, status);
    // TODO: will need to change the following if we aren't tracking!
    fits_update_key(pf->fptr, TSTRING, "RA", hdr->ra_str, NULL, status);
    fits_update_key(pf->fptr, TSTRING, "DEC", hdr->dec_str, NULL, status);
    fits_update_key(pf->fptr, TSTRING, "STT_CRD1", hdr->ra_str, NULL, status);
    fits_update_key(pf->fptr, TSTRING, "STP_CRD1", hdr->ra_str, NULL, status);
    // TODO: update these at the end of the file or obs
    fits_update_key(pf->fptr, TSTRING, "STT_CRD2", hdr->dec_str, NULL, status);
    fits_update_key(pf->fptr, TSTRING, "STP_CRD2", hdr->dec_str, NULL, status);
    fits_update_key(pf->fptr, TDOUBLE, "BMAJ", &(hdr->beam_FWHM), NULL, status);
    fits_update_key(pf->fptr, TDOUBLE, "BMIN", &(hdr->beam_FWHM), NULL, status);
    if (strcmp("OFF", hdr->cal_mode)) {
        fits_update_key(pf->fptr, TDOUBLE, "CAL_FREQ", &(hdr->cal_freq), NULL, status);
        fits_update_key(pf->fptr, TDOUBLE, "CAL_DCYC", &(hdr->cal_dcyc), NULL, status);
        fits_update_key(pf->fptr, TDOUBLE, "CAL_PHS", &(hdr->cal_phs), NULL, status);
    }
    fits_update_key(pf->fptr, TDOUBLE, "SCANLEN", &(hdr->scanlen), NULL, status);
    itmp = (int) hdr->MJD_epoch;
    fits_update_key(pf->fptr, TINT, "STT_IMJD", &itmp, NULL, status);
    ldtmp = (hdr->MJD_epoch - (long double) itmp) * 86400.0L;   // in sec
    itmp = (int) ldtmp;
    fits_update_key(pf->fptr, TINT, "STT_SMJD", &itmp, NULL, status);
    ldtmp -= (long double) itmp;
    dtmp = (double) ldtmp;
    fits_update_key(pf->fptr, TDOUBLE, "STT_OFFS", &dtmp, NULL, status);
    fits_update_key(pf->fptr, TDOUBLE, "STT_LST", &(hdr->start_lst), NULL, status);

    // If fold mode, copy the parfile into the PSRFITS EPHEM table
    if (mode==fold) {
        if (strcmp("CAL",hdr->obs_mode)==0) {
            // CAL mode has no par file, or no par file given
            psrfits_remove_ephem(pf);
        } else if (fld->parfile[0]=='\0') {
            // No par file given
            fprintf(stderr, 
                    "psrfits_create warning:  "
                    "Fold mode selected, but no parfile given - "
                    "EPHEM table will be removed.\n"
                    );
            psrfits_remove_ephem(pf);
        } else {
            FILE *parfile = fopen(fld->parfile, "r");
            if (parfile==NULL) {
                fprintf(stderr, 
                        "psrfits_create warning:  "
                        "Error opening parfile %s - "
                        "EPHEM table will be removed.\n", fld->parfile
                        );
                psrfits_remove_ephem(pf);
            } else {
                psrfits_write_ephem(pf, parfile);
                fclose(parfile);
            }
        }
    }

    // Go to the SUBINT HDU
    fits_movnam_hdu(pf->fptr, BINARY_TBL, "SUBINT", 0, status);

    // Update the keywords that need it
    if (hdr->onlyI) {
        itmp = 1;
        fits_update_key(pf->fptr, TINT, "NPOL", &itmp, NULL, status);
    } else {
        fits_update_key(pf->fptr, TINT, "NPOL", &(hdr->npol), NULL, status);
    }
    if (!hdr->onlyI && !hdr->summed_polns) {
        // TODO:  These need to be updated for the real machine.
        if (hdr->npol==1)
            strcpy(ctmp, "AA");
        else if (hdr->npol==2)
            strcpy(ctmp, "AABB");
        else if (hdr->npol==4) {
            if (strncmp(hdr->poln_order, "AABBCRCI", 8)==0)
                strcpy(ctmp, hdr->poln_order);
            else
                strcpy(ctmp, "IQUV");
        }
        fits_update_key(pf->fptr, TSTRING, "POL_TYPE", ctmp, NULL, status);
    } else {
        fits_update_key(pf->fptr, TSTRING, "POL_TYPE", "AA+BB", NULL, status);
    }
    // TODO what does TBIN mean in fold mode?
    dtmp = hdr->dt * hdr->ds_time_fact;
    fits_update_key(pf->fptr, TDOUBLE, "TBIN", &dtmp, NULL, status);
    fits_update_key(pf->fptr, TINT, "NSUBOFFS", &(hdr->offset_subint), NULL, status);
    itmp = hdr->nchan / hdr->ds_freq_fact;
    fits_update_key(pf->fptr, TINT, "NCHAN", &itmp, NULL, status);
    dtmp = hdr->df * hdr->ds_freq_fact;
    fits_update_key(pf->fptr, TDOUBLE, "CHAN_BW", &dtmp, NULL, status);
    if (mode==search) {
        int out_nsblk = hdr->nsblk / hdr->ds_time_fact;
        itmp = 1;
        fits_update_key(pf->fptr, TINT, "NSBLK", &out_nsblk, NULL, status);
        fits_update_key(pf->fptr, TINT, "NBITS", &(hdr->nbits), NULL, status);
        fits_update_key(pf->fptr, TINT, "NBIN", &itmp, NULL, status);
    } else if (mode==fold) {
        itmp = 1;
        fits_update_key(pf->fptr, TINT, "NSBLK", &itmp, NULL, status);
        fits_update_key(pf->fptr, TINT, "NBITS", &itmp, NULL, status);
        fits_update_key(pf->fptr, TINT, "NBIN", &(hdr->nbin), NULL, status);
        fits_update_key(pf->fptr, TSTRING, "EPOCHS", "MIDTIME", NULL, status);
    }

    // Update the column sizes for the colums containing arrays
    {
        int out_npol = hdr->npol;
        int out_nchan = hdr->nchan / hdr->ds_freq_fact;
        if (hdr->onlyI) out_npol = 1;
        int out_nsblk = hdr->nsblk / hdr->ds_time_fact;

        fits_modify_vector_len(pf->fptr, 13, out_nchan, status); // DAT_FREQ
        fits_modify_vector_len(pf->fptr, 14, out_nchan, status); // DAT_WTS
        itmp = out_nchan * out_npol;
        fits_modify_vector_len(pf->fptr, 15, itmp, status); // DAT_OFFS
        fits_modify_vector_len(pf->fptr, 16, itmp, status); // DAT_SCL
        
        if (mode==search) {
            lltmp = out_nsblk;
            lltmp = (lltmp * hdr->nbits * out_nchan * out_npol) / 8L;
        } else if (mode==fold)
            lltmp = (hdr->nbin * out_nchan * out_npol);
        fits_modify_vector_len(pf->fptr, 17, lltmp, status); // DATA
        // Update the TDIM field for the data column
        if (mode==search)
            sprintf(ctmp, "(1,%d,%d,%d)", out_nchan, out_npol, out_nsblk);
        else if (mode==fold) 
            sprintf(ctmp, "(%d,%d,%d,1)", hdr->nbin, out_nchan, out_npol);
        fits_update_key(pf->fptr, TSTRING, "TDIM17", ctmp, NULL, status);
    }

    fits_flush_file(pf->fptr, status);
    
    return *status;
}
예제 #16
0
// Routine to read the header from a PSRFITS file 
void readpsrfits_hd(char *filename,int *machine_id,int *telescope_id,int *data_type,char *source_name,
		    double *fch1,int *nchans,double *foff,int *nifs,double *tsamp,
		    double *src_raj,double *src_dej,double *tstart,int *nbits,int *ibeam)
{
  fitsfile *fp;
  int status;
  float obsbw,fc;
  char sobsbw[100],sfc[100],ras[100],decs[100];
  char name[100],telescope[100];
  double h,m,sec,chanbw,smjd,offs;
  int imjd;

  int ncol, NCHANS, anynul;
  unsigned char nulval = 0;
  long long row, firstelem, nelem;
  float ch_freq[MX_NCHAN];

  // Defaults that are not being set
  *machine_id=-1;
  *data_type = 0;
  *ibeam = 1;
  status=0;

  fits_open_file(&fp,filename,READONLY,&status);
  fits_report_error(stderr,status);
  fits_movabs_hdu( fp, 1, NULL, &status );
  fits_read_key(fp, TSTRING, "SRC_NAME", source_name, NULL, &status);
  if(strlen(source_name)==0){
	  strcpy(source_name,"UNKNOWN      ");
  }
  fits_report_error(stderr,status);
  if (fits_read_key(fp, TINT, "IBEAM", ibeam, NULL, &status))
    {
      *ibeam = 1;
      status=0;
    }
  fits_report_error(stderr,status);
  //fits_read_key(fp, TINT, "OBSNCHAN", nchans, NULL, &status);
  //fits_report_error(stderr,status);
  fits_read_key(fp, TFLOAT, "OBSBW", &obsbw, NULL, &status);
  //  if (obsbw > 0) obsbw = -obsbw; // We must invert the data
  // The bandwidth in FITS is always positive
  // In order to determine whether sigproc should be given a negative bandwidth
  // the sign of the CHANBW parameter needs to be determined
  // This is done below
  fits_report_error(stderr,status);
  fits_read_key(fp, TFLOAT, "OBSFREQ", &fc, NULL, &status);
  fits_report_error(stderr,status);
  fits_read_key(fp, TINT, "STT_IMJD", &imjd, NULL, &status);
  fits_report_error(stderr,status);
  fits_read_key(fp, TDOUBLE, "STT_SMJD", &smjd, NULL, &status);
  fits_report_error(stderr,status);
  fits_read_key(fp, TDOUBLE, "STT_OFFS", &offs, NULL, &status);
  fits_report_error(stderr,status);
  fits_read_key(fp, TSTRING, "TELESCOP", telescope, NULL, &status);
  fits_report_error(stderr,status);
  if (strcasecmp(telescope,"PARKES")==0)
    *telescope_id=4;
  else if (strcasecmp(telescope,"ARECIBO")==0)
    *telescope_id=1;
  else if (strcasecmp(telescope,"JODRELL")==0)
    *telescope_id=5;
  else if (strcasecmp(telescope,"GBT")==0)
    *telescope_id=6;
  else if (strcasecmp(telescope,"EFFELSBERG")==0)
    *telescope_id=8;
  else if (strcasecmp(telescope,"SRT")==0)
    *telescope_id=10;
  else 
    *telescope_id = -1;

  // Start time
  *tstart = imjd+(smjd+offs)/86400.0;

  fits_read_key(fp, TSTRING, "RA", ras, NULL, &status);
  sscanf(ras,"%lf:%lf:%lf",&h,&m,&sec);
  *src_raj  = (double)h*10000.0 + (double)m*100.0 + (double)sec;

  fits_read_key(fp, TSTRING, "DEC", decs, NULL, &status);
  sscanf(decs,"%lf:%lf:%lf",&h,&m,&sec);
  
  *src_dej  = (double)fabs(h)*10000.0 + (double)m*100.0 + (double)sec;
  if (h < 0) (*src_dej)*=-1;

  
  // Now get information from the subint header
  strcpy(name,"SUBINT");
  fits_movnam_hdu(fp, BINARY_TBL, name, 0, &status);
  fits_read_key(fp, TDOUBLE, "TBIN", tsamp, NULL, &status );
  fits_read_key(fp, TINT, "NPOL", nifs, NULL, &status );
  fits_read_key(fp, TINT, "NBITS", nbits, NULL, &status );
  fits_read_key(fp, TDOUBLE, "CHAN_BW", &chanbw, NULL, &status );
//  if (chanbw < 0) obsbw=-(obsbw);

  fits_movnam_hdu( fp, BINARY_TBL, "SUBINT", 0, &status );
  fits_read_key( fp, TINT, "NCHAN", &NCHANS, NULL, &status);
  fits_get_colnum( fp, CASESEN, "DAT_FREQ", &ncol, &status );

  firstelem = 1LL;
  nelem = NCHANS;
  *nchans = NCHANS;
  row = 1LL;

  fits_read_col( fp, TFLOAT, ncol, row, firstelem, nelem, &nulval,
		  ch_freq, &anynul, &status );

  //*fch1 = ch_freq[0] > ch_freq[nelem-1] ? ch_freq[0] : ch_freq[nelem-1];
  //*fch1 = fc-obsbw/2.0 + obsbw/(*nchans)/2.0;
  //*fch1 = fc - ((*nchans-1)/ 2.0)*chanbw;
  *fch1=ch_freq[0];
  *foff = chanbw;

  fprintf(stderr,"Native fch1=%f, foff=%f\n",*fch1,*foff);
  if(chanbw > 0){
	 fprintf(stderr,"Will flip the band!\n");
  }
  
  fits_close_file(fp,&status);
  fits_report_error(stderr,status);
}
예제 #17
0
int main(int argc, char *argv[]) {
    fitsfile *infile;
    int ii, jj, kk, status = 0;
    int nchan, nchan2, npol, wgts_col, offs_col;
    long nrows;
    float *weights, *offsets;
    char comment[120];

    // Read the weights and offsets
    read_wgts_and_offs(argv[1], &nchan, &weights, &offsets);
    printf("Read in %d channels of weights and offsets from\n\t'%s'\n", 
           nchan, argv[1]);

    // Step through the FITS files
    for (ii = 0 ; ii < argc-2 ; ii++) {
        printf("Updating '%s'\n", argv[ii+2]);
        
        // Is the file a PSRFITS file?
        if (!is_PSRFITS(argv[ii+2])) {
            fprintf(stderr,
                    "  Error!  '%s' does not appear to be PSRFITS!\n",
                    argv[ii+2]);
            exit(1);
        }
        
        // Open the PSRFITS file
        fits_open_file(&infile, argv[ii+2], READWRITE, &status);
        if (status) {
            printf("  Error!  Cannot open '%s'!\n", argv[ii+2]);
            exit(1);
        }

        // Move to the SUBINT HDU
        fits_movnam_hdu(infile, BINARY_TBL, "SUBINT", 0, &status);
        if (status) {
            printf("  Warning!  Cannot find NPOL in '%s'!  Assuming NPOL=1\n", 
                   argv[ii+2]);
            status = 0;
        }

        // Read the number of channels and polarizations
        fits_read_key(infile, TINT, "NCHAN", &nchan2, comment, &status); \
        if (status) {
            printf("  Warning!  Cannot find NCHAN in '%s'!\n", argv[ii+2]);
            status = 0;
        } else if (nchan != nchan2) {
            printf("  Error!  The number of channels in '%s'\n", argv[1]);
            printf("          and in '%s' do not match!\n", argv[ii+2]);
            exit(1);
        }
        fits_read_key(infile, TINT, "NPOL", &npol, comment, &status); \
        if (status) {
            printf("  Warning!  Cannot find NPOL in '%s'!  Assuming NPOL=1\n", 
                   argv[ii+2]);
            npol = 1;
            status = 0;
        }
        
        // How many rows are there?
        fits_get_num_rows(infile, &nrows, &status);
        if (status) {
            printf("  Error!  Cannot read the number of rows in '%s'!\n", 
                   argv[ii+2]);
            exit(1);
        }

        // Get the column numbers for the weights
        fits_get_colnum(infile, 0, "DAT_WTS", &wgts_col, &status);
        if (status==COL_NOT_FOUND) {
            printf("  Warning!:  Can't find the channel weights!\n");
            status = 0;
        } else {
            // update the weights, row by row
            for (jj = 1 ; jj < nrows+1 ; jj++)
                fits_write_col(infile, TFLOAT, wgts_col, jj, 
                               1L, nchan, weights, &status);
        }
        
        // Get the column numbers for the offsets
        if (0) {
            fits_get_colnum(infile, 0, "DAT_OFFS", &offs_col, &status);
            if (status==COL_NOT_FOUND) {
                printf("  Warning!:  Can't find the channel offsets!\n");
                status = 0;
            } else {
                // update the offsets, row by row
                for (jj = 1 ; jj < nrows+1 ; jj++)
                    for (kk = 0 ; kk < npol ; kk++)
                        fits_write_col(infile, TFLOAT, offs_col, jj, 
                                       kk*nchan+1L, nchan, offsets, &status);
            }
        }
        
        // Close the file
        fits_close_file(infile, &status);
        if (status) {
            printf("  Warning!:  Cannot properly close '%s' (status=%d)!\n", 
                   argv[ii+2], status);
            status = 0;
        }
    }
    free(weights);
    free(offsets);
    printf("Finished.\n");
    exit(0);
}
int quickfits_read_map_header(const char* filename , fitsinfo_map* fitsi)
{

/*
    Read in map header information
 
	INPUTS:
		char* tfilename : c string = name of FITS file to be read
	OUTPUTS:
		ra = right ascention
		dec = declination
		object = name of source
		freq = frequency
		cell =  cellsize (degrees)
		dim = image size
		bmaj, bmin, bpa = beam information (degrees)
*/
	fitsfile *fptr;

	int status,i,j;
	int err;
	char comment[FLEN_VALUE];
	char key_name[FLEN_VALUE];
	char key_type[FLEN_VALUE];
	char beamhdu[]="AIPS CG ";
	char cchdu[]="AIPS CC ";
	char bmajname[]="BMAJ";
	char bminname[]="BMIN";
	char bpaname[]="BPA";
	int colnum;
	double temp;
	float floatbuff;
	float float_null=0;
	int int_null=0;
	long longbuff;


	status = 0;	// for error processing
	err=0;



	if ( fits_open_file(&fptr,filename, READONLY, &status) )	// open file and make sure it's open
	{
		printf("ERROR : quickfits_read_map_header --> Error opening FITS file, error = %d\n",status);
		return(status);
	}

	if (fits_movabs_hdu(fptr,1,&i,&status))		// move to main AIPS image HDU (assuming it's the first one)
	{
		printf("ERROR : quickfits_read_map_header --> Error locating AIPS ACSII table extension, error = %d\n",status);
		printf("ERROR : quickfits_read_map_header --> Did you remember to use the AIPS FITAB task instead of FITTP?\n");
		return(status);
	}

	// read in some optional keys (these may fail on strange files - but are not that important)

	fits_read_key(fptr,TSTRING,"OBJECT",fitsi[0].object,comment,&status);
	fits_read_key(fptr,TSTRING,"OBSERVER",fitsi[0].observer,comment,&status);
	fits_read_key(fptr,TSTRING,"TELESCOP",fitsi[0].telescope,comment,&status);
	fits_read_key(fptr,TDOUBLE,"EQUINOX",&fitsi[0].equinox,comment,&status);
	fits_read_key(fptr,TSTRING,"DATE-OBS",fitsi[0].date_obs,comment,&status);
	
	//	Now iterate through CTYPE coords to get important information about RA, DEC, cellsize etc.
	//  Most of this data is important - at least notify the user if some is missing
	
	i=1;
	status=0;
	j=0;
	while(status!=KEY_NO_EXIST)
	{
		if(status != 0) {
			printf("ERROR : quickfits_read_map_header -->  Error reading from %s\n", filename);
			printf("ERROR : quickfits_read_map_header -->  FITSIO error code: %d\n", status);
			return(1);
		}
		sprintf(key_name,"CTYPE%d",i);
		fits_read_key(fptr,TSTRING,key_name,key_type,comment,&status);

		if( !strncmp(key_type,"RA---SIN",8) )
		{
			j++;
			
			sprintf(key_name,"CRVAL%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&fitsi[0].ra,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing RA information %s\n",key_name);
				status= 0;
			}
			
			sprintf(key_name,"CDELT%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing RA information %s\n",key_name);
				status= 0;
			}
			else
			{
				fitsi[0].cell_ra=fabs(temp);
			}
			
			sprintf(key_name,"CRPIX%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing RA information %s\n",key_name);
				status= 0;
			}
			else
			{
				fitsi[0].centre_shift[0]=temp;
			}
			
			sprintf(key_name,"CROTA%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing RA information %s\n",key_name);
				status= 0;
			}
			else
			{
				fitsi[0].rotations[0]=temp;
			}
		}

		if( !strncmp(key_type,"DEC--SIN",8) )
		{
			j++;
			
			sprintf(key_name,"CRVAL%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&fitsi[0].dec,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing DEC information %s\n",key_name);
				status = 0;
			}
			
			sprintf(key_name,"CDELT%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing RA information %s\n",key_name);
				status= 0;
			}
			else
			{
				fitsi[0].cell_dec=fabs(temp);
			}

			sprintf(key_name,"CRPIX%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing DEC information %s\n",key_name);
				status = 0;
			}
			else
			{
				fitsi[0].centre_shift[1]=temp;
			}
			
			sprintf(key_name,"CROTA%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);			
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing DEC information %s\n",key_name);
				status = 0;
			}
			else
			{
				fitsi[0].rotations[1]=temp;
			}
		}
		
		if( !strncmp(key_type,"FREQ",4) )
		{
			j++;
			
			sprintf(key_name,"CRVAL%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&fitsi[0].freq,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing FREQ information %s\n",key_name);
				status = 0;
			}

			sprintf(key_name,"CDELT%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&fitsi[0].freq_delta,comment,&status);
			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing FREQ information %s\n",key_name);
				status = 0;
			}
		}

		if( !strncmp(key_type,"STOKES",6) )
		{
			sprintf(key_name,"CRVAL%d",i);
			fits_read_key(fptr,TDOUBLE,key_name,&temp,comment,&status);

			if(status==KEY_NO_EXIST)
			{
				printf("WARNING : quickfits_read_map_header --> Missing Stokes information %s\n",key_name);
				status = 0;
			}
			else
			{
				fitsi[0].stokes=(int)(temp);
			}
		}
		i++;
	}
	status=0;
	if(j!=3)
	{
		printf("WARNING : quickfits_read_map_header --> Error reading RA, DEC, FREQ information\n");
		printf("\t Only %d out of 3 read.\n",j);
	}


	fits_read_key(fptr,TDOUBLE,"NAXIS1",&temp,comment,&status);
	fitsi[0].imsize_ra=(int)(temp);	// dim is stored as a double in the FITS file
	
	fits_read_key(fptr,TDOUBLE,"NAXIS2",&temp,comment,&status);
	fitsi[0].imsize_dec=(int)(temp);	// dim is stored as a double in the FITS file

	if(status!=0)
	{
		printf("ERROR : quickfits_read_map_header --> Error reading image size from NAXIS1, error = %d\n",err);
		return(err);
	}

	fitsi[0].have_beam = true; 	// assume true until proved otherwise
	fits_read_key(fptr,TDOUBLE,"BMAJ",&fitsi[0].bmaj,comment,&status);
	err += status;
	fits_read_key(fptr,TDOUBLE,"BMIN",&fitsi[0].bmin,comment,&status);
	err += status;
	fits_read_key(fptr,TDOUBLE,"BPA",&fitsi[0].bpa,comment,&status);
	err += status;
	
	if(err!=0)	// if the beam information isn't in the main header, move to AIPS CG HDU for beam information
	{
		status=0;
		if (fits_movnam_hdu(fptr,BINARY_TBL,beamhdu,0,&status))		// move to beam information hdu
		{
			printf("WARNING : quickfits_read_map_header --> No beam information found.\n");
			fitsi[0].bmaj = 0.0;
			fitsi[0].bmin = 0.0;	// changed this because model files don't have any beam information. Should check to make sure beam info is valid in other code
			fitsi[0].bpa = 0.0;
			fitsi[0].have_beam = false;
		}
		else
		{
			fits_get_colnum(fptr,CASEINSEN,bmajname,&colnum,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error locating BMAJ information, error = %d\n",status);
				return(err);
			}
			fits_read_col(fptr,TFLOAT,colnum,1,1,1,&float_null,&floatbuff,&int_null,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error reading BMAJ information, error = %d\n",status);
				return(err);
			}
			else
			{
				fitsi[0].bmaj=(double)(floatbuff);
			}

			fits_get_colnum(fptr,CASEINSEN,bminname,&colnum,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error locating BMIN information, error = %d\n",status);
				return(err);
			}
			fits_read_col(fptr,TFLOAT,colnum,1,1,1,&float_null,&floatbuff,&int_null,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error reading BMIN information, error = %d\n",status);
				return(err);
			}
			else
			{
				fitsi[0].bmin=(double)(floatbuff);
			}

			fits_get_colnum(fptr,CASEINSEN,bpaname,&colnum,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error locating BPA information, error = %d\n",status);
				return(err);
			}
			fits_read_col(fptr,TFLOAT,colnum,1,1,1,&float_null,&floatbuff,&int_null,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error reading BPA information, error = %d\n",status);
				return(err);
			}
			else
			{
				fitsi[0].bpa=(double)(floatbuff);
			}
		}
	}






	// move to AIPS CC HDU for clean component information if requested. Read, or give error if a failure occurs. Allow for possibility of the outdated "A3DTABLE" table type 6 as well as normal BINARY_TBL

	if (fitsi[0].cc_table_version >=0 )
	{
		fits_movnam_hdu(fptr,ANY_HDU,cchdu,fitsi[0].cc_table_version,&status);
		if (status==0)		// move to main AIPS UV hdu
		{
			fits_get_num_rows(fptr,&longbuff,&status);
			fitsi[0].ncc=longbuff;
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map_header -->  Error reading number of clean components, error = %d\n",status);
				return(status);
			}
		}
		else
		{
			printf("WARNING : quickfits_read_map_header -->  No clean component table detected.\n");
			fitsi[0].ncc=0;
			return(status);
		}
	}
	else
	{
		fitsi[0].ncc=0;
	}


	

	status=0;
	if ( fits_close_file(fptr, &status) )
	{
		printf("ERROR : quickfits_read_map_header --> Error closing FITS file, error = %d\n",status);
		return(status);
	}

	return(status);
}
예제 #19
0
/* This function is similar to psrfits_create, except it
 * deals with reading existing files.  It is assumed that
 * basename and filenum are filled in correctly to point to 
 * the first file in the set OR that filename already contains
 * the correct file name.
 */
int psrfits_open(struct psrfits *pf) {

    int itmp;
    double dtmp;
    char ctmp[256];

    struct hdrinfo *hdr = &(pf->hdr);
    struct subint  *sub = &(pf->sub);
    struct foldinfo *fold = &(pf->fold);
    int *status = &(pf->status);

    if (pf->numfiles==0) {
        // Dynamically generated file names
        sprintf(pf->filename, "%s_%04d.fits", pf->basefilename, pf->filenum);
    } else {
        // Using explicit filenames
        if (pf->filenum < pf->numfiles) {
            strncpy(pf->filename, pf->filenames[pf->filenum], 200);
        } else {
            *status = FILE_NOT_OPENED;
            return *status;
        }
    }

    fits_open_file(&(pf->fptr), pf->filename, READONLY, status);
    pf->mode = 'r';

    // If file no exist, exit now
    if (*status) {
        return *status; 
    } else {
        printf("Opened file '%s'\n", pf->filename);
    }

    // Move to main HDU
    fits_movabs_hdu(pf->fptr, 1, NULL, status);

    // Figure out obs mode
    fits_read_key(pf->fptr, TSTRING, "OBS_MODE", hdr->obs_mode, NULL, status);
    int mode = psrfits_obs_mode(hdr->obs_mode);

    // Set the downsampling stuff to default values
    hdr->onlyI = 0;
    hdr->ds_time_fact = 1;
    hdr->ds_freq_fact = 1;

    // Blank parfile name, folding params
    fold->parfile[0] = '\0';
    fold->n_polyco_sets = 0;
    fold->pc = NULL;

    // Read some stuff
    fits_read_key(pf->fptr, TSTRING, "TELESCOP", hdr->telescope, NULL, status);
    fits_read_key(pf->fptr, TSTRING, "OBSERVER", hdr->observer, NULL, status);
    fits_read_key(pf->fptr, TSTRING, "PROJID", hdr->project_id, NULL, status);
    fits_read_key(pf->fptr, TSTRING, "FRONTEND", hdr->frontend, NULL, status);
    fits_read_key(pf->fptr, TSTRING, "BACKEND", hdr->backend, NULL, status);
    fits_read_key(pf->fptr, TSTRING, "FD_POLN", hdr->poln_type, NULL, status);
    fits_read_key(pf->fptr, TSTRING, "DATE-OBS", hdr->date_obs, NULL, status);
    fits_read_key(pf->fptr, TDOUBLE, "OBSFREQ", &(hdr->fctr), NULL, status);
    fits_read_key(pf->fptr, TDOUBLE, "OBSBW", &(hdr->BW), NULL, status);
    fits_read_key(pf->fptr, TINT, "OBSNCHAN", &(hdr->orig_nchan), NULL, status);
    hdr->orig_df = hdr->BW / hdr->orig_nchan;
    fits_read_key(pf->fptr, TDOUBLE, "CHAN_DM", &(hdr->chan_dm), NULL, status);
    if (*status==KEY_NO_EXIST) { hdr->chan_dm=0.0; *status=0; }
    fits_read_key(pf->fptr, TSTRING, "SRC_NAME", hdr->source, NULL, status);
    fits_read_key(pf->fptr, TSTRING, "TRK_MODE", hdr->track_mode, NULL, status);
    // TODO warn if not TRACK?
    fits_read_key(pf->fptr, TSTRING, "RA", hdr->ra_str, NULL, status);
    fits_read_key(pf->fptr, TSTRING, "DEC", hdr->dec_str, NULL, status);
    fits_read_key(pf->fptr, TDOUBLE, "BMAJ", &(hdr->beam_FWHM), NULL, status);
    fits_read_key(pf->fptr, TSTRING, "CAL_MODE", hdr->cal_mode, NULL, status);
    fits_read_key(pf->fptr, TDOUBLE, "CAL_FREQ", &(hdr->cal_freq), NULL, 
            status);
    fits_read_key(pf->fptr, TDOUBLE, "CAL_DCYC", &(hdr->cal_dcyc), NULL, 
            status);
    fits_read_key(pf->fptr, TDOUBLE, "CAL_PHS", &(hdr->cal_phs), NULL, status);
    fits_read_key(pf->fptr, TSTRING, "FD_MODE", hdr->feed_mode, NULL, status);
    fits_read_key(pf->fptr, TDOUBLE, "FA_REQ", &(hdr->feed_angle), NULL, 
            status);
    fits_read_key(pf->fptr, TDOUBLE, "SCANLEN", &(hdr->scanlen), NULL, status);
    fits_read_key(pf->fptr, TDOUBLE, "FD_SANG", &(hdr->fd_sang), NULL, status);
    fits_read_key(pf->fptr, TDOUBLE, "FD_XYPH", &(hdr->fd_xyph), NULL, status);
    fits_read_key(pf->fptr, TINT, "FD_HAND", &(hdr->fd_hand), NULL, status);
    fits_read_key(pf->fptr, TINT, "BE_PHASE", &(hdr->be_phase), NULL, status);

    fits_read_key(pf->fptr, TINT, "STT_IMJD", &itmp, NULL, status);
    hdr->MJD_epoch = (long double)itmp;
    hdr->start_day = itmp;
    fits_read_key(pf->fptr, TDOUBLE, "STT_SMJD", &dtmp, NULL, status);
    hdr->MJD_epoch += dtmp/86400.0L;
    hdr->start_sec = dtmp;
    fits_read_key(pf->fptr, TDOUBLE, "STT_OFFS", &dtmp, NULL, status);
    hdr->MJD_epoch += dtmp/86400.0L;
    hdr->start_sec += dtmp;

    fits_read_key(pf->fptr, TDOUBLE, "STT_LST", &(hdr->start_lst), NULL, 
            status);

    // Move to first subint
    fits_movnam_hdu(pf->fptr, BINARY_TBL, "SUBINT", 0, status);

    // Read some more stuff
    fits_read_key(pf->fptr, TINT, "NPOL", &(hdr->npol), NULL, status);
    fits_read_key(pf->fptr, TSTRING, "POL_TYPE", &(hdr->poln_order), NULL, status);
    if (strncmp(hdr->poln_order, "AA+BB", 6)==0) hdr->summed_polns=1;
    else hdr->summed_polns=0;
    fits_read_key(pf->fptr, TDOUBLE, "TBIN", &(hdr->dt), NULL, status);
    fits_read_key(pf->fptr, TINT, "NBIN", &(hdr->nbin), NULL, status);
    fits_read_key(pf->fptr, TINT, "NSUBOFFS", &(hdr->offset_subint), NULL, 
            status);
    fits_read_key(pf->fptr, TINT, "NCHAN", &(hdr->nchan), NULL, status);
    fits_read_key(pf->fptr, TDOUBLE, "CHAN_BW", &(hdr->df), NULL, status);
    fits_read_key(pf->fptr, TINT, "NSBLK", &(hdr->nsblk), NULL, status);
    fits_read_key(pf->fptr, TINT, "NBITS", &(hdr->nbits), NULL, status);

    if (mode==SEARCH_MODE) {
        long long lltmp = hdr->nsblk;  // Prevents a possible overflow in numerator below
        lltmp = (lltmp * hdr->nbits * hdr->nchan * hdr->npol) / 8L;
        sub->bytes_per_subint = (int) lltmp;
    } else if (mode==FOLD_MODE) {
        sub->bytes_per_subint = 
            (hdr->nbin * hdr->nchan * hdr->npol); // XXX data type??
    }

    // Init counters
    pf->rownum = 1;
    fits_read_key(pf->fptr, TINT, "NAXIS2", &(pf->rows_per_file), NULL, status);

    return *status;
}
예제 #20
0
파일: pfits.c 프로젝트: SixByNine/pfits
int extractFoldData(fitsfile *fp,dSet *data,float dm,float *fx,float *fy,float *freq_y,float *time_y,float *bpass, int sub0)
{
  int n=0;
  int status=0;
  int colnum;
  int i,j,k,l;
  int initflag=0;
  float nval=0;
  float ty[data->phead.nbin];
  float **offs;    // [data->phead.nsub];
  float **dat_scl; // [data->phead.nsub];
  double f0,chanbw,tdelay;
  int bn,cdelay;
  double bintime;
  int addDelay = 0; //500;
//  float bpass[data->phead.nchan*2];
  float bpass_offs[2];
  float bpass_scl[2];
  float meanVal,rmsVal;


  // get mean/RMS of off-pulse for scaling. no longer need OFFS/DAT_SCL
  printf("sub0 = %d\n",sub0);
  if (dm < 0)
    dm = data->phead.dm;
  
  // Need to remove a baseline from each polarisation channel before summing

  // Get first frequency channel
  // Central frequency
  f0 = data->phead.freq; //-data->phead.chanbw*data->phead.nchan/2;
  //  chanbw = data->phead.bw/data->phead.nchan;
  chanbw = data->phead.chanbw;

  bintime = (double)data->phead.period/(double)data->phead.nbin;

  fits_movnam_hdu(fp,BINARY_TBL,"BANDPASS",1,&status);
  if (status) {
    printf("Unable to move to bandpass table in FITS file\n");
    exit(1);
  }
  fits_get_colnum(fp,CASEINSEN,"DAT_OFFS",&colnum,&status);  
  fits_read_col_flt(fp,colnum,1,1,2,nval,bpass_offs,&initflag,&status);
  fits_get_colnum(fp,CASEINSEN,"DAT_SCL",&colnum,&status);  
  fits_read_col_flt(fp,colnum,1,1,2,nval,bpass_scl,&initflag,&status);
  // Now read the bandpass
  fits_get_colnum(fp,CASEINSEN,"DATA",&colnum,&status);  
  // NOTE: Starting at element 2 as element 1 is junk
  fits_read_col_flt(fp,colnum,1,2,data->phead.nchan,nval,bpass,&initflag,&status);
  fits_read_col_flt(fp,colnum,1,3+data->phead.nchan,data->phead.nchan,nval,bpass+data->phead.nchan,&initflag,&status);
  for (i=0;i<data->phead.nchan*2;i++)
    {
      if (i<data->phead.nchan)
	bpass[i] = bpass[i]*bpass_scl[0] + bpass_offs[0];
      else
	bpass[i] = bpass[i]*bpass_scl[1] + bpass_offs[1];
      //      printf("bpass: %d %g %g %g %g %g \n",i,bpass[i],bpass_scl[0],bpass_scl[1],bpass_offs[0],bpass_offs[1]);
    }
  //  exit(1);

  fits_movnam_hdu(fp,BINARY_TBL,"SUBINT",1,&status);
  if (status) {
    printf("Unable to move to subint table in FITS file\n");
    exit(1);
  }
  // REMOVED: No longer need dat_scl or offs. OFFS/DAT_SCL
//  offs = (float **)malloc(sizeof(float *)*data->phead.nsub);
//  dat_scl = (float **)malloc(sizeof(float *)*data->phead.nsub);
//  for (i=0;i<data->phead.nsub;i++)
//    {
//      offs[i] = (float *)malloc(sizeof(float)*data->phead.nchan*data->phead.npol);
//      dat_scl[i] = (float *)malloc(sizeof(float)*data->phead.nchan*data->phead.npol);
//    }
//  fits_get_colnum(fp,CASEINSEN,"DAT_OFFS",&colnum,&status);
//  if (status) {
//    printf("Unable to find DAT_OFFS in the subint table in FITS file\n");
//    exit(1);
//  }
//  for (i=0;i<data->phead.nsub;i++)
//    {
//      fits_read_col_flt(fp,colnum,i+1,1,data->phead.nchan*data->phead.npol,nval,offs[i],&initflag,&status);
//      //      printf("offs = %g\n",offs[i][5]);
//      //      offs[i] =0;
//    }
//
//  fits_get_colnum(fp,CASEINSEN,"DAT_SCL",&colnum,&status);
//  if (status) {
//    printf("Unable to find DAT_SCL in the subint table in FITS file\n");
//    exit(1);
//  }
//  for (i=0;i<data->phead.nsub;i++)
//    {
//      fits_read_col_flt(fp,colnum,i+1,1,data->phead.nchan*data->phead.npol,nval,dat_scl[i],&initflag,&status);
//      //      printf("dat_scl = %g\n",dat_scl[i][5]);
//      //            dat_scl[i]=1.0;
//    }

  fits_get_colnum(fp,CASEINSEN,"DATA",&colnum,&status);
  if (status) {
    printf("Unable to find data in the subint table in FITS file\n");
    exit(1);
  }
  if (sub0==0)
    {
      for (i=0;i<data->phead.nbin;i++)
	{
	  fx[i] = i;
	  fy[i] = 0;
	}
      //
      printf("Loading %d subintegrations\n",data->phead.nsub);
      printf("Number of frequency channels = %d\n",data->phead.nchan);
      printf("Number of polarisations = %d\n",data->phead.npol);
      for (i=0;i<data->phead.nchan*data->phead.nbin;i++)
	freq_y[i] = 0;
    }
  for (i=sub0;i<data->phead.nsub;i++) // *data->phead.nbin;i++)
    {
      for (j=0;j<data->phead.nbin;j++)
	time_y[i*data->phead.nbin+j] = 0;
    } 
  for (l=sub0;l<data->phead.nsub;l++)
    {
      for (j=0;j<data->phead.npol && j < 2;j++) // Do not add cross terms!
	{
	  for (i=0;i<data->phead.nchan;i++)
	    {
	      // Must calculate the frequency of this channel
	      // ... calculate the delay caused by the DM
	      // ... dedisperse the subintegration
	      
	      //	      tdelay = 4.15e-3*dm*(pow(f0/1000.0,-2)-pow((f0+chanbw*i)/1000.0,-2));
	      tdelay = 4.15e-3*dm*(pow(f0/1000.0,-2)-pow((f0+(chanbw*i-chanbw*data->phead.nchan/2.0))/1000.0,-2));
	      cdelay = nint(-tdelay/bintime);
	      //	      if (l==0 && j==0)
	      //		printf("Have %g %g %g %d %d\n",dm,f0,f0+chanbw*i,i,cdelay);
	      fits_read_col_flt(fp,colnum,l+1,j*(data->phead.nchan*data->phead.nbin)+i*data->phead.nbin+1,data->phead.nbin,nval,ty,&initflag,&status);
	      meanVal=0;
	      //for (k=0;k<data->phead.nbin;k++)
		//{
		 // ty[k] = ((ty[k]+offs[l][j*data->phead.nchan+i])*dat_scl[l][j*data->phead.nchan+i]); //+offs[l][j*data->phead.nchan+i]);

		  /*		  if (j==0)
		    ty[k] -= bpass[i];
		  else if (j==1)
		    ty[k] -= bpass[data->phead.nchan+i];
		  else
		    {
		      ty[k] -= sqrt(bpass[data->phead.nchan+i]*bpass[i]);
		      } */
		  //meanVal+=ty[k];
	//	}

	      getbaseline(ty,data->phead.nbin,0.35,&meanVal,&rmsVal);
	      if (rmsVal == 0.0 ) rmsVal=1.0;
	      //	      printf("Val = %g\n",ty[10]);
	      for (k=0;k<data->phead.nbin;k++)
		{
		  //		  if (i==10 && l==10)
		  //		    printf("Orig value = %g\n",ty[k]);

		  //ty[k] = ((ty[k]+offs[l][j*data->phead.nchan+i])*dat_scl[l][j*data->phead.nchan+i]); //+offs[l][j*data->phead.nchan+i]);
		  ty[k] -= meanVal;
		  ty[k] /= rmsVal;
		  // Subtract bandpass
		  /*		  if (j==0)
		    ty[k] -= bpass[i];
		  else if (j==1)
		    ty[k] -= bpass[data->phead.nchan+i];
		  else
		    {
		      ty[k] -= sqrt(bpass[data->phead.nchan+i]*bpass[i]);
		      } */
		  //		  if (l==10)
		      
		  //		    printf("New value = %g\n",ty[k]);
		  bn = k-cdelay + addDelay;
		  //		  bn = nint(fmod(k-tdelay/bintime,data->phead.nbin));
		  while (bn >= data->phead.nbin)
		    bn -= data->phead.nbin;
		  while (bn < 0)
		    bn += data->phead.nbin;
		  freq_y[i*data->phead.nbin+k]+=(ty[k]); ///(float)(data->phead.npol*data->phead.nsub));
		  time_y[l*data->phead.nbin+bn]+=(ty[k]);///(float)(data->phead.npol*data->phead.nchan));
		  //		  printf("timey = %g\n",time_y[l*data->phead.nbin+bn]);
		  fy[bn]+=(ty[k]/(float)(data->phead.nchan*data->phead.npol*data->phead.nsub));
		}
	    }
	}
    }
   
  // REMOVED: OFFS/DAT_SCL table no longer needed.
  //for (i=0;i<data->phead.nsub;i++)
  //  {
  //    free(offs[i]);
  //    free(dat_scl[i]);
  //  }
  //free(offs);
  //free(dat_scl);*/
  printf("Status = %d\n",status);
}
예제 #21
0
파일: pfits.c 프로젝트: SixByNine/pfits
int extractPolData(fitsfile *fp,dSet *data,int pol,float *arr,float t1,float t2)
{
  int nsblk;
  long s1,s2,sub_1,samp_1,sub_2,samp_2,s,r1,r2;
  int nchan = data->phead.nchan;
  int nbits = data->phead.nbits;
  int npol  = data->phead.npol;
  int samplesperbyte = 8/data->phead.nbits;
  float chanVal[nchan];
  long ipos=0;
  int status=0;
  int colnum;
  int initflag=0;
  unsigned char *cval;
  unsigned char nval = '0';
  int i,c,count=0,sa;
  unsigned char chVals[nchan];
  int smoothSamp=1;
  int sm;
  int t=0;
  float tempVal;
  long pos=0,p,cc=0;
  printf("Have t1/t2 %g %g %g\n",t1,t2,(double)data->phead.tsamp);
  s1 = (long)(t1/data->phead.tsamp);
  s2 = (long)(t2/data->phead.tsamp);
  printf("samples per byte = %d\n",samplesperbyte);
  printf("Searching for %g %g\n",(double)s1,(double)s2);

  nsblk = data->phead.nsblk;
  if (s1 < 0) s1=0;
  findPosSample(data,s1,&sub_1,&samp_1);
  findPosSample(data,s2,&sub_2,&samp_2);
  if (sub_1 < 0) sub_1=0;


  printf("Have samples (%d,%d) (%d,%d)\n",sub_1,samp_1,sub_2,samp_2);
  fits_movnam_hdu(fp,BINARY_TBL,"SUBINT",1,&status);
  if (status) {
    printf("Unable to move to subint table in FITS file\n");
    exit(1);
  }
  fits_get_colnum(fp,CASEINSEN,"DATA",&colnum,&status);
  if (status) {
    printf("Unable to find data in the subint table in FITS file\n");
    exit(1);
  }
  cval = (unsigned char *)malloc(sizeof(unsigned char)*nsblk*nchan/samplesperbyte*npol);
  //  printf("Allocated memory\n");
  t=0;
  printf("Have sub1/2 = %g %g\n",(double)sub_1,(double)sub_2);
  for (s=sub_1;s<=sub_2;s++)
    {
      //            printf("Loading sub: %d\n",s);
      if (s==sub_1)
	r1 = samp_1;
      else
	r1 = 0;
      if (s==sub_2)
	r2 = samp_2;
      else
	r2 = nsblk;
      printf("Reading from %d to %d for subint %d\n",r1,r2,s);

      // Read nchan data points
      for (sa=r1;sa<r2;sa++)
	{
	  fits_read_col_byt(fp,colnum,s+1,sa*nchan/samplesperbyte+1,nchan/samplesperbyte,nval,cval,&initflag,&status);
	  if (status)
	    {
	      fits_report_error(stderr,status);
	      exit(1);
	    }
	  bytesToValues(samplesperbyte, nchan, cval, chVals);
	  tempVal = 0.0;
	  //	  val[count] = 0.0;
	  for (i=0;i<nchan;i++)
	    {
	      //	      printf("Here with %g\n",(float)chVals[i]);
	      	      p = cc+(s2-s1)*i;
	      //	      printf("pos-p = %d\n",p);
	      //	      	      p=pos;
	      if (samplesperbyte==8)
		{
		  if (chVals[i]==0) arr[p] = 0.5;
		  else arr[p] = -0.5;
		}
	      else if (samplesperbyte==4)
		{
		  if (chVals[i]==0) arr[p]=-2.5;
		  else if (chVals[i]==1) arr[p] = -0.5;
		  else if (chVals[i]==2) arr[p] = 0.5;
		  else arr[p] = 2.5;
		}
	      else
		{
		  arr[p] = chVals[i];
		  //		  printf("Have got %g\n",arr[p]);
		}
	      //	      if (chVals[i]==0) arr[pos] = 0.5;
	      //	      else arr[pos] =- 0.5;
	      //	      pos++;
	      pos++;

	    }
	  cc++;
	  //	  pos++;
	}
    }
    printf("Complete %d %d %d\n",pos,s2-s1,nchan);
  free(cval);
    return cc;
    //return pos;

}
예제 #22
0
int psrfits_write_polycos(struct psrfits *pf, struct polyco *pc, int npc) {

    // Usual setup
    int *status = &(pf->status);

    // If mode!=fold, exit?

    // Save current HDU, move to polyco table
    int hdu;
    fits_get_hdu_num(pf->fptr, &hdu);
    fits_movnam_hdu(pf->fptr, BINARY_TBL, "POLYCO", 0, status);

    int itmp;
    double dtmp;
    char datestr[32], ctmp[32];
    char *cptr;
    fits_get_system_time(datestr, &itmp, status);
    int i, col, n_written=0; 
    long row;
    fits_get_num_rows(pf->fptr, &row, status); // Start at end of table
    for (i=0; i<npc; i++) {

        // Only write polycos that were used
        if (!pc[i].used) continue; 

        // Go to next row (1-based index)
        row++;

        cptr = datestr;
        fits_get_colnum(pf->fptr,CASEINSEN,"DATE_PRO",&col,status);
        fits_write_col(pf->fptr,TSTRING,col,row,1,1,&cptr,status);

        sprintf(ctmp, "11.005"); // Tempo version?
        cptr = ctmp;
        fits_get_colnum(pf->fptr,CASEINSEN,"POLYVER",&col,status);
        fits_write_col(pf->fptr,TSTRING,col,row,1,1,&cptr,status);

        fits_get_colnum(pf->fptr,CASEINSEN,"NSPAN",&col,status);
        fits_write_col(pf->fptr,TINT,col,row,1,1,&(pc[i].nmin),status);

        fits_get_colnum(pf->fptr,CASEINSEN,"NCOEF",&col,status);
        fits_write_col(pf->fptr,TINT,col,row,1,1,&(pc[i].nc),status);

        sprintf(ctmp,"%d", pc[i].nsite); // XXX convert to letter?
        cptr = ctmp;
        fits_get_colnum(pf->fptr,CASEINSEN,"NSITE",&col,status);
        fits_write_col(pf->fptr,TSTRING,col,row,1,1,&cptr,status);

        fits_get_colnum(pf->fptr,CASEINSEN,"REF_FREQ",&col,status);
        fits_write_col(pf->fptr,TFLOAT,col,row,1,1,&(pc[i].rf),status);

        // XXX needs to be accurate??
        dtmp=0.0;
        fits_get_colnum(pf->fptr,CASEINSEN,"PRED_PHS",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dtmp,status);

        dtmp = (double)pc[i].mjd + pc[i].fmjd;
        fits_get_colnum(pf->fptr,CASEINSEN,"REF_MJD",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dtmp,status);

        fits_get_colnum(pf->fptr,CASEINSEN,"REF_PHS",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&(pc[i].rphase),status);

        fits_get_colnum(pf->fptr,CASEINSEN,"REF_F0",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&(pc[i].f0),status);

        // XXX don't parse this yet
        dtmp=-6.0;
        fits_get_colnum(pf->fptr,CASEINSEN,"LGFITERR",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dtmp,status);

        fits_get_colnum(pf->fptr,CASEINSEN,"COEFF",&col,status);
        fits_write_col(pf->fptr,TDOUBLE,col,row,1,pc[i].nc,pc[i].c,status);

        n_written++;
    }

    // Update polyco block count, only if new info was added
    if (n_written) {
        itmp = row;
        fits_get_colnum(pf->fptr,CASEINSEN,"NPBLK",&col,status);
        for (i=1; i<=row; i++) 
            fits_write_col(pf->fptr,TINT,col,i,1,1,&itmp,status);
    }

    // Flush buffers (so files are valid as they are created)
    fits_flush_file(pf->fptr, status);

    // Go back to orig HDU
    fits_movabs_hdu(pf->fptr, hdu, NULL, status);

    return *status;
}
예제 #23
0
파일: pfits.c 프로젝트: SixByNine/pfits
void loadPrimaryHeader(fitsfile *fp,dSet *data)
{
  int status=0;
  int nkey=-1;
  int morekeys=-1;
  int i;
  char keyname[128],val[128],comment[128];

  fits_get_hdrspace(fp,&nkey,&morekeys,&status);
  data->pheaderSet = 1;

  data->phead.nhead = nkey;
  // Allocate memory
  data->phead.keyname = (char **)malloc(sizeof(char *)*nkey);
  data->phead.val = (char **)malloc(sizeof(char *)*nkey);
  data->phead.comment = (char **)malloc(sizeof(char *)*nkey);
  for (i=0;i<nkey;i++)
    {
      data->phead.keyname[i] = (char *)malloc(sizeof(char)*128);
      data->phead.val[i] = (char *)malloc(sizeof(char)*128);
      data->phead.comment[i] = (char *)malloc(sizeof(char)*128);
    }
  data->pheaderSet=1;

  // Complete allocating memory

  for (i=1;i<=nkey;i++)
    {
      fits_read_keyn(fp,i+1,data->phead.keyname[i-1],data->phead.val[i-1],data->phead.comment[i-1],&status);
      if (strcmp(data->phead.keyname[i-1],"OBSFREQ")==0)
	sscanf(data->phead.val[i-1],"%f",&(data->phead.freq));
      else if (strcmp(data->phead.keyname[i-1],"STT_IMJD")==0)
	sscanf(data->phead.val[i-1],"%d",&(data->phead.imjd));
      else if (strcmp(data->phead.keyname[i-1],"STT_SMJD")==0)
	sscanf(data->phead.val[i-1],"%f",&(data->phead.smjd));
      else if (strcmp(data->phead.keyname[i-1],"STT_OFFS")==0)
	sscanf(data->phead.val[i-1],"%f",&(data->phead.stt_offs));
      else if (strcmp(data->phead.keyname[i-1],"OBSBW")==0)
	sscanf(data->phead.val[i-1],"%f",&(data->phead.bw));
    }
  // Read specific parameters
  fits_read_key(fp,TSTRING,"OBS_MODE",data->phead.obsMode,NULL,&status);
  fits_read_key(fp,TSTRING,"SRC_NAME",data->phead.source,NULL,&status);
  if (status)
    {
      fits_report_error(stderr,status);
      exit(1);
    }

  // Now load information from the subintegration table
  fits_movnam_hdu(fp,BINARY_TBL,"SUBINT",1,&status);
  if (status)
    {
      printf("No subintegration table\n");
      data->subintTable=0;
      status=0;
    }
  else
    {
      data->subintTable=1;
      fits_read_key(fp,TINT,"NAXIS2",&(data->phead.nsub),NULL,&status);
      if (status)
	{
	  printf("Reading naxis2\n");
	  fits_report_error(stderr,status);
	  exit(1);
	}     
      fits_read_key(fp,TINT,"NCHAN",&(data->phead.nchan),NULL,&status);
      if (status)
	{
	  printf("Reading nchan\n");
	  fits_report_error(stderr,status);
	  exit(1);
	}
      
      fits_read_key(fp,TFLOAT,"ZERO_OFF",&(data->phead.zeroOff),NULL,&status);
      if (status)
	{
	  printf("Reading zero_off\n");
	  fits_report_error(stderr,status);
	  data->phead.zeroOff = 0;
	  status=0;
	}

      fits_read_key(fp,TINT,"NBITS",&(data->phead.nbits),NULL,&status);
      if (status)
	{
	  printf("Reading nbits\n");
	  fits_report_error(stderr,status);
	  exit(1);
	}

      fits_read_key(fp,TINT,"NPOL",&(data->phead.npol),NULL,&status);
      if (status)
	{
	  printf("Reading npol\n");
	  fits_report_error(stderr,status);
	  exit(1);
	}
      
      fits_read_key(fp,TINT,"NSBLK",&(data->phead.nsblk),NULL,&status);
      if (status)
	{
	  printf("Reading nsblk\n");
	  fits_report_error(stderr,status);
	  exit(1);
	}

      fits_read_key(fp,TINT,"NBIN",&(data->phead.nbin),NULL,&status);
      if (status)
	{
	  printf("Reading nbin\n");
	  fits_report_error(stderr,status);
	  exit(1);
	}

      //      printf("nbin = %d (%d)\n",data->phead.nbin,status);
      fits_read_key(fp,TFLOAT,"CHAN_BW",&(data->phead.chanbw),NULL,&status);
      if (data->phead.chanbw < 0 && data->phead.bw > 0)
	data->phead.bw*=-1;
      
      fits_read_key(fp,TFLOAT,"TBIN",&(data->phead.tsamp),NULL,&status);
      
    }
  fits_movnam_hdu(fp,BINARY_TBL,"PSRPARAM",1,&status);
  if (status)
    {
      printf("No PSRPARM table\n");
      data->psrparamTable=0;
      status=0;
    }
  else
    {
      int len,i,colnum;
      char **line,str1[1024],str2[1024];
      data->psrparamTable=1;
      char nval[128]="UNKNOWN";
      int anynul=0;
      float tt;
      fits_read_key(fp,TINT,"NAXIS2",&len,NULL,&status);

      fits_get_colnum(fp,CASEINSEN,"PARAM",&colnum,&status);
      if (status) {
	printf("Unable to find data in the psrparam table in FITS file\n");
	exit(1);
      }

      line = (char **)malloc(sizeof(char *));
      line[0] = (char *)malloc(sizeof(char)*1024); 

      for (i=0;i<len;i++)
	{
	  fits_read_col_str(fp,colnum,i+1,1,1,nval,line,&anynul,&status);
	  if (sscanf(line[0],"%s %s",str1,str2)==2)
	    {
	      if (strcasecmp(str1,"DM")==0)
		sscanf(str2,"%f",&(data->phead.dm));
	      if (strcasecmp(str1,"F0")==0)
		{
		  sscanf(str2,"%f",&tt);
		  data->phead.period = 1.0/tt;
		}
	    }
	  //	  printf("Read: %s\n",line[0]);
	}
      //      printf("Lenght = %d\n",len);
  free(line[0]);
  free(line);

    }
    
}
예제 #24
0
int psrfits_write_ephem(struct psrfits *pf, FILE *parfile) {
    // Read a pulsar ephemeris (par file) and put it into
    // the psrfits PSREPHEM table.  Only minimal checking
    // is done.
   
    // Get status
    int *status = &(pf->status);

    // Save current HDU, move to psrephem table
    int hdu;
    fits_get_hdu_num(pf->fptr, &hdu);
    fits_movnam_hdu(pf->fptr, BINARY_TBL, "PSREPHEM", 0, status);

    // Loop over lines in par file
    int row=1, col, dtype;
    double dval;
    int ival;
    long double ldval;
    char line[256], *ptr, *saveptr, *key, *val;
    while (fgets(line, 256, parfile)!=NULL) {

        // Convert tabs to spaces
        while ((ptr=strchr(line,'\t'))!=NULL) { *ptr=' '; }

        // strip leading whitespace
        ptr = line;
        while (*ptr==' ') { ptr++; }

        // Identify comments or blank lines
        if (line[0]=='\n' || line[0]=='#' || 
                (line[0]=='C' && line[1]==' '))
            continue;

        // Split into key/val (ignore fit flag and error)
        key = strtok_r(line,  " ", &saveptr);
        val = strtok_r(NULL, " ", &saveptr);
        if (key==NULL || val==NULL) continue; // TODO : complain?

        // Deal with any special cases here
        if (strncmp(key, "PSR", 3)==0)  {

            // PSR(J) -> PSR_NAME
            fits_get_colnum(pf->fptr,CASEINSEN,"PSR_NAME",&col,status);
            fits_write_col(pf->fptr,TSTRING,col,row,1,1,&val,status);

        } else if (strncmp(key, "RA", 2)==0) {

            // RA -> RAJ
            fits_get_colnum(pf->fptr,CASEINSEN,"RAJ",&col,status);
            fits_write_col(pf->fptr,TSTRING,col,row,1,1,&val,status);

        } else if (strncmp(key, "DEC", 3)==0) {

            // DEC -> DECJ
            fits_get_colnum(pf->fptr,CASEINSEN,"DECJ",&col,status);
            fits_write_col(pf->fptr,TSTRING,col,row,1,1,&val,status);

        } else if (key[0]=='E' && key[1]=='\0') {

            // E -> ECC
            dval = atof(val);
            fits_get_colnum(pf->fptr,CASEINSEN,"ECC",&col,status);
            fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dval,status);

        } else if (strncmp(key, "F0", 2)==0) {

            // F is converted to mHz and split into int/frac
            ldval = strtold(val,NULL) * 1000.0; // Hz->mHz
            ival = (int)ldval;
            dval = ldval - (long double)ival;
            fits_get_colnum(pf->fptr,CASEINSEN,"IF0",&col,status);
            fits_write_col(pf->fptr,TINT,col,row,1,1,&ival,status);
            fits_get_colnum(pf->fptr,CASEINSEN,"FF0",&col,status);
            fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dval,status);

        } else if (strncmp(key, "TZRMJD", 6)==0) {

            // TZRMJD is split into int/frac
            ldval = strtold(val,NULL);
            ival = (int)ldval;
            dval = ldval - (long double)ival;
            fits_get_colnum(pf->fptr,CASEINSEN,"TZRIMJD",&col,status);
            fits_write_col(pf->fptr,TINT,col,row,1,1,&ival,status);
            fits_get_colnum(pf->fptr,CASEINSEN,"TZRFMJD",&col,status);
            fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dval,status);

        } else {

            // Find column, skip/warn if this one isn't present
            fits_get_colnum(pf->fptr,CASEINSEN,key,&col,status);
            if (*status==COL_NOT_FOUND) {
#if (DEBUGOUT)
                fprintf(stderr, 
                        "psrfits_write_epherm warning: Couldn't find keyword %s "
                        "in ephemeris table.\n",
                        key);
#endif
                *status=0;
                continue;
            }

            // Need to convert string to appropriate column data type
            // and then write it to the column.  These should all be
            // either double int or string.
            fits_get_coltype(pf->fptr,col,&dtype,NULL,NULL,status);
            if (dtype==TDOUBLE || dtype==TFLOAT) { 
                dval = atof(val);
                fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dval,status);
            } else if (dtype==TINT || dtype==TLONG || dtype==TSHORT) {
                ival = atoi(val);
                fits_write_col(pf->fptr,TINT,col,row,1,1,&ival,status);
            } else if (dtype==TSTRING) {
                fits_write_col(pf->fptr,TSTRING,col,row,1,1,&val,status);
            } else {
                fprintf(stderr, "psrfits_write_ephem warning: "
                        "Unhandled column datatype (key=%s)\n", key);
                continue;
            }
        }

        // sucess/failure
        if (*status) {
            fprintf(stderr, "psrfits_write_ephem failed: key=%s val=%s\n",
                    key, val);
            fits_report_error(stderr, *status);
            *status=0;
        } 
#if 0  // DEBUG
        else {
            fprintf(stderr, "psrfits_write_ephem success: key=%s val=%s\n",
                    key, val);
        }
#endif

    }

    // Go back to orig HDU
    fits_movabs_hdu(pf->fptr, hdu, NULL, status);

    return *status;
}
예제 #25
0
int sdfits_create(struct sdfits *sf) {
    int itmp, *status;
    char ctmp[40];
    struct hdrinfo *hdr;

    hdr = &(sf->hdr);        // dereference the ptr to the header struct
    status = &(sf->status);  // dereference the ptr to the CFITSIO status

    // Initialize the key variables if needed
    if (sf->new_file == 1) {  // first time writing to the file
        sf->status = 0;
        sf->tot_rows = 0;
        sf->N = 0L;
        sf->T = 0.0;
        sf->mode = 'w';

        // Create the output directory if needed
        char datadir[1024];
        strncpy(datadir, sf->basefilename, 1023);
        char *last_slash = strrchr(datadir, '/');
        if (last_slash!=NULL && last_slash!=datadir) {
            *last_slash = '\0';
            printf("Using directory '%s' for output.\n", datadir);
            char cmd[1024];
            sprintf(cmd, "mkdir -m 1777 -p %s", datadir);
            system(cmd);
        }
        sf->new_file = 0;
    }
    sf->filenum++;
    sf->rownum = 1;

    sprintf(sf->filename, "%s_%04d.fits", sf->basefilename, sf->filenum);

    // Create basic FITS file from our template
    char *vegas_dir = getenv("VEGAS_DIR");
    char template_file[1024];
    if (vegas_dir==NULL) {
        fprintf(stderr, 
                "Error: VEGAS_DIR environment variable not set, exiting.\n");
        exit(1);
    }
    printf("Opening file '%s'\n", sf->filename);
    sprintf(template_file, "%s/%s", vegas_dir, SDFITS_TEMPLATE);
    fits_create_template(&(sf->fptr), sf->filename, template_file, status);

    // Check to see if file was successfully created
    if (*status) {
        fprintf(stderr, "Error creating sdfits file from template.\n");
        fits_report_error(stderr, *status);
        exit(1);
    }

    // Go to the primary HDU
    fits_movabs_hdu(sf->fptr, 1, NULL, status);

    // Update the keywords that need it
    fits_get_system_time(ctmp, &itmp, status);      // date the file was written
    fits_update_key(sf->fptr, TSTRING, "DATE", ctmp, NULL, status);

    // Go to the SINGLE DISH HDU
    fits_movnam_hdu(sf->fptr, BINARY_TBL, "SINGLE DISH", 0, status);

    // Update the keywords that need it
    fits_update_key(sf->fptr, TSTRING, "TELESCOP", hdr->telescope,NULL, status);
    fits_update_key(sf->fptr, TDOUBLE, "BANDWID", &(hdr->bandwidth), NULL, status);
    fits_update_key(sf->fptr, TSTRING, "DATE-OBS", hdr->date_obs, NULL, status);
    fits_update_key(sf->fptr, TDOUBLE, "TSYS", &(hdr->tsys), NULL, status);

    fits_update_key(sf->fptr, TSTRING, "PROJID", hdr->projid, NULL, status);
    fits_update_key(sf->fptr, TSTRING, "FRONTEND", hdr->frontend, NULL, status);
    fits_update_key(sf->fptr, TDOUBLE, "OBSFREQ", &(hdr->obsfreq), NULL, status);
    fits_update_key(sf->fptr, TDOUBLE, "SCAN", &(hdr->scan), NULL, status);

    fits_update_key(sf->fptr, TSTRING, "INSTRUME", hdr->instrument, NULL, status);
    fits_update_key(sf->fptr, TSTRING, "CAL_MODE", hdr->cal_mode, NULL, status);
    if (strcmp("OFF", hdr->cal_mode) != 0)
    {
        fits_update_key(sf->fptr, TDOUBLE, "CAL_FREQ", &(hdr->cal_freq), NULL, status);
        fits_update_key(sf->fptr, TDOUBLE, "CAL_DCYC", &(hdr->cal_dcyc), NULL, status);
        fits_update_key(sf->fptr, TDOUBLE, "CAL_PHS", &(hdr->cal_phs), NULL, status);
    }
    fits_update_key(sf->fptr, TINT,    "NPOL", &(hdr->npol), NULL, status);
    fits_update_key(sf->fptr, TINT,    "NCHAN", &(hdr->nchan), NULL, status);
    fits_update_key(sf->fptr, TDOUBLE, "CHAN_BW", &(hdr->chan_bw), NULL, status);
    fits_update_key(sf->fptr, TINT,    "NSUBBAND", &(hdr->nsubband), NULL, status);
    fits_update_key(sf->fptr, TDOUBLE, "EFSAMPFR", &(hdr->efsampfr), NULL, status);
    fits_update_key(sf->fptr, TDOUBLE, "FPGACLK", &(hdr->fpgaclk), NULL, status);
    fits_update_key(sf->fptr, TDOUBLE, "HWEXPOSR", &(hdr->hwexposr), NULL, status);
    fits_update_key(sf->fptr, TDOUBLE, "FILTNEP", &(hdr->filtnep), NULL, status);
    fits_update_key(sf->fptr, TDOUBLE, "STTMJD", &(hdr->sttmjd), NULL, status);

    // Update the column sizes for the colums containing arrays
    itmp = hdr->nsubband * hdr->nchan * 4;                          //num elements, not bytes
    fits_modify_vector_len(sf->fptr, 20, itmp, status);             // DATA
    fits_modify_vector_len(sf->fptr, 14, hdr->nsubband, status);    // SUBFREQ

    // Update the TDIM field for the data column
    sprintf(ctmp, "(%d,%d,4,1,1)", hdr->nchan, hdr->nsubband);
    fits_update_key(sf->fptr, TSTRING, "TDIM20", ctmp, NULL, status);

    fits_flush_file(sf->fptr, status);
   
    return *status;
}
예제 #26
0
int quickfits_read_map(const char* filename, fitsinfo_map fitsi , double* tarr , double* cc_xarray, double* cc_yarray, double* cc_varray)
{
/*
	INPUTS:
		const char* tfilename : c string = name of FITS file to be read
		int dim2 : number of pixels to be read
		int ncc : number of clean components to be read (0 if no cc table expected/needed)
	OUTPUTS:
		tarr : 1D floating point array containing pixel values.  ****** NB! This is in row major order, converted Fortran code ****
		cc_xarray : 1D fp array containing x coords of clean components in degrees
		cc_yarray : 1D fp array containing y coords of clean components in degrees
		cc_varray : 1D fp array containing values of clean components in degrees
*/
	fitsfile *fptr;

	int status;
	char comment[FLEN_VALUE];
	double nullval=NAN;
	int int_null=0;
	double double_null=0;
	long fpixel=1;
	char cchdu[]="AIPS CC ";
	char fluxname[]="FLUX";
	char xname[]="DELTAX";
	char yname[]="DELTAY";
	int colnum;
	int i;


	status = 0;	// for error processing


	if ( fits_open_file(&fptr,filename, READONLY, &status) )	// open file and make sure it's open
	{
		printf("ERROR : quickfits_read_map --> Error opening FITS file, error = %d\n",status);
		return(status);
	}


	if (fits_movabs_hdu(fptr,1,IMAGE_HDU,&status))		// move to main AIPS image hdu
	{
		printf("ERROR : quickfits_read_map --> Error locating AIPS primary image extension, error = %d\n",status);
		return(status);
	}
	// read in main image data data

	i = fitsi.imsize_ra * fitsi.imsize_dec;
	fits_read_img(fptr, TDOUBLE, fpixel, i, &nullval, tarr, &int_null, &status);
	if(status!=0)
	{
		printf("ERROR : quickfits_read_map --> Error reading map, error = %d\n",status);
	}

	if(fitsi.ncc > 0)	// read in cc data if present/required
	{
		if (fits_movnam_hdu(fptr,BINARY_TBL,cchdu,fitsi.cc_table_version,&status))		// move to main AIPS image hdu
		{
			printf("ERROR : quickfits_read_map --> Error locating AIPS clean component extension, error = %d\n",status);
			return(status);
		}
		else
		{
			fits_get_colnum(fptr,CASEINSEN,xname,&colnum,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map -->  Error locating CC x position information, error = %d\n",status);
			}
			fits_read_col(fptr,TDOUBLE,colnum,1,1,fitsi.ncc,&double_null,cc_xarray,&int_null,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map -->  Error reading CC x position information, error = %d\n",status);
			}

			fits_get_colnum(fptr,CASEINSEN,yname,&colnum,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map -->  Error locating CC y position information, error = %d\n",status);
			}
			fits_read_col(fptr,TDOUBLE,colnum,1,1,fitsi.ncc,&double_null,cc_yarray,&int_null,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map -->  Error reading CC y position information, error = %d\n",status);
			}

			fits_get_colnum(fptr,CASEINSEN,fluxname,&colnum,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map -->  Error locating CC flux position information, error = %d\n",status);
			}
			fits_read_col(fptr,TDOUBLE,colnum,1,1,fitsi.ncc,&double_null,cc_varray,&int_null,&status);
			if(status!=0)
			{
				printf("ERROR : quickfits_read_map -->  Error reading CC flux position information, error = %d\n",status);
			}
		}
	}

	if ( fits_close_file(fptr, &status) )
	{
		printf("ERROR : quickfits_read_map --> Error closing FITS file, error = %d\n",status);
		return(status);
	}

	return(status);
}
예제 #27
0
파일: getwcstab.c 프로젝트: jguze/astropy
int fits_read_wcstab(
  fitsfile   *fptr,
  int  nwtb,
  wtbarr *wtb,
  int  *status)

{
  int  anynul, colnum, hdunum, iwtb, m, naxis, nostat;
  long *naxes = 0, nelem;
  wtbarr *wtbp;


  if (*status) return *status;

  if (fptr == 0) {
    return (*status = NULL_INPUT_PTR);
  }

  if (nwtb == 0) return 0;

  /* Zero the array pointers. */
  wtbp = wtb;
  for (iwtb = 0; iwtb < nwtb; iwtb++, wtbp++) {
    *wtbp->arrayp = 0x0;
  }

  /* Save HDU number so that we can move back to it later. */
  fits_get_hdu_num(fptr, &hdunum);

  wtbp = wtb;
  for (iwtb = 0; iwtb < nwtb; iwtb++, wtbp++) {
    /* Move to the required binary table extension. */
    if (fits_movnam_hdu(fptr, BINARY_TBL, (char *)(wtbp->extnam),
        wtbp->extver, status)) {
      goto cleanup;
    }

    /* Locate the table column. */
    if (fits_get_colnum(fptr, CASEINSEN, (char *)(wtbp->ttype), &colnum,
        status)) {
      goto cleanup;
    }

    /* Get the array dimensions and check for consistency. */
    if (wtbp->ndim < 1) {
      *status = NEG_AXIS;
      goto cleanup;
    }

    if (!(naxes = calloc(wtbp->ndim, sizeof(long)))) {
      *status = MEMORY_ALLOCATION;
      goto cleanup;
    }

    if (fits_read_tdim(fptr, colnum, wtbp->ndim, &naxis, naxes, status)) {
      goto cleanup;
    }

    if (naxis != wtbp->ndim) {
      if (wtbp->kind == 'c' && wtbp->ndim == 2) {
        /* Allow TDIMn to be omitted for degenerate coordinate arrays. */
        naxis = 2;
        naxes[1] = naxes[0];
        naxes[0] = 1;
      } else {
        *status = BAD_TDIM;
        goto cleanup;
      }
    }

    if (wtbp->kind == 'c') {
      /* Coordinate array; calculate the array size. */
      nelem = naxes[0];
      for (m = 0; m < naxis-1; m++) {
        *(wtbp->dimlen + m) = naxes[m+1];
        nelem *= naxes[m+1];
      }
    } else {
      /* Index vector; check length. */
      if ((nelem = naxes[0]) != *(wtbp->dimlen)) {
        /* N.B. coordinate array precedes the index vectors. */
        *status = BAD_TDIM;
        goto cleanup;
      }
    }

    free(naxes);
    naxes = 0;

    /* Allocate memory for the array. */
    if (!(*wtbp->arrayp = calloc((size_t)nelem, sizeof(double)))) {
      *status = MEMORY_ALLOCATION;
      goto cleanup;
    }

    /* Read the array from the table. */
    if (fits_read_col_dbl(fptr, colnum, wtbp->row, 1L, nelem, 0.0,
        *wtbp->arrayp, &anynul, status)) {
      goto cleanup;
    }
  }

cleanup:
  /* Move back to the starting HDU. */
  nostat = 0;
  fits_movabs_hdu(fptr, hdunum, 0, &nostat);

  /* Release allocated memory. */
  if (naxes) free(naxes);
  if (*status) {
    wtbp = wtb;
    for (iwtb = 0; iwtb < nwtb; iwtb++, wtbp++) {
      if (*wtbp->arrayp) free(*wtbp->arrayp);
    }
  }

  return *status;
}
예제 #28
0
파일: ASPAdd.c 프로젝트: rferdman/afr
int main(int argc, char **argv)
{

  int             i_file,i_scan,i_chan,i_bin,n_omit,status=0;
  int             NFirstTable, NumHDU, NDumps, TotDumps=0, hdutype;
  // int             OutChans;
  int             spk;
  int             got_bins=0, got_mjd1=0; //, zeroed_outprofs=0;
  long            NPtsProf=0, FirstNPtsProf=0;
  float           Weight=1.0, TotWeight=0.;
  // int             ProfSum=0;
  double          x, ptype;
  double          MJD_first=0., MJD_last=0., MJD_mid;
  double          IMJDMid, MJDSecsMid;
  double          SBase,Srms,Duty,SPeak,FinalMask[NBINMAX];
  double          OutFreq;
  char            ProgName[32];
  char            Outfile[128];
  char            Header[256];  
  struct ASPHdr   *Hdr;
  struct SubHdr   Subhdr;
  struct StdProfs *InProfile, OutProfile;
  struct RunVars  RunMode;
  fitsfile        **Fin;
  FILE            *Fout, *Fcheck;
  Cmdline         *Cmd;


  /* Get command line variables */
  Cmd = parseCmdline(argc, argv);  

  /* Normally use this somewhere, and not showOptionValues */
  Cmd->tool = Cmd->tool;

  strcpy(ProgName, argv[0]);

  Fin = (fitsfile **)malloc(Cmd->InfileC*sizeof(fitsfile));
  Hdr = (struct ASPHdr *)malloc(Cmd->InfileC*sizeof(struct ASPHdr));

  /* Dynamically allocate RunMode variables */
  if (AllocRunMode(&RunMode) < 0){
    printf("Could not allocate RunMode structure.  Exiting...\n");
    exit(2);
  }
  strcpy(RunMode.Infile,Cmd->Infile); 
  

 //    if(!zeroed_outprofs) {
      /*     if(Cmd->SortChansP){
	     OutChans=Hdr[0].obs.NChan;
	     } 
	     else{ */
  // OutChans=1;
  // }
  // OutProfile=(struct StdProfs *)malloc(OutChans*sizeof(struct StdProfs));
  // TotWeight=(float *)malloc(OutChans*sizeof(float));
  
  /* Zero out profiles */
  //     for(i_chan=0;i_chan<OutChans;i_chan++){
  FZero(OutProfile.rstds,NBINMAX);
  FZero(OutProfile.rstdq,NBINMAX);
  FZero(OutProfile.rstdu,NBINMAX);
  FZero(OutProfile.rstdv,NBINMAX);
  // }
  //zeroed_outprofs=1;
      //    }

  /* Create an output file to check omissions if in vebose mode */
  if (Cmd->VerboseP || Cmd->CheckOmitP){
    if((Fcheck = fopen("check_omit.dat","w")) == 0)
       { printf("Cannot open %s. Exiting...\n",Outfile); exit(1); }   
  }


  /* read in all input files and add each to the final profile */

  /* read in all input file headers */
  NPtsProf=0;
  for (i_file=0;i_file<Cmd->InfileC;i_file++){
    n_omit=0;
    status=0;    
    if(fits_open_file(&Fin[i_file], Cmd->Infile[i_file], READONLY, &status)){
      printf("Error opening FITS file %s !!!\n", Cmd->Infile[i_file]);
      exit(1);
    }
    if(ReadASPHdr(&Hdr[i_file], Fin[i_file]) < 0){
      printf("%s> Unable to read Header from file %s.  Exiting...\n",
	     ProgName,Cmd->Infile[i_file]);
      exit(1);
    }

    /* Write file name in verbose-mode omit check file */
    if(Cmd->VerboseP || Cmd->CheckOmitP) 
      fprintf(Fcheck, "\n%s\n",Cmd->Infile[i_file]);


    /* for now just check if all files have same number of channels */
    /* if(Cmd->SortChansP)
        if(i_file>0 && Hdr[i_file].obs.NChan!=Hdr[0].obs.NChan){
        fprintf(stderr,"%s> Different numbers of channels in different files:\n\n",
        ProgName);
        fprintf(stderr,"%s: %d channels,  %s: %d channels\n",
	Cmd->Infile[0],Hdr[0].obs.NChan,
	Cmd->Infile[i_file],Hdr[i_file].obs.NChan);
	} */
    
    /* now find the number of dumps in the file */    
    fits_get_num_hdus(Fin[i_file], &NumHDU, &status);
    if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0")){
      NDumps = NumHDU-3;  /* the "3" is temporary, depending on how 
				   many non-data tables we will be using */
    }
    else if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0.1")){
      NDumps = (NumHDU-3)/2;
    }
    else{
      fprintf(stderr,"%s> Do not recognize FITS file version in header.\n",
	      ProgName);
      fprintf(stderr,"This header is %s. Exiting...\n",Hdr[i_file].gen.HdrVer);
      exit(1);
    }

    printf("File %s:\n",Cmd->Infile[i_file]);
    printf("     Number of channels:  %d\n",Hdr[i_file].obs.NChan) ;
    printf("     Number of dumps:     %d\n",NDumps);

    /* Move to the first data table HDU in the fits file */
    if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0"))
      fits_movnam_hdu(Fin[i_file], BINARY_TBL, "STOKES0", 0, &status);
    else if (!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0.1"))
      fits_movnam_hdu(Fin[i_file], ASCII_TBL, "DUMPREF0", 0, &status);

    /* Get the current HDU number */
    fits_get_hdu_num(Fin[i_file], &NFirstTable);

    /* Set up Profile structure size */


    for(i_scan=0;i_scan<NDumps;i_scan++){
      
      InProfile=(struct StdProfs *)malloc(Hdr[i_file].obs.NChan*
					sizeof(struct StdProfs));
     /* move to next dump's data */
      if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0")){
	fits_movabs_hdu(Fin[i_file], NFirstTable+i_scan, &hdutype, &status); 
      }
      else if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0.1")){
	/* if we've reached the end of the FITS file then increase FileNo */
	fits_movabs_hdu(Fin[i_file],NFirstTable+(i_scan%MAXDUMPS)*2+1,&hdutype,
			&status);
	fits_get_num_rows(Fin[i_file], &NPtsProf, &status);status=0; 
	fits_movrel_hdu(Fin[i_file], -1, NULL, &status);
      }
      
      /* IF not done so, use number of bins from first file to compare to 
	 the rest of the files */
      if(got_bins==0){
	FirstNPtsProf=NPtsProf;  
	got_bins=1;
      }

      /**********  FIX:  SKIP THIS WITHOUT DOING THE OMIT THING ***********/
      /**********         AND DON'T ADD TO NUMBER COUNT  ************/
      if(NPtsProf != FirstNPtsProf) {
	fprintf(stderr,"Warning: Skipping scan %d (%ld bins ",
		i_scan,NPtsProf);
	fprintf(stderr,"vs. %ld bins in others).\n",FirstNPtsProf);
		
	n_omit += Hdr[i_file].obs.NChan;
      }
      else{
	
	/* find NPtsProf */
	ReadASPStokes(&Hdr[i_file], &Subhdr, Fin[i_file], NPtsProf, 
		      InProfile, i_scan, Cmd->VerboseP);
	
	
	/* Add this profile onto running output profile */
	
	for(i_chan=0;i_chan<Hdr[i_file].obs.NChan;i_chan++){
	  
	  /* Bad scans are zeroed so if summ of the profile is zero, it's 
	     not to be used in summation */
	  //	  ProfSum = FSum(&InProfile[i_chan].rstds[0], NPtsProf);
	  //	  ProfSum = 0;
	  // ProfSum = ArrayZero(InProfile[i_chan].rstds, NPtsProf);
	  //	  if(ProfSum != 0.0) { // i.e. good data
	  /* Test that all bins in current profile are not zeroed */
	  if(!ArrayZero(InProfile[i_chan].rstds, NPtsProf)) { // i.e. good data
	    //	  if(InProfile[i_chan].rstds[0] > -99998.) { // i.e. good data
	    
	    /* If first MJD has not been registered, then do so since this 
	       would be the first non-omitted scan */
	    if (got_mjd1==0) {
	      MJD_first = (double)Hdr[i_file].obs.IMJDStart + 
		Subhdr.DumpMiddleSecs/86400.;
	      got_mjd1=1;
	    }
	    if (i_scan==NDumps-1) {
	      /* Just keep overwriting MJD_last every i_file -- that way we 
		 ensure getting the last MJD of the FINAL non-omitted scan 
		 used */
	      MJD_last = (double)Hdr[i_file].obs.IMJDStart + 
		Subhdr.DumpMiddleSecs/86400.;
	    }

	    /* Get SNR for each Profile if we want to use weighting; 
	       otherwise weights will all be 1.0 */
	    if(Cmd->WeightP) {
	      Duty = DutyLookup(Hdr[i_file].target.PSRName);
	      BMask(InProfile[i_chan].rstds,&Hdr[i_file].redn.RNBinTimeDump,
		    &Duty,FinalMask);
	      Baseline(InProfile[i_chan].rstds,FinalMask,
		       &Hdr[i_file].redn.RNBinTimeDump,&SBase,&Srms);
	      SPeak =  FindPeak(InProfile[i_chan].rstds,
				&Hdr[i_file].redn.RNBinTimeDump,&spk);
	      InProfile[i_chan].SNR = SPeak*Srms;
	      //	      Weight = InProfile[i_chan].SNR;
	      Weight = Srms; // which is actually 1/RMS.
	    }
	    // printf("SNR %d = %lf\n",i_chan,InProfile[i_chan].SNR);
	    
	    /* Need to figure out how to organize input channels to match 
	     *  output channels */
	    /* if(Cmd->SortChansP){
	          for(i_bin=0;i_bin<NPtsProf;i_bin++) {
	             OutProfile[i_chan].rstds[i_bin] +=
		     Weight*InProfile[i_chan].rstds[i_bin];
		     OutProfile[i_chan].rstdq[i_bin] +=
		     Weight*InProfile[i_chan].rstdq[i_bin];
		     OutProfile[i_chan].rstdu[i_bin] +=
		     Weight*InProfile[i_chan].rstdu[i_bin];
		     OutProfile[i_chan].rstdv[i_bin] +=
		     Weight*InProfile[i_chan].rstdv[i_bin];
		  }
	       } 
	       else{ */
	    for(i_bin=0;i_bin<NPtsProf;i_bin++) {
	      OutProfile.rstds[i_bin] += 
		Weight*InProfile[i_chan].rstds[i_bin];
	      OutProfile.rstdq[i_bin] += 
		Weight*InProfile[i_chan].rstdq[i_bin];
	      OutProfile.rstdu[i_bin] += 
		Weight*InProfile[i_chan].rstdu[i_bin];
	      OutProfile.rstdv[i_bin] += 
		Weight*InProfile[i_chan].rstdv[i_bin];  
	      //   printf("%f\n",OutProfile[0].rstds[i_bin]);fflush(stdout);
	    }
	    //  }
	    TotWeight += Weight;  // for now keep at zero index
	    /* Print profile weights for each scan, for each channel */
	    if(RunMode.Verbose) {
	      if(i_chan==0) printf("Profile weights -- scan %d: \n   ",i_scan);
	      printf("%6.2f  ",Weight);
	      if(i_chan==Hdr[i_file].obs.NChan-1) printf("\n");fflush(stdout);
	    }
	  }
	  else {
	    n_omit++;
	    if(Cmd->VerboseP || Cmd->CheckOmitP){
	      fprintf(Fcheck, "%6d     %.1lf\n",
		      i_scan,Hdr[i_file].obs.ChanFreq[i_chan]);
	 /* printf("File %d, Dump %d, Channel %d (%lf MHz) were found to be\n",
		   i_file,i_scan,i_chan,Hdr[i_file].obs.ChanFreq[i_chan]);
	    printf("  zeroed and so are not included.\n");fflush(stdout); */
	    }
	  }
	  //    if(i_chan==0) {for(i=0;i<50;i++) printf("%lf  ",OutProfile[0].rstds[i]);printf("\n\n");fflush(stdout);};
	}
	
	/*****************/
	
	/*     }  */
	
	
      } /* else from positive check on NPtsProf */
     free(InProfile);
    }    
    /****** maybe bring this inside the ELSE where entire scans aren't being omitted ******/
    /* if (Cmd->SortChansP) 
      TotDumps += (NDumps - n_omit);
      else */ 
    TotDumps += (NDumps*Hdr[i_file].obs.NChan - n_omit); 
    //free(InProfile);
    
    printf("Reading of file %s complete and successful.\n",
	     Cmd->Infile[i_file]);
    printf("%d scans omitted.\n\n",n_omit);fflush(stdout);
  }

  if(Cmd->VerboseP || Cmd->CheckOmitP) fclose(Fcheck);

  /* Appease the format of the MakePol routine by making up these RunMode 
     structure members */
  strcpy(RunMode.Source,Hdr[0].target.PSRName);
  RunMode.Verbose = Cmd->VerboseP;
  RunMode.FlipPA = 0;
  RunMode.NoBase = Cmd->NoBaseP;
  /* divide out total number of dumps to get the average */
  // for(i_chan=0;i_chan<OutChans;i_chan++){
   
  printf("Totdumps = %d\n",TotDumps);
  fflush(stdout);
  
  for(i_bin=0;i_bin<NPtsProf;i_bin++) {
    OutProfile.rstds[i_bin] /= TotWeight;
    OutProfile.rstdq[i_bin] /= TotWeight;
    OutProfile.rstdu[i_bin] /= TotWeight;
    OutProfile.rstdv[i_bin] /= TotWeight;
  }
  
  MakePol(&RunMode, (int)NPtsProf, &OutProfile);
  /* Open file for writing */
  sprintf(Outfile,"AddProf.out");
  
  /* now write the output ascii added profile */
  if ((Fout = fopen(Outfile,"w")) == 0)
    { printf("Cannot open %s. Exiting...\n",Outfile); exit(1); }
  
  /* take average MJD of first to last scan */
  MJD_mid = (MJD_first + MJD_last)/2.;
  IMJDMid = floor(MJD_mid);
  MJDSecsMid = (MJD_mid - IMJDMid)*86400.;
  
  printf("MJD_mid = %lf, IMJDMid = %lf, MJDSecsMid = %lf\n",MJD_mid,IMJDMid,MJDSecsMid);fflush(stdout); 

  /* to choose a channel to put in the header for now, ust use the average 
     of the first datafile's channels */ 
  OutFreq=0.;
  for(i_chan=0; i_chan<Hdr[0].obs.NChan; i_chan++){
    OutFreq += Hdr[0].obs.ChanFreq[i_chan];
  }
  OutFreq /= Hdr[0].obs.NChan;

  /* Create and print header line for output file(s) */
  sprintf(Header,"# %.1f %.7f %.10f %ld %.3f %.3f %d %s %d %9s %.10f",
	  IMJDMid, 
	  MJDSecsMid, 
	  //	  Subhdr.DumpRefPeriod[i_chan],
	  0.,
	  (long)1, OutFreq,
	  //	    Hdr[0].obs.DM, Hdr[i_file].redn.RNBinTimeDump,
	  Hdr[0].obs.DM, (int)NPtsProf,
	  Hdr[0].obs.ObsvtyCode, 1, Hdr[0].target.PSRName, 
	  0.);             
  //	  Subhdr.DumpRefPhase[i_chan]);             
  fprintf(Fout,"%s\n",Header);
  
  for(i_bin=0;i_bin<NPtsProf;i_bin++) {
    /* see how strong the linear polarization is */
    x = OutProfile.stdlin[i_bin]*OutProfile.Srms; 
    ptype = 43.1;
    if (x > 1.) ptype=43.2;
    if (x > 2.) ptype=43.3;
    if (x > 3.) ptype=43.4;
    if (x > 4.) ptype=43.5;
    if (x > 5.) ptype=43.6;
    fprintf(Fout,"%5d%15.7f%15.7f%15.7f%15.7f%15.7f%15.7f%15.7f%6.1f\n",i_bin,
	    OutProfile.rstds[i_bin],OutProfile.rstdq[i_bin],
	    OutProfile.rstdu[i_bin],
	    OutProfile.rstdv[i_bin],
	    /* phi in degrees */
	    OutProfile.stdlin[i_bin],
	    OutProfile.stdphi[i_bin]*180.0/TWOPI, 
	    OutProfile.stdphierr[i_bin]*180.0/TWOPI,ptype);
  }
  printf("Created output file %s\n",Outfile);
  fclose(Fout);
  // }
  
  /* Write all this to file */
  
  
  printf("\nCompleted successfully.\n\n");fflush(stdout);
  
  exit(0);

}
예제 #29
0
/* 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;
}
예제 #30
0
//----------------------------------------------------------
int write_integration_header(etfits_t * etf, scram_t *scram) {
//----------------------------------------------------------
    
    int * status_p = &(etf->status);
    *status_p = 0;

//fprintf(stderr, "writing integration header\n");
    if(etf->integration_cnt == 0) {
        // go to the template created HDU
        if(! *status_p) fits_movnam_hdu(etf->fptr, BINARY_TBL, (char *)"AOSCRAM", 0, status_p);
    } else {
        // create new HDU
        if(! *status_p) fits_create_tbl(etf->fptr, BINARY_TBL, 0, 0, NULL, NULL, NULL, (char *)"AOSCRAM", status_p);
    }

    if(! *status_p) fits_update_key(etf->fptr, TSTRING,  "EXTNAME",  (char *)"AOSCRAM",  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TINT,     "COARCHID", &scram->coarse_chan_id,   NULL, status_p); 

    // observatory (scram) data 
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "PNTSTIME",  &(scram->PNTSTIME), NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "PNTRA",     &(scram->PNTRA),    NULL, status_p);      
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "PNTDEC",    &(scram->PNTDEC),   NULL, status_p);      
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "PNTMJD",    &(scram->PNTMJD),   NULL, status_p);      
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "PNTAZCOR",  &(scram->PNTAZCOR), NULL, status_p);      
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "PNTZACOR",  &(scram->PNTZACOR), NULL, status_p);      

    if(! *status_p) fits_update_key(etf->fptr, TINT,    "AGCSTIME", &(scram->AGCSTIME),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "AGCAZ",    &(scram->AGCAZ),     NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "AGCZA",    &(scram->AGCZA),     NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "AGCTIME",  &(scram->AGCTIME),   NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "AGCLST",   &(scram->AGCLST),    NULL, status_p);     // TODO

    if(! *status_p) fits_update_key(etf->fptr, TINT,    "ALFSTIME", &(scram->ALFSTIME),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "ALFBIAS1", &(scram->ALFBIAS1),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "ALFBIAS2", &(scram->ALFBIAS2),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ALFMOPOS", &(scram->ALFMOPOS),  NULL, status_p);

    if(! *status_p) fits_update_key(etf->fptr, TINT,    "IF1STIME", &(scram->IF1STIME),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "IF1SYNHZ", &(scram->IF1SYNHZ),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "IF1SYNDB", &(scram->IF1SYNDB),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "IF1RFFRQ", &(scram->IF1RFFRQ),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "IF1IFFRQ", &(scram->IF1IFFRQ),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "IF1ALFFB", &(scram->IF1ALFFB),  NULL, status_p);

    if(! *status_p) fits_update_key(etf->fptr, TINT,    "IF2STIME", &(scram->IF2STIME),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "IF2ALFON", &(scram->IF2ALFON),  NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "IF2SYNHZ", &(scram->IF2SYNHZ),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "IF2SIGSR", &(scram->IF2SIGSR),  NULL, status_p); 

    if(! *status_p) fits_update_key(etf->fptr, TINT,    "TTSTIME",  &(scram->TTSTIME),   NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "TTTURENC", &(scram->TTTURENC),  NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "TTTURDEG", &(scram->TTTURDEG),  NULL, status_p);

    if(! *status_p) fits_update_key(etf->fptr, TINT,    "CLOCKTIM",  &(scram->CLOCKTIM), NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "CLOCKFRQ",  &(scram->CLOCKFRQ), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "CLOCKDBM",  &(scram->CLOCKDBM), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "CLOCKLOC",  &(scram->CLOCKLOC), NULL, status_p); 

    if(! *status_p) fits_update_key(etf->fptr, TINT,    "BIRDITIM",  &(scram->BIRDITIM), NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "BIRDIFRQ",  &(scram->BIRDIFRQ), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "BIRDIDBM",  &(scram->BIRDIDBM), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "BIRDILOC",  &(scram->BIRDILOC), NULL, status_p); 

    if(! *status_p) fits_update_key(etf->fptr, TINT,    "ADCRMSTM",  &(scram->ADCRMSTM),   NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS01",  &(scram->ADC1RMS[0]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS02",  &(scram->ADC1RMS[1]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS03",  &(scram->ADC1RMS[2]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS04",  &(scram->ADC1RMS[3]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS05",  &(scram->ADC1RMS[4]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS06",  &(scram->ADC1RMS[5]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS07",  &(scram->ADC1RMS[6]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS08",  &(scram->ADC1RMS[7]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS09",  &(scram->ADC2RMS[0]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS10",  &(scram->ADC2RMS[1]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS11",  &(scram->ADC2RMS[2]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS12",  &(scram->ADC2RMS[3]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS13",  &(scram->ADC2RMS[4]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS14",  &(scram->ADC2RMS[5]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS15",  &(scram->ADC2RMS[6]), NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TDOUBLE, "ADCRMS16",  &(scram->ADC2RMS[7]), NULL, status_p);
#if 0
    fits_update_key(etf->fptr, TINT,    "MISSEDPK", &(scram.MISSEDPK),    NULL, status_p);    // missed packets per input per second 
#endif

    //if(! *status_p) fits_flush_file(etf->fptr, status_p);

    if (*status_p) {
        hashpipe_error(__FUNCTION__, "Error writing integration header");
        //fprintf(stderr, "Error writing integration header.\n");
        fits_report_error(stderr, *status_p);
    }

    return *status_p;
}