Ejemplo n.º 1
0
void he_write_healpix_map(float **tmap,int nfields,long nside,char *fname)
{
  fitsfile *fptr;
  int ii,status=0;
  char *ttype[]={"T","Q","U"};
  char *tform[]={"1E","1E","1E"};
  char *tunit[]={"mK","mK","mK"};

  if((nfields!=1)&&(nfields!=3)) {
    fprintf(stderr,"CRIME: nfields must be 1 or 3\n");
    exit(1);
  }

  fits_create_file(&fptr,fname,&status);
  fits_create_tbl(fptr,BINARY_TBL,0,nfields,ttype,tform,
		  tunit,"BINTABLE",&status);
  fits_write_key(fptr,TSTRING,"PIXTYPE","HEALPIX","HEALPIX Pixelisation",
		 &status);

  fits_write_key(fptr,TSTRING,"ORDERING","RING",
		 "Pixel ordering scheme, either RING or NESTED",&status);
  fits_write_key(fptr,TLONG,"NSIDE",&nside,
		 "Resolution parameter for HEALPIX",&status);
  fits_write_key(fptr,TSTRING,"COORDSYS","G",
		 "Pixelisation coordinate system",&status);
  fits_write_comment(fptr,
		     "G = Galactic, E = ecliptic, C = celestial = equatorial",
		     &status);
  for(ii=0;ii<nfields;ii++) {
    fits_write_col(fptr,TFLOAT,ii+1,1,1,nside2npix(nside),tmap[ii],&status);
  }
  fits_close_file(fptr, &status);
}
Ejemplo n.º 2
0
int     ngp_keyword_all_write(NGP_HDU *ngph, fitsfile *ffp, int mode)
 { int		i, r, ib;
   char		buf[200];
   long		l;


   if (NULL == ngph) return(NGP_NUL_PTR);
   if (NULL == ffp) return(NGP_NUL_PTR);
   r = NGP_OK;
   
   for (i=0; i<ngph->tokcnt; i++)
    { if ((NGP_REALLY_ALL & mode) || (NGP_OK == ngp_keyword_is_write(&(ngph->tok[i]))))
        { switch (ngph->tok[i].type)
           { case NGP_TTYPE_BOOL:
			ib = ngph->tok[i].value.b;
			fits_write_key(ffp, TLOGICAL, ngph->tok[i].name, &ib, ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_STRING:
			fits_write_key_longstr(ffp, ngph->tok[i].name, ngph->tok[i].value.s, ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_INT:
			l = ngph->tok[i].value.i;	/* bugfix - 22-Jan-99, BO - nonalignment of OSF/Alpha */
			fits_write_key(ffp, TLONG, ngph->tok[i].name, &l, ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_REAL:
			fits_write_key(ffp, TDOUBLE, ngph->tok[i].name, &(ngph->tok[i].value.d), ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_COMPLEX:
			fits_write_key(ffp, TDBLCOMPLEX, ngph->tok[i].name, &(ngph->tok[i].value.c), ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_NULL:
			fits_write_key_null(ffp, ngph->tok[i].name, ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_RAW:
			if (0 == strcmp("HISTORY", ngph->tok[i].name))
			  { fits_write_history(ffp, ngph->tok[i].comment, &r);
			    break;
			  }
			if (0 == strcmp("COMMENT", ngph->tok[i].name))
			  { fits_write_comment(ffp, ngph->tok[i].comment, &r);
			    break;
			  }
			sprintf(buf, "%-8.8s%s", ngph->tok[i].name, ngph->tok[i].comment);
			fits_write_record(ffp, buf, &r);
                        break;
           }
          if (r) return(r);
        }
    }
     
   fits_set_hdustruc(ffp, &r);				/* resync cfitsio */
   return(r);
 }
Ejemplo n.º 3
0
void
writeWCS(fitsfile *fptr, const int i, int axesOrder[4], float cdelt[4], double crpix[4], double crval[4], char ctype[4][9], char cunit[4][9]){
  char myStr[9];
  int status = 0;

  sprintf(myStr, "CTYPE%d  ", i+1);
  fits_write_key(fptr, TSTRING, myStr, &ctype[axesOrder[i]], "", &status);
  sprintf(myStr, "CDELT%d  ", i+1);
  fits_write_key(fptr, TFLOAT, myStr, &cdelt[axesOrder[i]], "", &status);
  sprintf(myStr, "CRPIX%d  ", i+1);
  fits_write_key(fptr, TDOUBLE, myStr, &crpix[axesOrder[i]], "", &status);
  sprintf(myStr, "CRVAL%d  ", i+1);
  fits_write_key(fptr, TDOUBLE, myStr, &crval[axesOrder[i]], "", &status);
  sprintf(myStr, "CUNIT%d  ", i+1);
  fits_write_key(fptr, TSTRING, myStr, &cunit[axesOrder[i]], "", &status);	
}
Ejemplo n.º 4
0
int write_map(const char *filename, double *intensity, double *q, double *u, long nrows)
{
    
    fitsfile *fptr;
    int status = 0;
    int hdutype;
    int tfields=3;
    char extname[] = "BINTABLE";   /* extension name */
    char *ttype[] = { "I","Q","U" };
    char *tform[] = { "1E","1E","1E" };
    char *tunit[] = { " "," ", " " };
    if (fits_create_file(&fptr, filename, &status)) 
    fprintf(stderr, "%s (%d): Could not create new fits file.\n", 
        __FILE__, __LINE__);

    /* move to 1st HDU  */
    fits_movabs_hdu(fptr, 1, &hdutype, &status);
    //long nrows = 12L*nside*nside*2;
    //long nside = sqrtl(nrows/12L);
    long nside = 1024; //FIXME compute it

    /* append a new empty binary table onto the FITS file */
    fits_create_tbl( fptr, BINARY_TBL, nrows, tfields, ttype, tform,
            tunit, extname, &status);

    fits_write_key(fptr, TSTRING, "ORDERING", "NESTED", 
             "Pixel ordering scheme, either RING or NESTED", &status);

    fits_write_key(fptr, TLONG, "NSIDE", &nside, "Resolution parameter for HEALPIX", &status);
    long firstrow  = 1;  /* first row in table to write   */
    long firstelem = 1;  /* first element in row  (ignored in ASCII tables)  */

    if (fits_write_col(fptr, TDOUBLE, 1, firstrow, firstelem, nrows, intensity,
             &status))
    fprintf(stderr, "%s (%d): Could not write signal.\n", __FILE__, __LINE__);
    if (fits_write_col(fptr, TDOUBLE, 2, firstrow, firstelem, nrows, q,
             &status))
    fprintf(stderr, "%s (%d): Could not write signal.\n", __FILE__, __LINE__);
    if (fits_write_col(fptr, TDOUBLE, 3, firstrow, firstelem, nrows, u,
             &status))
    fprintf(stderr, "%s (%d): Could not write signal.\n", __FILE__, __LINE__);

    fits_close_file(fptr, &status);

    return true;
}
Ejemplo n.º 5
0
int init_filter_file(const char *fname, int nspec, int nchan, int nphase,
        int imjd0, double fmjd0) {
    int status=0;
    fitsfile *fptr;
    fits_create_file(&fptr, fname, &status);
    fits_movabs_hdu(fptr, 1, NULL, &status);
    long naxes[3] = {2, nchan, nspec};
    fits_create_img(fptr, FLOAT_IMG, 3, naxes, &status);
    fits_write_key(fptr, TINT, "IMJD", &imjd0, NULL, &status);
    fits_write_key(fptr, TDOUBLE, "FMJD", &fmjd0, NULL, &status);
    naxes[0] = nphase;
    naxes[1] = nspec;
    fits_create_img(fptr, FLOAT_IMG, 2, naxes, &status);
    fits_movabs_hdu(fptr, 2, NULL, &status);
    fits_write_key(fptr, TSTRING, "EXTNAME", "PROFILE", NULL, &status);
    fits_close_file(fptr, &status);
    if (status) {
        fprintf(stderr, "Error in init_filter_file:\n");
        fits_report_error(stderr, status);
        return(-1);
    }
    return(0);
}
Ejemplo n.º 6
0
Archivo: data.c Proyecto: glenco/lensed
void write_fits(fitsfile* fptr, int datatype, size_t width, size_t height,
                size_t num, void** images, const char* names[], int* status)
{
    // total number of pixels
    long npix = width*height;
    
    // dimensions
    int naxis = 2;
    long naxes[2] = { width, height };
    
    // writing offset
    long fpixel[2] = { 1, 1 };
    
    // write primary HDU
    fits_create_img(fptr, SHORT_IMG, 0, NULL, status);
    
    // record file origin
    fits_write_key(fptr, TSTRING, "ORIGIN", "Lensed " LENSED_VERSION, "FITS file originator", status);
    fits_write_comment(fptr, "for more information, see http://glenco.github.io/lensed/", status);
    
    // record the date of FITS creation
    fits_write_date(fptr, status);
    
    // write images
    for(size_t n = 0; n < num; ++n)
    {
        // create image extension
        fits_create_img(fptr, FLOAT_IMG, naxis, naxes, status);
        
        // write pixels
        fits_write_pix(fptr, datatype, fpixel, npix, images[n], status);
        
        // give extension name
        if(names && names[n])
            fits_write_key(fptr, TSTRING, "EXTNAME", (void*)names[n], "extension name", status);
    }
}
Ejemplo n.º 7
0
int append_filter(const char *fname, int ispec, int imjd, double fmjd, 
        struct filter_freq *hf) {
    int status=0;
    fitsfile *fptr;
    fits_open_file(&fptr, fname, READWRITE, &status);
    fits_movabs_hdu(fptr, 1, NULL, &status);
    int naxis;
    long naxes[3];
    fits_get_img_dim(fptr, &naxis, &status);
    if (naxis!=3) { 
        fits_close_file(fptr, &status);
        return(-1); 
    }
    fits_get_img_size(fptr, 3, naxes, &status);
    if (naxes[0]!=2 || naxes[1]!=hf->nchan || naxes[2]<ispec) {
        fits_close_file(fptr, &status);
        return(-2);
    }
    int imjd0;
    double fmjd0;
    fits_read_key(fptr, TINT, "IMJD", &imjd0, NULL, &status);
    fits_read_key(fptr, TDOUBLE, "FMJD", &fmjd0, NULL, &status);
    double toffs = (double)(imjd-imjd0) + (fmjd-fmjd0);
    toffs *= 86400.0;
    char key[80];
    sprintf(key, "DT%5.5d", ispec);
    fits_write_key(fptr, TDOUBLE, key, &toffs, "[s]", &status);
    naxes[0] = naxes[1] = 1;
    naxes[2] = ispec;
    fits_write_pix(fptr, TFLOAT, naxes, 2*hf->nchan, 
            (float *)hf->data, &status);
    fits_close_file(fptr, &status);
    if (status) {
        fprintf(stderr, "Error in append_filter:\n");
        fits_report_error(stderr, status);
        return(-1);
    }
    return(0);
}
Ejemplo n.º 8
0
void 
writefits(int im, inputPars *par, molData *m, image *img){
  double bscale,bzero,epoch,lonpole,equinox,restfreq;
  double cdelt1,crpix1,crval1,cdelt2,crpix2,crval2;
  double cdelt3,crpix3,crval3,ru3;
  int velref;
  float *row;
  int px,py,ichan;
  fitsfile *fptr;
  int status = 0;
  int naxis=3, bitpix=-32;
  long naxes[3];
  long int fpixels[3],lpixels[3];
  char negfile[100]="! ";

  row = malloc(sizeof(*row)*img[im].pxls);

  naxes[0]=img[im].pxls;
  naxes[1]=img[im].pxls;
  if(img[im].doline==1) naxes[2]=img[im].nchan;
  else if(img[im].doline==0 && par->polarization) naxes[2]=3;
  else naxes[2]=1;

  fits_create_file(&fptr, img[im].filename, &status);

  if(status!=0){
    if(!silent) warning("Overwriting existing fits file                   ");
    status=0;
    strcat(negfile,img[im].filename);
    fits_create_file(&fptr, negfile, &status);
  }

  /* Write FITS header */ 
  fits_create_img(fptr, bitpix, naxis, naxes, &status);
  epoch   =2.0e3;
  lonpole =1.8e2;
  equinox =2.0e3;
  restfreq=img[im].freq;
  velref  =257;
  cdelt1  =-1.8e2*img[im].imgres/PI;
  crpix1  =(double) img[im].pxls/2+0.5;
  crval1  =0.0e0;
  cdelt2  =1.8e2*img[im].imgres/PI;
  crpix2  =(double) img[im].pxls/2+0.5;
  crval2  =0.0e0;
  cdelt3  =img[im].velres;
  crpix3  =(double) (img[im].nchan-1)/2.+1;
  crval3  =0.0e0;
  bscale  =1.0e0;
  bzero   =0.0e0;

  fits_write_key(fptr, TSTRING, "OBJECT  ", &"LIMEMDL ",    "", &status);
  fits_write_key(fptr, TDOUBLE, "EPOCH   ", &epoch,         "", &status);
  fits_write_key(fptr, TDOUBLE, "LONPOLE ", &lonpole,       "", &status);
  fits_write_key(fptr, TDOUBLE, "EQUINOX ", &equinox,       "", &status);
  fits_write_key(fptr, TSTRING, "SPECSYS ", &"LSRK    ",    "", &status);
  fits_write_key(fptr, TDOUBLE, "RESTFREQ", &restfreq,      "", &status);
  fits_write_key(fptr, TINT,    "VELREF  ", &velref,        "", &status);
  fits_write_key(fptr, TSTRING, "CTYPE1  ", &"RA---SIN",    "", &status);
  fits_write_key(fptr, TDOUBLE, "CDELT1  ", &cdelt1,        "", &status);
  fits_write_key(fptr, TDOUBLE, "CRPIX1  ", &crpix1,        "", &status);
  fits_write_key(fptr, TDOUBLE, "CRVAL1  ", &crval1,        "", &status);
  fits_write_key(fptr, TSTRING, "CUNIT1  ", &"DEG     ",    "", &status);	
  fits_write_key(fptr, TSTRING, "CTYPE2  ", &"DEC--SIN",    "", &status);
  fits_write_key(fptr, TDOUBLE, "CDELT2  ", &cdelt2,        "", &status);
  fits_write_key(fptr, TDOUBLE, "CRPIX2  ", &crpix2,        "", &status);  	
  fits_write_key(fptr, TDOUBLE, "CRVAL2  ", &crval2,        "", &status);
  fits_write_key(fptr, TSTRING, "CUNIT2  ", &"DEG     ",    "", &status);
  fits_write_key(fptr, TSTRING, "CTYPE3  ", &"VELO-LSR",    "", &status);  
  fits_write_key(fptr, TDOUBLE, "CDELT3  ", &cdelt3,        "", &status);
  fits_write_key(fptr, TDOUBLE, "CRPIX3  ", &crpix3,        "", &status);
  fits_write_key(fptr, TDOUBLE, "CRVAL3  ", &crval3,        "", &status);
  fits_write_key(fptr, TSTRING, "CUNIT3  ", &"M/S     ",    "", &status);
  fits_write_key(fptr, TDOUBLE, "BSCALE  ", &bscale,        "", &status);
  fits_write_key(fptr, TDOUBLE, "BZERO   ", &bzero,         "", &status);
  if(img[im].unit==0) fits_write_key(fptr, TSTRING, "BUNIT", &"K       ", "", &status);
  if(img[im].unit==1) fits_write_key(fptr, TSTRING, "BUNIT", &"JY/PIXEL", "", &status);
  if(img[im].unit==2) fits_write_key(fptr, TSTRING, "BUNIT", &"WM2HZSR ", "", &status);
  if(img[im].unit==3) fits_write_key(fptr, TSTRING, "BUNIT", &"Lsun/PX ", "", &status);
  if(img[im].unit==3) fits_write_key(fptr, TSTRING, "BUNIT", &"        ", "", &status);

  /* Write FITS data */
  for(py=0;py<img[im].pxls;py++){
    for(ichan=0;ichan<img[im].nchan;ichan++){
      for(px=0;px<img[im].pxls;px++){
        if(img[im].unit==0) row[px]=(float) img[im].pixel[px+py*img[im].pxls].intense[ichan]*(CLIGHT/img[im].freq)*(CLIGHT/img[im].freq)/2./KBOLTZ*m[0].norm; 
        else if(img[im].unit==1) row[px]=(float) img[im].pixel[px+py*img[im].pxls].intense[ichan]*1e26*img[im].imgres*img[im].imgres*m[0].norm;
        else if(img[im].unit==2) row[px]=(float) img[im].pixel[px+py*img[im].pxls].intense[ichan]*m[0].norm;
        else if(img[im].unit==3) {
          ru3 = img[im].distance/1.975e13;
          row[px]=(float) img[im].pixel[px+py*img[im].pxls].intense[ichan]*4.*PI*ru3*ru3*img[im].freq*img[im].imgres*img[im].imgres*m[0].norm;
        }
        else if(img[im].unit==4) row[px]=(float) img[im].pixel[px+py*img[im].pxls].tau[ichan];
        else {
          if(!silent) bail_out("Image unit number invalid");
          exit(0);
        }
        if (fabs(row[px])<(float) eps) row[px]=(float)eps;
      }
      fpixels[0]=1;
      fpixels[1]=py+1;
      fpixels[2]=ichan+1;
      lpixels[0]=img[im].pxls;
      lpixels[1]=py+1;
      lpixels[2]=ichan+1;
      fits_write_subset(fptr, TFLOAT, fpixels, lpixels, row, &status);
    }
  }
  fits_close_file(fptr, &status);

  free(row);

  if(!silent) done(13);
}
Ejemplo n.º 9
0
int put_header(fitsfile *fptr, struct uvf_header *header, int gcount,
	       double refdat, char *origin)
{
  int naxis = 7;
  long pcount = 6;
  long naxes[7] = {0, 3, 1, 1, 1, 1, 1};
  float bscale = 1.0, bzero = 0.0;
  int one = 1,  zero = 0;
  double dfac1, dfac2, dref1, dref2, frac;
  char str[80];
  int status = 0;
  int ier, year, month, day;
  char datobs[16];

  /* Create the DATOBS string */

  slaDjcl(refdat, &year, &month, &day, &frac, &ier);
  if (ier != 0)
    fputs("Invalid DATOBS for FITS file.\n", stderr);
  sprintf(datobs, "%4.4d-%2.2d-%2.2d", year, month, day);

  /* Check for presence of INTTIM */

  if (header->index_inttim >=0)
    pcount = 7;

  /* Write required keywords. */

  naxes[2] = header->nstokes;
  naxes[4] = header->nif;
  fits_write_grphdr(fptr, 1, FLOAT_IMG, naxis, naxes, pcount, gcount,
		    1, &status);    
  fits_write_key(fptr, TFLOAT, "BSCALE", &bscale, 0, &status);
  fits_write_key(fptr, TFLOAT, "BZERO",  &bzero, 0, &status);
  
  /* Additional keywords. */

  fits_write_key(fptr, TSTRING, "OBJECT",   header->object,
		 "Source name", &status);
  fits_write_key(fptr, TSTRING, "TELESCOP", header->telescop,
		 0, &status);
  fits_write_key(fptr, TSTRING, "INSTRUME", header->instrume,
		 0, &status);
  fits_write_key(fptr, TSTRING, "OBSERVER", header->observer,
		 0, &status);
  fits_write_key(fptr, TSTRING, "DATE-OBS", datobs,
		 0, &status);
  fits_write_key(fptr, TSTRING, "BUNIT",    header->bunit,   
		 0,  &status);
  fits_write_key(fptr, TSTRING, "RADECSYS", header->radecsys,
		 0, &status);
  fits_write_key(fptr, TDOUBLE,  "EQUINOX",  &header->equinox, 
		 "Equinox of RA/Dec",   &status);
  fits_write_key(fptr, TDOUBLE, "EPOCH",     &header->equinox,
		 "Alternate name for EQUINOX", &status);
  fits_write_key(fptr, TDOUBLE, "OBSRA",    &header->obsra,
		 "Antenna pointing RA", &status);
  fits_write_key(fptr, TDOUBLE, "OBSDEC",   &header->obsdec,
		 "Antenna pointing Dec", &status);

  /* FITS coordinate parameters */
  
  fits_write_key(fptr, TSTRING, "CTYPE2", "COMPLEX", "1=real, 2=imag, 3=weight", &status);
  fits_write_key(fptr, TINT,    "CRVAL2", &one,  0, &status);
  fits_write_key(fptr, TINT,    "CDELT2", &one,  0, &status);
  fits_write_key(fptr, TINT,    "CRPIX2", &one,  0, &status);

  fits_write_key(fptr, TSTRING, "CTYPE3", "STOKES", "Correlator: -1=RR, -2=LL, -3=RL, -4=LR",&status);
  fits_write_key(fptr, TINT,    "CRVAL3", &header->stokes,  0, &status);
  fits_write_key(fptr, TINT,    "CDELT3", &header->delta_stokes, 0, &status);
  fits_write_key(fptr, TINT,    "CRPIX3", &one,       0, &status);

  fits_write_key(fptr, TSTRING, "CTYPE4", "FREQ","Frequency, Hz", &status);
  fits_write_key(fptr, TDOUBLE, "CRVAL4", &header->freq, 0, &status);
  fits_write_key(fptr, TDOUBLE, "CDELT4", &header->bw,   0, &status);
  fits_write_key(fptr, TINT,    "CRPIX4", &one,  0, &status);

  fits_write_key(fptr, TSTRING, "CTYPE5", "IF", "IF number",&status);
  fits_write_key(fptr, TINT,    "CRVAL5", &one, 0, &status);
  fits_write_key(fptr, TINT,    "CDELT5", &one, 0, &status);
  fits_write_key(fptr, TINT,    "CRPIX5", &one, 0, &status);

  fits_write_key(fptr, TSTRING, "CTYPE6", "RA", "Right ascension, degrees", &status);
  fits_write_key(fptr, TDOUBLE, "CRVAL6", &header->ra, 0, &status);
  fits_write_key(fptr, TINT,    "CDELT6", &zero, 0, &status);
  fits_write_key(fptr, TINT,    "CRPIX6", &one,  0, &status);

  fits_write_key(fptr, TSTRING, "CTYPE7", "DEC", "Declination, degrees", &status);
  fits_write_key(fptr, TDOUBLE, "CRVAL7", &header->dec, 0, &status);
  fits_write_key(fptr, TINT,    "CDELT7", &zero, 0, &status);
  fits_write_key(fptr, TINT,    "CRPIX7", &one,  0, &status);

  /* FITS random parameters. */

  fits_write_key(fptr, TSTRING, "PTYPE1", "UU", "baseline u projection, seconds", &status);
  fits_write_key(fptr, TINT,    "PSCAL1", &one,  0, &status);
  fits_write_key(fptr, TINT,    "PZERO1", &zero, 0, &status);
  fits_write_key(fptr, TSTRING, "PTYPE2", "VV", "baseline v projection, seconds", &status);
  fits_write_key(fptr, TINT,    "PSCAL2", &one,  0, &status);
  fits_write_key(fptr, TINT,    "PZERO2", &zero, 0, &status);
  fits_write_key(fptr, TSTRING, "PTYPE3", "WW", "baseline w projection, seconds", &status);
  fits_write_key(fptr, TINT,    "PSCAL3", &one,  0, &status);
  fits_write_key(fptr, TINT,    "PZERO3", &zero, 0, &status);

  fits_write_key(fptr, TSTRING, "PTYPE4", "BASELINE", "256*ANT1 + ANT2", &status);
  fits_write_key(fptr, TINT,    "PSCAL4", &one,  0, &status);
  fits_write_key(fptr, TINT,    "PZERO4", &zero, 0, &status);

  dfac1 = 1.0;
  dref1 = refdat + 2400000.5; /* convert MJD to JD */
  fits_write_key(fptr, TSTRING, "PTYPE5", "DATE", "UTC Julian Date part 1", &status);
  fits_write_key(fptr, TDOUBLE, "PSCAL5", &dfac1, "Days", &status);
  fits_write_key(fptr, TDOUBLE, "PZERO5", &dref1,  0, &status);
  
  dfac2 = 1.0/86400.0;
  dref2 = 0.0;
  fits_write_key(fptr, TSTRING, "PTYPE6", "DATE", "UTC Julian Date part 2", &status);
  fits_write_key(fptr, TDOUBLE, "PSCAL6", &dfac2, "Days/86400 (sec)", &status);
  fits_write_key(fptr, TFLOAT,  "PZERO6", &dref2, 0, &status);
  if (pcount >= 7) {
    fits_write_key(fptr, TSTRING, "PTYPE7", "INTTIM", "Integration time (sec)", &status);
    fits_write_key(fptr, TINT,   "PSCAL7", &one, 0, &status);
    fits_write_key(fptr, TINT,   "PZERO7", &zero, 0, &status);
  }

  sprintf(str, "%.12s (run by %.12s on %.12s)", origin, 
	  getenv("USER"), getenv("HOST"));
  fits_write_key(fptr, TSTRING, "ORIGIN", str," ", &status);

  /* Date/time of file creation */

  fits_write_date(fptr, &status);
  fits_report_error(stderr, status);
  return status;
}
Ejemplo n.º 10
0
 void write(const char *key, const char *val, const char *comment) {
     fits_write_key(fptr, TSTRING, const_cast<char *>(key), const_cast<char *>(val), const_cast<char *>(comment), status);
 }
Ejemplo n.º 11
0
 void write(const char *key, unsigned int val, const char *comment) {
     fits_write_key(fptr, TUINT, const_cast<char *>(key), &val, const_cast<char *>(comment), status);
 }
Ejemplo n.º 12
0
 void write(const char *key, float val, const char *comment) {
     fits_write_key(fptr, TFLOAT, const_cast<char *>(key), &val, const_cast<char *>(comment), status);
 }
/*******************************************************************************
 * gaussian_test
 * This function creates a fits table, then populates it with the mean, sigma,
 * and error on the mean from experiments sampling from a gaussian num_samples
 * number of times.
 * Input:
 *      fptr:           Fits file to write the table to
 *      num_iter:       Number of experiments to run
 *      num_samples:    Number of samples for each experiment
 *      mean:           Mean for the distibution in the experiments
 *      sigma:          Sigma for the distribution in the experiments
 * Output:
 *      status:         Fits error status
 ******************************************************************************/
void gaussian_test(fitsfile *fptr, long num_iter, long num_samples, double mean,
        double sigma, int *status){
    long nrows, i, num_sigma;
    double *stats, ratio_sigma, ave_mean, mean_sd, *all_means;
    /* Fits file columns */
    char *ttype[] = {"mean", "sigma", "error"};
    char *tform[] = {"D", "D", "D"};
    char *tunit[] = {NULL, NULL, NULL};
    char *key[] = {"NSAMPLES", "MEAN", "SIGMA", "MEANAVE", "MEANSD"};
    char *comment[] = {"Number of samples per iteration",
        "True mean of the gaussian",
        "True standard deviation of the gaussian",
        "Average mean",
        "Standard deviation of all means"};

    /* Create the fits table */
    fits_create_tbl(fptr, BINARY_TBL, 0, 3, ttype, tform, tunit, NULL, status);
    if (*status){
        printf("Error creating fits table in guassian_test.\n");
        exit(*status);
    }

    /* Get mean, sigma, and error, then save to a fits file */
    all_means = (double *) malloc(num_iter * sizeof(double));
    ave_mean = 0;
    for (nrows = 0; nrows < num_iter; nrows++){
        stats = sample_gauss(num_samples, mean, sigma);
        ave_mean += stats[0];
        all_means[nrows] = stats[0];
        /* Write to file */
        for (i=0; i < 3; i++){
            fits_write_col(fptr, TDOUBLE, i+1, nrows+1, 1L,1L, stats+i, status);
            if (*status){
                printf("Error writing to fits table in gaussian_test.\n");
                exit(1);
            }
        }
        free(stats); /* free memory for next iteration */
    }
    ave_mean /= num_iter;

    /* Get standard deviation of all means */
    mean_sd = 0;
    for (i=0; i<num_iter; i++)
        mean_sd += pow(ave_mean - all_means[i], 2);
    mean_sd /= num_iter - 1;
    mean_sd = sqrt(mean_sd);

    /* Get percentage of experiments within 2 sigma */
    num_sigma = 0;
    for (i=0; i<num_iter; i++){
        if (fabs(all_means[i] - ave_mean) < 2 * mean_sd)
            num_sigma++;
    }
    ratio_sigma = (double) num_sigma / num_iter;
    free(all_means);

    /* print some results */
    printf("Average mean: %g\n", ave_mean);
    printf("Sigma of all means: %g\n", mean_sd);
    printf("Percentage of experiments within 2 sigma: ");
    printf("%g%c\n", 100 * ratio_sigma, (char) 37);

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

#ifdef DEBUG      
      fprintf(stderr,"writing %ld rays to file '%s' took %g seconds.\n",NumRaysInFile,name,t0);
#endif
      
      assert(nwg == NumRaysInFile-nw); //error check # of rays recvd
    }
  
  //error check # of rays written
  MPI_Allreduce(&nw,&nwg,1,MPI_LONG,MPI_SUM,fileComm);
  assert(nw == nwc);
  assert(nwg == NumRaysInFile);
  
  //clean up and close files for this task
  free(buff);
  free(StartRaysInPeanoCell);
  free(NumRaysInPeanoCell);
}
Ejemplo n.º 15
0
static void write_data_to_file(pi16u * buf, struct metadata * md, char * prepend, lua_State *L)
{
	fitsfile *ff;
	int status = 0, retcode = 0;
	long naxes[2] = {2048, 2048};
	char outdir[STR_BUF_SIZE];
	char outfile[STR_BUF_SIZE];
	float bscale1 = 1.0, bzero32768 = 32768.0;
	SYSTEMTIME str_t;

	/* Create output directory */
	GetLocalTime(&str_t);
	
	sprintf_s(outdir, STR_BUF_SIZE, "%s\\%4d%s%2d", path_prefix,
		str_t.wYear, months[str_t.wMonth], str_t.wDay);

	if(!DirectoryExists((LPCTSTR) outdir)) {
		printf("Creating directory %s\n", outdir);
		
		if(!mkdir(outdir)) {
			lua_pushstring(L,"Could not create path\n");
			lua_error(L);
			return;
		}
	}


	sprintf_s(outfile, STR_BUF_SIZE, "!%s\\%s%4.4d%2.2d%2.2d_%2.2i_%2.2i_%2.2i.fits", outdir, prepend, 
		str_t.wYear, str_t.wMonth, str_t.wDay, str_t.wHour, str_t.wMinute, str_t.wSecond);

	/* FITS housekeeping */
	retcode = fits_create_file(&ff, outfile, &status);

	if(retcode) {
		lua_pushstring(L,"Could not create FITS file\n");
		fits_report_error(stderr, status);
		lua_error(L);
		return;
	}


	retcode = fits_create_img(ff, 
		SHORT_IMG , // bitpix
		2, // naxis
		naxes, // naxes
		&status);
	if(retcode) {
		lua_pushstring(L,"Could not create image \n");
		fits_report_error(stderr, status);
		lua_error(L);
		fits_close_file(ff, &status);
		return;
	}
		
	// Following line is required to handle ushort, see:
	// "Support for Unsigned Integers and Signed Bytes" in
	// cfitsio manual
	fits_write_key(ff, TFLOAT, "BSCALE", &bscale1, NULL, &status);
	fits_write_key(ff, TFLOAT, "BZERO", &bzero32768, NULL, &status);
	fits_set_bscale(ff, 1, //BSCALE Factor
						32768, // BZERO factor
						&status); 

	fits_write_key(ff, TDOUBLE, "EXPTIME", &md->exptime, "Exposure time in s", &status);
	fits_write_key(ff, TDOUBLE, "ADCSPEED", &md->adcspeed, "Readout speed in MHz", &status);
	fits_write_key(ff, TDOUBLE, "TEMP", &md->temp, "Detector temp in deg C", &status);
	fits_write_key(ff, TINT, "BITDEPTH", &md->bitdepth, "Bit depth", &status);
	fits_write_key(ff, TINT, "GAIN_SET", &md->gain, "1: low, 2: medium, 3: high gain", &status);
	fits_write_key(ff, TINT, "ADC", &md->adc, "1: Low noise, 2: high capacity",  &status);
	fits_write_key(ff, TINT, "MODEL", &md->id->model, "PI Model #", &status);
	fits_write_key(ff, TINT, "INTERFC", &md->id->computer_interface, "PI Computer Interface", &status);
	fits_write_key(ff, TSTRING, "SNSR_NM", &md->id->sensor_name, "PI sensor name", &status);
	fits_write_key(ff, TSTRING, "SER_NO", &md->id->serial_number, "PI serial #", &status);


	retcode = fits_write_img(ff,
		TUSHORT, // (T)ype is unsigned short (USHORT)
		1, // Copy from [0, 0] but fits format is indexed by 1
		naxes[0] * naxes[1], // Number of elements
		buf,
		&status);
	if(retcode && status==412) {
		printf("Overflow\n");
	} else if(retcode) {
		lua_pushstring(L,"Could not copy data over \n");
		fits_report_error(stderr, status);
		lua_error(L);
		fits_close_file(ff, &status);
		return;
	}


	fits_close_file(ff, &status);
	printf("Wrote '%s'.\n", outfile);
}
Ejemplo n.º 16
0
int WrtPSRFITSHdr(struct    ASPHdr *hdr,
	          fitsfile  *Fout)
{
  int     status=0, ival, i, ii, colnum, indx, retval=-1;
  double  ra_hr, ra_min, ra_sec, dec_deg, dec_min, dec_sec;
  // char    *tunit[4*NCHMAX+10], *tform[4*NCHMAX+10], *ttype[4*NCHMAX+10];
  char    junkch1[2048], junkch2[2048], junkch3[2048];
  time_t  cur_time;
  struct tm *utctime;

  //  junkch1   = (char *) calloc(20, sizeof(char));


  /*     ival = 1; fits_update_key(Fout, TLOGICAL, "SIMPLE", &ival, NULL, &status); status = 0;
	 ival = 32; fits_update_key(Fout, TINT, "BITPIX", &ival, "FITS COMPATIBLE", &status); status = 0;
	 ival = 0; fits_update_key(Fout, TINT, "NAXIS", &ival, "FITS COMPATIBLE", &status); status = 0;     */

  /* Fill in primary header with current header variables, and change what 
     is needed */

  /* Create primary header */
  
  if(fits_create_img(Fout, 8, 0, NULL, &status)  != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot create primary table.\n");
    return -1;
  }


  /* Start adding keywords */

  /* Header version */
  sprintf(junkch1, "5.0");
  if(fits_write_key(Fout, TSTRING, "HDRVER", junkch1, "Header version", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword HDRVER.\n");
    return -1;
  }
 
  /* Type of FITS file */
  sprintf(dummy_txt, "PSRFITS");
  if(fits_write_key(Fout, TSTRING, "FITSTYPE", junkch1, "FITS definition for pulsar data files", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword FITSTYPE.\n");
    return -1;
  }
  
  /* File creation date (YYYY-MM-DDThh:mm:ss UTC) */ 
  /* Get current time */
  curtime = time(NULL);
  /* Convert time to gmtine representation */
  utctime = gmtime(&curtime);
  /* String it up */
  strftime(junkch1, 256, "%Y-%m-%dT%H:%M:%S");
  //  sprintf(junkch1, "%sT%s", hdr->filecont.FileDate, hdr->filecont.FileUT);
  if(fits_write_key(Fout, TSTRING, "DATE", junkch1, "File creation date (YYYY-MM-DDThh:mm:ss UTC)", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword DATE.\n");
    return -1;
  }
  
  /* Observer name */
  if(fits_write_key(Fout, TSTRING, "OBSERVER", hdr->gen.Observer, "Observer name(s)", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword OBSERVER.\n");
    return -1;
  }

/* Project ID */
  if(fits_write_key(Fout, TSTRING, "PROJID", hdr->gen.ProjID, "Project name", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword PROJID.\n");
    return -1;
  } 

  /* Telescope identifier */
  if(fits_write_key(Fout, TSTRING, "TELESCOP", hdr->obs.ObsvtyCode, "Telescope name", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword TELESCOP.\n");
    return -1;
  }
 
/* Antenna ITRF X, Y, and Z coordinates */
  if(fits_write_key(Fout, TDOUBLE, "ANT_X", &hdr->target.Ant_X, "Antenna ITRF X-coordinate", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword ANT_X.\n");
    return -1;
  }
  if(fits_write_key_unit(Fout, "ANT_X", "m", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write units for keyword ANT_X.\n");
    return -1;
  }

  if(fits_write_key(Fout, TDOUBLE, "ANT_Y", &hdr->target.Ant_Y, "Antenna ITRF Y-coordinate", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword ANT_Y.\n");
    return -1;
  }
  if(fits_write_key_unit(Fout, "ANT_Y", "m", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write units for keyword ANT_Y.\n");
    return -1;
  }

  if(fits_write_key(Fout, TDOUBLE, "ANT_Z", &hdr->target.Ant_Z, "Antenna ITRF Z-coordinate", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword ANT_Z.\n");
    return -1;
  }
  if(fits_write_key_unit(Fout, "ANT_Z", "m", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write units for keyword ANT_Z.\n");
    return -1;
  }


/* Frontend name GREG/CH etc */
  if(fits_write_key(Fout, TSTRING, "FRONTEND", hdr->gen.FEName, "Receiver ID", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword FRONTEND.\n");
    return -1;
  }

/* Beam ID for multiple-beam systems */
  if(fits_write_key(Fout, TSTRING, "IBEAM", hdr->gen.IBeam, "Beam ID for multibeam systems", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword IBEAM.\n");
    return -1;
  }
  
/* Number of receiver polarisation channels */
  if(fits_write_key(Fout, TSTRING, "NRCVR", hdr->gen.NRcvr, "Number of receiver polarisation channels", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword NRCVR.\n");    
    return -1;
  } 

/* Polarisation type CIRC/LIN */
  if (!strncmp(hdr->gen.FEPol, "L", 1))
    strcpy(junkch1, "LIN");
  else if (!strncmp(hdr->gen.FEPol, "C", 1))
    strcpy(junkch1, "CIRC");
  else {
    fprintf(stderr,"WrtPSRFITSHdr ERROR: Unrecognized polarization basis %s\n",
	    hdr->gen.FEPol);
    return -1;
  }
  if(fits_write_key(Fout, TSTRING, "FD_POLN", hdr->gen.FEPol, "Polarisation type CIRC/LIN", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword FD_POLN.\n");    
    return -1;  
  } 


/* A/B polarization swap -- +/- 1.  +1 is LIN: A=X, B=Y, CIRC:A=L, B=R */
  if(fits_write_key(Fout, TINT, "FD_HAND", &hdr->gen.FDHand, "+/- 1.  +1 is LIN: A=X, B=Y, CIRC:A=L, B=R", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword FD_HAND.\n");    
    return -1;
  }
/* FA of E vector for equal sig in A&B */
  if(fits_write_key(Fout, TFLOAT, "FD_SANG", &hdr->gen.FDSang, "FA of E vector for equal sig in A&B", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword FD_SANG.\n");   
    return -1; 
  }
  if(fits_write_key_unit(Fout, "FD_SANG", "deg", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write units for keyword FD_SANG.\n");
    return -1;
  }

/* Phase of A*B for injected cal */ 
  if(fits_write_key(Fout, TFLOAT, "FD_XYPH", &hdr->gen.FDXYph, "Phase of A^* B for injected cal", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword FD_XYPH.\n");   
    return -1;
  }
  if(fits_write_key_unit(Fout, "FD_XYPH", "deg", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write units for keyword FD_XYPH.\n");
    return -1;
  }


  /* Name of backend instrument used */
  if(fits_write_key(Fout, TSTRING, "BACKEND", hdr->gen.BEName, "Backend ID", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword BACKEND.\n");
    return -1;
  }

/* Backend Config filename */
  if(fits_write_key(Fout, TSTRING, "BECONFIG", hdr->gen.BEConfFile, "Backend configuration file name", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword BECONFIG.\n");
    return -1;
  }
  
/* 0/+1/-1 BE cross-phase: 0 unknown, +/-1 std/rev */
  if(fits_write_key(Fout, TINT, "BE_PHASE", &hdr->gen.BEPhase, "0/+1/-1 BE cross-phase: 0 unknown, +/-1 std/rev", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword BE_PHASE.\n");
    return -1;
  }

/* 0/1 BE downconversion conjugation */
  if(fits_write_key(Fout, TINT, "BE_DCC", &hdr->gen.BEDownConv, "0/1 BE downconversion conjugation", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword BE_DCC.\n");
    return -1;
  } 

/* Backend propn delay from digitiser in seconds */
  if(fits_write_key(Fout, TFLOAT, "BE_DELAY", &hdr->gen.BEDelay, "Backend propn delay from digitiser in seconds", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword BE_DELAY.\n");
    return -1;
  }
  if(fits_write_key_unit(Fout, "BE_DELAY", "s", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write units for keyword BE_DELAY.\n");
    return -1;
  }

/* On-line cycle time */
  if(fits_write_key(Fout, TDOUBLE, "TCYCLE", &hdr->gen.TCycle, "On-line cycle time", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword TCYCLE.\n");
    return -1;
  }
  if(fits_write_key_unit(Fout, "TCYCLE", "s", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write units for keyword TCYCLE.\n");
    return -1;
  }

  /* Mode of observing (usually PSR or CAL) */
  if(fits_write_key(Fout, TSTRING, "OBS_MODE", hdr->gen.ObsMode, "", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword OBS_MODE.\n");
    return -1;
  }

/* Date of observation (YYYY-MM-DDThh:mm:ss UTC) */ 
  sprintf(junkch1, "%sT%s", hdr->obs.StartDate, hdr->obs.StartUT);
  if(fits_write_key(Fout, TSTRING, "DATE-OBS", tempstr1, "Date of observation (YYYY-MM-DDThh:mm:ss UTC)", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword DATE-OBS.\n");
    return -1;
  }

   /* Centre observing frequency */
  if(fits_write_key(Fout, TDOUBLE, "OBSFREQ", hdr->obs.FSkyCent, "Centre frequency for observation", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword OBSFREQ.\n");
    return -1;
  }
  if(fits_write_key_unit(Fout, "OBSFREQ", "MHz", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write units for keyword OBSFREQ.\n");
    return -1;
  }

  /* Bandwidth for observation [MHz] */
  /* Multiply by Sideband to get it in proper format for psrfits definition */
  hdr->obs.BW *= (double)hdr->obs.Sideband;
  if(fits_write_key(Fout, TDOUBLE, "OBSBW", &hdr->obs.BW, "Bandwidth for observation", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword OBSBW.\n");
    return -1;
  }
  if(fits_write_key_unit(Fout, "OBSBW", "MHz", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write units for keyword OBSBW.\n");
    return -1;
  }

/* Number of frequency channels (original number) */
  if(fits_write_key(Fout, TINT, "OBSNCHAN", &hdr->obs.NChanOrig, "Number of frequency channels (original number)", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword OBSNCHAN.\n");
    return -1;
  }


  /* DM used for online dedispaersion [cm-3 pc] */
  if(fits_write_key(Fout, TDOUBLE, "CHAN_DM", &hdr->obs.ChanDM, "DM used for online dedispaersion", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword CHAN_DM.\n");
    return -1;
  } 
  if(fits_write_key_unit(Fout, "CHAN_DM", "cm-3 pc", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write units for keyword CHAN_DM.\n");
    return -1;
  }
 
  
  /* Name or ID for pointing centre (multibeam feeds) */
  if(fits_write_key(Fout, TSTRING, "PNT_ID", hdr->gen.PntID, "Name or ID for pointing centre (multibeam feeds)", &status) != 0){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword PNT_ID.\n");
    return -1;
  }
  
  
  /* Pulsar or source name */
  if(fits_write_key(Fout, TSTRING, "SRC_NAME", hdr->target.PSRName, "Source or scan ID", &status) != 0) {
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword SRC_NAME.\n");
    return -1;
  }
  
  /*===========================================*/

/* Coordinate mode for following 4 entries  J2000/GAL/ECLIPTIC/AZEL etc. */
if(fits_write_key(Fout, TSTRING, "COORD_MD", hdr->target.CoordMode, "Coordinate mode (J2000/GAL/ECLIPTIC/AZEL etc.)", &status) !=0 ){
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword COORD_MD.\n");
    return -1;
 }

/* Epoch of the coordinates */
/* Read in as string and convert depending on PSRFITS version */
  if(fits_write_key(Fout, TFLOAT, "EQUINOX", &hdr->target.Epoch, "Epoch of the coordinates", &status) !=0 ){ 
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword EQUINOX.\n");
    return -1; 
  }
 
/* Right Assention hh:mm:ss.sss */
  ra_hr = floor(hdr->target.RA);
  ra_min = floor((hdr->target.RA - ra_hr)*60.);
  ra_sec = ((hdr->target.RA - ra_hr)*60. - ra_min) * 60.;
  sprintf(junkch1, "%2d:%2d:%lf", (int)ra_hr, (int)ra_min, ra_sec);
  if(fits_write_key(Fout, TSTRING, "RA", junkch1, "Right Assention (hh:mm:ss.sss)", &status) !=0 ){ 
    fprintf(stderr, "WrtPSRFITSHdr ERROR: Cannot write keyword RA.\n");
    return -1;
  }

/* Declination -dd:mm:ss.sss */
  dec_deg = floor(hdr->target.Dec);
  dec_min = floor((hdr->target.Dec - dec_deg)*60.);
  dec_sec = ((hdr->target.Dec - dec_deg)*60. - dec_min) * 60.;
  if(hdr->target.Dec < 0): 
    sprintf(junkch1, "-%2d:%2d:%lf", (int)dec_deg, (int)dec_min, dec_sec);
  else
Ejemplo n.º 17
0
int append_image_FITS(void *image,SID_Datatype dtype,int n_D,int *D_in,const char *filename,const char *ext_name){
  fitsfile *fp;
  FILE     *fp_test;
  int   naxis=2;
  int   fpixel=1;
  int   anynull;
  int   i,j;
  long  naxes[2];
  long *D;
  char  keyname[50];
  char  error_msg[80];
  int   status=0;
  long  n_pixels=1;
  int   i_D;
  int   bit_pix;

  // Fits files store data in FORTRAN order, so we need to perform a transpose
  transpose_array(image,dtype,n_D,D_in);

  // Convert the array dimensions to a type-long array
  D=(long *)SID_malloc(sizeof(long)*n_D);
  for(i_D=0;i_D<n_D;i_D++)
    D[i_D]=(long)(D_in[i_D]);

  // Open the file
  fits_open_file(&fp,filename,1,&status);
  if(status){
    ffgmsg(error_msg);
    SID_trap_error("FITS open file: filename={%s} status=%d message={%s}",ERROR_IO_OPEN,filename,status,error_msg);
  }

  // Count the number of pixels
  for(i_D=0;i_D<n_D;i_D++)
    n_pixels*=D[i_D];

  // Creeate FLOAT image
  if(dtype==SID_FLOAT){
    fits_create_img(fp,FLOAT_IMG,n_D,D,&status);
    if(status){
      ffgmsg(error_msg);
      SID_trap_error("FITS create image: filename={%s} status=%d message={%s}",ERROR_IO_OPEN,filename,status,error_msg);
    }
    fits_write_img(fp,TFLOAT,fpixel,n_pixels,image,&status);
    if(status){
      ffgmsg(error_msg);
      SID_trap_error("FITS write image: filename={%s} status=%d message={%s}",ERROR_IO_OPEN,filename,status,error_msg);
    }
    bit_pix=FLOAT_IMG;
  }
  // Creeate FLOAT image
  else if(dtype==SID_DOUBLE){
    fits_create_img(fp,DOUBLE_IMG,n_D,D,&status);
    if(status){
      ffgmsg(error_msg);
      SID_trap_error("FITS create image: filename={%s} status=%d message={%s}",ERROR_IO_OPEN,filename,status,error_msg);
    }
    fits_write_img(fp,TDOUBLE,fpixel,n_pixels,image,&status);
    if(status){
      ffgmsg(error_msg);
      SID_trap_error("FITS write image: filename={%s} status=%d message={%s}",ERROR_IO_OPEN,filename,status,error_msg);
    }
    bit_pix=DOUBLE_IMG;
  }
  // Creeate INTEGER image
  else if(dtype==SID_INT){
    fits_create_img(fp,LONG_IMG,n_D,D,&status);
    if(status){
      ffgmsg(error_msg);
      SID_trap_error("FITS create image: filename={%s} status=%d message={%s}",ERROR_IO_OPEN,filename,status,error_msg);
    }
    fits_write_img(fp,TINT,fpixel,n_pixels,image,&status);
    if(status){
      ffgmsg(error_msg);
      SID_trap_error("FITS write image: filename={%s} status=%d message={%s}",ERROR_IO_OPEN,filename,status,error_msg);
    }
    bit_pix=LONG_IMG;
  }

  // Throw error if the given dtype is not supported
  else
    SID_trap_error("Unsupported datatype in write_image_FITS",ERROR_LOGIC);

  // Set extension name
  if(ext_name!=NULL)
    fits_write_key(fp,TSTRING,"EXTNAME",(void *)ext_name,NULL,&status);

  // Close the file
  fits_close_file(fp,&status);

  // Fits files store data in FORTRAN order, so we need to perform a transpose
  transpose_array(image,dtype,n_D,D_in);

  SID_free(SID_FARG D);

  return(status);
}
Ejemplo n.º 18
0
void 
write4Dfits(int im, int unit_index, configInfo *par, imageInfo *img){
  /*
Users have complained that downstream packages (produced by lazy coders >:8) will not deal with FITS cubes having less that 4 axes. Thus all LIME output images are now sent to the present function.
  */
  const int numAxes=4;
  double bscale,bzero,epoch,lonpole,equinox,restfreq;
  int axesOrder[] = {0,1,2,3};
  char ctype[numAxes][9],cunit[numAxes][9];
  double crpix[numAxes],crval[numAxes];
  float cdelt[numAxes];
  double ru3,scale=1.0;
  int velref,unitI,i;
  float *row;
  int px,py,ichan;
  fitsfile *fptr;
  int status = 0;
  int naxis=numAxes, bitpix=-32;
  long naxes[numAxes];
  long int fpixels[numAxes],lpixels[numAxes];
  char negfile[100]="! ",message[STR_LEN_0];
  unsigned long ppi;

  unitI = img[im].imgunits[unit_index];
  row = malloc(sizeof(*row)*img[im].pxls);

  naxes[axesOrder[0]] = img[im].pxls;
  naxes[axesOrder[1]] = img[im].pxls;

  if(img[im].doline)
    naxes[axesOrder[2]] = img[im].nchan;
  else
    naxes[axesOrder[2]] = 1; /* In this case nchan can =3, the number of active Stokes parameters, if the dust is polarized. */

  if(!img[im].doline && par->polarization)
    naxes[axesOrder[3]]=4;
  else
    naxes[axesOrder[3]]=1;

  fits_create_file(&fptr, img[im].filename, &status);

  if(status!=0){
    if(!silent) warning("Overwriting existing fits file                   ");
    status=0;
    strcat(negfile,img[im].filename);
    fits_create_file(&fptr, negfile, &status);
  }

  /* Write FITS header */ 
  fits_create_img(fptr, bitpix, naxis, naxes, &status);
  epoch   =2.0e3;
  lonpole =1.8e2;
  equinox =2.0e3;
  restfreq=img[im].freq;
  velref  =257;

  sprintf(ctype[axesOrder[0]], "RA---SIN");
  cdelt[axesOrder[0]] = -1.8e2*(float)(img[im].imgres/M_PI);
  crpix[axesOrder[0]] = ((double)img[im].pxls)/2.0 + 0.5;
  crval[axesOrder[0]] = 0.0e0;
  sprintf(cunit[axesOrder[0]], "DEG    ");

  sprintf(ctype[axesOrder[1]], "DEC--SIN");
  cdelt[axesOrder[1]] = 1.8e2*(float)(img[im].imgres/M_PI);
  crpix[axesOrder[1]] = ((double)img[im].pxls)/2.0 + 0.5;
  crval[axesOrder[1]] = 0.0e0;
  sprintf(cunit[axesOrder[1]], "DEG    ");

  sprintf(ctype[axesOrder[2]], "VELO-LSR");
  if(img[im].doline)
    cdelt[axesOrder[2]] = (float)img[im].velres;
  else
    cdelt[axesOrder[2]] = 1.0;
  crpix[axesOrder[2]] = (double) (naxes[axesOrder[2]]-1)/2.+1;
  crval[axesOrder[2]] = 0.0e0;
  sprintf(cunit[axesOrder[2]], "M/S    ");

  sprintf(ctype[axesOrder[3]], "STOKES  ");
  cdelt[axesOrder[3]] = 1.0;
  crpix[axesOrder[3]] = (double) (naxes[axesOrder[3]]-1)/2.+1;
  crval[axesOrder[3]] = 1.0e0;
  sprintf(cunit[axesOrder[3]], "       ");

  bscale  =1.0e0;
  bzero   =0.0e0;

  fits_write_key(fptr, TSTRING, "OBJECT  ", &"LIMEMDL ",    "", &status);
  fits_write_key(fptr, TDOUBLE, "EPOCH   ", &epoch,         "", &status);
  fits_write_key(fptr, TDOUBLE, "LONPOLE ", &lonpole,       "", &status);
  fits_write_key(fptr, TDOUBLE, "EQUINOX ", &equinox,       "", &status);
  fits_write_key(fptr, TSTRING, "SPECSYS ", &"LSRK    ",    "", &status);
  fits_write_key(fptr, TDOUBLE, "RESTFREQ", &restfreq,      "", &status);
  fits_write_key(fptr, TINT,    "VELREF  ", &velref,        "", &status);

  for(i=0;i<numAxes;i++)
    writeWCS(fptr, i, axesOrder, cdelt, crpix, crval, ctype, cunit);

  fits_write_key(fptr, TDOUBLE, "BSCALE  ", &bscale,        "", &status);
  fits_write_key(fptr, TDOUBLE, "BZERO   ", &bzero,         "", &status);

  if(unitI==0) fits_write_key(fptr, TSTRING, "BUNIT", &"K       ", "", &status);
  if(unitI==1) fits_write_key(fptr, TSTRING, "BUNIT", &"JY/PIXEL", "", &status);
  if(unitI==2) fits_write_key(fptr, TSTRING, "BUNIT", &"WM2HZSR ", "", &status);
  if(unitI==3) fits_write_key(fptr, TSTRING, "BUNIT", &"Lsun/PX ", "", &status);
  if(unitI==4) fits_write_key(fptr, TSTRING, "BUNIT", &"        ", "", &status);

  if(     unitI==0)
    scale=0.5*(CLIGHT/img[im].freq)*(CLIGHT/img[im].freq)/KBOLTZ;
  else if(unitI==1)
    scale=1e26*img[im].imgres*img[im].imgres;
  else if(unitI==2)
    scale=1.0;
  else if(unitI==3) {
    ru3 = img[im].distance/1.975e13;
    scale=4.*M_PI*ru3*ru3*img[im].freq*img[im].imgres*img[im].imgres;
  }
  else if(unitI!=4) {
    if(!silent) bail_out("Image unit number invalid");
    exit(0);
  }

  /* Write FITS data */
  if(img[im].doline){
    for(ichan=0;ichan<img[im].nchan;ichan++){
      for(py=0;py<img[im].pxls;py++){
        for(px=0;px<img[im].pxls;px++){
          ppi = py*img[im].pxls + px;

          if(unitI>-1 && unitI<4)
            row[px]=(float) img[im].pixel[ppi].intense[ichan]*scale;
          else if(unitI==4)
            row[px]=(float) img[im].pixel[ppi].tau[ichan];
          else {
            if(!silent) bail_out("Image unit number invalid");
            exit(0);
          }
          if (fabs(row[px])<IMG_MIN_ALLOWED) row[px]=IMG_MIN_ALLOWED;
        }
        fpixels[axesOrder[0]] = 1;
        fpixels[axesOrder[1]] = py+1;
        fpixels[axesOrder[2]] = ichan+1;
        fpixels[axesOrder[3]] = 1;
        lpixels[axesOrder[0]] = img[im].pxls;
        lpixels[axesOrder[1]] = py+1;
        lpixels[axesOrder[2]] = ichan+1;
        lpixels[axesOrder[3]] = 1;
        fits_write_subset(fptr, TFLOAT, fpixels, lpixels, row, &status);
      }
    }
  }else{
    for(ichan=0;ichan<img[im].nchan;ichan++){
      for(py=0;py<img[im].pxls;py++){
        for(px=0;px<img[im].pxls;px++){
          ppi = py*img[im].pxls + px;

          if(unitI>-1 && unitI<4)
            row[px]=(float) img[im].pixel[ppi].intense[ichan]*scale;
          else if(unitI==4)
            row[px]=(float) img[im].pixel[ppi].tau[ichan];
          else {
            if(!silent) bail_out("Image unit number invalid");
            exit(0);
          }
          if (fabs(row[px])<IMG_MIN_ALLOWED) row[px]=IMG_MIN_ALLOWED;
        }
        fpixels[axesOrder[0]] = 1;
        fpixels[axesOrder[1]] = py+1;
        fpixels[axesOrder[3]] = ichan+1;
        fpixels[axesOrder[2]] = 1;
        lpixels[axesOrder[0]] = img[im].pxls;
        lpixels[axesOrder[1]] = py+1;
        lpixels[axesOrder[3]] = ichan+1;
        lpixels[axesOrder[2]] = 1;
        fits_write_subset(fptr, TFLOAT, fpixels, lpixels, row, &status);
      }
    }

    if(par->polarization){ /* ichan should have run from 0 to 2 in this case. Stokes I, Q and U but no V. Load zeros into the last pol channel: */
      if(img[im].nchan!=3){
        if(!silent){
          sprintf(message, "%d pol channels found but %d expected.", img[im].nchan, 3);
          bail_out(message);
        }
exit(1);
      }
      ichan = 3;
      for(px=0;px<img[im].pxls;px++)
        row[px] = IMG_MIN_ALLOWED;
      for(py=0;py<img[im].pxls;py++){
        fpixels[axesOrder[0]] = 1;
        fpixels[axesOrder[1]] = py+1;
        fpixels[axesOrder[3]] = ichan+1;
        fpixels[axesOrder[2]] = 1;
        lpixels[axesOrder[0]] = img[im].pxls;
        lpixels[axesOrder[1]] = py+1;
        lpixels[axesOrder[3]] = ichan+1;
        lpixels[axesOrder[2]] = 1;
        fits_write_subset(fptr, TFLOAT, fpixels, lpixels, row, &status);
      }
    }
  }

  fits_close_file(fptr, &status);

  free(row);
}
Ejemplo n.º 19
0
int HPXhdr(fitsfile *fptr, struct healpix *hpxdat)

{
  char   comment[64], cval[16], *ctype1, *ctype2, *descr1, *descr2, *pcode;
  int    status;
  float  cos45, crpix1, crpix2, crval1, crval2, lonpole;
  double cdelt1, cdelt2;

  status = 0;

  fits_update_key_log(fptr, "EXTEND", 0,
    "No FITS extensions are present", &status);
  fits_write_date(fptr, &status);

  /* Set pixel transformation parameters. */
  if (hpxdat->layout == 0) {
    crpix1 = (5 * hpxdat->nside + 1) / 2.0f;
  } else {
    crpix1 = (4 * hpxdat->nside + 1) / 2.0f;
  }
  crpix2 = crpix1;

  fits_write_key(fptr, TFLOAT, "CRPIX1", &crpix1,
    "Coordinate reference pixel", &status);
  fits_write_key(fptr, TFLOAT, "CRPIX2", &crpix2,
    "Coordinate reference pixel", &status);

  cos45 = (float)sqrt(2.0) / 2.0f;
  if (hpxdat->layout == 0) {
    fits_write_key_flt(fptr, "PC1_1",  cos45, -8,
      "Transformation matrix element", &status);
    fits_write_key_flt(fptr, "PC1_2",  cos45, -8,
      "Transformation matrix element", &status);
    fits_write_key_flt(fptr, "PC2_1", -cos45, -8,
      "Transformation matrix element", &status);
    fits_write_key_flt(fptr, "PC2_2",  cos45, -8,
      "Transformation matrix element", &status);
  }

  cdelt1 = -90.0 / hpxdat->nside / sqrt(2.0);
  cdelt2 = -cdelt1;
  fits_write_key_dbl(fptr, "CDELT1", cdelt1, -8,
    "[deg] Coordinate increment", &status);
  fits_write_key_dbl(fptr, "CDELT2", cdelt2, -8,
    "[deg] Coordinate increment", &status);


  /* Celestial transformation parameters. */
  if (hpxdat->layout == 0) {
    pcode = "HPX";
  } else {
    pcode = "XPH";
  }

  if (hpxdat->crdsys == 'G') {
    /* Galactic. */
    ctype1 = "GLON";
    ctype2 = "GLAT";
    descr1 = "Galactic longitude";
    descr2 = "Galactic  latitude";
  } else if (hpxdat->crdsys == 'E') {
    /* Ecliptic, who-knows-what. */
    ctype1 = "ELON";
    ctype2 = "ELAT";
    descr1 = "Ecliptic longitude";
    descr2 = "Ecliptic  latitude";
  } else if (hpxdat->crdsys == 'Q') {
    /* Equatorial, who-knows-what. */
    ctype1 = "RA--";
    ctype2 = "DEC-";
    descr1 = "Right ascension";
    descr2 = "Declination";
  } else {
    /* Unknown. */
    ctype1 = "XLON";
    ctype2 = "XLAT";
    descr1 = "Longitude";
    descr2 = " Latitude";
  }

  sprintf(cval, "%s-%s", ctype1, pcode);
  sprintf(comment, "%s in an %s projection", descr1, pcode);
  fits_write_key_str(fptr, "CTYPE1", cval, comment, &status);
  sprintf(cval, "%s-%s", ctype2, pcode);
  sprintf(comment, "%s in an %s projection", descr2, pcode);
  fits_write_key_str(fptr, "CTYPE2", cval, comment, &status);


  crval1 = 0.0f + 90.0f * hpxdat->quad;
  if (hpxdat->layout == 0) {
    crval2 =   0.0f;
  } else if (hpxdat->layout == 1) {
    crval1 += 180.0f;
    crval2  =  90.0f;
  } else {
    crval1 += 180.0f;
    crval2  = -90.0f;
  }
  if (360.0f < crval1) crval1 -= 360.0f;

  sprintf(comment, "[deg] %s at the reference point", descr1);
  fits_write_key(fptr, TFLOAT, "CRVAL1", &crval1, comment, &status);
  sprintf(comment, "[deg] %s at the reference point", descr2);
  fits_write_key(fptr, TFLOAT, "CRVAL2", &crval2, comment, &status);

  if (hpxdat->layout) {
    lonpole = 180.0f;
    sprintf(comment, "[deg] Native longitude of the celestial pole");
    fits_write_key(fptr, TFLOAT, "LONPOLE", &lonpole, comment, &status);
  }

  if (hpxdat->layout == 0) {
    fits_write_key_lng(fptr, "PV2_1", (LONGLONG)4,
      "HPX H parameter (longitude)", &status);
    fits_write_key_lng(fptr, "PV2_2", (LONGLONG)3,
      "HPX K parameter  (latitude)", &status);
  }

  /* Commentary. */
  fits_write_record(fptr, " ", &status);
  if (hpxdat->layout == 0) {
    fits_write_comment(fptr,
      "Celestial map with FITS-standard HPX coordinate system generated by",
      &status);
  } else {
    fits_write_comment(fptr,
      "Celestial map with XPH coordinate system (polar HPX) generated by",
      &status);
  }

  fits_write_comment(fptr,
    "'HPXcvt' which reorganises HEALPix data without interpolation as",
    &status);
  fits_write_comment(fptr,
    "described in \"Mapping on the HEALPix grid\" by Mark Calabretta and",
    &status);
  fits_write_comment(fptr,
    "Boud Roukema.  See http://www.atnf.csiro.au/people/Mark.Calabretta",
    &status);

  return status;
}
Ejemplo n.º 20
0
int	ngp_read_xtension(fitsfile *ff, int parent_hn, int simple_mode)
 { int		r, exflg, l, my_hn, tmp0, incrementor_index, i, j;
   int		ngph_dim, ngph_bitpix, ngph_node_type, my_version;
   char		incrementor_name[NGP_MAX_STRING], ngph_ctmp;
   char 	*ngph_extname = 0;
   long		ngph_size[NGP_MAX_ARRAY_DIM];
   NGP_HDU	ngph;
   long		lv;

   incrementor_name[0] = 0;			/* signal no keyword+'#' found yet */
   incrementor_index = 0;

   if (NGP_OK != (r = ngp_hdu_init(&ngph))) return(r);

   if (NGP_OK != (r = ngp_read_line(0))) return(r);	/* EOF always means error here */
   switch (NGP_XTENSION_SIMPLE & simple_mode)
     {
       case 0:  if (NGP_TOKEN_XTENSION != ngp_keyidx) return(NGP_TOKEN_NOT_EXPECT);
		break;
       default:	if (NGP_TOKEN_SIMPLE != ngp_keyidx) return(NGP_TOKEN_NOT_EXPECT);
		break;
     }
       	
   if (NGP_OK != (r = ngp_hdu_insert_token(&ngph, &ngp_linkey))) return(r);

   for (;;)
    { if (NGP_OK != (r = ngp_read_line(0))) return(r);	/* EOF always means error here */
      exflg = 0;
      switch (ngp_keyidx)
       { 
	 case NGP_TOKEN_SIMPLE:
	 		r = NGP_TOKEN_NOT_EXPECT;
			break;
	 		                        
	 case NGP_TOKEN_END:
         case NGP_TOKEN_XTENSION:
         case NGP_TOKEN_GROUP:
         		r = ngp_unread_line();	/* WARNING - not break here .... */
         case NGP_TOKEN_EOF:
			exflg = 1;
 			break;

         default:	l = strlen(ngp_linkey.name);
			if ((l >= 2) && (l <= 6))
			  { if ('#' == ngp_linkey.name[l - 1])
			      { if (0 == incrementor_name[0])
			          { memcpy(incrementor_name, ngp_linkey.name, l - 1);
			            incrementor_name[l - 1] = 0;
			          }
			        if (((l - 1) == (int)strlen(incrementor_name)) && (0 == memcmp(incrementor_name, ngp_linkey.name, l - 1)))
			          { incrementor_index++;
			          }
			        sprintf(ngp_linkey.name + l - 1, "%d", incrementor_index);
			      }
			  }
			r = ngp_hdu_insert_token(&ngph, &ngp_linkey);
 			break;
       }
      if ((NGP_OK != r) || exflg) break;
    }

   if (NGP_OK == r)
     { 				/* we should scan keywords, and calculate HDU's */
				/* structure ourselves .... */

       ngph_node_type = NGP_NODE_INVALID;	/* init variables */
       ngph_bitpix = 0;
       ngph_extname = NULL;
       for (i=0; i<NGP_MAX_ARRAY_DIM; i++) ngph_size[i] = 0;
       ngph_dim = 0;

       for (i=0; i<ngph.tokcnt; i++)
        { if (!strcmp("XTENSION", ngph.tok[i].name))
            { if (NGP_TTYPE_STRING == ngph.tok[i].type)
                { if (!ngp_strcasencmp("BINTABLE", ngph.tok[i].value.s,8)) ngph_node_type = NGP_NODE_BTABLE;
                  if (!ngp_strcasencmp("TABLE", ngph.tok[i].value.s,5)) ngph_node_type = NGP_NODE_ATABLE;
                  if (!ngp_strcasencmp("IMAGE", ngph.tok[i].value.s,5)) ngph_node_type = NGP_NODE_IMAGE;
                }
            }
          else if (!strcmp("SIMPLE", ngph.tok[i].name))
            { if (NGP_TTYPE_BOOL == ngph.tok[i].type)
                { if (ngph.tok[i].value.b) ngph_node_type = NGP_NODE_IMAGE;
                }
            }
          else if (!strcmp("BITPIX", ngph.tok[i].name))
            { if (NGP_TTYPE_INT == ngph.tok[i].type)  ngph_bitpix = ngph.tok[i].value.i;
            }
          else if (!strcmp("NAXIS", ngph.tok[i].name))
            { if (NGP_TTYPE_INT == ngph.tok[i].type)  ngph_dim = ngph.tok[i].value.i;
            }
          else if (!strcmp("EXTNAME", ngph.tok[i].name))	/* assign EXTNAME, I hope struct does not move */
            { if (NGP_TTYPE_STRING == ngph.tok[i].type)  ngph_extname = ngph.tok[i].value.s;
            }
          else if (1 == sscanf(ngph.tok[i].name, "NAXIS%d%c", &j, &ngph_ctmp))
            { if (NGP_TTYPE_INT == ngph.tok[i].type)
		if ((j>=1) && (j <= NGP_MAX_ARRAY_DIM))
		  { ngph_size[j - 1] = ngph.tok[i].value.i;
		  }
            }
        }

       switch (ngph_node_type)
        { case NGP_NODE_IMAGE:
			if (NGP_XTENSION_FIRST == ((NGP_XTENSION_FIRST | NGP_XTENSION_SIMPLE) & simple_mode))
			  { 		/* if caller signals that this is 1st HDU in file */
					/* and it is IMAGE defined with XTENSION, then we */
					/* need create dummy Primary HDU */			  
			    fits_create_img(ff, 16, 0, NULL, &r);
			  }
					/* create image */
			fits_create_img(ff, ngph_bitpix, ngph_dim, ngph_size, &r);

					/* update keywords */
			if (NGP_OK == r)  r = ngp_keyword_all_write(&ngph, ff, NGP_NON_SYSTEM_ONLY);
			break;

          case NGP_NODE_ATABLE:
          case NGP_NODE_BTABLE:
					/* create table, 0 rows and 0 columns for the moment */
			fits_create_tbl(ff, ((NGP_NODE_ATABLE == ngph_node_type)
					     ? ASCII_TBL : BINARY_TBL),
					0, 0, NULL, NULL, NULL, NULL, &r);
			if (NGP_OK != r) break;

					/* add columns ... */
			r = ngp_append_columns(ff, &ngph, 0);
			if (NGP_OK != r) break;

					/* add remaining keywords */
			r = ngp_keyword_all_write(&ngph, ff, NGP_NON_SYSTEM_ONLY);
			if (NGP_OK != r) break;

					/* if requested add rows */
			if (ngph_size[1] > 0) fits_insert_rows(ff, 0, ngph_size[1], &r);
			break;

	  default:	r = NGP_BAD_ARG;
	  		break;
	}

     }

   if ((NGP_OK == r) && (NULL != ngph_extname))
     { r = ngp_get_extver(ngph_extname, &my_version);	/* write correct ext version number */
       lv = my_version;		/* bugfix - 22-Jan-99, BO - nonalignment of OSF/Alpha */
       fits_write_key(ff, TLONG, "EXTVER", &lv, "auto assigned by template parser", &r); 
     }

   if (NGP_OK == r)
     { if (parent_hn > 0)
         { fits_get_hdu_num(ff, &my_hn);
           fits_movabs_hdu(ff, parent_hn, &tmp0, &r);	/* link us to parent */
           fits_add_group_member(ff, NULL, my_hn, &r);
           fits_movabs_hdu(ff, my_hn, &tmp0, &r);
           if (NGP_OK != r) return(r);
         }
     }

   if (NGP_OK != r)					/* in case of error - delete hdu */
     { tmp0 = 0;
       fits_delete_hdu(ff, NULL, &tmp0);
     }

   ngp_hdu_clear(&ngph);
   return(r);
 }
Ejemplo n.º 21
0
void GuiderOneStar::SaveStarFITS()
{
    double StarX = m_star.X;
    double StarY = m_star.Y;
    usImage *pImage = CurrentImage();
    usImage tmpimg;

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

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

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

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

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

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

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

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

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

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

    }
    PHD_fits_close_file(fptr);
}
Ejemplo n.º 22
0
bool Fits2D::writeKeywords(fitsfile *fptr){

    /*

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FITS 2D Keywords template %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        1.  SIMPLE      = T                                         / file does conform to FITS standard
        2.  BITPIX      = 8                                         / number of bits per pixel
        3.  NAXIS       = 2                                         / number of data axes
        4.  NAXIS1      = 1280                                      / length of data axis 1
        5.  NAXIS2      = 960                                       / length of data axis 2
        6.  EXTEND      = T                                         / FITS dataset may contain extensions
        7.  FILENAME    = 'stationOrsay_YYYYMMJJ_HHMMSS_UT.fits'    / name of the fits file
        8.  DATE        = 'YYYY-MM-JJT HH:MM:SS.SS'                 / date of the creation of the fits file
        9.  DATE-OBS    = 'YYYY-MM-JJT HH:MM:SS.SS'                 / acquisition date of the first frame
        10. OBS_MODE    = 'SINGLE'                                  / observation method used to get this fits file 'SINGLE' 'SUM' 'AVERAGE' ('MEDIAN')
        11. ELAPTIME    = 60                                        / end observation date - start observation date (sec.)
        12. EXPOSURE    = 0.033                                     / frame exp (sec). 999999 if different exposure.
        13. ONTIME      = 0.033                                     / total integration time, sum of each frame exp (sec)
        14. FILTER      = "NONE"
        15. TELESCOP    = "<Code station>"                          / station <stationName>
        16. OBSERVER    = "<responsable camera>"
        17. INSTRUME    = 'FRIPON-CAM'
        18. CAMERA      = 'BASLER 1300gm'
        19. FOCAL       = 1.25
        20. APERTURE    = 2.0
        21. SITELONG    = 2.1794397                                 / geodetic WGS84 longitude (DD)
        22. SITELAT     = 48.7063906                                / geodetic WGS84 latitude (DD)
        23. SITEELEV    = 90                                        / geodetic WGS84 elevation (m)
        24. XPIXEL      = 3.75
        25. YPIXEL      = 3.75
        26. GAINDB      = 400                                       / detector gain
        27. SATURATE    = 4095                                      / saturation value
        28. PROGRAM     = 'FreeTure v0.1'                           / name of the acquisition software
        29. CREATOR     = 'FRIPON TEAM'                             / http://fripon.org
        30. BZERO       = 0
        31. BSCALE      = 1
        32. RADESYS     = 'ICRS'
        33. TIMESYS     = 'UTC'
        34. EQUINOX     = 2.000000000000E+03                        / equinox of equatorial coordinates
        35. CTYPE1      = 'RA---ARC'                                / projection and reference system
        36. CTYPE2      = 'DEC--ARC'                                / projection and reference system
        37. TIMEUNIT    = 's '
        38. CD1_1       = 0.0                                       / deg/px
        39. CD1_2       = 0.17                                      / deg/px
        40. CD2_1       = 0.17                                      / deg/pix
        41. CD2_2       = 0.0                                       / deg/pix
        42. CD3_3       = 30                                        / fps
        43. CRPIX1      = 640
        44. CRPIX2      = 480
        45. CRVAL1      =                                           / Sidereal time (decimal degree)
        46. CRVAL2      =                                           / geodetic WGS84 latitude (DD)
        47. K1          =
        48. K2          =

    */

    int status = 0;

    // DELETE DEFAULT COMMENTS.

    if(ffdkey(fptr, "COMMENT", &status))
       printerror( status );

    if(ffdkey(fptr, "COMMENT", &status))
       printerror( status );

    /// 7. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% FILENAME %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr, TSTRING, "FILENAME", filename, cfilename, &status)){

        delete filename;
        delete cfilename;
        printerror(status, "Error fits_write_key(FILENAME)");
        return false;

    }

    delete cfilename;
    delete filename;

    /// 8. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% DATE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"DATE",date,cdate,&status)){

        delete date;
        delete cdate;
        printerror(status, "Error fits_write_key(DATE)");
        return false;

    }

    delete cdate;
    delete date;

    /// 9. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% DATE-OBS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"DATE-OBS",dateobs,cdateobs,&status)){

        delete dateobs;
        delete cdateobs;
        printerror(status, "Error fits_write_key(DATE-OBS)");
        return false;

    }

    delete cdateobs;
    delete dateobs;

    /// 10. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% OBS_MODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"OBS_MODE",obsmode,cobsmode,&status)){

        delete cobsmode;
        delete obsmode;
        printerror(status, "Error fits_write_key(OBS_MODE)");
        return false;

    }

    delete cobsmode;
    delete obsmode;

    /// 11. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% ELAPTIME %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"ELAPTIME",&kELAPTIME,celaptime,&status)){

        delete celaptime;
        printerror(status, "Error fits_write_key(ELAPTIME)");
        return false;

    }

    delete celaptime;

    /// 12. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXPOSURE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"EXPOSURE",&kEXPOSURE,ceposure,&status)){

        delete ceposure;
        printerror(status, "Error fits_write_key(EXPOSURE)");
        return false;

    }

    delete ceposure;

    /// 13. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% ONTIME %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"ONTIME",&kONTIME,contime,&status)){

        delete contime;
        printerror(status, "Error fits_write_key(ONTIME)");
        return false;

    }

    delete contime;


    /// 14. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% FILTER %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"FILTER",f,cfilter,&status)){

        delete cfilter;
        delete f;
        printerror(status, "Error fits_write_key(FILTER)");
        return false;

    }

    delete cfilter;
    delete f;


    /// 15. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% TELESCOP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"TELESCOP",t,ctelescop,&status)){

        delete ctelescop;
        delete t;
        printerror(status, "Error fits_write_key(TELESCOP)");
        return false;

    }

    delete ctelescop;
    delete t;

    /// 16. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% OBSERVER %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"OBSERVER",o,cobserver,&status)){

        delete cobserver;
        delete o;
        printerror(status, "Error fits_write_key(OBSERVER)");
        return false;

    }

    delete cobserver;
    delete o;

    /// 17. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% INSTRUME %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"INSTRUME",i,cinstrume,&status)){

        delete cinstrume;
        delete i;
        printerror(status, "Error fits_write_key(OBSERVER)");
        return false;

    }

    delete cinstrume;
    delete i;

    /// 18. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CAMERA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"CAMERA",cam,ccamera,&status)){

        delete ccamera;
        delete cam;
        printerror(status, "Error fits_write_key(CAMERA)");
        return false;

    }

    delete ccamera;
    delete cam;

    /// 19. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% FOCAL %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"FOCAL",&kFOCAL,cfocal,&status)){

        delete cfocal;
        printerror(status, "Error fits_write_key(FOCAL)");
        return false;

    }

    delete cfocal;

    /// 20. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% APERTURE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"APERTURE",&kAPERTURE,caperture,&status)){

        delete caperture;
        printerror(status, "Error fits_write_key(APERTURE)");
        return false;

    }

    delete caperture;

    /// 21. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% SITELONG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"SITELONG",&kSITELONG,csitelong,&status)){

        delete csitelong;
        printerror(status, "Error fits_write_key(APERTURE)");
        return false;

    }

    delete csitelong;

    /// 22. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% SITELAT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"SITELAT",&kSITELAT,csitelat,&status)){

        delete csitelat;
        printerror(status, "Error fits_write_key(SITELAT)");
        return false;

    }

    delete csitelat;

    /// 23. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% SITEELEV %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"SITEELEV",&kSITEELEV,csiteelev,&status)){

        delete csiteelev;
        printerror(status, "Error fits_write_key(SITEELEV)");
        return false;

    }

    delete csiteelev;

    /// 24. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% XPIXEL %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"XPIXEL",&kXPIXEL,cxpixel,&status)){

        delete cxpixel;
        printerror(status, "Error fits_write_key(XPIXEL)");
        return false;

    }

    delete cxpixel;

    /// 25. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% YPIXEL %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"YPIXEL",&kYPIXEL,cypixel,&status)){

        delete cypixel;
        printerror(status, "Error fits_write_key(YPIXEL)");
        return false;

    }

    delete cypixel;

    /// 26. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% GAINDB %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TINT,"GAINDB",&kGAINDB,cgaindb,&status)){

        delete cgaindb;
        printerror(status, "Error fits_write_key(GAINDB)");
        return false;

    }

    delete cgaindb;

    /// 27. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% SATURATE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"SATURATE",&kSATURATE,csaturate,&status)){

        delete csaturate;
        printerror(status, "Error fits_write_key(SATURATE)");
        return false;

    }

    delete csaturate;

    /// 28. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% PROGRAM %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"PROGRAM",p,cprograme,&status)){

        delete cprograme;
        delete p;
        printerror(status, "Error fits_write_key(PROGRAM)");
        return false;

    }

    delete cprograme;
    delete p;

    /// 29. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CREATOR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"CREATOR",c,ccreator,&status)){

        delete ccreator;
        delete c;
        printerror(status, "Error fits_write_key(CREATOR)");
        return false;

    }

    delete ccreator;
    delete c;

    /// 30. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% BZERO %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"BZERO",&kBZERO,cbzero,&status)){

        delete cbzero;
        printerror(status, "Error fits_write_key(BZERO)");
        return false;

    }

    delete cbzero;

    /// 31. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% BSCALE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"BSCALE",&kBSCALE,cbscale,&status)){

        delete cbscale;
        printerror(status, "Error fits_write_key(BSCALE)");
        return false;

    }

    delete cbscale;

    /// 32. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% RADESYS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"RADESYS",radesys,cradesys,&status)){

        delete cradesys;
        delete radesys;
        printerror(status, "Error fits_write_key(RADESYS)");
        return false;

    }

    delete cradesys;
    delete radesys;

    /// 33. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% TIMESYS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"TIMESYS",timesys,ctimesys,&status)){

        delete ctimesys;
        delete timesys;
        printerror(status, "Error fits_write_key(TIMESYS)");
        return false;

    }

    delete ctimesys;
    delete timesys;


    /// 34. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% EQUINOX %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"EQUINOX",&kEQUINOX,cequinox,&status)){

        delete cequinox;
        printerror(status, "Error fits_write_key(EQUINOX)");
        return false;

    }

    delete cequinox;

    /// 35. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CTYPE1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"CTYPE1",ktype1,ctype1,&status)){

        delete ctype1;
        delete ktype1;
        printerror(status, "Error fits_write_key(CTYPE1)");
        return false;

    }

    delete ctype1;
    delete ktype1;

    /// 36. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CTYPE2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"CTYPE2",ktype2,ctype2,&status)){

        delete ctype2;
        delete ktype2;
        printerror(status, "Error fits_write_key(CTYPE2)");
        return false;

    }

    delete ctype2;
    delete ktype2;

    /// 37. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% TIMEUNIT %%%%%%%%%%%%%%%%%%%%%%%%%%%

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

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

    if(fits_write_key(fptr,TSTRING,"TIMEUNIT",ktimeunit,ctimeunit,&status)){

        delete ctimeunit;
        delete ktimeunit;
        printerror(status, "Error fits_write_key(TIMEUNIT)");
        return false;

    }

    delete ctimeunit;
    delete ktimeunit;

    /// 38. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CD1_1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"CD1_1",&kCD1_1,ccd1_1,&status)){

        delete ccd1_1;
        printerror(status, "Error fits_write_key(CD1_1)");
        return false;

    }

    delete ccd1_1;

    /// 39. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CD1_2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"CD1_2",&kCD1_2,ccd1_2,&status)){

        delete ccd1_2;
        printerror(status, "Error fits_write_key(CD1_2)");
        return false;

    }

    delete ccd1_2;

    /// 40. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CD2_1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"CD2_1",&kCD2_1,ccd2_1,&status)){

        delete ccd2_1;
        printerror(status, "Error fits_write_key(CD2_1)");
        return false;

    }

    delete ccd2_1;

    /// 41. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CD2_2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"CD2_2",&kCD2_2,ccd2_2,&status)){

        delete ccd2_2;
        printerror(status, "Error fits_write_key(CD2_2)");
        return false;

    }

    delete ccd2_2;

    /// 42. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CD3_3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"CD3_3",&kCD3_3,ccd3_3,&status)){

        delete ccd3_3;
        printerror(status, "Error fits_write_key(CD3_3)");
        return false;

    }

    delete ccd3_3;

    /// 43. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CRPIX1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TINT,"CRPIX1",&kCRPIX1,ccrpix1,&status)){

        delete ccrpix1;
        printerror(status, "Error fits_write_key(CRPIX1)");
        return false;

    }

    delete ccrpix1;

    /// 44. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CRPIX2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TINT,"CRPIX2",&kCRPIX2,ccrpix2,&status)){

        delete ccrpix2;
        printerror(status, "Error fits_write_key(CRPIX2)");
        return false;

    }

    delete ccrpix2;

    /// 45. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CRVAL1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"CRVAL1",&kCRVAL1,ccrval1,&status)){

        delete ccrval1;
        printerror(status, "Error fits_write_key(CRVAL1)");
        return false;

    }

    delete ccrval1;

    /// 46. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% CRVAL2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"CRVAL2",&kSITELAT,ccrval2,&status)){

        delete ccrval2;
        printerror(status, "Error fits_write_key(CRVAL2)");
        return false;

    }

    delete ccrval2;

    /// 47. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% K1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"K1",&kK1,ck1,&status)){

        delete ck1;
        printerror(status, "Error fits_write_key(K1)");
        return false;

    }

    delete ck1;

    /// 48. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% K2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

    if(fits_write_key(fptr,TDOUBLE,"K2",&kK2,ck2,&status)){

        delete ck2;
        printerror(status, "Error fits_write_key(K2)");
        return false;

    }

    delete ck2;

    return true;


}
Ejemplo n.º 23
0
int     ngp_keyword_all_write(NGP_HDU *ngph, fitsfile *ffp, int mode)
 { int		i, r, ib;
   char		buf[200];
   long		l;


   if (NULL == ngph) return(NGP_NUL_PTR);
   if (NULL == ffp) return(NGP_NUL_PTR);
   r = NGP_OK;
   
   for (i=0; i<ngph->tokcnt; i++)
    { r = ngp_keyword_is_write(&(ngph->tok[i]));
      if ((NGP_REALLY_ALL & mode) || (NGP_OK == r))
        { switch (ngph->tok[i].type)
           { case NGP_TTYPE_BOOL:
			ib = ngph->tok[i].value.b;
			fits_write_key(ffp, TLOGICAL, ngph->tok[i].name, &ib, ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_STRING:
			fits_write_key_longstr(ffp, ngph->tok[i].name, ngph->tok[i].value.s, ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_INT:
			l = ngph->tok[i].value.i;	/* bugfix - 22-Jan-99, BO - nonalignment of OSF/Alpha */
			fits_write_key(ffp, TLONG, ngph->tok[i].name, &l, ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_REAL:
			fits_write_key(ffp, TDOUBLE, ngph->tok[i].name, &(ngph->tok[i].value.d), ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_COMPLEX:
			fits_write_key(ffp, TDBLCOMPLEX, ngph->tok[i].name, &(ngph->tok[i].value.c), ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_NULL:
			fits_write_key_null(ffp, ngph->tok[i].name, ngph->tok[i].comment, &r);
			break;
             case NGP_TTYPE_RAW:
			if (0 == strcmp("HISTORY", ngph->tok[i].name))
			  { fits_write_history(ffp, ngph->tok[i].comment, &r);
			    break;
			  }
			if (0 == strcmp("COMMENT", ngph->tok[i].name))
			  { fits_write_comment(ffp, ngph->tok[i].comment, &r);
			    break;
			  }
			sprintf(buf, "%-8.8s%s", ngph->tok[i].name, ngph->tok[i].comment);
			fits_write_record(ffp, buf, &r);
                        break;
           }
        }
      else if (NGP_BAD_ARG == r) /* enhancement 10 dec 2003, James Peachey: template comments replace defaults */
        { r = NGP_OK;						/* update comments of special keywords like TFORM */
          if (ngph->tok[i].comment && *ngph->tok[i].comment)	/* do not update with a blank comment */
            { fits_modify_comment(ffp, ngph->tok[i].name, ngph->tok[i].comment, &r);
            }
        }
      else /* other problem, typically a blank token */
        { r = NGP_OK;						/* skip this token, but continue */
        }
      if (r) return(r);
    }
     
   fits_set_hdustruc(ffp, &r);				/* resync cfitsio */
   return(r);
 }
Ejemplo n.º 24
0
int hpic_fits_vecindx_write(char *filename, char *creator, char *extname,
                            char *comment, hpic_vec_int * indx,
                            hpic_vec_fltarr * vecs, char **vecnames,
                            char **vecunits, hpic_keys * keys)
{

  size_t i, j, k, m;
  fitsfile *fp;
  int ret = 0;
  int bitpix = SHORT_IMG;
  int nax = 0;
  long axes[] = { 0, 0 };
  int total;
  int type;
  long rows;
  long frow = 1;
  long fsamp = 1;
  size_t veclen;
  char **vectypes;
  char **names;
  char **units;
  size_t nvecs = hpic_vec_fltarr_n_get(vecs);
  hpic_vec_float *tempvec;

  if (nvecs == 0) {
    HPIC_ERROR(HPIC_ERR_FITS, "must specify more than zero vectors!");
  }
  if (!indx) {
    HPIC_ERROR(HPIC_ERR_ACCESS, "index vector is not allocated");
  }
  for (i = 0; i < nvecs; i++) {
    tempvec = hpic_vec_fltarr_get(vecs, i);
    if (!tempvec) {
      HPIC_ERROR(HPIC_ERR_ACCESS, "input vector is not allocated");
    }
  }
  vectypes = hpic_strarr_alloc(nvecs + 1);
  names = hpic_strarr_alloc(nvecs + 1);
  units = hpic_strarr_alloc(nvecs + 1);

  veclen = hpic_vec_int_n_get(indx);
  for (i = 0; i < nvecs; i++) {
    tempvec = hpic_vec_fltarr_get(vecs, i);
    if (veclen != hpic_vec_float_n_get(tempvec)) {
      HPIC_ERROR(HPIC_ERR_FITS, "all vectors must have the same length");
    }
  }

  /* setup column parameters */

  strncpy(vectypes[0], "1J", HPIC_STRNL);
  strncpy(names[0], "INDEX", HPIC_STRNL);
  strncpy(units[0], "", HPIC_STRNL);
  for (i = 1; i < nvecs + 1; i++) {
    strncpy(vectypes[i], "1E", HPIC_STRNL);
    strncpy(names[i], vecnames[i - 1], HPIC_STRNL);
    strncpy(units[i], vecunits[i - 1], HPIC_STRNL);
  }

  /* create file */
  if (fits_create_file(&fp, filename, &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  creating file");
  }

  /* create empty primary image */
  if (fits_create_img(fp, bitpix, nax, axes, &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  creating primary image");
  }

  /* write header */
  if (fits_write_comment(fp, "    ", &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  writing header comment 1");
  }
  if (fits_write_comment(fp, comment, &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  writing header comment 2");
  }
  if (fits_write_comment(fp, "    ", &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  writing header comment 3");
  }
  if (fits_write_date(fp, &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  writing date");
  }
  if (fits_write_key
      (fp, TSTRING, "CREATOR", creator, "Software creating the map", &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  writing creator");
  }

  /* write extension */
  if (fits_create_tbl
      (fp, BINARY_TBL, (long)veclen, (int)(nvecs + 1), names, vectypes, units,
       extname, &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  creating binary table");
  }
  if (fits_movabs_hdu(fp, 2, &type, &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  moving to extension");
  }

  /* write mandatory keywords */
  if (fits_write_comment(fp, "     ", &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  writing ext comment 1");
  }
  if (fits_write_comment
      (fp, "-----------------------------------------------", &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  writing ext comment 2");
  }
  if (fits_write_comment(fp, "            Data Specific Keywords    ", &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  writing ext comment 3");
  }
  if (fits_write_comment
      (fp, "-----------------------------------------------", &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  writing ext comment 4");
  }
  if (fits_write_comment(fp, "      ", &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  writing comment 5");
  }

  /* write optional keywords */

  hpic_keys_write(keys, fp, &ret);

  /* write the data and clean up */
  if (fits_write_col
      (fp, TINT, 1, frow, fsamp, (long)veclen, indx->data, &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  writing index column");
  }
  for (i = 0; i < nvecs; i++) {
    tempvec = hpic_vec_fltarr_get(vecs, i);
    if (fits_write_col
        (fp, TFLOAT, (int)(i + 2), frow, fsamp, (long)veclen, tempvec->data,
         &ret)) {
      fitserr(ret, "hpic_fits_vecindx_write:  writing data column");
    }
  }
  
  hpic_strarr_free(vectypes, nvecs + 1);
  hpic_strarr_free(names, nvecs + 1);
  hpic_strarr_free(units, nvecs + 1);

  if (fits_close_file(fp, &ret)) {
    fitserr(ret, "hpic_fits_vecindx_write:  closing file");
  }

  return ret;
}