Exemplo n.º 1
0
int 
vot_addFieldMeta (int handle, fitsfile *fp, int index)
{
    char  *ucd, *utype, *id, keyw[SZ_FNAME];
    int   status = 0;


    if ( (ucd = vot_getAttr (handle, "ucd")) ) {	/* UCD attribute     */
        memset (keyw, 0, SZ_FNAME);
        sprintf (keyw, "TUCD%d", index);
        if (fits_update_key (fp, TSTRING, keyw, ucd, "UCD attribute", &status))
	    printerror ( status );
    }

    if ( (utype = vot_getAttr (handle, "utype")) ) {	/* UTYPE attribute   */
        memset (keyw, 0, SZ_FNAME);
        sprintf (keyw, "TUTYPE%d", index);
        if (fits_update_key (fp, TSTRING, keyw, utype, "UTYPE attribute",
	    &status))
	        printerror ( status );
    }

    if ( (id = vot_getAttr (handle, "id")) ) {		/* ID attribute     */
        memset (keyw, 0, SZ_FNAME);
        sprintf (keyw, "TID%d", index);
        if (fits_update_key (fp, TSTRING, keyw, id, "ID attribute", &status))
	    printerror ( status );
    }

    return (0);
}
Exemplo n.º 2
0
//----------------------------------------------------------
int write_primary_header(etfits_t * etf) {
//----------------------------------------------------------
    int * status_p = &(etf->status);
    *status_p = 0;

    int itmp;
    char ctmp[40];

//fprintf(stderr, "writing primary header\n");

    if(! *status_p) fits_get_system_time(ctmp, &itmp, status_p);      // date the file was written

    if(! *status_p) fits_movabs_hdu(etf->fptr, 1, NULL, status_p);    // go to primary HDU

    if(! *status_p) fits_update_key(etf->fptr, TSTRING, "DATE",     ctmp,                            NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TSTRING, "TELESCOP", &(etf->primary_hdr.receiver),    NULL, status_p);
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "NSUBBAND", &(etf->primary_hdr.n_subband),   NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "NCHAN",    &(etf->primary_hdr.n_chan),      NULL, status_p); 
    if(! *status_p) fits_update_key(etf->fptr, TINT,    "NINPUTS",  &(etf->primary_hdr.n_inputs),    NULL, status_p); 
    // TODO not yet implemented
    //if(! *status_p) fits_update_key(etf->fptr, TINT,    "BANDWID",  &(etf->primary_hdr.bandwidth),       NULL, status_p); 
    //if(! *status_p) fits_update_key(etf->fptr, TINT,    "CHAN_BW",  &(etf->primary_hdr.chan_bandwidth),  NULL, status_p); 
    //if(! *status_p) its_update_key(etf->fptr, TINT,    "FREQRES",  &(etf->primary_hdr.freq_res),        NULL, status_p);    // redundant w/ CHAN_BW? 

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

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

    return *status_p;
}
Exemplo n.º 3
0
static void image_keywords_to_fits(image_str *image, fitsfile *fits)
{
    int status = 0;
    int d;

    for(d = 0; d < image->Nkeywords; d++){
        image_keyword_str *kw = &image->keywords[d];

        switch(kw->type){
        case 'I':
            {
                int value = 0;

                sscanf(kw->unquoted, "%d", &value);
                fits_update_key(fits, TINT, kw->key, &value, kw->comment, &status);
            break;
            }
        case 'F':
            {
                double value = 0;

                sscanf(kw->unquoted, "%lf", &value);
                fits_update_key(fits, TDOUBLE, kw->key, &value, kw->comment, &status);
            break;
            }
        default:
            status = 0;
            fits_update_key(fits, TSTRING, kw->key, kw->unquoted, kw->comment, &status);
            break;
        }
    }
}
Exemplo n.º 4
0
int 
vot_addFITSMeta (int handle, fitsfile *fp, char *meta, int index)
{
    char  *id, *nam, *val, *unit, keyw[SZ_FNAME], comment[SZ_FNAME];
    int   status = 0;


    if ( (id = vot_getAttr (handle, "id")) ) {		/* ID attribute	      */
        memset (keyw, 0, SZ_FNAME);
        memset (comment, 0, SZ_FNAME);
        sprintf (keyw, "%3.3sID%d", meta, index);
        sprintf (comment, "%s id attribute", meta);
        if (fits_update_key (fp, TSTRING, keyw, id, comment, &status))
	    printerror ( status );
    }

    if ( (nam = vot_getAttr (handle, "name")) ) {	/* NAME attribute    */
        memset (keyw, 0, SZ_FNAME);
        memset (comment, 0, SZ_FNAME);
        sprintf (keyw, "%3.3sNAM%d", meta, index);
        sprintf (comment, "%s name attribute", meta);

        if (fits_update_key (fp, TSTRING, keyw, nam, comment, &status))
	    printerror ( status );
    }

    if ( (val = vot_getAttr (handle, "value")) ) {	/* VALUE attribute   */
        memset (keyw, 0, SZ_FNAME);
        memset (comment, 0, SZ_FNAME);
        sprintf (keyw, "%3.3sVAL%d", meta, index);
        sprintf (comment, "%s val attribute", meta);

        if (fits_update_key (fp, TSTRING, keyw, val, comment, &status))
	    printerror ( status );
    }

    if ( (unit = vot_getAttr (handle, "unit")) ) {	/* UNIT attribute   */
        memset (keyw, 0, SZ_FNAME);
        memset (comment, 0, SZ_FNAME);
        sprintf (keyw, "%3.3sUNI%d", meta, index);
        sprintf (comment, "%s unit attribute", meta);

        if (fits_update_key (fp, TSTRING, keyw, unit, comment, &status))
	    printerror ( status );
    }

    return (0);
}
Exemplo n.º 5
0
int CDfits_open_file( char *filename )
{
  int status;
  int bitpix   =  8;
  int naxis   =  0;
  long *naxes;
  
  status = 0;
  /* Open file */
  fits_create_file( &cfitsptr, filename, &status );
  /* Write primary header */
  bitpix = 8;
  naxis = 0;
  fits_create_img( cfitsptr, bitpix, naxis, naxes, &status );

  /* Add first keywords */
  fits_update_key( cfitsptr, TSTRING, "HDRVER", "1.19", "Header version", &status);
  fits_write_date( cfitsptr, &status);

  new_file = 1;
  
  
  return( status );
  
}
Exemplo n.º 6
0
std::string write_image(std::string pathname, float *array, std::string name, int naxis, long *naxes) {
  // this function writes a float array to a FITS image file
  TRACE_ENTER();
  // create new file
  fitsfile *fptr;
  int status = 0;
  fits_create_file(&fptr, pathname.c_str(), &status);
  if (status != 0) {
    // cannot create the file
    // likely, the file already exists
    // try to open it, delete it and create it anew
    // try to open the file
    status = 0;
    fits_open_file(&fptr, pathname.c_str(), READWRITE, &status);
    if (status != 0) {
      // cannot open the file, for some reason
      return FORMAT_STATUS(status);
    }
    // try to delete the file
    status = 0;
    fits_delete_file(fptr, &status);
    if (status != 0) {
      // cannot delete the file, for some reason
      return FORMAT_STATUS(status);
    }
    // try to create the file
    status = 0;
    fits_create_file(&fptr, pathname.c_str(), &status);
    if (status != 0) {
      // cannot create the file, for some reason
      return FORMAT_STATUS(status);
    }
  }
  // create the primary array image
  fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // write a keyword
  fits_update_key(fptr, TFLOAT, name.c_str(), array, name.c_str(), &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // write the array of floats to the image
  long fpixel = 1;
  long nelements = 1;
  for (int i = 0; i < naxis; i++) {
    nelements = nelements * naxes[i];
  }
  fits_write_img(fptr, TFLOAT, fpixel, nelements, (void*)array, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // close the file
  fits_close_file(fptr, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  return "WRITE_OK";
}
Exemplo n.º 7
0
int nemo_main(void)
{
    fitsfile *fptr;       /* pointer to the FITS file; defined in fitsio.h */
    int status, ii, jj;
    long  fpixel = 1, naxis = 2, nelements, exposure;
    long naxes[2] = { 300, 200 };   /* image is 300 pixels wide by 200 rows */
    short array[200][300];
    string fname = getparam("out");
    float time4 = PI;
    double time8 = PI;

    status = 0;         /* initialize status before calling fitsio routines */
    fits_create_file(&fptr, fname, &status);   /* create new file */

    /* Create the primary array image (16-bit short integer pixels */
    fits_create_img(fptr, SHORT_IMG, naxis, naxes, &status);

    /* Write a keyword; must pass the ADDRESS of the value */
    exposure = 1500.;
    fits_update_key(fptr, TLONG, "EXPOSURE", &exposure,
         "Total Exposure Time", &status);
    dprintf(1,"exposure %d\n",status);
    fits_update_key(fptr, TFLOAT, "TIME4", &time4,
		    "Sample REAL*4", &status);    
    dprintf(1,"time4    %d\n",status);
    fits_update_key(fptr, TDOUBLE, "TIME8", &time8,
		    "Sample REAL*8", &status);
    dprintf(1,"time8    %d\n",status);
    fits_update_key(fptr, TSTRING, "DATEOBS", "2001/09/30",
		    "Sample STRING", &status);
    dprintf(1,"string   %d\n",status);

    /* Initialize the values in the image with a linear ramp function */
    for (jj = 0; jj < naxes[1]; jj++)
        for (ii = 0; ii < naxes[0]; ii++)
            array[jj][ii] = ii + jj;

    nelements = naxes[0] * naxes[1];          /* number of pixels to write */

    /* Write the array of integers to the image */
    fits_write_img(fptr, TSHORT, fpixel, nelements, array[0], &status);

    fits_close_file(fptr, &status);            /* close the file */

    fits_report_error(stderr, status);  /* print out any error messages */
    return status ;
}
Exemplo n.º 8
0
void Pulsar::FITSArchive::unload (fitsfile* fptr, const ITRFExtension* ext)
{
  // status returned by FITSIO routines
  int status = 0;

  // no comment
  char* comment = 0;

  fits_update_key (fptr, TDOUBLE, "ANT_X",
		   const_cast<double*>(&(ext->ant_x)), comment, &status);
  fits_update_key (fptr, TDOUBLE, "ANT_Y",
		   const_cast<double*>(&(ext->ant_y)), comment, &status);
  fits_update_key (fptr, TDOUBLE, "ANT_Z",
		   const_cast<double*>(&(ext->ant_z)), comment, &status);

  if (status)
    throw FITSError (status, "Pulsar::FITSArchive::unload ITRFExtension");

}
Exemplo n.º 9
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);
    }
}
Exemplo n.º 10
0
/**
 * Saves the image to a FITS file using the cfitsio library.
 *
 * @param output_filename string, where to save the FITS file
 * @param sx, integer, horizontal image size
 * @param sy, integer, vertical image size
 * @param data, rows of a two dimensional integer array, image data
 * @return  Zero on success, non-zero on failure.
 */
