int CDfits_open_file( char *filename ) { int status; int bitpix = 8; int naxis = 0; long *naxes; status = 0; /* Open file */ fits_create_file( &cfitsptr, filename, &status ); /* Write primary header */ bitpix = 8; naxis = 0; fits_create_img( cfitsptr, bitpix, naxis, naxes, &status ); /* Add first keywords */ fits_update_key( cfitsptr, TSTRING, "HDRVER", "1.19", "Header version", &status); fits_write_date( cfitsptr, &status); new_file = 1; return( status ); }
std::string write_image(std::string pathname, float *array, std::string name, int naxis, long *naxes) { // this function writes a float array to a FITS image file TRACE_ENTER(); // create new file fitsfile *fptr; int status = 0; fits_create_file(&fptr, pathname.c_str(), &status); if (status != 0) { // cannot create the file // likely, the file already exists // try to open it, delete it and create it anew // try to open the file status = 0; fits_open_file(&fptr, pathname.c_str(), READWRITE, &status); if (status != 0) { // cannot open the file, for some reason return FORMAT_STATUS(status); } // try to delete the file status = 0; fits_delete_file(fptr, &status); if (status != 0) { // cannot delete the file, for some reason return FORMAT_STATUS(status); } // try to create the file status = 0; fits_create_file(&fptr, pathname.c_str(), &status); if (status != 0) { // cannot create the file, for some reason return FORMAT_STATUS(status); } } // create the primary array image fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status); if (status != 0) { return FORMAT_STATUS(status); } // write a keyword fits_update_key(fptr, TFLOAT, name.c_str(), array, name.c_str(), &status); if (status != 0) { return FORMAT_STATUS(status); } // write the array of floats to the image long fpixel = 1; long nelements = 1; for (int i = 0; i < naxis; i++) { nelements = nelements * naxes[i]; } fits_write_img(fptr, TFLOAT, fpixel, nelements, (void*)array, &status); if (status != 0) { return FORMAT_STATUS(status); } // close the file fits_close_file(fptr, &status); if (status != 0) { return FORMAT_STATUS(status); } return "WRITE_OK"; }
void save_2d_image_potential(SimulationData &sim_data, double *potential, const char * fits_file_name) { double *save_data; save_data = (double*)mkl_malloc(sim_data.get_num_x() * sim_data.get_num_y() * sizeof(double), 64); fitsfile *fptr; int status = 0; long fpixel = 1, naxis = 2, nelements; long naxes[2] = {sim_data.get_num_y(), sim_data.get_num_x()}; for (int i = 0; i < sim_data.get_num_x(); ++i) { for (int j = 0; j < sim_data.get_num_y(); ++j) { save_data[i * sim_data.get_num_y() + j] = 0; for (int k = 0; k < sim_data.get_num_z(); ++k) { save_data[i * sim_data.get_num_y() + j] += potential[i * sim_data.get_num_y() * sim_data.get_num_z() + j * sim_data.get_num_z() + k]; } } } fits_create_file(&fptr, fits_file_name, &status); fits_create_img(fptr, DOUBLE_IMG, naxis, naxes, &status); nelements = naxes[0] * naxes[1]; fits_write_img(fptr, TDOUBLE, fpixel, nelements, save_data, &status); fits_close_file(fptr, &status); fits_report_error(stderr, status); mkl_free(save_data); }
//---------------------------------------------------------------------------------- void sfits_to_lfits(char *source_fits,double *posx1, double *posx2, double *alpha1, double *alpha2,double ysc1,double ysc2, double dsi, int nlx, int nly, char *lensed_fits) { fitsfile *fptr_in; int status, nfound, anynull; long naxes[2],fpixel,npixels, i, j, index; float nullval; status = 0; fits_open_file(&fptr_in, source_fits, READONLY, &status); fits_read_keys_lng(fptr_in, "NAXIS", 1, 2, naxes, &nfound, &status); long nsx = naxes[0]; long nsy = naxes[1]; npixels = nsx*nsy; fpixel = 1; nullval = 0; double *source_map = calloc(npixels,sizeof(double)); fits_read_img(fptr_in, TDOUBLE, fpixel, npixels, &nullval, source_map, &anynull, &status); fits_close_file(fptr_in, &status); double *posy1 = calloc(nlx*nly,sizeof(double)); double *posy2 = calloc(nlx*nly,sizeof(double)); for(i=0;i<nlx;i++) for(j=0;j<nly;j++){ index = i*nlx+j; posy1[index] = posx1[index]-alpha1[index]; posy2[index] = posx2[index]-alpha2[index]; } double *lensed_map = calloc(nlx*nly,sizeof(double)); Interplation_on_source_plane(source_map,posy1,posy2,ysc1,ysc2,dsi,nsx,nsy,nlx,nly,lensed_map); fitsfile *fptr_out; int fpixel_out = fpixel; long bitpix_out = DOUBLE_IMG; long naxis_out = 2; long npixels_out = nlx*nly; long naxes_out[naxis_out]; naxes_out[0] = nlx; naxes_out[1] = nly; status = 0; remove(lensed_fits); fits_create_file(&fptr_out, lensed_fits, &status); fits_create_img(fptr_out, bitpix_out, naxis_out, naxes_out, &status); fits_write_img(fptr_out, TDOUBLE, fpixel_out, npixels_out, lensed_map, &status); fits_close_file(fptr_out, &status); free(posy1); free(posy2); }
static void write_pixels(oskar_Mem* data, const char* filename, int width, int height, int num_planes, int i_plane, int* status) { long naxes[3], firstpix[3], num_pix; int dims_ok = 0; fitsfile* f = 0; if (*status) return; if (oskar_file_exists(filename)) { int naxis = 0, imagetype = 0; fits_open_file(&f, filename, READWRITE, status); fits_get_img_param(f, 3, &imagetype, &naxis, naxes, status); if (naxis == 3 && naxes[0] == width && naxes[1] == height && naxes[2] == num_planes) { dims_ok = 1; } else { *status = 0; fits_close_file(f, status); remove(filename); f = 0; } } if (!dims_ok) { naxes[0] = width; naxes[1] = height; naxes[2] = num_planes; fits_create_file(&f, filename, status); fits_create_img(f, oskar_mem_is_double(data) ? DOUBLE_IMG : FLOAT_IMG, 3, naxes, status); } if (*status || !f) { if (f) fits_close_file(f, status); *status = OSKAR_ERR_FILE_IO; return; } num_pix = width * height; firstpix[0] = 1; firstpix[1] = 1; firstpix[2] = 1 + i_plane; if (i_plane < 0) { firstpix[2] = 1; num_pix *= num_planes; } fits_write_pix(f, oskar_mem_is_double(data) ? TDOUBLE : TFLOAT, firstpix, num_pix, oskar_mem_void(data), status); fits_close_file(f, status); }
/* This routine provides simple FITS writer. It uses the routines * provided by the fitsTcl/cfitsio libraries * * NOTE : It will fail if the image already exists */ int ApogeeAltaManager::saveimage(unsigned short *src_buffer, char *filename, int nx, int ny) { fitsfile *fptr; /* pointer to the FITS file, defined in fitsio.h */ long fpixel, nelements; unsigned short *array; unsigned short *simg; int status; /* initialize FITS image parameters */ int bitpix = USHORT_IMG; /* 16-bit unsigned short pixel values */ long naxis = 2; /* 2-dimensional image */ long naxes[2]; naxes[0] = nx-bcols; naxes[1] = ny; array = src_buffer; status = 0; /* initialize status before calling fitsio routines */ simg = (unsigned short *)CCD_locate_buffer(const_cast<char *>("stemp"),2,nx-bcols,ny,1,1); if (fits_create_file(&fptr, filename, &status)) /* create new FITS file */ printerror( status ); /* call printerror if error occurs */ /* write the required keywords for the primary array image. */ /* Since bitpix = USHORT_IMG, this will cause cfitsio to create */ /* a FITS image with BITPIX = 16 (signed short integers) with */ /* BSCALE = 1.0 and BZERO = 32768. This is the convention that */ /* FITS uses to store unsigned integers. Note that the BSCALE */ /* and BZERO keywords will be automatically written by cfitsio */ /* in this case. */ if ( fits_create_img(fptr, bitpix, naxis, naxes, &status) ) printerror( status ); fpixel = 1; /* first pixel to write */ nelements = naxes[0] * naxes[1]; /* number of pixels to write */ if (bcols > 0) { dobiassubtract(src_buffer,simg,naxes[0],naxes[1]); /* write the array of unsigned integers to the FITS file */ if ( fits_write_img(fptr, TUSHORT, fpixel, nelements, simg, &status) ) printerror( status ); } else { /* write the array of unsigned integers to the FITS file */ if ( fits_write_img(fptr, TUSHORT, fpixel, nelements, src_buffer, &status) ) printerror( status ); } if ( fits_close_file(fptr, &status) ) /* close the file */ printerror( status ); return(status); }
/** * Saves the image to a FITS file using the cfitsio library. * * @param output_filename string, where to save the FITS file * @param sx, integer, horizontal image size * @param sy, integer, vertical image size * @param data, rows of a two dimensional integer array, image data * @return Zero on success, non-zero on failure. */ int camera_save_fits_image(char * output_filename, long sx, long sy, unsigned short * data) { fitsfile *fptr; int status = 0; long fpixel, nelements; float gain; int bitpix = USHORT_IMG; long naxis = 2; long naxes[2] = {sx, sy}; /* Delete old file if it already exists */ remove(output_filename); /* create new FITS file */ if (fits_create_file(&fptr, output_filename, &status)) { if (status) fits_report_error(stderr, status); return status; } /* the setting of bitpix = USHORT_IMG implies that BITPIX = 16, BSCALE = 1.0 and BZERO = 32768, and the latter two keywords are added automatically. */ if (fits_create_img(fptr, bitpix, naxis, naxes, &status)) { if (status) fits_report_error(stderr, status); return status; } /* first pixel to write */ fpixel = 1; /* number of pixels to write */ nelements = naxes[0] * naxes[1]; /* write the array of unsigned integers to the FITS file */ if (fits_write_img(fptr, TUSHORT, fpixel, nelements, data, &status)) { if (status) fits_report_error(stderr, status); return status; } /* write the gain parameter of the camera to the header */ gain = ML16803_CAMERA_GAIN; if (fits_update_key(fptr, TFLOAT, "GAIN", &gain, "Camera gain of ML16803", &status)) { if (status) fits_report_error(stderr, status); return status; } /* close the file */ if (fits_close_file(fptr, &status)) { if (status) fits_report_error(stderr, status); return status; } return 0; }
void writeFITS(const cv::Mat& cvImage, const std::string& filename) { if(cvImage.channels() != 1) { CustomException("writeFITS: Only able to write FITS from single channel images."); } fitsfile *fptr; //pointer to the FITS file defined in fitsioh int status; char err_text[100]; cv::Mat floatImg = cv::Mat_<float>(cvImage); long fpixel = 1, naxis = 2, nelements; long naxes[2] = {cvImage.cols, cvImage.rows}; float array[cvImage.cols][cvImage.rows]; for(int i = 0;i < floatImg.rows ;i++) { for(int j = 0;j < floatImg.cols ;j++) { array[j][i] = floatImg.at<float>(j,i); } } status=0; fits_create_file(&fptr, filename.c_str(), &status); if (status) { fits_report_error(stdout, status); fits_get_errstatus(status,err_text); fptr = nullptr; throw CustomException("writeFITS: Cannot create fits file."); } fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status); if (status) { fits_report_error(stdout, status); fits_get_errstatus(status,err_text); fptr = nullptr; throw CustomException("writeFITS: Cannot create image file."); } nelements = naxes[0] * naxes[1]; fits_write_img(fptr, TFLOAT, fpixel, nelements, array[0], &status); if (status) { fits_report_error(stdout, status); fits_get_errstatus(status,err_text); fptr = nullptr; throw CustomException("writeFITS: Cannot write image file."); } fits_close_file(fptr, &status); fits_report_error(stderr, status); }
fitsfile* create_fits_file(const char* filename, int precision, int width, int height, int num_times, int num_channels, double centre_deg[2], double fov_deg[2], double start_time_mjd, double delta_time_sec, double start_freq_hz, double delta_freq_hz, int* status) { long naxes[4]; double delta; fitsfile* f = 0; FILE* t = 0; if (*status) return 0; /* Create a new FITS file and write the image headers. */ t = fopen(filename, "rb"); if (t) { fclose(t); remove(filename); } naxes[0] = width; naxes[1] = height; naxes[2] = num_channels; naxes[3] = num_times; fits_create_file(&f, filename, status); fits_create_img(f, (precision == OSKAR_DOUBLE ? DOUBLE_IMG : FLOAT_IMG), 4, naxes, status); fits_write_date(f, status); /* Write axis headers. */ delta = oskar_convert_fov_to_cellsize(fov_deg[0] * M_PI/180, width) * 180/M_PI; write_axis_header(f, 1, "RA---SIN", "Right Ascension", centre_deg[0], -delta, width / 2 + 1, 0.0, status); delta = oskar_convert_fov_to_cellsize(fov_deg[1] * M_PI/180, height) * 180/M_PI; write_axis_header(f, 2, "DEC--SIN", "Declination", centre_deg[1], delta, height / 2 + 1, 0.0, status); write_axis_header(f, 3, "FREQ", "Frequency", start_freq_hz, delta_freq_hz, 1.0, 0.0, status); write_axis_header(f, 4, "UTC", "Time", start_time_mjd, delta_time_sec, 1.0, 0.0, status); /* Write other headers. */ fits_write_key_str(f, "BUNIT", "JY/BEAM", "Brightness units", status); fits_write_key_str(f, "TIMESYS", "UTC", NULL, status); fits_write_key_str(f, "TIMEUNIT", "s", "Time axis units", status); fits_write_key_dbl(f, "MJD-OBS", start_time_mjd, 10, "Start time", status); fits_write_key_dbl(f, "OBSRA", centre_deg[0], 10, "RA", status); fits_write_key_dbl(f, "OBSDEC", centre_deg[1], 10, "DEC", status); /*fits_flush_file(f, status);*/ return f; }
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); }
int write_fits(char* path,unsigned char* image) { fitsfile *fptrout; unsigned int naxis = 2; long naxes[2]; int status = 0; long nelements = width*height; naxes[0] = width; naxes[1] = height; fits_create_file(&fptrout,path, &status); fits_create_img(fptrout, BYTE_IMG, naxis, naxes, &status); fits_write_img(fptrout, TBYTE, 1, nelements, image, &status); fits_close_file(fptrout, &status); }
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); } }
void save_3d_image(SimulationData &sim_data, WaveFunction &psi, const char * fits_file_name) { fitsfile *fptr; int status = 0; long fpixel = 1, naxis = 3, nelements; long naxes[3] = {sim_data.get_num_x(), sim_data.get_num_y(), sim_data.get_num_z()}; fits_create_file(&fptr, fits_file_name, &status); fits_create_img(fptr, DOUBLE_IMG, naxis, naxes, &status); nelements = naxes[0] * naxes[1] * naxes[2]; fits_write_img(fptr, TDOUBLE, fpixel, nelements, psi.abs_psi, &status); fits_close_file(fptr, &status); fits_report_error(stderr, status); }
int nemo_main(void) { fitsfile *fptr; /* pointer to the FITS file; defined in fitsio.h */ int status, ii, jj; long fpixel = 1, naxis = 2, nelements, exposure; long naxes[2] = { 300, 200 }; /* image is 300 pixels wide by 200 rows */ short array[200][300]; string fname = getparam("out"); float time4 = PI; double time8 = PI; status = 0; /* initialize status before calling fitsio routines */ fits_create_file(&fptr, fname, &status); /* create new file */ /* Create the primary array image (16-bit short integer pixels */ fits_create_img(fptr, SHORT_IMG, naxis, naxes, &status); /* Write a keyword; must pass the ADDRESS of the value */ exposure = 1500.; fits_update_key(fptr, TLONG, "EXPOSURE", &exposure, "Total Exposure Time", &status); dprintf(1,"exposure %d\n",status); fits_update_key(fptr, TFLOAT, "TIME4", &time4, "Sample REAL*4", &status); dprintf(1,"time4 %d\n",status); fits_update_key(fptr, TDOUBLE, "TIME8", &time8, "Sample REAL*8", &status); dprintf(1,"time8 %d\n",status); fits_update_key(fptr, TSTRING, "DATEOBS", "2001/09/30", "Sample STRING", &status); dprintf(1,"string %d\n",status); /* Initialize the values in the image with a linear ramp function */ for (jj = 0; jj < naxes[1]; jj++) for (ii = 0; ii < naxes[0]; ii++) array[jj][ii] = ii + jj; nelements = naxes[0] * naxes[1]; /* number of pixels to write */ /* Write the array of integers to the image */ fits_write_img(fptr, TSHORT, fpixel, nelements, array[0], &status); fits_close_file(fptr, &status); /* close the file */ fits_report_error(stderr, status); /* print out any error messages */ return status ; }
/** Writes single NDArray to the FITS file. * \param[in] pArray Pointer to the NDArray to be written */ asynStatus NDFileFITS::writeFile(NDArray *pArray) { static const char *functionName = "writeFile"; asynPrint(this->pasynUserSelf, ASYN_TRACE_FLOW, "%s:%s: %lu, %lu\n", driverName, functionName, (unsigned long)pArray->dims[0].size, (unsigned long)pArray->dims[1].size); NDArrayInfo arrayInfo; pArray->getInfo(&arrayInfo); int nx = (int) arrayInfo.xSize; int ny = (int) arrayInfo.ySize; long naxis = 2; // 2-dimensional image long naxes[2] = { nx, ny }; fitsStatus = 0; if(fits_create_img(fitsFilePtr, USHORT_IMG, naxis, naxes, &fitsStatus)) { fits_get_errstatus(fitsStatus, fits_status_str); asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s::%s error creating fits image: error=%s\n", driverName, functionName, fits_status_str); fits_clear_errmsg(); return asynError; } if(fits_write_img(fitsFilePtr, CFITSIO_TUSHORT, 1, naxes[0]*naxes[1], pArray->pData, &fitsStatus)) { fits_get_errstatus(fitsStatus, fits_status_str); asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s::%s error writing fits image: error=%s\n", driverName, functionName, fits_status_str); fits_close_file(fitsFilePtr, &fitsStatus); fits_clear_errmsg(); return asynError; } if(WriteKeys(fitsFilePtr, &fitsStatus)) { fits_get_errstatus(fitsStatus, fits_status_str); asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s::%s error writing fits image: error=%s\n", driverName, functionName, fits_status_str); fits_close_file(fitsFilePtr, &fitsStatus); return asynError; } return(asynSuccess); }
local void print_ccd(real **ccd, char filename[], real t_exposure) { fitsfile *fptr; int status, ii, jj; long fpixel, nelements, exposure; // unsigned short array[512][512]; unsigned short array[XCCD_MAX][YCCD_MAX]; // char filename[] = "ccd.fit"; int bitpix = USHORT_IMG; long naxis = 2; // long naxes[2] = { 512, 512 }; long naxes[2] = { XCCD_MAX, YCCD_MAX }; remove(filename); status = 0; if (fits_create_file(&fptr, filename, &status)) printf("%s\n", status); if ( fits_create_img(fptr, bitpix, naxis, naxes, &status) ) printf("%s\n", status); float val; for (jj = 0; jj < naxes[1]; jj++) { for (ii = 0; ii < naxes[0]; ii++) { // cin >> val; array[jj][ii] = (unsigned short)ccd[jj][ii]; } } fpixel = 1; nelements = naxes[0] * naxes[1]; if ( fits_write_img(fptr, TUSHORT, fpixel, nelements, array[0], &status) ) printf("%s\n", status); exposure = long(t_exposure); if ( fits_update_key(fptr, TLONG, "EXPOSURE", &exposure, "Exposure time in seconds", &status) ) printf("%s\n", status); if ( fits_close_file(fptr, &status) ) printf("%s\n", status); }
int write2Dfits(char *fname, double *f, int pwidth, int pheight) { /* write out image as a fits file */ fitsfile *afptr; int status = 0; int anaxis; long anaxes[2], fpixel[2]={1,1}; int bitpix; int size; bitpix = -32; anaxis = 2; anaxes[0] = pwidth; anaxes[1] = pheight; size = anaxes[0]*anaxes[1]; fits_create_file(&afptr, fname, &status); fits_create_img(afptr, bitpix, anaxis, anaxes, &status); if (status) { fits_report_error(stderr, status); /* print error message */ return(status); } /* write all data into image array */ if (fits_write_pix(afptr, TDOUBLE, fpixel, size, f, &status) ) { printf(" error reading pixel data \n"); exit (2); } /* close the fits file */ fits_close_file(afptr, &status); if (status) { fits_report_error(stderr, status); /* print error message */ exit(2); } return 0; }
//---------------------------------------------------------------------------------- void save_to_fits(double *lensed_map, int nlx, int nly, char *lensed_fits) { fitsfile *fptr_out; int fpixel_out = 1; long bitpix_out = DOUBLE_IMG; long naxis_out = 2; long npixels_out = nlx*nly; long naxes_out[naxis_out]; naxes_out[0] = nlx; naxes_out[1] = nly; int status = 0; remove(lensed_fits); fits_create_file(&fptr_out, lensed_fits, &status); fits_create_img(fptr_out, bitpix_out, naxis_out, naxes_out, &status); fits_write_img(fptr_out, TDOUBLE, fpixel_out, npixels_out, lensed_map, &status); fits_close_file(fptr_out, &status); }
void FitsFile::AppendImageHUD(enum FitsFile::ImageType imageType, long width, long height) { int status = 0; int bitPixInt; switch(imageType) { case Int8ImageType: bitPixInt = BYTE_IMG; break; case Int16ImageType: bitPixInt = SHORT_IMG; break; case Int32ImageType: bitPixInt = LONG_IMG; break; case Float32ImageType: bitPixInt = FLOAT_IMG; break; case Double64ImageType: bitPixInt = DOUBLE_IMG; break; default: throw FitsIOException(); } long *naxes = new long[2]; naxes[0] = width; naxes[1] = height; fits_create_img(_fptr, bitPixInt, 2, naxes, &status); delete[] naxes; CheckStatus(status); }
void writeimage(const image_t *image, const char *filename) { if (debug) { fprintf(stderr, "%s:%d: writing image %s\n", __FILE__, __LINE__, filename); } char errmsg[80]; int status = 0; fitsfile *fits = NULL; if (fits_create_file(&fits, filename, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot create fits file %s: %s\n", filename, errmsg); return; } // find dimensions of pixel array int naxis = 2; long naxes[2] = { image->width, image->height }; if (fits_create_img(fits, DOUBLE_IMG, naxis, naxes, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot create image: %s\n", errmsg); goto bad; } // read the pixel data long npixels = image->width * image->height; long firstpixel[3] = { 1, 1, 1 }; if (fits_write_pix(fits, TDOUBLE, firstpixel, npixels, image->data, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot write pixel data: %s\n", errmsg); } bad: // close the file if (fits_close_file(fits, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot close fits file %s: %s\n", filename, errmsg); goto bad; } }
int WriteFITS(unsigned short *buffer, int cols, int rows, char *filename) { #ifdef HAVE_FITSIO_H int status = 0; fitsfile *fits; unlink(filename); fits_create_file(&fits, filename, &status); if (status) { std::cerr << "cannot create file " << filename << std::endl; return -1; } long naxes[2] = { cols, rows }; fits_create_img(fits, SHORT_IMG, 2, naxes, &status); long fpixel[2] = { 1, 1 }; fits_write_pix(fits, TUSHORT, fpixel, cols * rows, buffer, &status); fits_close_file(fits, &status); #else std::cerr << "FITS not supported" << std::endl; return -1; #endif }
void save_file( const std::string& filename, const image_type& img ) { fitsfile* f; int status = 0; std::string fname = "!" + filename; fits_create_file( &f, fname.c_str(), &status ); long dims[2]; dims[0] = img.extents.first; dims[1] = img.extents.second; typedef CFitsIOTypeMap< image_type::element > map; fits_create_img( f, map::image_type, 2, dims, &status ); fits_write_img( f, map::type, 1, img.num_elements(), (void*)img.ptr(), &status ); fits_close_file( f, &status ); if( status ) { fits_report_error( stderr, status ); } }
void writefitsimagefile( char *filename, long int bitpix, long int naxis, long int naxes[], void *address ) { /* N.B. If filename exists then we get an error trying to write it. */ /* long int bitpix - Must be proper image type for data type of array at address. */ /* long int naxis - Number of axes. */ /* long int naxes - Array of axes values. */ /* void *address - Pointer to array of data values. */ long int i, nElements, fpixel = 1; /* fpixel means always start at pixel number 1, i.e., first pixel. */ fitsfile *fptr; /* A pointer to a FITS file; defined in fitsio.h */ int status = 0; if ( fits_create_file( &fptr, filename, &status ) ) { /* Create new FITS file */ printerror( status, __LINE__ ); } /* Write the required keywords for the primary array image */ if ( fits_create_img( fptr, bitpix, naxis, naxes, &status ) ) { printerror( status, __LINE__ ); } /* Compute number of pixels to write */ nElements = naxes[0]; for (i = 1; i < naxis; i++ ) { nElements = nElements * naxes[i]; } /* Write the array of floats to the file. */ if ( fits_write_img(fptr, getDataTypeFromImgType( bitpix ), fpixel, nElements, address, &status) ) { printerror( status, __LINE__ ); } if ( fits_close_file(fptr, &status) ) { /* close the file */ printerror( status, __LINE__ ); } return; }
void makebasisfile( int kk, int datax, int slice, void *address ) { long int bitpix = -32, nElements, naxis = 2, naxes[2], fpixel = 1; fitsfile *fptr; /* pointer to output FITS files; defined in fitsio.h */ int status = 0; char tname[128]; /* Initialize FITS image parameters */ /* First build the file name. */ (void)strcpy( tname, "basis" ); (void)sprintf( strBuf, "%d", kk+1 ); (void)strcat( tname, strBuf ); (void)strcat( tname, ".fits" ); (void)printf( "tname = %s\n", tname ); naxes[0] = datax; /* datax pixels wide */ naxes[1] = slice; /* by slice rows */ if ( fits_create_file( &fptr, tname, &status ) ) { /* Create new FITS file */ printerror( status, __LINE__ ); } /* Write the required keywords for the primary array image */ if ( fits_create_img( fptr, bitpix, naxis, naxes, &status ) ) { printerror( status, __LINE__ ); } nElements = naxes[0] * naxes[1]; /* number of pixels to write */ /* Write the array of floats to the file. */ if ( fits_write_img(fptr, TFLOAT, fpixel, nElements, address, &status) ) { printerror( status, __LINE__ ); } if ( fits_close_file(fptr, &status) ) { /* close the file */ printerror( status, __LINE__ ); } return; }
// / Converts a matrix composed of doubles into a FITS file void mat2fits(Matrix < double >&m, const char *filename) { int status = 0; fitsfile *fptr; long fpixel = 1, naxis = 2, nelements; long naxes[2]; // Initialise storage naxes[0] = (long)m.GetRows(); naxes[1] = (long)m.GetCols(); nelements = naxes[0] * naxes[1]; double *ptrimg; // Create pointer image ptrimg = (double *)malloc(nelements * sizeof(double)); for (int ii = 0; ii < naxes[0]; ii++) for (int jj = 0; jj < naxes[1]; jj++) ptrimg[ ii + jj * naxes[0] ] = m[ii][jj]; // Create new file, write image, then close file if (status == 0) fits_create_file(&fptr, filename, &status); if (status == 0) fits_create_img(fptr, DOUBLE_IMG, naxis, naxes, &status); if (status == 0) fits_write_img(fptr, TDOUBLE, fpixel, nelements, &ptrimg[0], &status); if (status == 0) fits_close_file(fptr, &status); free(ptrimg); fits_report_error(stderr, status); }
int main(int argc, char *argv[]) { fitsfile *fptr; long fpixel=1, nelements, naxes[3]; dc1394camera_t *camera; int grab_n_frames; struct timeval start_time, end_time; time_t start_sec, end_sec; suseconds_t start_usec, end_usec; float elapsed_time, fps; int i, status; unsigned int min_bytes, max_bytes, max_height, max_width; unsigned int actual_bytes; uint64_t total_bytes = 0; unsigned int width, height; dc1394video_frame_t *frame=NULL; dc1394_t * d; dc1394camera_list_t * list; dc1394error_t err; char *filename; grab_n_frames = atoi(argv[1]); filename = argv[2]; width = 320; height = 240; naxes[0] = width; naxes[1] = height; naxes[2] = grab_n_frames; nelements = naxes[0]*naxes[1]*naxes[2]; stderr = freopen("grab_cube.log", "w", stderr); d = dc1394_new (); if (!d) return 1; err=dc1394_camera_enumerate (d, &list); DC1394_ERR_RTN(err,"Failed to enumerate cameras"); if (list->num == 0) { dc1394_log_error("No cameras found"); return 1; } camera = dc1394_camera_new (d, list->ids[0].guid); if (!camera) { dc1394_log_error("Failed to initialize camera with guid %"PRIx64, list->ids[0].guid); return 1; } dc1394_camera_free_list (list); printf("Using camera with GUID %"PRIx64"\n", camera->guid); /*----------------------------------------------------------------------- * setup capture for format 7 *-----------------------------------------------------------------------*/ // err=dc1394_video_set_operation_mode(camera, DC1394_OPERATION_MODE_1394B); // DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot operate at 1394B"); // libdc1394 doesn't work well with firewire800 yet so set to legacy 400 mode dc1394_video_set_iso_speed(camera, DC1394_ISO_SPEED_400); // configure camera for format7 err = dc1394_video_set_mode(camera, DC1394_VIDEO_MODE_FORMAT7_1); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot choose format7_0"); printf ("I: video mode is format7_0\n"); err = dc1394_format7_get_max_image_size (camera, DC1394_VIDEO_MODE_FORMAT7_1, &max_width, &max_height); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot get max image size for format7_0"); printf ("I: max image size is: height = %d, width = %d\n", max_height, max_width); printf ("I: current image size is: height = %d, width = %d\n", height, width); err = dc1394_format7_set_roi (camera, DC1394_VIDEO_MODE_FORMAT7_1, DC1394_COLOR_CODING_MONO16, // not sure why RAW8/16 don't work DC1394_USE_MAX_AVAIL, 0, 0, // left, top width, height); // width, height DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set roi"); printf ("I: roi is (0, 0) - (%d, %d)\n", width, height); // set the frame rate to absolute value in frames/sec err = dc1394_feature_set_mode(camera, DC1394_FEATURE_FRAME_RATE, DC1394_FEATURE_MODE_MANUAL); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set framerate to manual"); err = dc1394_feature_set_absolute_control(camera, DC1394_FEATURE_FRAME_RATE, DC1394_TRUE); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set framerate to absolute mode"); err = dc1394_feature_set_absolute_value(camera, DC1394_FEATURE_FRAME_RATE, 330.0); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set framerate"); printf("I: framerate is %f fps\n", 330.0); // set the shutter speed to absolute value in seconds err = dc1394_feature_set_mode(camera, DC1394_FEATURE_SHUTTER, DC1394_FEATURE_MODE_MANUAL); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set shutter to manual"); err = dc1394_feature_set_absolute_control(camera, DC1394_FEATURE_SHUTTER, DC1394_TRUE); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set shutter to absolute mode"); err = dc1394_feature_set_absolute_value(camera, DC1394_FEATURE_SHUTTER, 3.0e-3); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set shutter"); printf("I: exptime is %f s\n", 3.0e-3); // set gain manually. use relative value here in range 48 to 730. err = dc1394_feature_set_mode(camera, DC1394_FEATURE_GAIN, DC1394_FEATURE_MODE_MANUAL); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set gain to manual"); err = dc1394_feature_set_value(camera, DC1394_FEATURE_GAIN, 400); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set gain"); printf ("I: gain is %d\n", 400); // set brightness manually. use relative value in range 0 to 1023. err = dc1394_feature_set_mode(camera, DC1394_FEATURE_BRIGHTNESS, DC1394_FEATURE_MODE_MANUAL); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set brightness to manual"); err = dc1394_feature_set_value(camera, DC1394_FEATURE_BRIGHTNESS, 100); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set brightness"); printf ("I: brightness is %d\n", 100); err = dc1394_format7_get_total_bytes (camera, DC1394_VIDEO_MODE_FORMAT7_1, &total_bytes); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot get total bytes"); printf ("I: total bytes is %"PRIu64" before SFF enabled\n", total_bytes); err=dc1394_capture_setup(camera, 16, DC1394_CAPTURE_FLAGS_DEFAULT); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "Error capturing"); /*----------------------------------------------------------------------- * print allowed and used packet size *-----------------------------------------------------------------------*/ err=dc1394_format7_get_packet_parameters(camera, DC1394_VIDEO_MODE_FORMAT7_1, &min_bytes, &max_bytes); DC1394_ERR_RTN(err,"Packet para inq error"); printf( "camera reports allowed packet size from %d - %d bytes\n", min_bytes, max_bytes); err=dc1394_format7_get_packet_size(camera, DC1394_VIDEO_MODE_FORMAT7_1, &actual_bytes); DC1394_ERR_RTN(err,"dc1394_format7_get_packet_size error"); printf( "camera reports actual packet size = %d bytes\n", actual_bytes); err=dc1394_format7_get_total_bytes(camera, DC1394_VIDEO_MODE_FORMAT7_1, &total_bytes); DC1394_ERR_RTN(err,"dc1394_query_format7_total_bytes error"); printf( "camera reports total bytes per frame = %"PRId64" bytes\n", total_bytes); /*----------------------------------------------------------------------- * have the camera start sending us data *-----------------------------------------------------------------------*/ err=dc1394_video_set_transmission(camera,DC1394_ON); if (err!=DC1394_SUCCESS) { dc1394_log_error("unable to start camera iso transmission"); dc1394_capture_stop(camera); dc1394_camera_free(camera); exit(1); } // set up FITS image and capture fits_create_file(&fptr, filename, &status); dc1394_get_image_size_from_video_mode(camera, DC1394_VIDEO_MODE_FORMAT7_1, &width, &height); fits_create_img(fptr, USHORT_IMG, 3, naxes, &status); /*----------------------------------------------------------------------- * capture frames and measure the time for this operation *-----------------------------------------------------------------------*/ gettimeofday(&start_time, NULL); printf("Start capture:\n"); for( i = 0; i < grab_n_frames; ++i) { /*----------------------------------------------------------------------- * capture one frame *-----------------------------------------------------------------------*/ err=dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_WAIT, &frame); if (err!=DC1394_SUCCESS) { dc1394_log_error("unable to capture"); dc1394_capture_stop(camera); dc1394_camera_free(camera); exit(1); } // attempt to preallocate image array and write to memory before dumping to disk. // turns out to be slow due to large size of images. cfitsio buffering is far // more efficient. //memcpy(im_buffer+2*i*naxes[0]*naxes[1], //frame->image-1, //naxes[0]*naxes[1]*sizeof(short)); // just writing each frame to the FITS file goes pretty fast fits_write_img(fptr, TUSHORT, fpixel+i*naxes[0]*naxes[1], naxes[0]*naxes[1], frame->image-1, &status); // release buffer dc1394_capture_enqueue(camera,frame); } gettimeofday(&end_time, NULL); printf("End capture.\n"); /*----------------------------------------------------------------------- * stop data transmission *-----------------------------------------------------------------------*/ start_sec = start_time.tv_sec; start_usec = start_time.tv_usec; end_sec = end_time.tv_sec; end_usec = end_time.tv_usec; elapsed_time = (float)((end_sec + 1.0e-6*end_usec) - (start_sec + 1.0e-6*start_usec)); fps = grab_n_frames/elapsed_time; printf("Elapsed time = %g seconds.\n", elapsed_time); printf("Framerate = %g fps.\n", fps); err=dc1394_video_set_transmission(camera,DC1394_OFF); DC1394_ERR_RTN(err,"couldn't stop the camera?"); /*----------------------------------------------------------------------- * save FITS image to disk *-----------------------------------------------------------------------*/ //fits_write_img(fptr, TUSHORT, fpixel, naxes[0]*naxes[1]*naxes[2], im_buffer, &status); fits_close_file(fptr, &status); fits_report_error(stderr, status); //free(im_buffer); printf("wrote: %s\n", filename); printf("Image is %d bits/pixel.\n", frame->data_depth); /*----------------------------------------------------------------------- * close camera, cleanup *-----------------------------------------------------------------------*/ dc1394_capture_stop(camera); dc1394_video_set_transmission(camera, DC1394_OFF); dc1394_camera_free(camera); dc1394_free (d); return 0; }
int main(int argc, char *argv []) { if(populate_env_variable(REF_ERROR_CODES_FILE, "L2_ERROR_CODES_FILE")) { printf("\nUnable to populate [REF_ERROR_CODES_FILE] variable with corresponding environment variable. Routine will proceed without error handling\n"); } if (argc != 7) { if(populate_env_variable(SPE_BLURB_FILE, "L2_SPE_BLURB_FILE")) { RETURN_FLAG = 1; } else { print_file(SPE_BLURB_FILE); } write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -1, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); return 1; } else { // *********************************************************************** // Redefine routine input parameters char *input_f = strdup(argv[1]); char *method = strdup(argv[2]); char *ss_method = strdup(argv[3]); double target_half_aperture_px = strtod(argv[4], NULL); int sky_window_half_aperture_px = strtol(argv[5], NULL, 0); char *output_f = strdup(argv[6]); // *********************************************************************** // Open input file (ARG 1), get parameters and perform any data format // checks fitsfile *input_f_ptr; int input_f_maxdim = 2, input_f_status = 0, input_f_bitpix, input_f_naxis; long input_f_naxes [2] = {1,1}; if(!fits_open_file(&input_f_ptr, input_f, IMG_READ_ACCURACY, &input_f_status)) { if(!populate_img_parameters(input_f, input_f_ptr, input_f_maxdim, &input_f_bitpix, &input_f_naxis, input_f_naxes, &input_f_status, "INPUT FRAME")) { if (input_f_naxis != 2) { // any data format checks here write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -2, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); free(input_f); free(output_f); free(method); free(ss_method); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); return 1; } } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -3, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, input_f_status); free(input_f); free(output_f); free(method); free(ss_method); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); return 1; } } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -4, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, input_f_status); free(input_f); free(output_f); free(method); free(ss_method); return 1; } // *********************************************************************** // Set the range limits int cut_x [2] = {1, input_f_naxes[0]}; int cut_y [2] = {1, input_f_naxes[1]}; // *********************************************************************** // Set parameters used when reading data from input file (ARG 1) long fpixel [2] = {cut_x[0], cut_y[0]}; long nxelements = (cut_x[1] - cut_x[0]) + 1; long nyelements = (cut_y[1] - cut_y[0]) + 1; // *********************************************************************** // Create arrays to store pixel values from input fits file (ARG 1) double input_f_pixels [nxelements]; // *********************************************************************** // Get input fits file (ARG 1) values and store in 2D array int ii; double input_frame_values [nyelements][nxelements]; memset(input_frame_values, 0, sizeof(double)*nxelements*nyelements); for (fpixel[1] = cut_y[0]; fpixel[1] <= cut_y[1]; fpixel[1]++) { memset(input_f_pixels, 0, sizeof(double)*nxelements); if(!fits_read_pix(input_f_ptr, TDOUBLE, fpixel, nxelements, NULL, input_f_pixels, NULL, &input_f_status)) { for (ii=0; ii<nxelements; ii++) { input_frame_values[fpixel[1]-1][ii] = input_f_pixels[ii]; } } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -5, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, input_f_status); free(input_f); free(output_f); free(method); free(ss_method); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); return 1; } } // *********************************************************************** // Open [SPFIND_OUTPUTF_PEAKS_FILE] input file FILE *inputfile; if (!check_file_exists(SPFIND_OUTPUTF_PEAKS_FILE)) { inputfile = fopen(SPFIND_OUTPUTF_PEAKS_FILE , "r"); } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -6, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); return 1; } // *********************************************************************** // Find some [SPFIND_OUTPUTF_PEAKS_FILE] input file details char input_string [150]; int row_count = 0; while(!feof(inputfile)) { memset(input_string, '\0', sizeof(char)*150); fgets(input_string, 150, inputfile); if (strtol(&input_string[0], NULL, 0) > 0) { // check the line begins with a positive number (usable) row_count++; } } rewind(inputfile); // *********************************************************************** // Store [SPFIND_OUTPUTF_PEAKS_FILE] data double x_coords[row_count]; memset(x_coords, 0, sizeof(double)*(row_count)); double y_coords[row_count]; memset(y_coords, 0, sizeof(double)*(row_count)); double coord_x, coord_y; int idx = 0; while(!feof(inputfile)) { memset(input_string, '\0', sizeof(char)*150); fgets(input_string, 150, inputfile); if (strtol(&input_string[0], NULL, 0) > 0) { // check the line begins with a positive number (usable) sscanf(input_string, "%lf\t%lf\n", &coord_x, &coord_y); x_coords[idx] = coord_x; y_coords[idx] = coord_y; idx++; } } double output_frame_values[nxelements]; memset(output_frame_values, 0, sizeof(double)*nxelements); // *********************************************************************** // EXTRACTION if (strcmp(method, "simple") == 0) { // *********************************************************************** // PARTIAL PIXEL APERTURE int ii, jj; double y; y = y_coords[0]; // should only be one bin in [SPFIND_OUTPUTF_PEAKS_FILE] data file double this_col_value; for (ii=0; ii<nxelements; ii++) { this_col_value = 0.; // *********************************************************************** // Does [y] violate the img boundaries? if ((y + target_half_aperture_px > nyelements) || (y - target_half_aperture_px <= 0)) { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -7, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, input_f_status); free(input_f); free(output_f); free(method); free(ss_method); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); fclose(inputfile); return 1; } // *********************************************************************** // Extract flux within aperture double y_low, y_high; y_low = y-target_half_aperture_px-0.5; y_high = y+target_half_aperture_px+0.5; int y_low_floor, y_high_floor; y_low_floor = floor(y-target_half_aperture_px-0.5); // 0.5 as taking (half_ap*2) + 1 as total aperture y_high_floor = floor(y+target_half_aperture_px+0.5); for (jj=y_low_floor; jj<=y_high_floor; jj++) { if (jj == y_low_floor) { // outside pixel where partial flux needs to be taken into account double partial_fraction_of_bin = (y_low_floor + 1) - y_low; this_col_value += partial_fraction_of_bin * input_frame_values[jj][ii]; } else if (jj == y_high_floor) { // outside pixel where partial flux needs to be taken into account double partial_fraction_of_bin = y_high - y_high_floor; this_col_value += partial_fraction_of_bin * input_frame_values[jj][ii]; } else { this_col_value += input_frame_values[jj][ii]; } } output_frame_values[ii] = this_col_value; } } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -8, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, input_f_status); free(input_f); free(output_f); free(method); free(ss_method); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); fclose(inputfile); return 1; } // *********************************************************************** // SKY SUBTRACTION if (strcmp(ss_method, "none") == 0) { } else if (strcmp(ss_method, "median") == 0) { // *********************************************************************** // MEDIAN SUBTRACTION int ii, jj; double y; y = y_coords[0]; // should only be one bin in [SPFIND_OUTPUTF_PEAKS_FILE] data file double this_col_value; for (ii=0; ii<nxelements; ii++) { this_col_value = 0.; // *********************************************************************** // Does [y] violate the img boundaries? if ((y + target_half_aperture_px + sky_window_half_aperture_px > nyelements) || (y - target_half_aperture_px - sky_window_half_aperture_px <= 0)) { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -9, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, input_f_status); free(input_f); free(output_f); free(method); free(ss_method); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); fclose(inputfile); return 1; } // *********************************************************************** // Find pixels for sky aperture int ap_lower_lo, ap_lower_hi, ap_upper_lo, ap_upper_hi; ap_lower_lo = floor(y-target_half_aperture_px-0.5) - sky_window_half_aperture_px - 1; ap_lower_hi = floor(y-target_half_aperture_px-0.5) - 1; ap_upper_lo = floor(y+target_half_aperture_px+0.5) + 1; ap_upper_hi = floor(y+target_half_aperture_px+0.5) + sky_window_half_aperture_px + 1; int n_ap_values = (ap_lower_hi-ap_lower_lo) + (ap_upper_hi-ap_upper_lo) + 2; double ap_values[n_ap_values]; int idx = 0; for (jj=ap_lower_lo; jj<=ap_lower_hi; jj++) { ap_values[idx] = input_frame_values[jj][ii]; idx++; } for (jj=ap_upper_lo; jj<=ap_upper_hi; jj++) { ap_values[idx] = input_frame_values[jj][ii]; idx++; } // DEBUG /*for (jj=0; jj<idx; jj++) printf("%f,", ap_values[jj]); printf("\n"); for (jj=0; jj<idx; jj++) printf("%d,", jj); printf("\n");*/ // Take median double ap_values_sorted [n_ap_values]; memcpy(ap_values_sorted, ap_values, sizeof(double)*n_ap_values); gsl_sort(ap_values_sorted, 1, (ap_lower_hi-ap_lower_lo) + (ap_upper_hi-ap_upper_lo) + 2); double ap_values_median = gsl_stats_median_from_sorted_data(ap_values_sorted, 1, n_ap_values); this_col_value = ap_values_median * ((target_half_aperture_px*2) + 1); // need to scale up to target extraction aperture size output_frame_values[ii] -= this_col_value; } } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -10, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, input_f_status); free(input_f); free(output_f); free(method); free(ss_method); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); fclose(inputfile); return 1; } // *********************************************************************** // Set output frame parameters fitsfile *output_f_ptr; int output_f_status = 0; long output_f_naxes [2] = {nxelements, 1}; long output_f_fpixel = 1; // *********************************************************************** // Create and write [output_frame_values] to output file (ARG 6) if (!fits_create_file(&output_f_ptr, output_f, &output_f_status)) { if (!fits_create_img(output_f_ptr, INTERMEDIATE_IMG_ACCURACY[0], 2, output_f_naxes, &output_f_status)) { if (!fits_write_img(output_f_ptr, INTERMEDIATE_IMG_ACCURACY[1], output_f_fpixel, nxelements, output_frame_values, &output_f_status)) { } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -11, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, output_f_status); free(input_f); free(output_f); free(method); free(ss_method); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); if(fits_close_file(output_f_ptr, &output_f_status)) fits_report_error (stdout, output_f_status); fclose(inputfile); return 1; } } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -12, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, output_f_status); free(input_f); free(output_f); free(method); free(ss_method); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); if(fits_close_file(output_f_ptr, &output_f_status)) fits_report_error (stdout, output_f_status); fclose(inputfile); return 1; } } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -13, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, output_f_status); free(input_f); free(output_f); free(method); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); fclose(inputfile); return 1; } // *********************************************************************** // Free arrays on heap free(input_f); free(output_f); free(method); free(ss_method); // *********************************************************************** // Close input file (ARG 1) and output file (ARG 6) if(fits_close_file(input_f_ptr, &input_f_status)) { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -14, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error (stdout, input_f_status); return 1; } if(fits_close_file(output_f_ptr, &output_f_status)) { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", -15, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error (stdout, output_f_status); return 1; } if (fclose(inputfile)) { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATTR", -16, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); return 1; } // Write success to [ERROR_CODES_FILE] write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATEX", RETURN_FLAG, "Status flag for L2 spextract routine", ERROR_CODES_FILE_WRITE_ACCESS); return 0; } }
/// Saves the current image in the OpenCL memory buffer to the specified FITS file /// If the OpenCL memory has not been initialzed, this function immediately returns void CLibOI::ExportImage(string filename) { if(mImage_cl == NULL) return; // TODO: Adapt for multi-spectral images Normalize(); // Create a storage buffer for the image and copoy the image to it: valarray<float> image(mImageWidth * mImageHeight * mImageDepth); ExportImage(&image[0], mImageWidth, mImageHeight, mImageDepth); // write out the FITS file: fitsfile *fptr; int status = 0; long fpixel = 1, naxis = 2, nelements; long naxes[2]; /*Initialise storage*/ naxes[0] = (long) mImageWidth; naxes[1] = (long) mImageHeight; nelements = mImageWidth * mImageWidth; /*Create new file*/ if (status == 0) fits_create_file(&fptr, filename.c_str(), &status); /*Create primary array image*/ if (status == 0) fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status); double RPMAS = (M_PI / 180.0) / 3600000.0; double image_scale_rad = mImageScale * RPMAS; // Write keywords to get WCS to work // fits_write_key_dbl(fptr, "CDELT1", -image_scale_rad, 3, "Radians per pixel", &status); fits_write_key_dbl(fptr, "CDELT2", image_scale_rad, 3, "Radians per pixel", &status); fits_write_key_dbl(fptr, "CRVAL1", 0.0, 3, "X-coordinate of reference pixel", &status); fits_write_key_dbl(fptr, "CRVAL2", 0.0, 3, "Y-coordinate of reference pixel", &status); fits_write_key_lng(fptr, "CRPIX1", naxes[0]/2, "reference pixel in X", &status); fits_write_key_lng(fptr, "CRPIX2", naxes[1]/2, "reference pixel in Y", &status); fits_write_key_str(fptr, "CTYPE1", "RA", "Name of X-coordinate", &status); fits_write_key_str(fptr, "CTYPE2", "DEC", "Name of Y-coordinate", &status); fits_write_key_str(fptr, "CUNIT1", "rad", "Unit of X-coordinate", &status); fits_write_key_str(fptr, "CUNIT2", "rad", "Unit of Y-coordinate", &status); /*Write a keywords (datafile, target, image scale) */ // if (status == 0) // fits_update_key(fptr, TSTRING, "DATAFILE", "FakeImage", "Data File Name", &status); // if (status == 0) // fits_update_key(fptr, TSTRING, "TARGET", "FakeImage", "Target Name", &status); // if (status == 0) // fits_update_key(fptr, TFLOAT, "SCALE", &mImageScale, "Scale (mas/pixel)", &status); /*Write image*/ if (status == 0) fits_write_img(fptr, TFLOAT, fpixel, nelements, &image[0], &status); /*Close file*/ if (status == 0) fits_close_file(fptr, &status); /*Report any errors*/ fits_report_error(stderr, status); }
static fitsfile* create_fits_file(const char* filename, int precision, int width, int height, int num_times, int num_channels, double centre_deg[2], double fov_deg[2], double start_time_mjd, double delta_time_sec, double start_freq_hz, double delta_freq_hz, int horizon_mode, const char* settings_log, size_t settings_log_length, int* status) { int imagetype; long naxes[4], naxes_dummy[4] = {1l, 1l, 1l, 1l}; double delta; const double deg2rad = M_PI / 180.0; const double rad2deg = 180.0 / M_PI; fitsfile* f = 0; const char* line; size_t length; if (*status) return 0; /* Create a new FITS file and write the image headers. */ if (oskar_file_exists(filename)) remove(filename); imagetype = (precision == OSKAR_DOUBLE ? DOUBLE_IMG : FLOAT_IMG); naxes[0] = width; naxes[1] = height; naxes[2] = num_channels; naxes[3] = num_times; fits_create_file(&f, filename, status); fits_create_img(f, imagetype, 4, naxes_dummy, status); fits_write_date(f, status); fits_write_key_str(f, "TELESCOP", "OSKAR " OSKAR_VERSION_STR, 0, status); /* Write axis headers. */ if (horizon_mode) { delta = oskar_convert_fov_to_cellsize(M_PI, width); write_axis(f, 1, "-----SIN", "Azimuthal angle", 0.0, -delta * rad2deg, (width + 1) / 2.0, status); delta = oskar_convert_fov_to_cellsize(M_PI, height); write_axis(f, 2, "-----SIN", "Elevation", 90.0, delta * rad2deg, (height + 1) / 2.0, status); } else { delta = oskar_convert_fov_to_cellsize(fov_deg[0] * deg2rad, width); write_axis(f, 1, "RA---SIN", "Right Ascension", centre_deg[0], -delta * rad2deg, (width + 1) / 2.0, status); delta = oskar_convert_fov_to_cellsize(fov_deg[1] * deg2rad, height); write_axis(f, 2, "DEC--SIN", "Declination", centre_deg[1], delta * rad2deg, (height + 1) / 2.0, status); } write_axis(f, 3, "FREQ", "Frequency", start_freq_hz, delta_freq_hz, 1.0, status); write_axis(f, 4, "UTC", "Time", start_time_mjd * 86400.0, delta_time_sec, 1.0, status); /* Write other headers. */ fits_write_key_str(f, "TIMESYS", "UTC", NULL, status); fits_write_key_str(f, "TIMEUNIT", "s", "Time axis units", status); fits_write_key_dbl(f, "MJD-OBS", start_time_mjd, 10, "Start time", status); if (!horizon_mode) { fits_write_key_dbl(f, "OBSRA", centre_deg[0], 10, "RA", status); fits_write_key_dbl(f, "OBSDEC", centre_deg[1], 10, "DEC", status); } /* Write the settings log up to this point as HISTORY comments. */ line = settings_log; length = settings_log_length; for (; settings_log_length > 0;) { const char* eol; fits_write_history(f, line, status); eol = (const char*) memchr(line, '\0', length); if (!eol) break; eol += 1; length -= (eol - line); line = eol; } /* Update header keywords with the correct axis lengths. * Needs to be done here because CFITSIO doesn't let us write only the * file header with the correct axis lengths to start with. This trick * allows us to create a small dummy image block to write only the headers, * and not waste effort moving a huge block of zeros within the file. */ fits_update_key_lng(f, "NAXIS1", naxes[0], 0, status); fits_update_key_lng(f, "NAXIS2", naxes[1], 0, status); fits_update_key_lng(f, "NAXIS3", naxes[2], 0, status); fits_update_key_lng(f, "NAXIS4", naxes[3], 0, status); return f; }
void write_fits(char *filename, int w, int h, unsigned short *data, double obs_duration, char* obs_type, double obs_temperature, int obs_filterNumber, char* serial_number, char* name, char* ra, char* dec, char* alt, char * az ) { fitsfile *fptr; /* pointer to the FITS file, defined in fitsio.h */ int status; long fpixel, nelements; /* Initialize FITS image parameters */ int bitpix = USHORT_IMG; /* 16-bit unsigned short pixel values */ long naxis = 2; /* 2-dimensional image */ long naxes[2] = { 256,256 }; /* default image 256 wide by 256 rows */ /* Set the actual width and height of the image */ naxes[0] = w; naxes[1] = h; /* Delete old FITS file if it already exists */ remove(filename); /* Must initialize status before calling fitsio routines */ status = 0; /* Create a new FITS file and show error message if one occurs */ if (fits_create_file(&fptr, filename, &status)) show_cfitsio_error( status ); /* Write the required keywords for the primary array image. */ /* Since bitpix = USHORT_IMG, this will cause cfitsio to create */ /* a FITS image with BITPIX = 16 (signed short integers) with */ /* BSCALE = 1.0 and BZERO = 32768. This is the convention that */ /* FITS uses to store unsigned integers. Note that the BSCALE */ /* and BZERO keywords will be automatically written by cfitsio */ /* in this case. */ if ( fits_create_img(fptr, bitpix, naxis, naxes, &status) ) show_cfitsio_error( status ); fpixel = 1; /* first pixel to write */ nelements = naxes[0] * naxes[1]; /* number of pixels to write */ /* Write the array of unsigned integers to the FITS file */ if ( fits_write_img(fptr, TUSHORT, fpixel, nelements, data, &status) ) show_cfitsio_error( status ); /* Write optional keywords to the header */ if ( fits_update_key_dbl(fptr, "EXPTIME", obs_duration, -3, "exposure time (seconds)", &status) ) show_cfitsio_error( status ); if ( fits_update_key_dbl(fptr, "TEMPERAT", obs_temperature, -3, "temperature (C)", &status) ) show_cfitsio_error( status ); if ( fits_update_key_str(fptr, "IMAGETYP", obs_type, "image type", &status) ) show_cfitsio_error( status ); if ( fits_update_key(fptr, TSHORT, "FILTNUM", &obs_filterNumber, NULL, &status)) show_cfitsio_error( status ); if ( fits_write_date(fptr, &status) ) show_cfitsio_error( status ); if ( fits_update_key_str(fptr, "SERIALNO", serial_number, "serial number", &status) ) show_cfitsio_error( status ); if ( fits_update_key_str(fptr, "TARGET", name, "target name", &status) ) show_cfitsio_error( status ); if ( fits_update_key_str(fptr, "RA", ra, "right ascension", &status) ) show_cfitsio_error( status ); if ( fits_update_key_str(fptr, "DEC", dec, "declination", &status) ) show_cfitsio_error( status ); if ( fits_update_key_str(fptr, "EPOCH", "JNOW", "epoch of coordinates", &status) ) show_cfitsio_error( status ); if ( fits_update_key_str(fptr, "OBJCTRA", ra, "right ascension", &status) ) show_cfitsio_error( status ); if ( fits_update_key_str(fptr, "OBJCTDEC", dec, "declination", &status) ) show_cfitsio_error( status ); if ( fits_update_key_dbl(fptr, "ALTITUDE", atof(alt), -4, "Altitude (deg)", &status) ) show_cfitsio_error( status ); if ( fits_update_key_dbl(fptr, "AZIMUTH", atof(az), -4, "Azimuth (deg)", &status) ) show_cfitsio_error( status ); /* Close the file */ if ( fits_close_file(fptr, &status) ) show_cfitsio_error( status ); return; }