int camera_save_fits_image(char * output_filename, long sx, long sy, unsigned short * data) {
  fitsfile *fptr;
  int status = 0;
  long fpixel, nelements;
  float gain;
  int bitpix = USHORT_IMG;
  long naxis = 2;
  long naxes[2] = {sx, sy};

  /* Delete old file if it already exists */
  remove(output_filename);

  /* create new FITS file */
  if (fits_create_file(&fptr, output_filename, &status)) {
    if (status) fits_report_error(stderr, status);
    return status;
  }

  /* the setting of bitpix = USHORT_IMG implies that BITPIX = 16,
   BSCALE = 1.0 and BZERO = 32768, and the latter two keywords are
   added automatically. */
  if (fits_create_img(fptr, bitpix, naxis, naxes, &status)) {
    if (status) fits_report_error(stderr, status);
    return status;
  }

  /* first pixel to write */
  fpixel = 1;
  /* number of pixels to write */
  nelements = naxes[0] * naxes[1];

  /* write the array of unsigned integers to the FITS file */
  if (fits_write_img(fptr, TUSHORT, fpixel, nelements, data, &status)) {
    if (status) fits_report_error(stderr, status);
    return status;
  }

  /* write the gain parameter of the camera to the header */
  gain = ML16803_CAMERA_GAIN;
  if (fits_update_key(fptr, TFLOAT, "GAIN", &gain, "Camera gain of ML16803", &status)) {
    if (status) fits_report_error(stderr, status);
    return status;
  }

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

  return 0;
}
Exemplo n.º 11
0
local void print_ccd(real **ccd, char filename[], real t_exposure) { 

    fitsfile *fptr;
    int status, ii, jj;
    long  fpixel, nelements, exposure;
    //    unsigned short array[512][512];  
    unsigned short array[XCCD_MAX][YCCD_MAX];  

//    char filename[] = "ccd.fit";
    int bitpix   =  USHORT_IMG; 
    long naxis    =   2;
    //    long naxes[2] = { 512, 512 }; 
    long naxes[2] = { XCCD_MAX, YCCD_MAX }; 

    remove(filename); 
    status = 0;


    if (fits_create_file(&fptr, filename, &status)) 
         printf("%s\n", status);       

    if ( fits_create_img(fptr,  bitpix, naxis, naxes, &status) )
         printf("%s\n", status);     

    float val;
    for (jj = 0; jj < naxes[1]; jj++) {   
      for (ii = 0; ii < naxes[0]; ii++) {
//          cin >> val;
            array[jj][ii] = (unsigned short)ccd[jj][ii];
        }
    }

    fpixel = 1;
    nelements = naxes[0] * naxes[1]; 

    if ( fits_write_img(fptr, TUSHORT, fpixel, nelements, array[0], &status) )
         printf("%s\n", status);

    exposure = long(t_exposure);
    if ( fits_update_key(fptr, TLONG, "EXPOSURE", &exposure,
         "Exposure time in seconds", &status) )
         printf("%s\n", status);  

    if ( fits_close_file(fptr, &status) )  
         printf("%s\n", status);        
}
asynStatus
NDFileFITS::WriteKeys(fitsfile *fitsFilePtr, int* fitsStatus) {
  *fitsStatus = 0;
  std::ifstream fHeader;
  char filePath[MAX_PATH] = {0};
  *fitsStatus = getStringParam(NDFITSFileHeaderFullPathname, sizeof(filePath), filePath); 

  if (*fitsStatus) return asynSuccess;
  fHeader.open(filePath, std::ios_base::in);
  if(fHeader.fail()) 
    return asynSuccess; // If the file does not exists there is nothing to add
  
  char lineBuf[256], keyword[FLEN_KEYWORD], value[FLEN_VALUE], comment[FLEN_COMMENT];
  char *pToken;
  char *context	= NULL;
  
  while (fHeader.getline(lineBuf, sizeof(lineBuf), '\n')) {
    if (strstr(lineBuf, "//")) continue;// It is a comment
    pToken= strtok_s(lineBuf, "\n\t ", &context);
    if (!pToken) continue;// It is an empty line
    strncpy_s(keyword, sizeof(keyword), pToken, _TRUNCATE);
    pToken= strtok_s(0, "\n\t ", &context);
    if (!pToken) continue;// No value specified.. skip entire line
    strncpy_s(value, sizeof(value), pToken, _TRUNCATE);
    pToken= strtok_s(0, "\n", &context);
    if (pToken)
      strncpy_s(comment, sizeof(comment), pToken, _TRUNCATE);
    else
      strncpy_s(comment, sizeof(comment), "", _TRUNCATE);
      
	  fits_update_key(fitsFilePtr, CFITSIO_TSTRING, keyword, value, comment, fitsStatus);
  }
  
  fits_close_file(fitsFilePtr, fitsStatus); // close the fits file
  fHeader.close();
  if(*fitsStatus) return asynError;
  return asynSuccess;  
}
Exemplo n.º 13
0
// filterTableToImage: filter a binary table, create a temp image
fitsfile *filterTableToImage(fitsfile *fptr, char *filter, char **cols,
			     int *dims, double *cens, int bin, int *status){
  int i, dim1, dim2;
  int imagetype=TINT, naxis=IDIM, recip=0;
  int tstatus;
  long nirow, norow;
  float weight=1;
  float xcen, ycen;
  double dvalue;
  double minin[IDIM], maxin[IDIM], binsizein[IDIM];
  char comment[81];
  char *rowselect=NULL;
  char *outfile=IFILE;
  char wtcol[FLEN_VALUE];
  char colname[IDIM][FLEN_VALUE];
  char minname[IDIM][FLEN_VALUE];
  char maxname[IDIM][FLEN_VALUE];
  char binname[IDIM][FLEN_VALUE];
  int colnum[IDIM];
  long haxes[IDIM];
  float amin[IDIM];
  float amax[IDIM];
  float binsize[IDIM];
  fitsfile *ofptr;

  // set up defaults
  if( !bin ) bin = 1;
  wtcol[0] = '\0';
  if( cols && cols[0] && cols[1] ){
    strcpy(colname[0], cols[0]);
    strcpy(colname[1], cols[1]);
  } else {
    colname[0][0] = '\0';
    colname[1][0] = '\0';
  }
  for(i=0; i<IDIM; i++){
    minin[i] = DOUBLENULLVALUE;
    maxin[i] = DOUBLENULLVALUE;
    binsizein[i] = (double)bin;
    minname[i][0] = '\0';
    maxname[i][0] = '\0';
    binname[i][0] = '\0';
  }
  // get total number of rows in input file
  fits_get_num_rows(fptr, &nirow, status);
  // and allocate memory for selected rows array
  rowselect = malloc(nirow+1);
  // filter the input file and generate selected rows array
  if( filter && *filter ){
    fits_find_rows(fptr, filter, 0, nirow, &norow, rowselect,  status);
  } else {
    for(i=0; i<nirow+1; i++){
      rowselect[i] = TRUE;
    }
  }
  // get binning parameters so we can know the image dims for these cols
  // and from that, get the default center of the image
  fits_calc_binning(fptr, naxis, colname, minin, maxin, binsizein, 
		    minname, maxname, binname,
		    colnum, haxes, amin, amax, binsize, status);
  // why truncate to int? otherwise, cfitsio is 0.5 pixels off from js9 ...
  xcen = (int)(amax[0] - amin[0])/2;
  ycen = (int)(amax[1] - amin[1])/2;
  dim1 = haxes[0];
  dim2 = haxes[0];
  // get limits of extracted section
  if( dims && dims[0] && dims[1] ){
    // read image section
    if( cens && cens[0] && cens[1] ){
      xcen = cens[0];
      ycen = cens[1];
      dim1 = dims[0];
      dim2 = dims[1];
    } else {
      if( haxes[0] >= dims[0] ){
	dim1 = dims[0];
      }
      if( haxes[1] >= dims[1] ){
	dim2 = dims[1];
      }
    }
    minin[0] = (int)(xcen - ((dim1+1)/2) + 1);
    minin[1] = (int)(ycen - ((dim2+1)/2) + 1);
    maxin[0] = (int)(xcen + (dim1/2));
    maxin[1] = (int)(ycen + (dim2/2));
  }
  // make 2D section histogram from selected rows
  ofptr = ffhist3(fptr, outfile, imagetype, naxis, colname, 
		  minin, maxin, binsizein, minname, maxname, binname,
		  weight, wtcol, recip, rowselect, status);

  // update/add LTM and LTV header params
  dvalue = 0.0; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTV1", &dvalue, comment, &tstatus); 
  dvalue = (dim1 / 2) - xcen; tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTV1", &dvalue, comment, &tstatus);

  dvalue = 0.0; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTV2", &dvalue, comment, &tstatus); 
  dvalue = (dim2 / 2) - ycen; tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTV2", &dvalue, comment, &tstatus);

  dvalue = 1.0 / bin; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTM1_1", &dvalue, comment, &tstatus); 
  tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTM1_1", &dvalue, comment, &tstatus);

  dvalue = 0.0; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTM1_2", &dvalue, comment, &tstatus); 
  tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTM1_2", &dvalue, comment, &tstatus);

  dvalue = 0.0; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTM2_1", &dvalue, comment, &tstatus); 
  tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTM2_1", &dvalue, comment, &tstatus);

  dvalue = 1.0 / bin; *comment = '\0'; tstatus = 0;
  fits_read_key(fptr, TDOUBLE, "LTM2_2", &dvalue, comment, &tstatus); 
  tstatus = 0;
  fits_update_key(ofptr, TDOUBLE, "LTM2_2", &dvalue, comment, &tstatus);

  // return the center and dims used
  if( dims ){
    dims[0] = dim1;
    dims[1] = dim2;
  }
  if( cens ){
    cens[0] = xcen;
    cens[1] = ycen;
  }
  // free up space
  if( rowselect ) free(rowselect);
  // return new file pointer
  return ofptr;
}
Exemplo n.º 14
0
int edit_image(char filename[], char newfilename[], double **ppix )
{
 fitsfile *fptr, *newfptr;
 int status, nfound, day, month, year, timeref;
 int naxis = 2;			/* 2-dimensional image */
 int bitpix = DOUBLE_IMG;		/* Output image type is double */
 int datatype = TDOUBLE;
 long naxes[2];			/* dimensions of the image */
 long fpixel, npixels;
 char date[FLEN_VALUE], time[FLEN_VALUE];
 char *nullcomment;
 char outfilename[MAXLENGTH];

 nullcomment=0;

  /***********************************************************************/
  status = 0;		/* Initialize status before calling fitsio routines */
  /***********************************************************************/

 /* Copy newfilename to outfilename.  'newfilename' is passed has a reference,
  * therefore any change to it will be passed back to the calling routine
  * which is not really what one wants.  (as I discovered...)
  * The addition of the '!' is meaningful here but not necessarly useful in
  * the calling routine. */
 if (!strcmp(newfilename,filename)) {
   strcpy(outfilename,"!");
   strcat(outfilename,filename);
 }
 else {
   strcpy(outfilename,newfilename);
 }
 printf("Writing %s ... ",newfilename);
 fflush(stdout);

/* Open the existing FITS file */
 if ( fits_open_file(&fptr, filename, READONLY, &status) )
 	printerror( status );

/* Create the new FITS file  (should I use a template?)*/
 if ( fits_create_file(&newfptr, outfilename, &status) )
 	printerror( status );

 /* No need to create an image in the new FITS file because the primary
  * array is automatically created when the header is copied */

/* Copy the header from the existing FITS file to the new FITS file */
 if ( fits_copy_header(fptr, newfptr, &status) )
 	printerror( status );
 
/* Get the length of the axes */
 if ( fits_read_keys_lng(newfptr, "NAXIS", 1, 2, naxes, &nfound, &status) )
 	printerror( status );

/* Write the image (array of pixel values) in the new FITS file */
 fpixel = 1;				/* first pixel to write */
 npixels = naxes[0] * naxes[1];	/* number of pixels to write */

 if ( fits_write_img(newfptr, datatype, fpixel, npixels, ppix[0], &status) )
 	printerror( status );

/* Edit header */
 if ( fits_get_system_date(&day, &month, &year, &status) )
 	printerror( status );
 if ( fits_date2str(year, month, day, date, &status) )
 	printerror( status );
 if ( fits_update_key(newfptr, TSTRING, "DATE", date, "", &status) )
 	printerror( status );

 if ( fits_get_system_time(time, &timeref, &status) )
 	printerror( status );
 if ( timeref == 0 )		/* Convert UTC/GMT to Local time */
 	if ( utc2local(time, FITS_FMT) ) {
		printf("Error : Unable to convert time.\n");
		exit(1);
	} 
 if ( status = cnvtimefmt(time, FITS_FMT, IRAF_FMT))
 	printerror( status ); 	/* Stupid IRAF cannot read the new FITS
 					 *  date-time Y2K format */
 if ( fits_update_key(newfptr, TSTRING, "IRAF-TLM", time, nullcomment, &status) )
 	printerror( status );
 
/* Close the existing FITS file */
 if ( fits_close_file(fptr, &status) )
 	printerror( status );

/* Close the new FITS file */
 if ( fits_close_file(newfptr, &status) )
 	printerror( status );

 printf("done\n");

 return(0);
}
Exemplo n.º 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;
}
Exemplo n.º 16
0
int CDfits_write_subint( int num_cycles, int num_bins, int num_chans, int num_pols )
{
  int status;
  int j, k;
  int nscl, ndata;
  float x;
  double dx, dy, dz, ds, dc;
    
  int nrows, ncols, col;
  char *ttype[19], *tform[19], *tunit[19];
  long naxes[3];
  
  char Cstr16[16], Estr16[16], Istr16[16];

#define ASTR_LEN 32
  char astr[ ASTR_LEN ];

  
  /* BEGIN */

  nscl =  num_chans * num_pols;
  ndata = num_bins * nscl;

  status = 0;
  
  /* Increment SUBINT counter and if first SUBINT, write header */
  if( ++subint_cnt == 1 ) {

    /* Add START TIME to primary HDU */
    /* Move to primary HDU */
    fits_movabs_hdu( cfitsptr, 1, NULL, &status );

    if( bat_to_ut_str( astr, ASTR_LEN, newcycle.WBpsr_timer_start_bat ) < 0 ) {
      return( -9999 );
    }
    
    astr[10] = '\0';
    fits_update_key( cfitsptr, TSTRING, "STT_DATE", astr,
		     "Start UT date (YYYY-MM-DD)", &status);
    fits_update_key( cfitsptr, TSTRING, "STT_TIME", &astr[11],
		     "Start UT (hh:mm:ss)", &status);

    bat_to_mjd( &dx, newcycle.WBpsr_timer_start_bat );

    dz = modf( dx, &dy );   /* dz = fractional day,  dy = days */    

    j = (int) floor( ( dy + 0.1 ) );  /* Add 0.1d to make sure we get the correct one */
    fits_update_key( cfitsptr, TINT, "STT_IMJD", &j,
		     "Start MJD (UTC days) (J)", &status);
    
    dy = dz * 86400.0;   /* This should be an exact second - timer starts on 1pps */
    k = (int) floor( ( dy + 0.1 ) );   /* Add 0.1s to make sure we get the correct one */
    fits_update_key( cfitsptr, TINT, "STT_SMJD", &k,
		     "[s] Start time (sec past UTC 00h) (J)", &status);

    /* Add in offset = 1 - start phase - one bin !!!!!!!!!!! */
    /* 9 Jun 2004 - remove one bin offset - wrong !! */
    /* Was:
       dz = 1.0 - modf( newcycle.WBpsr_start_psr_phase, &dx ) - 1.0 / (double) num_bins; 
       dz *= (*c_c).pulsar_period;
       Now: the offset time is available directly */
    dz = newcycle.WBpsr_timer_start_offset_secs;
    
    /* Quantise to 128MHz clock cycles */
    dz *= 128.0E06;
    dx = floor( dz );
    dx /= 128.0E06;
    
    fits_update_key( cfitsptr, TDOUBLE, "STT_OFFS", &dx,
		     "[s] Start time offset (D)", &status);

    /* LST provided corresponds to integ. start time, i.e. oldcycle.bat */
    bat_to_ut_secs( &dy, oldcycle.bat );
    dy += dx;
    dx = scan_start_time_secs - dy;
    if( dx < -43200.0 ) dx += 86400.0;
    if( dx >  43200.0 ) dx -= 86400.0;
    dy = ( ( oldcycle.lst * 86400.0 ) / TwoPi ) + ( dx * 1.002737909350795 );
    if( dy < 0.0 ) dy += 86400.0;
    if( dy > 86400.0 ) dy -= 86400.0;
    fits_update_key( cfitsptr, TDOUBLE, "STT_LST ", &dy,
		     "[s] Start LST (D)", &status);

    /* Finished with primary HDU */

    /* Move to last created HDU in scan header */
    fits_movabs_hdu( cfitsptr, last_scanhdr_hdu, NULL, &status );
    

    /* Create SUBINT BINTABLE */

    nrows = 0; /* naxis2 - Let CFITSIO sort this out */
    ncols = 19; /* tfields */

    ttype[0] = "ISUBINT ";    /* Subint number. If NAXIS=-1, 0 indicates EOD. */
    tform[0] = "1J      ";
    tunit[0] = "";
    ttype[1] = "INDEXVAL";    /* Optionally used if INT_TYPE != TIME */
    tform[1] = "1D      ";
    tunit[1] = "";
    ttype[2] = "TSUBINT ";    /* [s] Length of subintegration */
    tform[2] = "1D      ";
    tunit[2] = "";
    ttype[3] = "OFFS_SUB";    /* [s] Offset from Start UTC of subint centre */
    tform[3] = "1D      ";
    tunit[3] = "";
    ttype[4] = "LST_SUB ";    /* [s] LST at subint centre */
    tform[4] = "1D      ";
    tunit[4] = "";
    ttype[5] = "RA_SUB  ";    /* [turns] RA (J2000) at subint centre */
    tform[5] = "1D      ";
    tunit[5] = "";
    ttype[6] = "DEC_SUB ";    /* [turns] Dec (J2000) at subint centre */
    tform[6] = "1D      ";
    tunit[6] = "";
    ttype[7] = "GLON_SUB";    /* [deg] Gal longitude at subint centre */
    tform[7] = "1D      ";
    tunit[7] = "";
    ttype[8] = "GLAT_SUB";    /* [deg] Gal latitude at subint centre */
    tform[8] = "1D      ";
    tunit[8] = "";
    ttype[9] = "FD_ANG  ";    /* [deg] Feed angle at subint centre */
    tform[9] = "1E      ";
    tunit[9] = "";
    ttype[10] = "POS_ANG ";    /* [deg] Position angle of feed at subint centre */
    tform[10] = "1E      ";
    tunit[10] = "";
    ttype[11] = "PAR_ANG ";    /* [deg] Parallactic angle at subint centre */
    tform[11] = "1E      ";
    tunit[11] = "";
    ttype[12] = "TEL_AZ  ";    /* [deg] Telescope azimuth at subint centre */
    tform[12] = "1E      ";
    tunit[12] = "";
    ttype[13] = "TEL_ZEN ";    /* [deg] Telescope zenith angle at subint centre */
    tform[13] = "1E      ";
    tunit[13] = "";

    sprintf( Cstr16, "%dE", num_chans );
    ttype[14] = "DAT_FREQ";
    tform[14] = Cstr16;
    tunit[14] = "";
    ttype[15] = "DAT_WTS ";
    tform[15] = Cstr16;
    tunit[15] = "";

    sprintf( Estr16, "%dE", nscl );
    ttype[16] = "DAT_OFFS";
    tform[16] = Estr16;
    tunit[16] = "";
    ttype[17] = "DAT_SCL ";
    tform[17] = Estr16;
    tunit[17] = "";

    sprintf( Istr16, "%dI", ndata );
    ttype[18] = "DATA    ";
    tform[18] = Istr16;
    tunit[18] = "Jy      ";


    fits_create_tbl( cfitsptr, BINARY_TBL, nrows, ncols, 
		     ttype, tform, tunit, "SUBINT  ", &status);

    /* Add dimensions of column 'ncols' = SUBINT Data */
    naxes[0] = num_bins;
    naxes[1] = num_chans;
    naxes[2] = num_pols;
  
    fits_write_tdim( cfitsptr, ncols, 3, naxes, &status );

    /* Add keywords */
    fits_update_key( cfitsptr, TSTRING, "INT_TYPE", "TIME",
		     "Time axis (TIME, BINPHSPERI, BINLNGASC, etc)", &status);

    fits_update_key( cfitsptr, TSTRING, "INT_UNIT", "SEC",
		     "Unit of time axis (SEC, PHS (0-1), DEG)", &status);

    fits_update_key( cfitsptr, TINT, "NCH_FILE", &num_chans,
		     "Number of channels/sub-bands in this file (I)", &status);
    j = 0;
    fits_update_key( cfitsptr, TINT, "NCH_STRT", &j,
		     "Start channel/sub-band number (0 to NCHAN-1) (I)", &status);
    
    /* Store subint hdu number */
    fits_get_hdu_num( cfitsptr, &subint_hdu );

  }
  
  /* Write SUBINT BINTABLE columns */

  /* Fill in columns of table */
  col = 1;
  
  /* Subint number. If NAXIS=-1, 0 indicates EOD. */
  fits_write_col( cfitsptr, TINT, col, subint_cnt, 1, 1, &subint_cnt, &status );
  col++;
  
  /* INDEXVAL - Optionally used if INT_TYPE != TIME */
  dx = 0.0;
  fits_write_col( cfitsptr, TDOUBLE, col, subint_cnt, 1, 1, &dx, &status );
  col++;

  /* [s] Length of subint */
  fits_write_col( cfitsptr, TDOUBLE, col, subint_cnt, 1, 1, &sum_subint_len_secs, &status );
  col++;

  /* [s] Offset from Start UTC of subint centre */
  dx = sum_subint_mid_pt / sum_subint_len_secs;
  fits_write_col( cfitsptr, TDOUBLE, col, subint_cnt, 1, 1, &dx, &status );
  col++;

  /* [s] LST at subint centre */
  ds = sum_subint_lst_sin / sum_subint_len_secs;
  dc = sum_subint_lst_cos / sum_subint_len_secs;
  if( ( dx = ( atan2( ds, dc ) / TwoPi ) ) < 0.0 ) dx += 1.0;
  dx *= 86400.0;
  fits_write_col( cfitsptr, TDOUBLE, col, subint_cnt, 1, 1, &dx, &status );
  col++;

  /* [turns] RA (J2000) at subint centre */
  ds = sum_subint_ra_sin / sum_subint_len_secs;
  dc = sum_subint_ra_cos / sum_subint_len_secs;
  if( ( dx = ( atan2( ds, dc ) / TwoPi ) ) < 0.0 ) dx += 1.0;
  fits_write_col( cfitsptr, TDOUBLE, col, subint_cnt, 1, 1, &dx, &status );
  col++;

  /* [turns] Dec (J2000) at subint centre */
  ds = sum_subint_dec_sin / sum_subint_len_secs;
  dc = sum_subint_dec_cos / sum_subint_len_secs;
  dx = atan2( ds, dc ) / TwoPi;
  fits_write_col( cfitsptr, TDOUBLE, col, subint_cnt, 1, 1, &dx, &status );
  col++;

  /* [deg] Gal longitude at subint centre */
  ds = sum_subint_Glon_sin / sum_subint_len_secs;
  dc = sum_subint_Glon_cos / sum_subint_len_secs;
  if( ( dx = ( atan2( ds, dc ) / TwoPi ) ) < 0.0 ) dx += 1.0;
  dx *= 360.0;
  fits_write_col( cfitsptr, TDOUBLE, col, subint_cnt, 1, 1, &dx, &status );
  col++;

  /* [deg] Gal latitude at subint centre */
  ds = sum_subint_Glat_sin / sum_subint_len_secs;
  dc = sum_subint_Glat_cos / sum_subint_len_secs;
  dx = atan2( ds, dc ) * 360.0 / TwoPi;
  fits_write_col( cfitsptr, TDOUBLE, col, subint_cnt, 1, 1, &dx, &status );
  col++;

  /* [deg] Feed angle at subint centre */
  ds = sum_subint_fa_sin / sum_subint_len_secs;
  dc = sum_subint_fa_cos / sum_subint_len_secs;
  dx = atan2( ds, dc ) * 360.0 / TwoPi;
  x = (float) dx;
  fits_write_col( cfitsptr, TFLOAT, col, subint_cnt, 1, 1, &x, &status );
  col++;

  /* [deg] Parallactic angle at subint centre */
  ds = sum_subint_pa_sin / sum_subint_len_secs;
  dc = sum_subint_pa_cos / sum_subint_len_secs;
  dy = atan2( ds, dc ) * 360.0 / TwoPi;

  /* [deg] Position angle of feed at subint centre */
  dx = dx + dy;
  if( dx > 180.0 ) dx -= 360.0;
  if( dx < 180.0 ) dx += 360.0;
  x = (float) dx;
  fits_write_col( cfitsptr, TFLOAT, col, subint_cnt, 1, 1, &x, &status );
  col++;

  /* [deg] Parallactic angle at subint centre */
  x = (float) dy;
  fits_write_col( cfitsptr, TFLOAT, col, subint_cnt, 1, 1, &x, &status );
  col++;

  /* [deg] Telescope azimuth at subint centre */
  ds = sum_subint_az_sin / sum_subint_len_secs;
  dc = sum_subint_az_cos / sum_subint_len_secs;
  if( ( dx = ( atan2( ds, dc ) / TwoPi ) ) < 0.0 ) dx += 1.0;
  dx *= 360.0;
  x = (float) dx;
  fits_write_col( cfitsptr, TFLOAT, col, subint_cnt, 1, 1, &x, &status );
  col++;

  /* [deg] Telescope zenith angle at subint centre */
  ds = sum_subint_el_sin / sum_subint_len_secs;
  dc = sum_subint_el_cos / sum_subint_len_secs;
  dx = 90.0 - ( atan2( ds, dc ) * 360.0 / TwoPi );
  x = (float) dx;
  fits_write_col( cfitsptr, TFLOAT, col, subint_cnt, 1, 1, &x, &status );
  col++;


  /* Centre freq. for each channel - NCHAN floats */
  fits_write_col( cfitsptr, TFLOAT, col, subint_cnt, 1, num_chans, binned_freq, &status );
  col++;

  /* Weights for each channel -  NCHAN floats */
  fits_write_col( cfitsptr, TFLOAT, col, subint_cnt, 1, num_chans, binned_weight, &status );
  col++;

  /* Data offset for each channel - NCHAN*NPOL floats */
  fits_write_col( cfitsptr, TFLOAT, col, subint_cnt, 1, nscl, binned_offset, &status );
  col++;

  /* Data scale factor for each channel - NCHAN*NPOL floats */
  fits_write_col( cfitsptr, TFLOAT, col, subint_cnt, 1, nscl, binned_scale, &status );
  col++;

  /* Subint data table - Dimensions of data table = (NBIN,NCHAN,NPOL) */
  fits_write_col( cfitsptr, TSHORT, col, subint_cnt, 1, ndata, binned_data, &status );
  col++;
  
  /* Finished SUBINT */

#define STEP_BACK
#ifdef STEP_BACK

  /* Move to digitiser statistics  */
  fits_movabs_hdu( cfitsptr, dig_stats_hdu, NULL, &status );

  if( subint_cnt == 1 ) {
    
    /* Now we know whether samplers are in fixed or auto mode - Add DIGLEV key */
    if( (*c_c).wb_ifsam.freq[0].ant[0].pol[0].sam_status & WBSAM_FIXED )
      strcpy( astr, "FIX" );
    else 
      strcpy( astr, "AUTO" );
    fits_update_key( cfitsptr, TSTRING, "DIGLEV", astr,
		     "Digitiser level-setting mode (AUTO, FIX)", &status);
  }
  
  /* Add data for this subint */
  fits_write_col( cfitsptr, TFLOAT, 1, subint_cnt, 1, num_wbsam_stats, wbsam_stats, &status );


  /* Move to bandpass  */
  fits_movabs_hdu( cfitsptr, bpass_hdu, NULL, &status );
  /* Overwrite row 1 with latest data  */

  /* Data offset for each receiver channel - NRCVR floats */
  fits_write_col( cfitsptr, TFLOAT, 1, 1, 1, nrcvr, bpass_offset, &status );

  /* Data scale factor for each receiver channel - NRCVR floats */
  fits_write_col( cfitsptr, TFLOAT, 2, 1, 1, nrcvr, bpass_scale, &status );

  /* Bandpass data table - Dimensions of data table = (NCHAN_orig,NRCVR) */
  ndata = nchan_orig * nrcvr;
  fits_write_col( cfitsptr, TSHORT, 3, 1, 1, ndata, bpass_data, &status );


  /* Move back to subint HDU for next subint */
  fits_movabs_hdu( cfitsptr, subint_hdu, NULL, &status );

#endif /* STEP_BACK */

  /* Now FLUSH any internal buffers to the file */
  fits_flush_file( cfitsptr, &status );


  return( status );
  
}
Exemplo n.º 17
0
void image_dump_to_fits(image_str *image, char *filename)
{
    fitsfile *fits;
    int status;
    long naxis = 2;
    long naxes[2] = {image->width, image->height};
    char *filename_exclam = make_string("!%s", filename);

    if(!filename)
        return;

    cfitsio_lock();

    status = 0;
    fits_create_file(&fits, filename_exclam, &status);
    free(filename_exclam);

    /* Creating 3-dimensional FITS file of necessary type. */
    if(image->type == IMAGE_DOUBLE){
        fits_create_img(fits, DOUBLE_IMG, naxis, naxes, &status);
        fits_write_2d_dbl(fits, 0, image->width, image->width, image->height,
                          image->double_data, &status);
    } else {
        fits_create_img(fits, USHORT_IMG, naxis, naxes, &status);
        fits_write_2d_usht(fits, 0, image->width, image->width, image->height,
                           image->data, &status);
    }

    if(!coords_is_empty(&image->coords))
        image_keyword_add_coords(image, image->coords);

    /* Write keywords */
    image_keywords_to_fits(image, fits);

    /* Write header */
    {
        double ra = image->coords.ra0;
        double dec = image->coords.dec0;
        char *ra_string = NULL;
        char *dec_string = NULL;
        char *time_string = time_str_get_date_time(image->time);
        char *date_obs_string = make_string("%04d-%02d-%02d", image->time.year, image->time.month, image->time.day);
        char *time_obs_string = make_string("%02d:%02d:%04.2lf", image->time.hour, image->time.minute, image->time.second + 1e-6*image->time.microsecond);
        double jd = time_str_get_JD(image->time);

        if(!coords_is_empty(&image->coords))
            coords_get_ra_dec(&image->coords, 0.5*image->width, 0.5*image->height, &ra, &dec);

        ra_string = make_ra_string(ra);
        dec_string = make_dec_string(dec);

        fits_update_key(fits, TSTRING, "RA", ra_string, "Rough center coordinates", &status);
        fits_update_key(fits, TSTRING, "DEC", dec_string, "Rough center coordinates", &status);
        fits_update_key(fits, TSTRING, "TIME", time_string, "Date and time", &status);
        fits_update_key(fits, TSTRING, "DATE-OBS", date_obs_string, NULL, &status);
        fits_update_key(fits, TSTRING, "TIME-OBS", time_obs_string, NULL, &status);

        fits_update_key(fits, TDOUBLE, "JD", &jd, "Julianic date, millisecond precision", &status);

        free(ra_string);
        free(dec_string);
        free(time_string);
        free(date_obs_string);
        free(time_obs_string);
    }

    fits_close_file(fits, &status);

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

    cfitsio_unlock();
}
Exemplo n.º 18
0
std::string write_image_3D(std::string pathname_3D, float *array_2D_real, float *array_2D_imag, std::string name_3D, int naxis_2D, long *naxes_2D) {
  // this function writes a float array to a FITS image file
  TRACE_ENTER();
  // create new file
  fitsfile *fptr;
  int status = 0;
  fits_create_file(&fptr, pathname_3D.c_str(), &status);
  if (status != 0) {
    // cannot create the file
    // likely, the file already exists
    // try to open it, delete it and create it anew
    // try to open the file
    status = 0;
    fits_open_file(&fptr, pathname_3D.c_str(), READWRITE, &status);
    if (status != 0) {
      // cannot open the file, for some reason
      return FORMAT_STATUS(status);
    }
    // try to delete the file
    status = 0;
    fits_delete_file(fptr, &status);
    if (status != 0) {
      // cannot delete the file, for some reason
      return FORMAT_STATUS(status);
    }
    // try to create the file
    status = 0;
    fits_create_file(&fptr, pathname_3D.c_str(), &status);
    if (status != 0) {
      // cannot create the file, for some reason
      return FORMAT_STATUS(status);
    }
  }
  // create the primary array image
  int naxis_3D = naxis_2D+1;
  long *naxes_3D = new long [naxis_3D];
  for (int i = 0; i < naxis_2D; i++) {
    naxes_3D[i] = naxes_2D[i];
  }
  naxes_3D[naxis_3D-1] = 2;
  fits_create_img(fptr, FLOAT_IMG, naxis_3D, naxes_3D, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // write a keyword
  fits_update_key(fptr, TFLOAT, name_3D.c_str(), array_2D_real, name_3D.c_str(), &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // write the array of floats to the image
  long *fpixel = new long [naxis_3D];
  fpixel[0] = 1;
  fpixel[1] = 1;
  fpixel[2] = 1;
  long *lpixel = new long [naxis_3D];
  lpixel[0] = naxes_2D[0];
  lpixel[1] = naxes_2D[1];
  lpixel[2] = 1;
  fits_write_subset(fptr, TFLOAT, fpixel, lpixel, (void*)array_2D_real, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // write a keyword
  fits_update_key(fptr, TFLOAT, name_3D.c_str(), array_2D_imag, name_3D.c_str(), &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // write the array of floats to the image
  fpixel[0] = 1;
  fpixel[1] = 1;
  fpixel[2] = 2;
  lpixel[0] = naxes_2D[0];
  lpixel[1] = naxes_2D[1];
  lpixel[2] = 2;
  fits_write_subset(fptr, TFLOAT, fpixel, lpixel, (void*)array_2D_imag, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // close the file
  fits_close_file(fptr, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  return "WRITE_OK";
}
Exemplo n.º 19
0
int CDfits_write_scanhdr( void )
{
  int status;
  int i, j, k, m, n;
  short int sj;
  
  double dx, dy, dz;
  
  long lk;
    
  int nrows, ncols;
  long naxes[3];

  char *ttype[4], *tform[4], *tunit[4];

  char str[16], Istr[16], *qch, *rch, *sch, *tch;

  int chan_inc, first_normal_group, npols, pol;
      
  float x;

#undef POINT_PAR
#ifdef POINT_PAR

  float xa[12];

#endif
  
  FILE *fp;
  char filename[80];
  
#define GSTR_LEN 88
  char gstr[GSTR_LEN];
  char astr[80];
  
  void *pv;

  char date_time[24];

#define MAX_BLKS 20
  char *pch[MAX_BLKS];
  char site[MAX_BLKS][2];
  short int nspan[MAX_BLKS];
  short int ncoeff[MAX_BLKS];
  double rfreq[MAX_BLKS];
  double rmjd[MAX_BLKS];
  double rphase[MAX_BLKS];
  double lgfiterr[MAX_BLKS];
  double f0[MAX_BLKS];
#define MAX_COEFF 15
  double coeff[MAX_BLKS][MAX_COEFF];


  /* For Pulsar History BINTABLE */
 
  static char *PHtype[18] = {
    "DATE_PRO","PROC_CMD","POL_TYPE","NPOL    ","NBIN    ","NBIN_PRD","TBIN    ","CTR_FREQ",
    "NCHAN   ","CHAN_BW ","PAR_CORR","RM_CORR ","DEDISP  ","DDS_MTHD","SC_MTHD ","CAL_MTHD",
    "CAL_FILE","RFI_MTHD"
  };
  
  static char *PHform[18] = {
    "24A     ","80A     ","8A      ","1I      ","1I      ","1I      ","1D      ","1D      ",
    "1I      ","1D      ","1I      ","1I      ","1I      ","32A     ","32A     ","32A     ",
    "32A     ","32A     "
  };
  
  static char *PHunit[18] = {
    "        ","        ","        ","        ","        ","        ","s       ","MHz     ",
    "        ","MHz     ","        ","        ","        ","        ","        ","        ",
    "        ","        "
  };


  /* For Pulsar Epmemeris BINTABLE */

  static char *PEtype[56] = {
    "DATE_PRO", "PROC_CMD", "EPHVER", "PSR_NAME", "RAJ", "DECJ", "PMRA", "PMDEC", 
    "PX", "POSEPOCH", "IF0", "FF0", "F1", "F2", "F3", "PEPOCH",
    "DM", "DM1", "RM", "BINARY", "T0", "PB", "A1", "OM", 
    "OMDOT", "ECC", "PBDOT", "GAMMA", "SINI", "M2", "T0_2", "PB_2",
    "A1_2", "OM_2", "ECC_2", "DTHETA", "XDOT", "EDOT", "TASC", "EPS1",
    "EPS2", "START", "FINISH", "TRES", "NTOA", "CLK", "EPHEM", "TZRIMJD",
    "TZRFMJD", "TZRFRQ", "TZRSITE", "GLEP_1", "GLPH_1", "GLF0_1", "GLF1_1", "GLF0D_1"
  };
  
  static char *PEform[56] = {
    "24A     ", "80A     ", "16A     ", "16A     ", "24A     ", "24A     ", "1D      ", "1D      ",
    "1D      ", "1D      ", "1J      ", "1D      ", "1D      ", "1D      ", "1D      ", "1D      ",
    "1D      ", "1D      ", "1D      ", "8A      ", "1D      ", "1D      ", "1D      ", "1D      ",
    "1D      ", "1D      ", "1D      ", "1D      ", "1D      ", "1D      ", "1D      ", "1D      ",
    "1D      ", "1D      ", "1D      ", "1D      ", "1D      ", "1D      ", "1D      ", "1D      ",
    "1D      ", "1D      ", "1D      ", "1D      ", "1I      ", "12A     ", "12A     ", "1J      ",
    "1D      ", "1D      ", "1A      ", "1D      ", "1D      ", "1D      ", "1D      ", "1D      "
  };
  
  /* For Pulsar Polyco BINTABLE */

  static char *PPtype[13] = {
    "DATE_PRO", "POLYVER ", "NSPAN   ", "NCOEF   ", "NPBLK   ", "NSITE   ", "REF_FREQ", "PRED_PHS",
    "REF_MJD ", "REF_PHS ", "REF_F0  ", "LGFITERR", "COEFF   "
  };
    
  static char *PPform[13] = {
    "24A     ", "16A     ", "1I      ", "1I      ", "1I      ", "1A      ", "1D      ", "1D      ",
    "1D      ", "1D      ", "1D      ", "1D      ", "15D     ",
  };

  /* BEGIN */

  status = 0;

  /* Get DateTime string - required in various BINTABLEs */
  fits_get_system_time( date_time, &n, &status );
  
  if( new_file ) {

    /* Add required keywords to primary header */

    /* fits_update_key( cfitsptr, TSTRING, "ORIGIN", "RNM", 
       "Output class", &status); */

    fits_update_key( cfitsptr, TSTRING, "OBSERVER", header.observer, 
		     "Observer name(s)", &status);
    fits_update_key( cfitsptr, TSTRING, "PROJID", supplhdr.project, 
		     "Project name", &status);
    fits_update_key( cfitsptr, TSTRING, "TELESCOP", supplhdr.site_name,
		     "Telescope name", &status);
    fits_update_key( cfitsptr, TDOUBLE, "ANT_X", &header.antenna[0].x,
		     "[m] Antenna ITRF X-coordinate (D)", &status);
    fits_update_key( cfitsptr, TDOUBLE, "ANT_Y", &header.antenna[0].y,
		     "[m] Antenna ITRF Y-coordinate (D)", &status);
    fits_update_key( cfitsptr, TDOUBLE, "ANT_Z", &header.antenna[0].z,
		     "[m] Antenna ITRF Z-coordinate (D)", &status);
    fits_update_key( cfitsptr, TSTRING, "FRONTEND", supplhdr.frontend, 
		     "Rx and feed ID", &status);

    fits_update_key( cfitsptr, TSTRING, "FD_POLN", supplhdr.polzn,
		     "LIN or CIRC", &status);
    x = 0.0;
    fits_update_key( cfitsptr, TFLOAT, "XPOL_ANG", &x,
		     "[deg] Angle of X-probe wrt platform zero (E)", &status);

    fits_update_key( cfitsptr, TSTRING, "BACKEND", supplhdr.backend, 
		     "Backend ID", &status);
    fits_update_key( cfitsptr, TSTRING, "BECONFIG", (*c_c).config_menu_name,
		     "Backend configuration file name", &status);

    /* Basic cycle time for integration */
    dx = (*c_c).integ_time / 1.0E06;
    fits_update_key( cfitsptr, TDOUBLE, "TCYCLE", &dx,
		     "[s] Correlator cycle time (D)", &status);

    /* Find the first normal group in band */
    first_normal_group = -1;
    i = (*c_c).band[0].first_group;
    k = i + (*c_c).band[0].num_group - 1;
    while( ( i <= k ) && ( first_normal_group < 0 ) ) {
      if( (*c_c).product[ (*c_c).prod_group[i].first_prod ].type < POL_CAL_OFF ) {
	first_normal_group = i;
      }
      i++;
    }
    if( first_normal_group < 0 ) first_normal_group = 0;

    npols = (*c_c).prod_group[first_normal_group].num_prod;

    /* Receiver channels - best guess */
    if( npols == 1 ) nrcvr = 1;
    else nrcvr = 2;
    
    fits_update_key( cfitsptr, TINT, "NRCVR", &nrcvr,
		     "Number of receiver channels (I)", &status);
    fits_update_key( cfitsptr, TSTRING, "OBS_MODE", supplhdr.obsmode,
		     "(PSR, CAL, SEARCH)", &status);
    /* fits_update_key( cfitsptr, TSTRING, "DATATYPE", "FOLD",
                     "FOLD or DUMP", &status);  */
    fits_update_key( cfitsptr, TSTRING, "SRC_NAME", header.source,
		     "Source or scan ID", &status);
    fits_update_key( cfitsptr, TSTRING, "COORD_MD", header.epoch,
		     "Coordinate mode (J2000, Gal, Ecliptic, etc.)", &status);

    /* J2000 or B1950 */
    if( header.epoch[0] == 'J' || header.epoch[0] == 'B') j = 0;
    /* All others */
    else j = 2;

    rads_to_str( gstr, 16, supplhdr.start_long, j );

    /*
    gstr[17] = '\0';
    printf("\n rads_to_str(mode0) on %f = '%s'", supplhdr.start_long, gstr );
    */

    fits_update_key( cfitsptr, TSTRING, "STT_CRD1", gstr,
		     "Start coord 1 (hh:mm:ss.sss or ddd.ddd)", &status);

    rads_to_str( gstr, 16, supplhdr.start_lat, j+1 );
    fits_update_key( cfitsptr, TSTRING, "STT_CRD2", gstr,
		     "Start coord 2 (-dd:mm:ss.sss or -dd.ddd)", &status);
   
    fits_update_key( cfitsptr, TSTRING, "TRK_MODE", supplhdr.trackmode,
		     "Track mode (TRACK, SCANGC, SCANLAT)", &status);

    rads_to_str( gstr, 16, supplhdr.stop_long, j );
    fits_update_key( cfitsptr, TSTRING, "STP_CRD1", gstr,
		     "Stop coord 1 (hh:mm:ss.sss or ddd.ddd)", &status);

    rads_to_str( gstr, 16, supplhdr.stop_lat, j+1 );
    fits_update_key( cfitsptr, TSTRING, "STP_CRD2", gstr,
		     "Stop coord 2 (-dd:mm:ss.sss or -dd.ddd)", &status);
   
    x = supplhdr.scan_cycles * ( (*c_c).integ_time / 1.0E06 );
    fits_update_key( cfitsptr, TFLOAT, "SCANLEN ", &x,
		     "[s] Requested scan length (E)", &status);
    
    fits_update_key( cfitsptr, TSTRING, "FD_MODE", supplhdr.fdmode,
		     "Feed track mode - Const FA, CPA, GPA", &status);

    fits_update_key( cfitsptr, TFLOAT, "FA_REQ", &supplhdr.xpolang,
		     "[deg] Feed/Posn angle requested (E)", &status);

    fits_update_key( cfitsptr, TFLOAT, "ATTEN_A", &supplhdr.atten_a,
		     "[db] Attenuator, Poln A (E)", &status);

    fits_update_key( cfitsptr, TFLOAT, "ATTEN_B", &supplhdr.atten_b,
		     "[db] Attenuator, Poln B (E)", &status);

    fits_update_key( cfitsptr, TSTRING, "CAL_MODE", supplhdr.calmode,
		     "Cal mode (OFF, SYNC, EXT1, EXT2)", &status);

    x = (float) (*c_c).pulsar_ncal_sig_frequency;
    fits_update_key( cfitsptr, TFLOAT, "CAL_FREQ", &x,
		     "[Hz] Cal modulation frequency (E)", &status);

    x = (float) (*c_c).pulsar_ncal_sig_duty_cycle;
    fits_update_key( cfitsptr, TFLOAT, "CAL_DCYC", &x,
		     "Cal duty cycle (E)", &status);

    x = (float) (*c_c).pulsar_ncal_sig_start_phase;
    fits_update_key( cfitsptr, TFLOAT, "CAL_PHS ", &x,
		     "Cal phase (wrt start time) (E)", &status);
    

    new_file = 0;

  }

#ifdef POINT_PAR

  /* Add Pointing Parameters BINTABLE */

  nrows = 0;  /* naxis2 - Let CFITSIO sort this out */
  ncols = 1; /* tfields */
  ttype[0] = "PPAR    ";
  tform[0] = "12E     ";

  fits_create_tbl( cfitsptr, BINARY_TBL, nrows, ncols, 
		   ttype, tform, NULL, "POINTPAR", &status);

  /* Pointing parameters */
  for( n=0; n<11; n++ ) xa[n] = (float) supplhdr.pointing_parameter[n];
  xa[11] = 0.0;
  fits_write_col( cfitsptr, TFLOAT, 1, 1, 1, 12, xa, &status );

#endif

  /* Add Processing History BINTABLE */

  nrows = 0;  /* naxis2 - Let CFITSIO sort this out */
  ncols = 18; /* tfields */
   
  fits_create_tbl( cfitsptr, BINARY_TBL, nrows, ncols, 
		   PHtype, PHform, PHunit, "HISTORY", &status);

  /* Processing date and time (YYYY-MM-DDThh:mm:ss UTC) */
  pch[0] = date_time;
  fits_write_col( cfitsptr, TSTRING, 1, 1, 1, 1, pch, &status );
  /* Processing program and command */
  pch[0] = "WBCOR";
  fits_write_col( cfitsptr, TSTRING, 2, 1, 1, 1, pch, &status );
  /* Polarisation identifier */
  if( npols < 4 ) {
    str[0] = '\0';
    k = (*c_c).prod_group[first_normal_group].first_prod;
    m = 0;
    for( j=0; j<npols; j++ ) {
      pol = (*c_c).product[k].polarisation;
      if( pol == 1 ) strcat( str, "XX" );
      else if( pol == 2 ) {
	/* An XY product will be written out as two pols, real and imag */
	strcat( str, "CRCI" );
	m++;
      }
      else if( pol == 3 ) {
	/* A YX product will be written out as two pols, real and imag */
	strcat( str, "CRCI" );
	m++;
      }
      else if( pol == 4 ) strcat( str, "YY" );
      else strcat( str, "??" );
      k++;
    }
  }
  else {
    strcpy( str, "XXYYXYYX" );
  }
  pch[0] = str;
  fits_write_col( cfitsptr, TSTRING, 3, 1, 1, 1, pch, &status );

  /* Nr of pols  - i.e. actually written out */
  sj = npols + m;
  fits_write_col( cfitsptr, TSHORT, 4, 1, 1, 1, &sj, &status );

  /* Nr of bins per product (0 for SEARCH mode) */
  sj = (*c_c).band[0].num_bins;
  fits_write_col( cfitsptr, TSHORT, 5, 1, 1, 1, &sj, &status );

  /* Nr of bins per period */
  fits_write_col( cfitsptr, TSHORT, 6, 1, 1, 1, &sj, &status );

  /* Bin time */
  dx =  (*c_c).pulsar_period / sj;
  fits_write_col( cfitsptr, TDOUBLE, 7, 1, 1, 1, &dx, &status );

  /* Centre freq. */
  dx = header.band[0].frequency;  
  fits_write_col( cfitsptr, TDOUBLE, 8, 1, 1, 1, &dx, &status );

  /* Number of channels */
  chan_inc = header.band[0].channel_increment;
  if( chan_inc <= 0 ) chan_inc = 1;
  n = ( ( header.band[0].last_channel - 
		   header.band[0].first_channel ) 
		 / chan_inc ) + 1;

  /* Don't include DC channel */  
  if( header.band[0].first_channel == 1 ) n--;
  
  sj = n;
  fits_write_col( cfitsptr, TSHORT, 9, 1, 1, 1, &sj, &status );

  /* Channel bandwidth */
  dy = header.band[0].bandwidth / (double) ( (*c_c).band[0].nfft / 2 );
  if( header.band[0].spectrum_inverted < 0 ) dy = -dy;

  /* Channel incr. width - signed */
  dx = (double) chan_inc * dy;
  fits_write_col( cfitsptr, TDOUBLE, 10, 1, 1, 1, &dx, &status );

  /* Create frequency array for later */
  /* Get freq. of first channel */
  if( ( k = header.band[0].first_channel ) == 1 ) k = 2;
  
  j = ( (*c_c).band[0].nfft / 4 ) + 1 - k;
  dz = header.band[0].frequency - ( j * dy );

  for(i=0; i<n; i++ ) {
    binned_freq[i] = (float) dz;
    dz += dx;
  }    


  sj = 0;
  /* Parallactic angle correction applied */
  fits_write_col( cfitsptr, TSHORT, 11, 1, 1, 1, &sj, &status );
  /* RM correction applied */
  fits_write_col( cfitsptr, TSHORT, 12, 1, 1, 1, &sj, &status );
  /* Data dedispersed */
  fits_write_col( cfitsptr, TSHORT, 13, 1, 1, 1, &sj, &status );
  /* Dedispersion method */
  pch[0] = "NONE";
  fits_write_col( cfitsptr, TSTRING, 14, 1, 1, 1, pch, &status );
  /* Scattered power correction method */
  pch[0] = supplhdr.scpwr;
  fits_write_col( cfitsptr, TSTRING, 15, 1, 1, 1, pch, &status );
  /* Calibration method */
  pch[0] = "NONE";
  fits_write_col( cfitsptr, TSTRING, 16, 1, 1, 1, pch, &status );
  /* Name of calibration file */
  pch[0] = "NONE";
  fits_write_col( cfitsptr, TSTRING, 17, 1, 1, 1, pch, &status );
  /* RFI excision method */
  pch[0] = supplhdr.rfiex;
  fits_write_col( cfitsptr, TSTRING, 18, 1, 1, 1, pch, &status );


  /* Add Original BANDPASS BINTABLE */

  nrows = 0;  /* naxis2 - Let CFITSIO sort this out */
  ncols = 3;  /* tfields */

  nchan_orig = ( (*c_c).band[0].nfft / 2 ) + 1;

  naxes[0] = nchan_orig;
  naxes[1] = nrcvr;

  sprintf( str, "%ldE", naxes[1] );

  ttype[0] = "DAT_OFFS";
  tform[0] = str;
  tunit[0] = "";

  ttype[1] = "DAT_SCL ";
  tform[1] = str;
  tunit[1] = "";

  sprintf( Istr, "%ldI", ( naxes[0] * naxes[1] ) );
  ttype[2] = "DATA    ";
  tform[2] = Istr;
  tunit[2] = "Jy      ";

  fits_create_tbl( cfitsptr, BINARY_TBL, nrows, ncols, 
		   ttype, tform, tunit, "BANDPASS", &status);

  /* Add dimensions of column 3 = BANDPASS Data */  
  fits_write_tdim( cfitsptr, 3, 2, naxes, &status );

  /* Add keywords */
  fits_update_key( cfitsptr, TINT, "NCH_ORIG", &nchan_orig,
		     "Number of channels in original bandpass (I)", &status);
  fits_update_key( cfitsptr, TINT, "BP_NPOL ", &nrcvr,
		     "Number of polarizations in bandpass (I)", &status);

  /* Store hdu number */
  fits_get_hdu_num( cfitsptr, &bpass_hdu );


  /* Add Pulsar Ephemeris BINTABLE */

  nrows = 0;  /* naxis2 - Let CFITSIO sort this out */
  ncols = 56; /* tfields */

  fits_create_tbl( cfitsptr, BINARY_TBL, nrows, ncols, 
		   PEtype, PEform, NULL, "PSREPHEM", &status);

  /* Processing date and time (YYYY-MM-DDThh:mm:ss UTC) */
  pch[0] = date_time;
  fits_write_col( cfitsptr, TSTRING, 1, 1, 1, 1, pch, &status );
  /* Processing program and command */
  pch[0] = "WBCOR";
  fits_write_col( cfitsptr, TSTRING, 2, 1, 1, 1, pch, &status );
  /* Ephemeris version */
  pch[0] = "PSRINFO:1.4";
  fits_write_col( cfitsptr, TSTRING, 3, 1, 1, 1, pch, &status );

  /* Open ephemeris file */
  /* Construct filename  */
  if( ( qch = getenv( "cor_pulsar" ) ) == NULL ) return(-11);

  strcpy( filename, qch );
  if( filename[ strlen(filename) - 1 ] != '/' )
    strcat( filename, "/" );
  strcat( filename, "online.eph" );
 
  if( ( fp = fopen( filename, "r" ) ) == NULL ) return(-12);

  while( fgets( gstr, GSTR_LEN, fp ) != NULL ) {

    if( ( qch = strtok( gstr, " " ) ) != NULL ) {

      /* Following gets a name change - From PSRJ to PSR_NAME */
      if( strcmp( qch, "PSRJ" ) == 0 ) i = 3;
      /* Following two get split into integer and fractional parts */
      else if( strcmp( qch, "F" ) == 0 ) i = 10;
      else if( strcmp( qch, "F0" ) == 0 ) i = 10; /* Possible alternative to just F */
      else if( strcmp( qch, "TZRMJD" ) == 0 ) i = 47;
      else {
	for( i=0; i<ncols; i++ ) {
	  if( strcmp( qch, PEtype[i] ) == 0 ) break;
	}
      }

      if( i < ncols ) {
	/* Get next parameter */
	if( ( rch = strtok( NULL, " " ) ) == NULL ) return(-13);

	if( i == 10 || i == 47 || ( qch = strchr( PEform[i], 'D' ) ) != NULL ) {
	  /* Change any D exponent to E */
	  if( ( sch = strrchr( rch, 'D' ) ) != NULL ) *sch = 'E';
	  tch = sch;
	
	  if( i == 10 || i == 47 ) {
	    /* Convert to integer + fractional part AND
	       if i == 10 convert from Hz to mHz i.e. multiply by 1000 */
	    /* Get exponent */
	    if( sch != NULL ) {
	      if( sscanf( ++sch, "%d", &j ) != 1 )  return(-91);
	    }
	    else j = 0;
	  
	    /* get position of decimal point */
	    if( ( sch = strrchr( rch, '.' ) ) == NULL ) {
	      /* Integer part only */
	      if( sscanf( rch, "%ld", &lk ) != 1 ) return(-92);
	      dx = 0.0;
	    }
	    else {
	      /* Decimal point present */
	      if( i == 10 ) j += 3;  /* multiply by 1000 - sec. to ms. */

	      if( j >= 0 ) {
		k = (int) ( sch - rch );
		if( k > 0 ) {
		  strncpy( astr, rch, k );
		  astr[k] = '\0';
		}
		else strcpy( astr, "0" );
	      
		if( j > 0 ) { /* multiply by 10**j, i.e. move decimal point */
		  strncat( astr, (sch+1), j );
		  *(sch += j) = '.';
		  *--sch = '0';
		}
		/* Now astr contains integer part, sch points to fractional part */
		if( sscanf( astr, "%ld", &lk ) != 1 ) return(-93);
		/* Don't want exponent - reduced to fraction */
		if( tch != NULL ) *tch = '\0';
		if( sscanf( sch, "%lf", &dx ) != 1 ) return(-94);
	      }
	      else {
		/* Fractional part only */
		lk = 0;
		if( sscanf( sch, "%lf", &dx ) != 1 ) return(-94);
		if( i == 10 ) dx *= 1000.0;
	      }
	    	    
	    }
	  
	    pv = &lk;
	    j = TLONG;

	  }
	  else {

	    if( sscanf( rch, "%lf", &dx ) != 1 ) return(-14);

	    j = TDOUBLE;
	    pv = &dx;

	  }	
	}
	else if( ( qch = strchr( PEform[i], 'A' ) ) != NULL ) {
	  j = TSTRING;
	  /* Strip off any trailing newline */
	  if( ( sch = strrchr( rch, '\n' ) ) != NULL ) *sch = '\0';
	  pch[0] = rch;
	  pv = pch;
	}
	else if( ( qch = strchr( PEform[i], 'I' ) ) != NULL ) {
	  j = TSHORT;
	  if( sscanf( rch, "%d", &k ) != 1 ) return(-15);
	  sj = k;
	  pv = &sj;
	}
	else if( ( qch = strchr( PEform[i], 'J' ) ) != NULL ) {
	  j = TINT;
	  if( sscanf( rch, "%d", &k ) != 1 ) return(-16);
	  pv = &k;
	}
	else return(-17);
            
	fits_write_col( cfitsptr, j, i+1, 1, 1, 1, pv, &status );

	/* Write fractional part */
	if( i == 10 || i == 47 ) {
	  j = TDOUBLE;
	  pv = &dx;
	  fits_write_col( cfitsptr, j, i+2, 1, 1, 1, pv, &status );
	  
	  printf( "\n In Ephemeris BINTABLE: %s = %ld %e", PEtype[i], lk, dx );
	}
      }
    }
  }
  fclose( fp );
  
  /* Add Digitiser Statistics BINTABLE */

  nrows = 0;  /* naxis2 - Let CFITSIO sort this out */
  ncols = 1; /* tfields */

  wbsam_levs = 2;
  num_wbsams = nrcvr;

  naxes[0] = wbsam_levs;
  naxes[1] = num_wbsams;
  if( ( n = header.cycles_to_avg ) <= 0 ) n = 1;
  naxes[2] = n;

  sprintf( str, "%ldE", ( naxes[0] * naxes[1] * naxes[2] ) );
  ttype[0] = "DATA    ";
  tform[0] = str;

  fits_create_tbl( cfitsptr, BINARY_TBL, nrows, ncols, 
		   ttype, tform, NULL, "DIG_STAT", &status);

  /* Add dimensions of column 1 = Data */  
  fits_write_tdim( cfitsptr, 1, 3, naxes, &status );

  /* Add keywords */
  fits_update_key( cfitsptr, TSTRING, "DIG_MODE", "2-bit,3-level",
		     "Digitiser mode", &status);
  fits_update_key( cfitsptr, TINT, "NDIGR", &num_wbsams,
		     "Number of digitised channels (I)", &status);
  fits_update_key( cfitsptr, TINT, "NLEV", &wbsam_levs,
		     "Number of digitiser levels (I)", &status);
  fits_update_key( cfitsptr, TINT, "NCYCSUB", &n,
		     "Number of correlator cycles per subint (I)", &status);

  /* Store current hdu number */
  fits_get_hdu_num( cfitsptr, &dig_stats_hdu );


  
  /* Add Polyco History BINTABLE */

  /* Read in polyco file */
  /* Construct filename from .eph name  */

  qch = strstr( filename, ".eph" );
  *qch = '\0';
  strcat( filename, ".polyco" );
  if( ( fp = fopen( filename, "r" ) ) == NULL ) return(-18);

  k = 0;
  while( ( k < MAX_BLKS ) && 
	 ( ( n = fscanf( fp, "%s %s%lf%lf%lf%lf%lf%lf%lf %s%hd%hd%lf%16c", 
			 gstr, gstr, &dx, &rmjd[k], &dx, &dx, &lgfiterr[k], &rphase[k], &f0[k],
			 site[k], &nspan[k], &ncoeff[k], &rfreq[k], gstr ) ) != EOF ) ) {
    if( n != 14 ) return(-20);
    if( ncoeff[k] > MAX_COEFF ) return(-21);
    
    for( i=0; i<ncoeff[k]; i++ ) {
      if( fscanf( fp, "%s", gstr  ) != 1 ) return(-22);
      /* Translate exponent D to E */
      if( ( qch = strchr( gstr, (int) 'D' ) ) != NULL ) *qch = 'E';
      if( sscanf( gstr, "%lE", &coeff[k][i] ) != 1 ) return(-23);
    }
    for( i=ncoeff[k]; i<MAX_COEFF; i++ ) coeff[k][i] = 0.0;
    k++;
  }
  if( k >= MAX_BLKS ) return(-24);
  
  fclose( fp );

  printf("\nCFITS_SUBS:  Polyco - Site[0,1](hex) = %x %x", site[0][0], site[0][1] );
  

  nrows = 0;  /* naxis2 - Let CFITSIO sort this out */
  ncols = 13; /* tfields */
  

  fits_create_tbl( cfitsptr, BINARY_TBL, nrows, ncols, 
		   PPtype, PPform, NULL, "POLYCO  ", &status);

  /* Processing date and time (YYYY-MM-DDThh:mm:ss UTC) */
  for( i=0; i<k; i++ ) pch[i] = date_time;
  fits_write_col( cfitsptr, TSTRING, 1, 1, 1, k, pch, &status );
  /* Polyco version */
  for( i=0; i<k; i++ ) pch[i] = "TEMPO:11.0";
  fits_write_col( cfitsptr, TSTRING, 2, 1, 1, k, pch, &status );
  /* Span of polyco in min */
  fits_write_col( cfitsptr, TSHORT, 3, 1, 1, k, nspan, &status );
  /* Nr of coefficients - per block */
  fits_write_col( cfitsptr, TSHORT, 4, 1, 1, k, ncoeff, &status );
  /* Nr of polyco blocks (of NCOEF coefficients) -reuse nspan array */
  for( i=0; i<k; i++ ) nspan[i] = k;
  fits_write_col( cfitsptr, TSHORT, 5, 1, 1, k, nspan, &status );
  /* TEMPO site code - 1 character */
  for( i=0; i<k; i++ ) pch[i] = &site[i][0];
  fits_write_col( cfitsptr, TSTRING, 6, 1, 1, k, pch, &status );
  /* Reference frequency for phase */
  fits_write_col( cfitsptr, TDOUBLE, 7, 1, 1, k, rfreq, &status );

  /* Predicted pulse phase at obs start - reuse rfreq  */
  for( i=0; i<k; i++ ) rfreq[i] = newcycle.WBpsr_timer_start_phase;
  fits_write_col( cfitsptr, TDOUBLE, 8, 1, 1, k, rfreq, &status );

  /* Reference MJD - NPBLK doubles */
  fits_write_col( cfitsptr, TDOUBLE, 9, 1, 1, k, rmjd, &status );
  /* Reference phase - NPBLK doubles */
  fits_write_col( cfitsptr, TDOUBLE, 10, 1, 1, k, rphase, &status );
  /* Reference F0 - NPBLK doubles */
  fits_write_col( cfitsptr, TDOUBLE, 11, 1, 1, k, f0, &status );
  /* Fit error - NPBLK doubles */
  fits_write_col( cfitsptr, TDOUBLE, 12, 1, 1, k, lgfiterr, &status );
  /* Polyco coefficients - NPBLK*NCOEF doubles */
  j = k * MAX_COEFF;
  fits_write_col( cfitsptr, TDOUBLE, 13, 1, 1, j, &coeff[0][0], &status );


  /* Store last header hdu number */
  fits_get_hdu_num( cfitsptr, &last_scanhdr_hdu );
  
  /* Restart SUBINT counter */
  subint_cnt = 0;
  
  return( status );

}
Exemplo n.º 20
0
void objects_head (struct fitpars *fpar, fitsfile *fptr, int offx, int offy)
{
    char par[FLEN_CARD], skyc[FLEN_CARD], comp[FLEN_KEYWORD],
         key[FLEN_KEYWORD];
    float parval;
    extern float xskycent, yskycent;
    int status = 0, i, j;

    j = 1;
    while (fpar != NULL) {
        sprintf (comp, "COMP_%i", j);
        fits_update_key(fptr, TSTRING, comp, fpar->objtype,
                        "Object type", &status);
        for (i=1; i<= 10; i++) {
            if (i==1 && strncmp(fpar->objtype, "sky", 3) != 0)
                parval = fpar->a[i] + offx;
            else if (i==2 && strncmp(fpar->objtype, "sky", 3) != 0)
                parval = fpar->a[2] + offy;
            else
                parval = fpar->a[i];

            sprintf (par, "%-.4f +/- %-.4f", parval, fpar->sig[i]);

            if (strncmp(fpar->objtype, "sky", 3) != 0) {

                if (i==1) {
                    sprintf (key, "%i_XCENT", j);
                    fits_update_key(fptr, TSTRING, key, par, "X center [pixel]",
                                    &status);
                };

                if (i==2) {
                    sprintf (key, "%i_YCENT", j);
                    fits_update_key(fptr, TSTRING, key, par, "Y center [pixel]",
                                    &status);
                };

                /*******\
                * Nuker *
                \*******/

                if (strncmp(fpar->objtype, "nuker", 5) == 0) {
                    if (i==3) {
                        sprintf (key, "%i_MU", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "Surface brightness at Rb", &status);
                    };

                    if (i==4) {
                        sprintf (key, "%i_Rb", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "Break radius Rb [pixels]", &status);
                    };

                    if (i==5) {
                        sprintf (key, "%i_alpha", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "alpha", &status);
                    };

                    if (i==6) {
                        sprintf (key, "%i_beta", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "beta", &status);
                    };

                    if (i==7) {
                        sprintf (key, "%i_gamma", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "gamma", &status);
                    };
                };

                /**************************\
                * Sersic and deVaucouleurs *
                \**************************/

                if (strncmp(fpar->objtype, "sersic", 6) == 0 ||
                        strncmp(fpar->objtype, "devauc", 6) == 0) {
                    if (i==3) {
                        sprintf (key, "%i_MAG", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "Total magnitude", &status);
                    };

                    if (i==4) {
                        sprintf (key, "%i_Re", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "Effective radius Re [pixels]", &status);
                    };

                    if (i==5 && strncmp(fpar->objtype, "sersic", 6) == 0) {
                        sprintf (key, "%i_n", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "Sersic index", &status);
                    };
                };

                /******************\
                * Exponential Disk *
                \******************/

                if (strncmp(fpar->objtype, "expdisk", 7) == 0) {
                    if (i==3) {
                        sprintf (key, "%i_MAG", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "Total magnitude", &status);
                    };

                    if (i==4) {
                        sprintf (key, "%i_Rs", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "Scalelength [pixels]", &status);
                    };
                };

                /*********************\
                * Gaussian and Moffat *
                \*********************/

                if (strncmp(fpar->objtype, "gauss", 5) == 0 ||
                        strncmp(fpar->objtype, "moffat", 6) == 0 ||
                        strncmp(fpar->objtype, "psf", 3) == 0 ) {

                    if (i==3) {
                        sprintf (key, "%i_MAG", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "Total magnitude", &status);
                    };

                    if (i==4 && strncmp(fpar->objtype, "psf", 3) != 0) {
                        sprintf (key, "%i_FWHM", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "FWHM [pixels]", &status);
                    };

                    if (i==5 && strncmp(fpar->objtype, "moffat", 6) == 0) {
                        sprintf (key, "%i_C", j);
                        fits_update_key(fptr, TSTRING, key, par,
                                        "Powerlaw", &status);
                    };
                };


                /*******************\
                * Common parameters *
                \*******************/

                if (i==8 && strncmp(fpar->objtype, "psf", 3) != 0) {
                    sprintf (key, "%i_AR", j);
                    fits_update_key(fptr, TSTRING, key, par,
                                    "Axis ratio (b/a)", &status);
                };

                if (i==9 && strncmp(fpar->objtype, "psf", 3) != 0) {
                    sprintf (key, "%i_PA", j);
                    fits_update_key(fptr, TSTRING, key, par,
                                    "Position Angle (PA) [Degrees: Up=0, Left=90]", &status);
                };

                if (i==10 && strncmp(fpar->objtype, "psf", 3) != 0) {
                    sprintf (key, "%i_C", j);
                    fits_update_key(fptr, TSTRING, key, par,
                                    "Diskiness (<0) or Boxiness (>0)", &status);
                };
            };

            /*****\
            * Sky *
            \*****/

            if (strncmp(fpar->objtype, "sky", 3) == 0) {
                if (i==1) {

                    sprintf (skyc, "%-.4f", xskycent + offx);
                    sprintf (key, "%i_XCENT", j);
                    fits_update_key(fptr, TSTRING, key, skyc, "X center [pixel]",
                                    &status);

                    sprintf (skyc, "%-.4f", yskycent + offy);
                    sprintf (key, "%i_YCENT", j);
                    fits_update_key(fptr, TSTRING, key, skyc, "Y center [pixel]",
                                    &status);

                    sprintf (key, "%i_SKY", j);
                    fits_update_key(fptr, TSTRING, key, par, "Sky background [ADUs]",
                                    &status);
                };

                if (i==2) {
                    sprintf (key, "%i_DSKYDX", j);
                    fits_update_key(fptr, TSTRING, key, par, "x sky gradient [ADUs]",
                                    &status);
                };

                if (i==3) {
                    sprintf (key, "%i_DSKYDY", j);
                    fits_update_key(fptr, TSTRING, key, par, "y sky gradient [ADUs]",
                                    &status);
                };
            };
        };

        fits_write_comment (fptr, "------------------------", &status);
        fpar = fpar->next;
        j++;
    };
}
Exemplo n.º 21
0
void addCol (IRAFPointer tp, IRAFPointer cp, char *colname, char *colunits) {

/* This is called by c_tbcdef1.  If the table does not exist yet, this
   function will return without doing anything.  If the table does exist,
   the column will be added to the table, and the keywords for units,
   display format, and undefined value (if int or short) will be added to
   the header.
arguments:
IRAFPointer tp          i: table descriptor
IRAFPointer cp          i: column descriptor
char *colname           i: column name
char *colunits          i: units for column, or null
*/
        
        TableDescr *tbl_descr;
        ColumnDescr *col_descr;
        char *keyword;
        int colnum;
        int datatype;           /* IRAF data type */
        int indef_int, indef_short;
        int status = 0;

        tbl_descr = (TableDescr *)tp;
        col_descr = (ColumnDescr *)cp;

        if (tbl_descr->table_exists) {
            keyword = (char *)calloc (SZ_FITS_STR+1, sizeof(char));

            colnum = col_descr->colnum;           /* one indexed */
            datatype = col_descr->datatype;
            indef_int = IRAF_INDEFI;
            indef_short = IRAF_INDEFS;

            /* fits_insert_col = fficol */
            fits_insert_col (tbl_descr->fptr, colnum, colname,
                        col_descr->tform, &status);
            if (status != 0) {
                setError (status, "c_tbcdef1:  couldn't create column");
                return;
            }
            tbl_descr->ncols = colnum;

            if (colunits[0] != '\0') {
                sprintf (keyword, "TUNIT%d", colnum);
                /* fits_update_key = ffuky */
                fits_update_key (tbl_descr->fptr, TSTRING, keyword,
                        colunits, "units for column", &status);
                if (status != 0) {
                    setError (status,
                        "c_tbcdef1:  couldn't add TUNITi keyword");
                    return;
                }
            }

            sprintf (keyword, "TDISP%d", colnum);
            fits_update_key (tbl_descr->fptr, TSTRING, keyword,
                        col_descr->tdisp, "display format for column",
                        &status);
            if (status != 0) {
                setError (status, "c_tbcdef1:  couldn't add TDISPi keyword");
                return;
            }

            if (datatype == IRAF_SHORT || datatype == IRAF_INT) {
                sprintf (keyword, "TNULL%d", colnum);
                if (datatype == IRAF_INT) {
                    int indef_int = IRAF_INDEFI;
                    fits_update_key (tbl_descr->fptr, TINT, keyword,
                        &indef_int, "undefined value for column", &status);
                } else {        /* short */
                    int indef_short = IRAF_INDEFS;
                    fits_update_key (tbl_descr->fptr, TINT, keyword,
                        &indef_short, "undefined value for column", &status);
                }
                if (status != 0) {
                    setError (status,
                        "c_tbcdef1:  couldn't add TNULLi keyword");
                    return;
                }
            }

            free (keyword);
        }
}
Exemplo n.º 22
0
void INDI::CCD::fits_update_key_s(fitsfile* fptr, int type, std::string name, void* p, std::string explanation, int* status)
{
        // this function is for removing warnings about deprecated string conversion to char* (from arg 5)
        fits_update_key(fptr,type,name.c_str(),p, const_cast<char*>(explanation.c_str()), status);
}
Exemplo n.º 23
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;
}
Exemplo n.º 24
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;
}
Exemplo n.º 25
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);
}
Exemplo n.º 26
0
int FITSImage::saveFITS( const QString &newFilename )
{
    int status=0;
    long fpixel[2], nelements;
    fitsfile *new_fptr;

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


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

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

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

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

    filename = newFilename;

    fptr = new_fptr;

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

    /* Write keywords */

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

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

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

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

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

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

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

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

  /* Check for needed updates */
    // Writing new FITS as double
    if(bitpix != DOUBLE_IMG){
      bitpix = DOUBLE_IMG;
      fits_update_key(fitsfp, TSHORT, "BITPIX", &bitpix, mod_comm, status);
    }
    
    // check for 'zero level' (needed for type long FITS headers)
    // NOTE: If input header does not contain this keyword (status = 202), 
    // skip update & reset CFITSIO status to zero.
    
    if(bzero != 0 || *status != 202){  
      bzero = 0;
      fits_update_key(fitsfp, TSHORT, "BZERO", &bzero, mod_comm, status);
    }
    *status = 0;                       // Reset Status
    
    // Check new axis lengths are correct
    if(naxes[0] != write_size[0])
      fits_update_key(fitsfp, TULONG,"NAXIS1",&write_size[0],mod_comm,status);
    if(naxes[1] != write_size[1])
      fits_update_key(fitsfp, TULONG,"NAXIS2",&write_size[1],mod_comm,status);
    
    
  /* Write array to file */
  fpixel[0] = 1;
  for(k=0; k < write_size[1]; k++){       // Loop over size[1] rows (i.e. y)
    fpixel[1] = k + 1; 
    if(fits_write_pix(fitsfp, TDOUBLE, fpixel, write_size[0], array[k], 
  		      status)){
      fits_report_error(stderr,*status);
      break;
    }
  }
  
  /* Add/modify keyword for date modified 'DATE-MOD' & 'TIME-MOD' */
  time(&now);
  ptr = localtime(&now);
  strftime(buf_date, FLEN_VALUE, "%Y-%m-%d", ptr);
  strftime(buf_time, FLEN_VALUE, "%H:%M:%S", ptr);
  fits_update_key(fitsfp, TSTRING, "DATE-MOD", buf_date, mod_comm, status);
  fits_update_key(fitsfp, TSTRING, "TIME-MOD", buf_time, NULL, status);
  
  /* Clean up */
  fits_close_file(fitsfp, status);
  fits_close_file(hdrfp,  status);
  
  /* Report any CFITSIO errors to stderr */
  if(!*status)
    fitswrap_catcherror(status);    // Send pointer not value
  
  return;
}
Exemplo n.º 28
0
void writeheader (struct image *img, struct fitpars *fpar, double chisq,
                  int ndof, int hdu, int offx, int offy)
{
    void objects_head (struct fitpars *fpar, fitsfile *fptr,
                       int offx, int offy);
    extern struct inpars input;
    char param[FLEN_CARD];
    fitsfile *fptr;
    int status = 0;
    float chi2nu;

    if (fits_open_file (&fptr, img->name, READWRITE, &status)) {
        pfunc ("\n Can't append to image header %s!\n", img->name);
        printerror( status );
    };

    if (fits_movabs_hdu (fptr, hdu, IMAGE_HDU, &status)) {
        pfunc ("\n Can't append to image header %s!\n", img->name);
        printerror( status );
    };

    fits_write_comment (fptr, " ", &status);
    fits_write_comment (fptr, "========== GALFIT Input Parameters ==========", &status);
    fits_write_comment (fptr, "", &status);

    fits_update_key(fptr, TSTRING, "INITFILE", input.initparfile,
                    "GALFIT input file", &status);

    fits_update_key(fptr, TSTRING, "DATAIN", input.data,
                    "Input data image", &status);

    fits_update_key(fptr, TSTRING, "SIGMA", input.sigma,
                    "Input sigma image", &status);

    fits_update_key(fptr, TSTRING, "PSF", input.psf,
                    "Convolution PSF", &status);

    fits_update_key(fptr, TSTRING, "CONSTRNT", input.constraints,
                    "Parameter constraint file", &status);

    fits_update_key(fptr, TSTRING, "MASK", input.badpix,
                    "Input mask image", &status);

    fits_update_key(fptr, TSTRING, "FITSECT", input.imgsect,
                    "Image section fitted", &status);

    sprintf (param, "%-.2f, %-.2f", input.cboxcent[1], input.cboxcent[2]);

    fits_update_key(fptr, TSTRING, "CBOXCENT", param,
                    "Convolution box center", &status);

    sprintf (param, "%i, %i", input.convbox[1], input.convbox[2]);

    fits_update_key(fptr, TSTRING, "CONVBOX", param,
                    "Convolution box size", &status);

    fits_update_key(fptr, TFLOAT, "MAGZPT", &input.magzpt,
                    "Magnitude zeropoint", &status);

    fits_write_comment (fptr, "========== GALFIT Final Parameters ==========", &status);

    objects_head (fpar, fptr, offx, offy);

    fits_update_key(fptr, TDOUBLE, "Chisq", &chisq,
                    "Chi^2 of fit", &status);
    fits_update_key(fptr, TINT, "NDOF", &ndof,
                    "Degrees of Freedom", &status);

    chi2nu = chisq/ndof;
    fits_update_key(fptr, TFLOAT, "Chi2nu", &chi2nu,
                    "Reduced Chi^2", &status);

    fits_write_comment (fptr, "=============================================", &status);
    fits_write_comment (fptr, " ", &status);

    fits_close_file(fptr, &status);                   /* close the file */

    return;
}
Exemplo n.º 29
0
void write_fits(char *filename, int w, int h, unsigned short *data, 
	double obs_duration, 
	char*  obs_type, 
	double obs_temperature,
    int    obs_filterNumber,
    char*  serial_number,
    char*  name,
    char*  ra,
    char*  dec,
    char*  alt,
    char * az
    )
{
    fitsfile *fptr;       /* pointer to the FITS file, defined in fitsio.h */
    int status;
    long  fpixel, nelements;

    /* Initialize FITS image parameters */

    int bitpix   =  USHORT_IMG;       /* 16-bit unsigned short pixel values */
    long naxis    =   2;              /* 2-dimensional image                */    
    long naxes[2] = { 256,256 };      /* default image 256 wide by 256 rows */

    /* Set the actual width and height of the image */

    naxes[0] = w;
    naxes[1] = h;

    /* Delete old FITS file if it already exists */  

    remove(filename); 

    /* Must initialize status before calling fitsio routines */           

    status = 0;  

    /* Create a new FITS file and show error message if one occurs */

    if (fits_create_file(&fptr, filename, &status)) 
	show_cfitsio_error( status );           

    /* Write the required keywords for the primary array image.       */
    /* Since bitpix = USHORT_IMG, this will cause cfitsio to create   */
    /* a FITS image with BITPIX = 16 (signed short integers) with     */
    /* BSCALE = 1.0 and BZERO = 32768.  This is the convention that   */
    /* FITS uses to store unsigned integers.  Note that the BSCALE    */
    /* and BZERO keywords will be automatically written by cfitsio    */
    /* in this case.                                                */

    if ( fits_create_img(fptr,  bitpix, naxis, naxes, &status) )
	show_cfitsio_error( status );          

    fpixel = 1;                               /* first pixel to write      */
    nelements = naxes[0] * naxes[1];          /* number of pixels to write */

    /* Write the array of unsigned integers to the FITS file */

    if ( fits_write_img(fptr, TUSHORT, fpixel, nelements, data, &status) )
	show_cfitsio_error( status );

    /* Write optional keywords to the header */

    if ( fits_update_key_dbl(fptr, "EXPTIME", obs_duration, -3,
		"exposure time (seconds)", &status) )
	show_cfitsio_error( status );

    if ( fits_update_key_dbl(fptr, "TEMPERAT", obs_temperature, -3,
		"temperature (C)", &status) )
	show_cfitsio_error( status );

    if ( fits_update_key_str(fptr, "IMAGETYP", 
		obs_type, "image type", &status) )
	show_cfitsio_error( status );       

    if ( fits_update_key(fptr, TSHORT, "FILTNUM", &obs_filterNumber, NULL, &status))
        show_cfitsio_error( status );       

    if ( fits_write_date(fptr, &status) )
	show_cfitsio_error( status );       

    if ( fits_update_key_str(fptr, "SERIALNO", 
		serial_number, "serial number", &status) )
	show_cfitsio_error( status ); 

    if ( fits_update_key_str(fptr, "TARGET", 
		name, "target name", &status) )
	show_cfitsio_error( status );  

    if ( fits_update_key_str(fptr, "RA", 
		ra, "right ascension", &status) )
	show_cfitsio_error( status );  

    if ( fits_update_key_str(fptr, "DEC", 
		dec, "declination", &status) )
	show_cfitsio_error( status );  

    if ( fits_update_key_str(fptr, "EPOCH", 
		"JNOW", "epoch of coordinates", &status) )
	show_cfitsio_error( status );  

    if ( fits_update_key_str(fptr, "OBJCTRA", 
		ra, "right ascension", &status) )
	show_cfitsio_error( status );  

    if ( fits_update_key_str(fptr, "OBJCTDEC", 
		dec, "declination", &status) )
	show_cfitsio_error( status );  

    if ( fits_update_key_dbl(fptr, "ALTITUDE", atof(alt), -4,
		"Altitude (deg)", &status) )
	show_cfitsio_error( status );

    if ( fits_update_key_dbl(fptr, "AZIMUTH", atof(az), -4,
		"Azimuth (deg)", &status) )
	show_cfitsio_error( status );

    /* Close the file */             

    if ( fits_close_file(fptr, &status) )              
	show_cfitsio_error( status );           

    return;
}
Exemplo n.º 30
0
int main(int argc, char *argv[])
{
    int numfiles, ii, numrows, rownum, ichan, itsamp, datidx;
    int spec_per_row, status, maxrows;
    unsigned long int maxfilesize;
    float offset, scale, datum, packdatum, maxval, fulltsubint;
    float *datachunk;
    FILE **infiles;
    struct psrfits pfin, pfout;
    Cmdline *cmd;
    fitsfile *infits, *outfits;
    char outfilename[128], templatename[128], tform[8];
    char *pc1, *pc2;
    int first = 1, dummy = 0, nclipped;
    short int *inrowdata;
    unsigned char *outrowdata;

    if (argc == 1) {
        Program = argv[0];
        usage();
        exit(1);
    }
    // Parse the command line using the excellent program Clig
    cmd = parseCmdline(argc, argv);
    numfiles = cmd->argc;
    infiles = (FILE **) malloc(numfiles * sizeof(FILE *));

    //Set the max. total size (in bytes) of all rows in an output file,
    //leaving some room for PSRFITS header
    maxfilesize = (unsigned long int)(cmd->numgb * GB);
    maxfilesize = maxfilesize - 1000*KB;
    //fprintf(stderr,"cmd->numgb: %f maxfilesize: %ld\n",cmd->numgb,maxfilesize);

#ifdef DEBUG
    showOptionValues();
#endif

    printf("\n         PSRFITS 16-bit to 4-bit Conversion Code\n");
    printf("         by J. Deneva, S. Ransom, & S. Chatterjee\n\n");

    // Open the input files
    status = 0;                 //fits_close segfaults if this is not initialized
    printf("Reading input data from:\n");
    for (ii = 0; ii < numfiles; ii++) {
        printf("  '%s'\n", cmd->argv[ii]);

        //Get the file basename and number from command-line argument
        //(code taken from psrfits2fil)
        pc2 = strrchr(cmd->argv[ii], '.');      // at .fits
        *pc2 = 0;               // terminate string
        pc1 = pc2 - 1;
        while ((pc1 >= cmd->argv[ii]) && isdigit(*pc1))
            pc1--;
        if (pc1 <= cmd->argv[ii]) {     // need at least 1 char before filenum
            puts("Illegal input filename. must have chars before the filenumber");
            exit(1);
        }
        pc1++;                  // we were sitting on "." move to first digit
        pfin.filenum = atoi(pc1);
        pfin.fnamedigits = pc2 - pc1;   // how many digits in filenumbering scheme.
        *pc1 = 0;               // null terminate the basefilename
        strcpy(pfin.basefilename, cmd->argv[ii]);
        pfin.initialized = 0;   // set to 1 in  psrfits_open()
        pfin.status = 0;
        //(end of code taken from psrfits2fil)

        //Open the existing psrfits file
        if (psrfits_open(&pfin, READONLY) != 0) {
            fprintf(stderr, "error opening file\n");
            fits_report_error(stderr, pfin.status);
            exit(1);
        }
        // Create the subint arrays
        if (first) {
            pfin.sub.dat_freqs = (float *) malloc(sizeof(float) * pfin.hdr.nchan);
            pfin.sub.dat_weights = (float *) malloc(sizeof(float) * pfin.hdr.nchan);
            pfin.sub.dat_offsets =
                (float *) malloc(sizeof(float) * pfin.hdr.nchan * pfin.hdr.npol);
            pfin.sub.dat_scales =
                (float *) malloc(sizeof(float) * pfin.hdr.nchan * pfin.hdr.npol);
            //first is set to 0 after data buffer allocation further below
        }

        infits = pfin.fptr;
        spec_per_row = pfin.hdr.nsblk;
	fits_read_key(infits, TINT, "NAXIS2", &dummy, NULL, &status);
	pfin.tot_rows = dummy;
        numrows = dummy;

	//If dealing with 1st input file, create output template
	if (ii == 0) {
	  sprintf(templatename, "%s.template.fits",cmd->outfile);
	  fits_create_file(&outfits, templatename, &status);
	  //fprintf(stderr,"pfin.basefilename: %s\n", pfin.basefilename);
	  //fprintf(stderr,"status: %d\n", status);
	  
	  //Instead of copying HDUs one by one, can move to the SUBINT
	  //HDU, and copy all the HDUs preceding it
	  fits_movnam_hdu(infits, BINARY_TBL, "SUBINT", 0, &status);
	  fits_copy_file(infits, outfits, 1, 0, 0, &status);
	  
	  //Copy the SUBINT table header
	  fits_copy_header(infits, outfits, &status);
	  fits_flush_buffer(outfits, 0, &status);
	  
	  //Set NAXIS2 in the output SUBINT table to 0 b/c we haven't 
	  //written any rows yet
	  dummy = 0;
	  fits_update_key(outfits, TINT, "NAXIS2", &dummy, NULL, &status);
	  
	  //Edit the NBITS key
	  if (DEBUG) {
	    dummy = 8;
	    fits_update_key(outfits, TINT, "NBITS", &dummy, NULL, &status);
	  } else {
	    fits_update_key(outfits, TINT, "NBITS", &(cmd->numbits), NULL,
			    &status);
	  }
	  
	  //Edit the TFORM17 column: # of data bytes per row 
	  //fits_get_colnum(outfits,1,"DATA",&dummy,&status);
	  if (DEBUG)
	    sprintf(tform, "%dB",
		    pfin.hdr.nsblk * pfin.hdr.nchan * pfin.hdr.npol);
	  else
	    sprintf(tform, "%dB", pfin.hdr.nsblk * pfin.hdr.nchan *
		    pfin.hdr.npol * cmd->numbits / 8);
	  
	  fits_update_key(outfits, TSTRING, "TTYPE17", "DATA", NULL, &status);
	  fits_update_key(outfits, TSTRING, "TFORM17", tform, NULL, &status);
	  
	  //Edit NAXIS1: row width in bytes
	  fits_read_key(outfits, TINT, "NAXIS1", &dummy, NULL, &status);
	  if (DEBUG) {
	    dummy = dummy - pfin.hdr.nsblk * pfin.hdr.nchan *
	      pfin.hdr.npol * (pfin.hdr.nbits - 8) / 8;
	  } else {
	    dummy = dummy - pfin.hdr.nsblk * pfin.hdr.nchan *
	      pfin.hdr.npol * (pfin.hdr.nbits - cmd->numbits) / 8;
	  }
	  fits_update_key(outfits, TINT, "NAXIS1", &dummy, NULL, &status);
	  
	  //Set the max # of rows per file, based on the requested 
	  //output file size
	  maxrows = maxfilesize / dummy;
	  //fprintf(stderr,"maxrows: %d\n",maxrows);

	  fits_close_file(outfits, &status);
	  
	  rownum = 0;
	}
	
        while (psrfits_read_subint(&pfin, first) == 0) {
	  fprintf(stderr, "Working on row %d\n", ++rownum);
	  
	  //If this is the first row, store the length of a full subint
	  if (ii == 0 && rownum == 1)
	    fulltsubint = pfin.sub.tsubint;

	  //If this is the last row and it's partial, drop it.
	  //(It's pfin.rownum-1 below because the rownum member of the psrfits struct seems to be intended to indicate at the *start* of what row we are, i.e. a row that has not yet been read. In contrast, pfout.rownum indicates how many rows have been written, i.e. at the *end* of what row we are in the output.)
	  
	  if (pfin.rownum-1 == numrows && fabs(pfin.sub.tsubint - fulltsubint) > pfin.hdr.dt) {
	    fprintf(stderr,
		    "Dropping partial row of length %f s (full row is %f s)\n",
		    pfin.sub.tsubint, fulltsubint);
	    break;
	  }
	  
	  //If we just read in the 1st row, or if we already wrote the last row in the current output file, create a new output file
	  if ((ii == 0 && rownum == 1) || pfout.rownum == maxrows) {
	    //Create new output file from the template
	    pfout.fnamedigits = pfin.fnamedigits;
	    if(ii == 0)
	      pfout.filenum = pfin.filenum;
	    else
	      pfout.filenum++;
	    
	    sprintf(outfilename, "%s.%0*d.fits", cmd->outfile, pfout.fnamedigits, pfout.filenum);
	    fits_create_template(&outfits, outfilename, templatename, &status);
	    //fprintf(stderr,"After fits_create_template, status: %d\n",status);
	    fits_close_file(outfits, &status);
	    
	    //Now reopen the file so that the pfout structure is initialized
	    pfout.status = 0;
	    pfout.initialized = 0;
	    
	    sprintf(pfout.basefilename, "%s.", cmd->outfile);
	    
            if (psrfits_open(&pfout, READWRITE) != 0) {
	      fprintf(stderr, "error opening file\n");
	      fits_report_error(stderr, pfout.status);
	      exit(1);
            }
            outfits = pfout.fptr;
            maxval = pow(2, cmd->numbits) - 1;
	    pfout.rows_per_file = maxrows;
	    
            //fprintf(stderr, "maxval: %f\n", maxval);
	    //fprintf(stderr, "pfout.rows_per_file: %d\n",pfout.rows_per_file);
	    
            //These are not initialized in psrfits_open but are needed 
            //in psrfits_write_subint (not obvious what are the corresponding 
            //fields in any of the psrfits table headers)
            pfout.hdr.ds_freq_fact = 1;
            pfout.hdr.ds_time_fact = 1;
	  }

            //Copy the subint struct from pfin to pfout, but correct 
            //elements that are not the same 
            pfout.sub = pfin.sub;       //this copies array pointers too
            pfout.sub.bytes_per_subint =
                pfin.sub.bytes_per_subint * pfout.hdr.nbits / pfin.hdr.nbits;
            pfout.sub.dataBytesAlloced = pfout.sub.bytes_per_subint;
            pfout.sub.FITS_typecode = TBYTE;

            if (first) {
                //Allocate scaling buffer and output buffer
                datachunk = gen_fvect(spec_per_row);
                outrowdata = gen_bvect(pfout.sub.bytes_per_subint);

                first = 0;
            }
            pfout.sub.data = outrowdata;

            inrowdata = (short int *) pfin.sub.data;
            nclipped = 0;

            // Loop over all the channels:
            for (ichan = 0; ichan < pfout.hdr.nchan * pfout.hdr.npol; ichan++) {
                // Populate datachunk[] by picking out all time samples for ichan
                for (itsamp = 0; itsamp < spec_per_row; itsamp++)
                    datachunk[itsamp] = (float) (inrowdata[ichan + itsamp *
                                                           pfout.hdr.nchan *
                                                           pfout.hdr.npol]);

                // Compute the statistics here, and put the offsets and scales in
                // pf.sub.dat_offsets[] and pf.sub.dat_scales[]

                if (rescale(datachunk, spec_per_row, cmd->numbits, &offset, &scale)
                    != 0) {
                    printf("Rescale routine failed!\n");
                    return (-1);
                }
                pfout.sub.dat_offsets[ichan] = offset;
                pfout.sub.dat_scales[ichan] = scale;

                // Since we have the offset and scale ready, rescale the data:
                for (itsamp = 0; itsamp < spec_per_row; itsamp++) {
                    datum = (scale == 0.0) ? 0.0 :
                        roundf((datachunk[itsamp] - offset) / scale);
                    if (datum < 0.0) {
                        datum = 0;
                        nclipped++;
                    } else if (datum > maxval) {
                        datum = maxval;
                        nclipped++;
                    }

                    inrowdata[ichan + itsamp * pfout.hdr.nchan * pfout.hdr.npol] =
                        (short int) datum;

                }
                // Now inrowdata[ichan] contains rescaled ints.
            }

            // Then do the conversion and store the
            // results in pf.sub.data[] 
            if (cmd->numbits == 8 || DEBUG) {
                for (itsamp = 0; itsamp < spec_per_row; itsamp++) {
                    datidx = itsamp * pfout.hdr.nchan * pfout.hdr.npol;
                    for (ichan = 0; ichan < pfout.hdr.nchan * pfout.hdr.npol;
                         ichan++, datidx++) {
                        pfout.sub.data[datidx] = (unsigned char) inrowdata[datidx];
                    }
                }
            } else if (cmd->numbits == 4) {
                for (itsamp = 0; itsamp < spec_per_row; itsamp++) {
                    datidx = itsamp * pfout.hdr.nchan * pfout.hdr.npol;
                    for (ichan = 0; ichan < pfout.hdr.nchan * pfout.hdr.npol;
                         ichan += 2, datidx += 2) {

                        packdatum = inrowdata[datidx] * 16 + inrowdata[datidx + 1];
                        pfout.sub.data[datidx / 2] = (unsigned char) packdatum;
                    }
                }
            } else {
                fprintf(stderr, "Only 4 or 8-bit output formats supported.\n");
                fprintf(stderr, "Bits per sample requested: %d\n", cmd->numbits);
                exit(1);
            }


            //pfout.sub.offs = (pfout.tot_rows+0.5) * pfout.sub.tsubint;
            fprintf(stderr, "nclipped: %d fraction clipped: %f\n", nclipped,
                    (float) nclipped / (pfout.hdr.nchan * pfout.hdr.npol *
                                        pfout.hdr.nsblk));

            // Now write the row. 
            status = psrfits_write_subint(&pfout);
            if (status) {
                printf("\nError (%d) writing PSRFITS...\n\n", status);
                break;
            }

	    //If current output file has reached the max # of rows, close it
	    if (pfout.rownum == maxrows)
	      fits_close_file(outfits, &status);
        }

        //Close the files 
        fits_close_file(infits, &status);
    }

    fits_close_file(outfits, &status);

    // Free the structure arrays too...
    free(datachunk);
    free(infiles);

    free(pfin.sub.dat_freqs);
    free(pfin.sub.dat_weights);
    free(pfin.sub.dat_offsets);
    free(pfin.sub.dat_scales);

    free(pfin.sub.data);
    free(pfout.sub.data);
    free(pfin.sub.stat);

    return 0;
}