/* 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); }
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); }
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 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); }
void __fastcall TForm1::BGuardarClick(TObject *Sender) { fitsfile *fptr; /* pointer to the FITS file, defined in fitsio.h */ int status; AnsiString N; ejex = X2; ejey = Y2; long n = X2*Y2; if(SD1->Execute()) { status = 0; N = SD1->FileName + ".fit"; if(ffinit(&fptr, N.c_str(), &status)) { printerror( status ); status = 0; if ( fits_open_file(&fptr, N.c_str(), READWRITE, &status) ) { printerror(status); return; } } } else return; long axes[2]; axes[0] = ejex; axes[1] = ejey; if(ffcrim(fptr, 16, 2, axes, &status)) { printerror(status); return; } unsigned short *datos; datos = new unsigned short [ejex*ejey]; memset(datos, 0, ejex*ejey*2); for(int py = 0; py < ejey; py++) { for (int px = ejex; px > 0; px--) { datos[n--] = Foto[py][px]; } } status = 0; if(fits_write_img(fptr, TSHORT, 1, ejex*ejey, datos, &status)) { printerror( status ); } delete datos; return; }
/** * 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); }
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 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); }
/** 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); }
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 ; }
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); }
//---------------------------------------------------------------------------------- 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 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 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; }
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; }
// / 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); }
bool INDI::CCD::ExposureComplete(CCDChip *targetChip) { void *memptr; size_t memsize; int img_type=0; int byte_type=0; int status=0; long naxes[2]; long naxis=2; int nelements=0; fitsfile *fptr=NULL; naxes[0]=targetChip->getSubW()/targetChip->getBinX(); naxes[1]=targetChip->getSubH()/targetChip->getBinY(); switch (targetChip->getBPP()) { case 8: byte_type = TBYTE; img_type = BYTE_IMG; break; case 16: byte_type = TUSHORT; img_type = USHORT_IMG; break; case 32: byte_type = TULONG; img_type = ULONG_IMG; break; default: IDLog("Unsupported bits per pixel value %d\n", targetChip->getBPP() ); return false; break; } nelements = naxes[0] * naxes[1]; // Now we have to send fits format data to the client memsize=5760; memptr=malloc(memsize); if(!memptr) { IDLog("Error: failed to allocate memory: %lu\n",(unsigned long)memsize); } fits_create_memfile(&fptr,&memptr,&memsize,2880,realloc,&status); if(status) { IDLog("Error: Failed to create FITS image\n"); fits_report_error(stderr, status); /* print out any error messages */ return false; } fits_create_img(fptr, img_type , naxis, naxes, &status); if (status) { IDLog("Error: Failed to create FITS image\n"); fits_report_error(stderr, status); /* print out any error messages */ return false; } addFITSKeywords(fptr, targetChip); fits_write_img(fptr,byte_type,1,nelements,targetChip->getFrameBuffer(),&status); if (status) { IDLog("Error: Failed to write FITS image\n"); fits_report_error(stderr, status); /* print out any error messages */ return false; } fits_close_file(fptr,&status); targetChip->ImageExposureNP->s=IPS_OK; IDSetNumber(targetChip->ImageExposureNP,NULL); targetChip->FitsB.blob=memptr; targetChip->FitsB.bloblen=memsize; targetChip->FitsB.size=memsize; strcpy(targetChip->FitsB.format,".fits"); targetChip->FitsBP->s=IPS_OK; //IDLog("Enter Uploadfile with %d total sending via %s, and format %s\n",total,targetChip->FitsB.name, targetChip->FitsB.format); IDSetBLOB(targetChip->FitsBP,NULL); free(memptr); return true; }
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ! !.func close_frame_fast() ! !.purp closes a currently active 2D frame !.desc ! close_frame(frame) ! ! IMAGE2D *frame; image structure !.ed -------------------------------------------------------------------- */ int close_frame_fast(IMAGE2D *frame) /* close active frame */ { char errtext[132], filename[lg_name+1]; int stat, int_datatype; float cuts[4]; #ifdef IRAF int one=1; #endif #ifdef FITS fitsfile *fptr; int npix; #endif strcpy(filename,frame->name); if (frame->iomode == (int)I_MODE) { switch (frame->data_format) { #ifdef MIDAS case MIDAS_FORMAT : stat = SCFCLO(frame->imno); break; #endif #ifdef IRAF case IRAF_FORMAT : case STSDAS_FORMAT : uimclo(&(frame->imno),&stat); break; #endif #ifdef FITS case FITS_A_FORMAT : case FITS_B_FORMAT : stat =0; fptr = (fitsfile *)frame->external_info; fits_close_file(fptr,&stat); free_frame_mem(frame); frame->external_info = NULL; break; #endif } if (stat) { sprintf(errtext,"close_frame: frame %s",filename); stat = get_tiger_errcode(frame->data_format,stat); Handle_Error(errtext,stat); } return(stat); } /* if (frame->data.d_data != NULL) { image_minmax(frame); cuts[0]=(float)frame->min; cuts[2]=(float)frame->min; cuts[1]=(float)frame->max; cuts[3]=(float)frame->max; stat = WR_desc(frame,"LHCUTS",FLOAT,4,cuts); } */ WR_history(frame, (Anyfile *)0); switch (frame->data_format) { #ifdef MIDAS case MIDAS_FORMAT : stat = SCFCLO(frame->imno); break; #endif #ifdef IRAF case IRAF_FORMAT : case STSDAS_FORMAT : switch(frame->data_type) { case SHORT : uips2s(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.s_data,&stat); break; case INT : case LONG : uips2l(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.l_data,&stat); break; case FLOAT : uips2r(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.f_data,&stat); break; case DOUBLE : uips2d(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny), frame->data.d_data,&stat); break; } if (stat == 0) uimclo(&(frame->imno),&stat); free_frame_mem(frame); break; #endif #ifdef FITS case FITS_A_FORMAT : case FITS_B_FORMAT : stat = 0; fptr = (fitsfile *)frame->external_info; if (frame->iomode != (int)I_MODE) { if (frame->data.d_data != NULL) { int_datatype = get_datatype_code(OutputIO.basic_io,frame->data_type); npix = frame->nx*frame->ny; if (fits_write_img(fptr,int_datatype,1L,npix, frame->data.s_data,&stat)) { stat = ERR_WRIT; } } } if (! stat) { fits_close_file(fptr,&stat); stat = wcs_free(frame); } free_frame_mem(frame); frame->external_info = NULL; break; #endif } if (stat) { sprintf(errtext,"close_frame: frame %s",filename); stat = get_tiger_errcode(frame->data_format,stat); Handle_Error(errtext,stat); } else { if (TK && (frame->iomode == O_MODE || frame->iomode == IO_MODE)) { printf("@ N {%s}\n",filename); } } return(stat); }
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); }
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; }
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; } }
bool Fits2D::writeFits(Mat img, ImgBitDepth imgType, string fileName, string compression) { int status = 0; long firstPixel, nbelements; // 2-dimensional image. long naxis = 2; // Image size. long naxes[2] = { img.cols, img.rows }; // First pixel to write. firstPixel = 1; // Number of pixels to write. nbelements = naxes[0] * naxes[1]; // Fits creation date : 'YYYY-MM-JJTHH:MM:SS.SS' boost::posix_time::ptime time = boost::posix_time::microsec_clock::universal_time(); kDATE = to_iso_extended_string(time); // Date in the fits filename. string dateFileName = TimeDate::getYYYYMMDDThhmmss(to_iso_string(time)); // Define CRPIX1 and CRPIX2 kCRPIX1 = (int)naxes[0] / 2; kCRPIX2 = (int)naxes[1] / 2; fitsfile *fptr; const char * filename; const char * filename2; // Creation of the fits filename. string pathAndname = ""; if(fileName != ""){ pathAndname = mFitsPath + fileName + ".fit"; kFILENAME = fileName + ".fit"; }else{ pathAndname = mFitsPath + kTELESCOP + "_" + dateFileName + "_UT.fit"; kFILENAME = kTELESCOP + "_" + dateFileName + "_UT.fit"; } filename = pathAndname.c_str(); pathAndname += compression; filename2 = pathAndname.c_str(); switch(imgType){ // UC8 case 0: { //https://www-n.oca.eu/pichon/Tableau_2D.pdf unsigned char ** tab = (unsigned char * *)malloc( img.rows * sizeof(unsigned char *)) ; if(tab == NULL){ BOOST_LOG_SEV(logger, fail) << "Fail to allocate unsigned char** array (NULL)."; return false; } tab[0] = (unsigned char *) malloc( naxes[0] * naxes[1] * sizeof(unsigned char) ) ; if(tab[0] == NULL){ BOOST_LOG_SEV(logger, fail) << "Fail to allocate unsigned char* array (NULL)."; return false; } for( int a = 1; a<naxes[1]; a++ ){ tab[a] = tab[a-1] + naxes[0]; } // Delete old file if it already exists. remove(filename); // Create new FITS file. if(fits_create_file(&fptr, filename2, &status)){ printerror(status); free(tab[0]); return false; } if (fits_create_img(fptr, BYTE_IMG, naxis, naxes, &status)){ printerror(status); free(tab[0]); return false; } // Initialize the values in the fits image with the mat's values. for ( int j = 0; j < naxes[1]; j++){ unsigned char * matPtr = img.ptr<unsigned char>(j); for ( int i = 0; i < naxes[0]; i++){ // Affect a value and inverse the image. tab[img.rows-1-j][i] = (unsigned char)matPtr[i]; } } // Write the array of unsigned short to the FITS file. if(fits_write_img(fptr, TBYTE, firstPixel, nbelements, tab[0], &status)){ printerror(status); free(tab[0]); return false; } // Free previously allocated memory. free(tab[0]); break; } case 1: { //https://www-n.oca.eu/pichon/Tableau_2D.pdf char ** tab = (char * *) malloc( img.rows * sizeof( char * ) ) ; if(tab == NULL){ BOOST_LOG_SEV(logger, fail) << "Fail to allocate char** array (NULL)."; return false; } tab[0] = (char *) malloc( naxes[0] * naxes[1] * sizeof(char) ) ; if(tab[0] == NULL){ BOOST_LOG_SEV(logger, fail) << "Fail to allocate char* array (NULL)."; return false; } for( int a = 1; a<naxes[1]; a++ ){ tab[a] = tab[a-1] + naxes[0]; } // Delete old file if it already exists. remove(filename); // Create new FITS file. if(fits_create_file(&fptr, filename2, &status)){ printerror(status); free(tab[0]); return false; } if(fits_create_img(fptr, SBYTE_IMG, naxis, naxes, &status)){ printerror(status); free(tab[0]); return false; } // Initialize the values in the fits image with the mat's values. for( int j = 0; j < naxes[1]; j++){ char * matPtr = img.ptr<char>(j); for(int i = 0; i < naxes[0]; i++){ // Affect a value and inverse the image. tab[img.rows-1-j][i] = (char)matPtr[i]; } } // Write the array of unsigned short to the FITS file. if(fits_write_img(fptr, TSBYTE, firstPixel, nbelements, tab[0], &status)){ printerror(status); free(tab[0]); return false; } // Free previously allocated memory. free(tab[0]); break; } case 2 : { //https://www-n.oca.eu/pichon/Tableau_2D.pdf unsigned short ** tab = (unsigned short * *) malloc( img.rows * sizeof( unsigned short * ) ) ; if(tab == NULL){ BOOST_LOG_SEV(logger, fail) << "Fail to allocate unsigned short** array (NULL)."; return false; } tab[0] = (unsigned short *) malloc( naxes[0] * naxes[1] * sizeof(unsigned short) ) ; if(tab[0] == NULL){ BOOST_LOG_SEV(logger, fail) << "Fail to allocate unsigned short* array (NULL)."; return false; } for( int a = 1; a<naxes[1]; a++ ){ tab[a] = tab[a-1] + naxes[0]; } // Delete old file if it already exists. remove(filename); // Create new FITS file. if (fits_create_file(&fptr, filename2, &status)){ printerror(status); free( *tab); free( tab ); return false; } if ( fits_create_img(fptr, USHORT_IMG, naxis, naxes, &status)){ printerror(status); free( *tab); free( tab ); return false; } // Initialize the values in the fits image with the mat's values. for ( int j = 0; j < naxes[1]; j++){ unsigned short * matPtr = img.ptr<unsigned short>(j); for ( int i = 0; i < naxes[0]; i++){ // Affect a value and inverse the image. tab[img.rows-1-j][i] = (unsigned short)matPtr[i]; } } // write the array of unsigned short to the FITS file if ( fits_write_img(fptr, TUSHORT, firstPixel, nbelements, tab[0], &status)){ printerror(status); free( *tab); free( tab ); return false; } // Free previously allocated memory. free( *tab); free( tab ); break; } case 3 : { Mat newMat; if(img.type() == CV_16UC1) { // Convert unsigned short type image in short type image. newMat = Mat(img.rows, img.cols, CV_16SC1, Scalar(0)); // Set bzero and bscale for print unsigned short value in soft visualization. kBZERO = 32768; kBSCALE = 1; unsigned short * ptr; short * ptr2; for(int i = 0; i < img.rows; i++){ ptr = img.ptr<unsigned short>(i); ptr2 = newMat.ptr<short>(i); for(int j = 0; j < img.cols; j++){ if(ptr[j] - 32768 > 32767){ ptr2[j] = 32767; }else{ ptr2[j] = ptr[j] - 32768; } } } }else{ img.copyTo(newMat); } //https://www-n.oca.eu/pichon/Tableau_2D.pdf short ** tab = (short * *) malloc( img.rows * sizeof( short * ) ) ; if(tab == NULL){ BOOST_LOG_SEV(logger, fail) << "Fail to allocate short** array (NULL)."; return false; } tab[0] = (short *) malloc( naxes[0] * naxes[1] * sizeof(short) ) ; if(tab[0] == NULL){ BOOST_LOG_SEV(logger, fail) << "Fail to allocate short* array (NULL)."; return false; } for( int a = 1; a<naxes[1]; a++ ){ tab[a] = tab[a-1] + naxes[0]; } // Delete old file if it already exists. remove(filename); // Create new FITS file. if (fits_create_file(&fptr, filename2, &status)){ printerror(status); free( *tab); free( tab ); return false; } if ( fits_create_img(fptr, SHORT_IMG, naxis, naxes, &status)){ printerror(status); free( *tab); free( tab ); return false; } // Initialize the values in the fits image with the mat's values. for ( int j = 0; j < naxes[1]; j++){ short * matPtr = newMat.ptr<short>(j); for ( int i = 0; i < naxes[0]; i++){ // Affect a value and inverse the image. tab[newMat.rows-1-j][i] = (short)matPtr[i]; } } // write the array of signed short to the FITS file if ( fits_write_img(fptr, TSHORT, firstPixel, nbelements, tab[0], &status)){ printerror(status); free( *tab); free( tab ); return false; } // Free previously allocated memory. free( *tab); free( tab ); break; } case 4 : { //https://www-n.oca.eu/pichon/Tableau_2D.pdf float ** tab = (float * *) malloc( img.rows * sizeof( float * ) ) ; if(tab == NULL){ BOOST_LOG_SEV(logger, fail) << "Fail to allocate float** array (NULL)."; return false; } tab[0] = (float *) malloc( naxes[0] * naxes[1] * sizeof(float) ) ; if(tab[0] == NULL){ BOOST_LOG_SEV(logger, fail) << "Fail to allocate float* array (NULL)."; return false; } for( int a = 1; a<naxes[1]; a++ ){ tab[a] = tab[a-1] + naxes[0]; } // Delete old file if it already exists. remove(filename); // Create new FITS file if(fits_create_file(&fptr, filename, &status)){ printerror(status); free( *tab); free( tab ); return false; } if( fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status)){ printerror(status); free( *tab); free( tab ); return false; } // Initialize the values in the fits image with the mat's values. for( int j = 0; j < naxes[1]; j++){ float * matPtr = img.ptr<float>(j); for ( int i = 0; i < naxes[0]; i++){ // Affect a value and inversed the image. tab[img.rows-1-j][i] = (float)matPtr[i]; } } // Write the array of unsigned short to the FITS file. if( fits_write_img(fptr, TFLOAT, firstPixel, nbelements, tab[0], &status)){ printerror(status); free( *tab); free( tab ); return false; } // Free previously allocated memory. free(*tab); free(tab); break; } } if(!writeKeywords(fptr)){ if(fits_close_file(fptr, &status)){ printerror(status); } return false; } if(fits_close_file(fptr, &status)){ printerror(status); return false; } return true; }
/// 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); }
int main(int argc, char **argv) { int i, j, l, m, c, count, ismag, ncol; int dl, dm, width, haveFlux, isImg, csys; int side, ibegin, iend, nstep, useCenter; int racol, deccol, fluxcol; int ra1col, dec1col; int ra2col, dec2col; int ra3col, dec3col; int ra4col, dec4col; long fpixel, nelements; double rac, decc; double ra[4], dec[4]; double x, y, z; double x0, y0, z0; double x1, y1, z1; double oxpix, oypix, equinox; int offscl; double ilon; double ilat; double pixscale, len, sideLength, dtr; double offset; double xn, yn, zn; double ran, decn; double sina, cosa; double sind, cosd; double a11, a12, a13; double a21, a22, a23; double a31, a32, a33; double x0p, y0p, z0p; double x1p, y1p, z1p; double lon0, lon1; double xp, yp; double lon; double pixel_value; double weights[5][5]; double weights3[5][5] = {{0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.1, 0.2, 0.1, 0.0}, {0.0, 0.2, 1.0, 0.2, 0.0}, {0.0, 0.1, 0.2, 0.1, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0}}; double weights5[5][5] = {{0.0, 0.1, 0.2, 0.1, 0.0}, {0.1, 0.3, 0.5, 0.3, 0.1}, {0.2, 0.5, 1.0, 0.5, 0.2}, {0.1, 0.3, 0.5, 0.3, 0.1}, {0.0, 0.1, 0.2, 0.1, 0.0}}; double **data; int status = 0; char input_file [MAXSTR]; char colname [MAXSTR]; char output_file [MAXSTR]; char template_file[MAXSTR]; int bitpix = DOUBLE_IMG; long naxis = 2; double sumweights; double refmag; dtr = atan(1.0)/45.; /***************************************/ /* Process the command-line parameters */ /***************************************/ ismag = 0; opterr = 0; useCenter = 0; strcpy(colname, ""); while ((c = getopt(argc, argv, "pm:d:w:c:")) != EOF) { switch (c) { case 'm': ismag = 1; refmag = atof(optarg); break; case 'd': debug = debugCheck(optarg); break; case 'w': width = atoi(optarg); break; case 'c': strcpy(colname, optarg); break; case 'p': useCenter = 1; break; default: printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-c column][-m refmag][-d level][-w size] in.tbl out.fits hdr.template\"]\n", argv[0]); exit(1); break; } } if (argc - optind < 3) { printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-c column][-m refmag][-d level][-w size] in.tbl out.fits hdr.template\"]\n", argv[0]); exit(1); } strcpy(input_file, argv[optind]); strcpy(output_file, argv[optind+1]); strcpy(template_file, argv[optind+2]); if(debug >= 1) { printf("input_file = [%s]\n", input_file); printf("colname = [%s]\n", colname); printf("output_file = [%s]\n", output_file); printf("template_file = [%s]\n", template_file); printf("width = %d\n", width); printf("ismag = %d\n", ismag); fflush(stdout); } /********************************************/ /* Set the weights for spreading the points */ /********************************************/ sumweights = 0.; for(i=0; i<5; ++i) { for(j=0; j<5; ++j) { if(width == 3) sumweights += weights3[i][j]; else if(width == 5) sumweights += weights5[i][j]; } } for(i=0; i<5; ++i) { for(j=0; j<5; ++j) { if(width == 3) weights[i][j] = weights3[i][j]/sumweights; else if(width == 5) weights[i][j] = weights5[i][j]/sumweights; else weights[i][j] = 0.; } } if(width != 3 && width != 5) weights[2][2] = 1.; /************************************************/ /* Open the table file and find the data column */ /************************************************/ ncol = topen(input_file); if(ncol <= 0) { printf("[struct stat=\"ERROR\", msg=\"Can't open input table %s\"]\n", input_file); exit(0); } racol = tcol( "ra"); deccol = tcol("dec"); ra1col = tcol( "ra1"); dec1col = tcol("dec1"); ra2col = tcol( "ra2"); dec2col = tcol("dec2"); ra3col = tcol( "ra3"); dec3col = tcol("dec3"); ra4col = tcol( "ra4"); dec4col = tcol("dec4"); haveFlux = 1; if(strlen(colname) == 0) haveFlux = 0; else fluxcol = tcol(colname); isImg = 1; if(ra1col < 0 || dec1col < 0 || ra2col < 0 || dec2col < 0 || ra3col < 0 || dec3col < 0 || ra4col < 0 || dec4col < 0) isImg = 0; if(useCenter) isImg = 0; if(!isImg) { if(racol < 0) { printf("[struct stat=\"ERROR\", msg=\"Can't find column 'ra'\"]\n"); exit(0); } if(deccol < 0) { printf("[struct stat=\"ERROR\", msg=\"Can't find column 'dec'\"]\n"); exit(0); } } if(haveFlux && fluxcol < 0) { printf("[struct stat=\"ERROR\", msg=\"Can't find column '%s'\"]\n", colname); exit(0); } /*************************************************/ /* Process the output header template to get the */ /* image size, coordinate system and projection */ /*************************************************/ readTemplate(template_file); pixscale = fabs(output.wcs->xinc); if(fabs(output.wcs->yinc) > pixscale) pixscale = fabs(output.wcs->yinc); csys = EQUJ; if(strncmp(output.wcs->c1type, "RA", 2) == 0) csys = EQUJ; if(strncmp(output.wcs->c1type, "GLON", 4) == 0) csys = GAL; if(strncmp(output.wcs->c1type, "ELON", 4) == 0) csys = ECLJ; equinox = output.wcs->equinox; if(debug >= 1) { printf("output.naxes[0] = %ld\n", output.naxes[0]); printf("output.naxes[1] = %ld\n", output.naxes[1]); printf("output.sys = %d\n", output.sys); printf("output.epoch = %-g\n", output.epoch); printf("output proj = %s\n", output.wcs->ptype); printf("output crval[0] = %-g\n", output.wcs->crval[0]); printf("output crval[1] = %-g\n", output.wcs->crval[1]); printf("output crpix[0] = %-g\n", output.wcs->crpix[0]); printf("output crpix[1] = %-g\n", output.wcs->crpix[1]); printf("output cdelt[0] = %-g\n", output.wcs->cdelt[0]); printf("output cdelt[1] = %-g\n", output.wcs->cdelt[1]); fflush(stdout); } /***********************************************/ /* Allocate memory for the output image pixels */ /***********************************************/ data = (double **)malloc(output.naxes[1] * sizeof(double *)); data[0] = (double *)malloc(output.naxes[0] * output.naxes[1] * sizeof(double)); if(debug >= 1) { printf("%ld bytes allocated for image pixels\n", output.naxes[0] * output.naxes[1] * sizeof(double)); fflush(stdout); } /**********************************************************/ /* Initialize pointers to the start of each row of pixels */ /**********************************************************/ for(i=1; i<output.naxes[1]; i++) data[i] = data[i-1] + output.naxes[0]; if(debug >= 1) { printf("pixel line pointers populated\n"); fflush(stdout); } for (j=0; j<output.naxes[1]; ++j) { for (i=0; i<output.naxes[0]; ++i) { data[j][i] = 0.; } } /************************/ /* Create the FITS file */ /************************/ remove(output_file); if(fits_create_file(&output.fptr, output_file, &status)) printFitsError(status); /*********************************************************/ /* Create the FITS image. All the required keywords are */ /* handled automatically. */ /*********************************************************/ if (fits_create_img(output.fptr, bitpix, naxis, output.naxes, &status)) printFitsError(status); if(debug >= 1) { printf("FITS image created (not yet populated)\n"); fflush(stdout); } /*****************************/ /* Loop over the input files */ /*****************************/ time(&currtime); start = currtime; /*******************/ /* For each source */ /*******************/ count = 0; while(tread() >= 0) { ++count; if(isImg) { if(debug && count/1000*1000 == count) { printf("%9d image outlines processed\n", count); fflush(stdout); } ra [0] = atof(tval( ra1col)); dec[0] = atof(tval(dec1col)); ra [1] = atof(tval( ra2col)); dec[1] = atof(tval(dec2col)); ra [2] = atof(tval( ra3col)); dec[2] = atof(tval(dec3col)); ra [3] = atof(tval( ra4col)); dec[3] = atof(tval(dec4col)); for(side=0; side<4; ++side) { ibegin = side; iend = (side+1)%4; x0 = cos(ra[ibegin]*dtr) * cos(dec[ibegin]*dtr); y0 = sin(ra[ibegin]*dtr) * cos(dec[ibegin]*dtr); z0 = sin(dec[ibegin]*dtr); x1 = cos(ra[iend]*dtr) * cos(dec[iend]*dtr); y1 = sin(ra[iend]*dtr) * cos(dec[iend]*dtr); z1 = sin(dec[iend]*dtr); xn = y0*z1 - z0*y1; yn = z0*x1 - x0*z1; zn = x0*y1 - y0*x1; len = sqrt(xn*xn + yn*yn + zn*zn); xn = xn / len; yn = yn / len; zn = zn / len; ran = atan2(yn, xn); decn = asin(zn); sina = sin(ran); cosa = cos(ran); sind = sin(decn); cosd = cos(decn); a11 = cosa*sind; a12 = sina*sind; a13 = -cosd; a21 = -sina; a22 = cosa; a23 = 0.; a31 = cosa*cosd; a32 = sina*cosd; a33 = sind; x0p = a11*x0 + a12*y0 + a13*z0; y0p = a21*x0 + a22*y0 + a23*z0; z0p = a31*x0 + a32*y0 + a33*z0; x1p = a11*x1 + a12*y1 + a13*z1; y1p = a21*x1 + a22*y1 + a23*z1; z1p = a31*x1 + a32*y1 + a33*z1; lon0 = atan2(y0p, x0p); lon1 = atan2(y1p, x1p); if(fabs(lon1-lon0)/dtr > 180.) { if(lon0 < 0.) lon0 += 360.*dtr; if(lon1 < 0.) lon1 += 360.*dtr; } sideLength = acos(x0*x1 + y0*y1 + z0*z1) / dtr; offset = pixscale/2.*dtr; if(lon0 > lon1) offset = -offset; nstep = (lon1 - lon0)/offset; lon = lon0; for(i=0; i<nstep; ++i) { lon += offset; xp = cos(lon); yp = sin(lon); x = a11*xp + a21*yp; y = a12*xp + a22*yp; z = a13*xp + a23*yp; rac = atan2(y,x)/dtr; decc = asin(z)/dtr; convertCoordinates (EQUJ, 2000., rac, decc, csys, equinox, &ilon, &ilat, 0.); offscl = 0; wcs2pix(output.wcs, ilon, ilat, &oxpix, &oypix, &offscl); fixxy(&oxpix, &oypix, &offscl); if(haveFlux) pixel_value = atof(tval(fluxcol)); else pixel_value = 1; l = (int)(oxpix + 0.5) - 1; m = (int)(oypix + 0.5) - 1; if(!offscl) data[m][l] = pixel_value; } } } else { if(debug && count/1000*1000 == count) { printf("%9d sources processed\n", count); fflush(stdout); } rac = atof(tval(racol)); decc = atof(tval(deccol)); convertCoordinates (EQUJ, 2000., rac, decc, csys, equinox, &ilon, &ilat, 0.); if(haveFlux) pixel_value = atof(tval(fluxcol)); else pixel_value = 1; if(ismag) pixel_value = pow(10., 0.4 * (refmag - pixel_value)); wcs2pix(output.wcs, ilon, ilat, &oxpix, &oypix, &offscl); if(pixel_value < 1.e10) { if(debug >= 3) { printf(" value = %11.3e at coord = (%12.8f,%12.8f)", pixel_value, ilon, ilat); if(offscl) { printf(" -> opix = (%7.1f,%7.1f) OFF SCALE\n", oxpix, oypix); fflush(stdout); } else { printf(" -> opix = (%7.1f,%7.1f)\n", oxpix, oypix); fflush(stdout); } } else if(pixel_value > 1000000.) { printf(" value = %11.3e at coord = (%12.8f,%12.8f)", pixel_value, ilon, ilat); if(offscl) { printf(" -> opix = (%7.1f,%7.1f) OFF SCALE\n", oxpix, oypix); fflush(stdout); } else { printf(" -> opix = (%7.1f,%7.1f)\n", oxpix, oypix); fflush(stdout); } } if(!offscl) { l = (int)(oxpix + 0.5) - 1; m = (int)(oypix + 0.5) - 1; if(l < 0 || m < 0 || l >= output.naxes[0] || m >= output.naxes[1]) { /* printf("ERROR: l=%d, m=%d\n", l, m); fflush(stdout); */ } else { for(dl=-2; dl<=2; ++dl) { if(l+dl < 0 || l+dl>= output.naxes[0]) continue; for(dm=-2; dm<=2; ++dm) { if(m+dm < 0 || m+dm>= output.naxes[1]) continue; data[m+dm][l+dl] += weights[dm+2][dl+2] * pixel_value; } } } } } } } /************************/ /* Write the image data */ /************************/ fpixel = 1; nelements = output.naxes[0] * output.naxes[1]; if (fits_write_img(output.fptr, TDOUBLE, fpixel, nelements, data[0], &status)) printFitsError(status); if(debug >= 1) { printf("Data array written to FITS image\n"); fflush(stdout); } /*************************************/ /* Add keywords from a template file */ /*************************************/ if(fits_write_key_template(output.fptr, template_file, &status)) printFitsError(status); if(debug >= 1) { printf("Template keywords written to FITS image\n"); fflush(stdout); } /***********************/ /* Close the FITS file */ /***********************/ if(fits_close_file(output.fptr, &status)) printFitsError(status); if(debug >= 1) { printf("FITS image finalized\n"); fflush(stdout); } time(&currtime); printf("[struct stat=\"OK\", time=%d]\n", (int)(currtime - start)); fflush(stdout); exit(0); }
int main(int argc, char **argv) { int i, iarg, nPix, anynul, status, mask; char help[4096]; fitsfile *iPtr; int iBitpix, iNaxis; long iNaxes[MAXDIM]; float *iRData=NULL; fitsfile *mPtr; int mBitpix, mNaxis; long mNaxes[MAXDIM]; int *mRData=NULL; char *inim=NULL, *maskim=NULL, *outim=NULL; float fillVal=D_FILLVAL; /* START */ status = 0; mask = D_MASK; fillVal = D_FILLVAL; sprintf(help, "Usage : maskim [options]\n"); sprintf(help, "%sRequired options:\n", help); sprintf(help, "%s [-inim fitsfile] : input image\n", help); sprintf(help, "%s [-maskim fitsfile]: corresponding mask image\n", help); sprintf(help, "%s [-outim fitsfile] : output masked image\n\n", help); sprintf(help, "%sOptions:\n", help); sprintf(help, "%s [-fi fillval] : Value of filled pixels (%.3f)\n", help, fillVal); sprintf(help, "%s [-mask hex] : Mask for bad pixels (0x%x)\n", help, mask); /* read in command options. j counts # of required args given */ for (iarg=1; iarg < argc; iarg++) { if (argv[iarg][0]=='-') { if (strcasecmp(argv[iarg]+1,"inim")==0) { inim = argv[++iarg]; } else if (strcasecmp(argv[iarg]+1,"maskim")==0) { maskim = argv[++iarg]; } else if (strcasecmp(argv[iarg]+1,"outim")==0) { outim = argv[++iarg]; } else if (strcasecmp(argv[iarg]+1,"fi")==0) { sscanf(argv[++iarg], "%f", &fillVal); } else if (strcasecmp(argv[iarg]+1,"mask")==0) { sscanf(argv[++iarg], "%d", &mask); } else { fprintf(stderr, "Unknown option : %s\n", argv[iarg]); exit(1); } } else { fprintf(stderr, "Unexpected string encountered on command line : %s\n", argv[iarg]); exit(1); } } /* read in command options */ if (argc < 2) { fprintf(stderr, "%s\n", help); exit(1); } /* insanity checking */ if ( !(inim) ) { fprintf(stderr, "FATAL ERROR inim is required command line option\n"); exit(1); } if ( !(maskim) ) { fprintf(stderr, "FATAL ERROR maskim is required command line option\n"); exit(1); } if ( !(outim) ) { fprintf(stderr, "FATAL ERROR outim is required command line option\n"); exit(1); } /* open up, get bitpix, # dimensions, image size */ if ( fits_open_file(&iPtr, inim, 0, &status) || fits_get_img_param(iPtr, 2, &iBitpix, &iNaxis, iNaxes, &status) ) { printError(status); } if ( fits_open_file(&mPtr, maskim, 0, &status) || fits_get_img_param(mPtr, 2, &mBitpix, &mNaxis, mNaxes, &status) ) { printError(status); } assert(iNaxes[0] == mNaxes[0]); assert(iNaxes[1] == mNaxes[1]); nPix = iNaxes[0]*iNaxes[1]; iRData = (float *)realloc(iRData, nPix*sizeof(float)); mRData = (int *)realloc(mRData, nPix*sizeof(int)); if (iRData == NULL || mRData == NULL) { fprintf(stderr, "Cannot Allocate Standard Data Arrays\n"); exit (1); } memset(iRData, 0.0, nPix*sizeof(float)); memset(mRData, 0x0, nPix*sizeof(int)); if (fits_read_img(iPtr, TFLOAT, 1, nPix, 0, iRData, &anynul, &status) || fits_read_img(mPtr, TINT, 1, nPix, 0, mRData, &anynul, &status) || fits_close_file(mPtr, &status)) printError(status); /* do the masking */ for (i = nPix; i--; ) if (mRData[i] & mask) iRData[i] = fillVal; /* reuse mptr and help */ sprintf(help, "!%s", outim); if (fits_create_template(&mPtr, help, inim, &status) || fits_write_img(mPtr, TFLOAT, 1, nPix, iRData, &status) || fits_close_file(mPtr, &status) || fits_close_file(iPtr, &status)) printError(status); free(iRData); free(mRData); return 0; }
int main(int argc, char *argv[]) { fitsfile *infptr, *outfptr; /* FITS file pointers defined in fitsio.h */ int status = 0, ii = 1, iteration = 0, single = 0, hdupos; int hdutype, bitpix, bytepix, naxis = 0, nkeys, datatype = 0, anynul; long naxes[9] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; long first, totpix = 0, npix; double *array, bscale = 1.0, bzero = 0.0, nulval = 0.; char card[81]; if (argc != 3) { printf("\n"); printf("Usage: imcopy inputImage outputImage[compress]\n"); printf("\n"); printf("Copy an input image to an output image, optionally compressing\n"); printf("or uncompressing the image in the process. If the [compress]\n"); printf("qualifier is appended to the output file name then the input image\n"); printf("will be compressed using the tile-compressed format. In this format,\n"); printf("the image is divided into rectangular tiles and each tile of pixels\n"); printf("is compressed and stored in a variable-length row of a binary table.\n"); printf("If the [compress] qualifier is omitted, and the input image is\n"); printf("in tile-compressed format, then the output image will be uncompressed.\n"); printf("\n"); printf("If an extension name or number is appended to the input file name, \n"); printf("enclosed in square brackets, then only that single extension will be\n"); printf("copied to the output file. Otherwise, every extension in the input file\n"); printf("will be processed in turn and copied to the output file.\n"); printf("\n"); printf("Examples:\n"); printf("\n"); printf("1) imcopy image.fit 'cimage.fit[compress]'\n"); printf("\n"); printf(" This compresses the input image using the default parameters, i.e.,\n"); printf(" using the Rice compression algorithm and using row by row tiles.\n"); printf("\n"); printf("2) imcopy cimage.fit image2.fit\n"); printf("\n"); printf(" This uncompress the image created in the first example.\n"); printf(" image2.fit should be identical to image.fit if the image\n"); printf(" has an integer datatype. There will be small differences\n"); printf(" in the pixel values if it is a floating point image.\n"); printf("\n"); printf("3) imcopy image.fit 'cimage.fit[compress GZIP 100,100;4]'\n"); printf("\n"); printf(" This compresses the input image using the following parameters:\n"); printf(" GZIP compression algorithm;\n"); printf(" 100 X 100 pixel compression tiles;\n"); printf(" noise_bits = 4 (only used with floating point images)\n"); printf("\n"); printf("The full syntax of the compression qualifier is:\n"); printf(" [compress ALGORITHM TDIM1,TDIM2,...; NOISE_BITS]\n"); printf("where the allowed ALGORITHM values are Rice, GZIP, PLIO, \n"); printf("and TDIMn is the size of the compression tile in each dimension,\n"); printf("and NOISE_BITS = 1, 2, 3, or 4 and controls the amount of noise\n"); printf("suppression when compressing floating point images. \n"); printf("\n"); printf("Note that it may be necessary to enclose the file names\n"); printf("in single quote characters on the Unix command line.\n"); return(0); } /* Open the input file and create output file */ fits_open_file(&infptr, argv[1], READONLY, &status); fits_create_file(&outfptr, argv[2], &status); if (status != 0) { fits_report_error(stderr, status); return(status); } fits_get_hdu_num(infptr, &hdupos); /* Get the current HDU position */ /* Copy only a single HDU if a specific extension was given */ if (hdupos != 1 || strchr(argv[1], '[')) single = 1; for (; !status; hdupos++) /* Main loop through each extension */ { fits_get_hdu_type(infptr, &hdutype, &status); if (hdutype == IMAGE_HDU) { /* get image dimensions and total number of pixels in image */ for (ii = 0; ii < 9; ii++) naxes[ii] = 1; fits_get_img_param(infptr, 9, &bitpix, &naxis, naxes, &status); totpix = naxes[0] * naxes[1] * naxes[2] * naxes[3] * naxes[4] * naxes[5] * naxes[6] * naxes[7] * naxes[8]; } if (hdutype != IMAGE_HDU || naxis == 0 || totpix == 0) { /* just copy tables and null images */ fits_copy_hdu(infptr, outfptr, 0, &status); } else { /* Explicitly create new image, to support compression */ fits_create_img(outfptr, bitpix, naxis, naxes, &status); if (status) { fits_report_error(stderr, status); return(status); } /* copy all the user keywords (not the structural keywords) */ fits_get_hdrspace(infptr, &nkeys, NULL, &status); for (ii = 1; ii <= nkeys; ii++) { fits_read_record(infptr, ii, card, &status); if (fits_get_keyclass(card) > TYP_CMPRS_KEY) fits_write_record(outfptr, card, &status); } switch(bitpix) { case BYTE_IMG: datatype = TBYTE; break; case SHORT_IMG: datatype = TSHORT; break; case LONG_IMG: datatype = TINT; break; case FLOAT_IMG: datatype = TFLOAT; break; case DOUBLE_IMG: datatype = TDOUBLE; break; } bytepix = abs(bitpix) / 8; npix = totpix; iteration = 0; /* try to allocate memory for the entire image */ /* use double type to force memory alignment */ array = (double *) calloc(npix, bytepix); /* if allocation failed, divide size by 2 and try again */ while (!array && iteration < 10) { iteration++; npix = npix / 2; array = (double *) calloc(npix, bytepix); } if (!array) { printf("Memory allocation error\n"); return(0); } /* turn off any scaling so that we copy the raw pixel values */ fits_set_bscale(infptr, bscale, bzero, &status); fits_set_bscale(outfptr, bscale, bzero, &status); first = 1; while (totpix > 0 && !status) { /* read all or part of image then write it back to the output file */ fits_read_img(infptr, datatype, first, npix, &nulval, array, &anynul, &status); fits_write_img(outfptr, datatype, first, npix, array, &status); totpix = totpix - npix; first = first + npix; } free(array); } if (single) break; /* quit if only copying a single HDU */ fits_movrel_hdu(infptr, 1, NULL, &status); /* try to move to next HDU */ } if (status == END_OF_FILE) status = 0; /* Reset after normal error */ fits_close_file(outfptr, &status); fits_close_file(infptr, &status); /* if error occurred, print out error message */ if (status) fits_report_error(stderr, status); return(status); }
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 != 8) { if(populate_env_variable(LOR_BLURB_FILE, "L2_LOR_BLURB_FILE")) { RETURN_FLAG = 1; } else { print_file(LOR_BLURB_FILE); } write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -1, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); return 1; } else { // *********************************************************************** // Redefine routine input parameters char *input_f = strdup(argv[1]); double start_wav = strtod(argv[2], NULL); double end_wav = strtod(argv[3], NULL); char *interpolation_type = strdup(argv[4]); double dispersion = strtod(argv[5], NULL); int conserve_flux = strtol(argv[6], NULL, 0); char *output_f = strdup(argv[7]); // *********************************************************************** // Open input file (ARG 1), get parameters and perform any data format // checks fitsfile *input_f_ptr; int input_f_maxdim = 2; int 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, READONLY, &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, "L2STATRE", -2, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); free(input_f); free(interpolation_type); free(output_f); 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, "L2STATRE", -3, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, input_f_status); free(input_f); free(interpolation_type); free(output_f); 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, "L2STATRE", -4, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, input_f_status); free(input_f); free(interpolation_type); free(output_f); return 1; } // *********************************************************************** // Set the range limits using input fits file (ARG 1) 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 fits 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]; // *********************************************************************** // Open [LOARCFIT_OUTPUTF_WAVFITS_FILE] dispersion solutions file FILE *dispersion_solutions_f; if (!check_file_exists(LOARCFIT_OUTPUTF_WAVFITS_FILE)) { dispersion_solutions_f = fopen(LOARCFIT_OUTPUTF_WAVFITS_FILE , "r"); } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -5, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); free(input_f); free(interpolation_type); free(output_f); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); return 1; } // *********************************************************************** // Find some [LOARCFIT_OUTPUTF_WAVFITS_FILE] file details char input_string [500]; bool find_polynomialorder_comment = FALSE; int polynomial_order; char search_string_1 [20] = "# Polynomial Order:\0"; // this is the comment to be found from the [LOARCFIT_OUTPUTF_WAVFITS_FILE] file while(!feof(dispersion_solutions_f)) { memset(input_string, '\0', sizeof(char)*500); fgets(input_string, 500, dispersion_solutions_f); if (strncmp(input_string, search_string_1, strlen(search_string_1)) == 0) { sscanf(input_string, "%*[^\t]%d", &polynomial_order); // read all data up to tab as string ([^\t]), but do not store (*) find_polynomialorder_comment = TRUE; break; } } if (find_polynomialorder_comment == FALSE) { // error check - didn't find the comment in the [LOARCFIT_OUTPUTF_WAVFITS_FILE] file write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -6, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); free(input_f); free(interpolation_type); free(output_f); fclose(dispersion_solutions_f); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); return 1; } // *********************************************************************** // Rewind and extract coefficients from [LOARCFIT_OUTPUTF_WAVFITS_FILE] // file rewind(dispersion_solutions_f); int token_index; // this variable will hold which token we're dealing with int coeff_index; // this variable will hold which coefficient we're dealing with double this_coeff; double this_chisquared; char *token; double coeffs [polynomial_order+1]; memset(coeffs, 0, sizeof(double)*(polynomial_order+1)); while(!feof(dispersion_solutions_f)) { memset(input_string, '\0', sizeof(char)*500); fgets(input_string, 500, dispersion_solutions_f); token_index = 0; coeff_index = 0; if (strtol(&input_string[0], NULL, 0) > 0) { // check the line begins with a positive number // *********************************************************************** // String tokenisation loop: // // 1. init calls strtok() loading the function with input_string // 2. terminate when token is null // 3. we keep assigning tokens of input_string to token until termination by calling strtok with a NULL first argument // // n.b. searching for tab or newline separators ('\t' and '\n') for (token=strtok(input_string, "\t\n"); token !=NULL; token = strtok(NULL, "\t\n")) { if (token_index == 0) { } else if ((token_index >= 1) && (token_index <= polynomial_order+1)) { // coeff token this_coeff = strtod(token, NULL); // printf("%d\t%e\n", coeff_index, this_coeff); // DEBUG coeffs[coeff_index] = this_coeff; coeff_index++; } else if (token_index == polynomial_order+2) { // chisquared token this_chisquared = strtod(token, NULL); //printf("%f\n", this_chisquared); // DEBUG } token_index++; } } } // *********************************************************************** // Find wavelength extremities from [LOARCFIT_OUTPUTF_WAVFITS_FILE] file // and ensure the input constraints [start_wav] (ARG 2) and [end_wav] // (ARG 3) don't lie outside these boundaries double smallest_wav, largest_wav; int ii; for (ii=0; ii<=polynomial_order; ii++) { smallest_wav += coeffs[ii]*pow(0+INDEXING_CORRECTION, ii); largest_wav += coeffs[ii]*pow((cut_x[1]-1)+INDEXING_CORRECTION, ii); } // *********************************************************************** // Need to find pixel indexes for starting/ending wavelength positions double this_element_wav; int first_element_index, last_element_index; int jj; for (ii=0; ii<nxelements; ii++) { this_element_wav = 0.0; for (jj=0; jj<=polynomial_order; jj++) { this_element_wav += coeffs[jj]*pow(ii,jj); } if (this_element_wav >= start_wav) { // the current index, ii, represents the first pixel with a wavelength >= start_wav. Comparing doubles but accuracy isn't a necessity so don't need gsl_fcmp function break; } first_element_index = ii; } // printf("%d\t%f\n", ii, this_element_wav); // DEBUG for (ii=nxelements; ii>=0; ii--) { this_element_wav = 0.0; for (jj=0; jj<=polynomial_order; jj++) { this_element_wav += coeffs[jj]*pow(ii,jj); } if (this_element_wav <= end_wav) { // the current index, ii, represents the first pixel with a wavelength <= end_wav. Comparing doubles but accuracy isn't a necessity so don't need gsl_fcmp function break; } last_element_index = ii; } // printf("%d\t%f\n", ii, this_element_wav); // DEBUG printf("\nWavelength boundaries"); printf("\n---------------------\n"); printf("\nInherent minimum wavelength:\t%.2f Å", smallest_wav); printf("\nInherent maximum wavelength:\t%.2f Å\n", largest_wav); if (start_wav < smallest_wav) { // Comparing doubles but accuracy isn't a necessity so don't need gsl_fcmp function write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -7, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); free(input_f); free(interpolation_type); free(output_f); fclose(dispersion_solutions_f); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); return 1; } else if (end_wav > largest_wav) { // Comparing doubles but accuracy isn't a necessity so don't need gsl_fcmp function write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -8, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); free(input_f); free(interpolation_type); free(output_f); fclose(dispersion_solutions_f); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); return 1; } // *********************************************************************** // Set the bin wavelengths int num_bins = 0; if (!gsl_fcmp((end_wav-start_wav)/dispersion, rint((end_wav-start_wav)/dispersion), 1e-5)) { // check to see if nearest integer is within tolerance value num_bins = rint((end_wav-start_wav)/dispersion) + 1; // if TRUE, round } else { num_bins = floor((end_wav-start_wav)/dispersion) + 1; // if FALSE, floor } // printf("%d\n", num_bins); // DEBUG double bin_wavelengths [num_bins]; memset(bin_wavelengths, 0, sizeof(double)*num_bins); for (ii=0; ii<num_bins; ii++) { bin_wavelengths[ii] = start_wav + dispersion*ii; // printf("%f\n", bin_wavelengths[ii]); // DEBUG } // printf("%f\t%f\n", bin_wavelengths[0], bin_wavelengths[num_bins-1]); // DEBUG // REBIN INPUT FRAME (ARG 1) AND CONSERVE FLUX IF APPLICABLE // *********************************************************************** // 1. Open input frame int this_row_index; double x_wav [nxelements]; double output_frame_values [nyelements][num_bins]; memset(output_frame_values, 0, sizeof(double)*nyelements*num_bins); double output_f_pixels [num_bins]; memset(output_f_pixels, 0, sizeof(double)*(num_bins)); double this_pre_rebin_row_flux, this_post_rebin_row_flux; double conservation_factor; for (fpixel[1] = cut_y[0]; fpixel[1] <= cut_y[1]; fpixel[1]++) { this_row_index = fpixel[1] - 1; memset(input_f_pixels, 0, sizeof(double)*nxelements); if(!fits_read_pix(input_f_ptr, IMG_READ_ACCURACY, fpixel, nxelements, NULL, input_f_pixels, NULL, &input_f_status)) { // 2. Calculate pre-rebin total fluxes this_pre_rebin_row_flux = 0.0; for (ii=first_element_index; ii<=last_element_index; ii++) { this_pre_rebin_row_flux += input_f_pixels[ii]; } // 3. Create pixel-wavelength translation array and perform interpolation memset(x_wav, 0, sizeof(double)*nxelements); for (ii=0; ii<nxelements; ii++) { for (jj=0; jj<=polynomial_order; jj++) { x_wav[ii] += coeffs[jj]*pow(ii+INDEXING_CORRECTION,jj); } // printf("%d\t%f\n", ii, x_wav[ii]); // DEBUG } // for (ii=0; ii< nxelements; ii++) printf("\n%f\t%f", x_wav[ii], input_f_pixels[ii]); // DEBUG if (interpolate(interpolation_type, x_wav, input_f_pixels, nxelements, bin_wavelengths[0], bin_wavelengths[num_bins-1], dispersion, output_f_pixels)) { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -9, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); free(input_f); free(interpolation_type); free(output_f); fclose(dispersion_solutions_f); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); return 1; } // 4. Calculate post-rebin total fluxes this_post_rebin_row_flux = 0.0; for (ii=0; ii<num_bins; ii++) { this_post_rebin_row_flux += output_f_pixels[ii]; } // 5. Conserve flux if applicable conservation_factor = this_pre_rebin_row_flux/this_post_rebin_row_flux; // printf("%f\t%f\t%f\n", this_pre_rebin_row_flux, this_post_rebin_row_flux, conservation_factor); // DEBUG for (ii=0; ii<num_bins; ii++) { if (conserve_flux == TRUE) { output_frame_values[this_row_index][ii] = output_f_pixels[ii]*conservation_factor; } else { output_frame_values[this_row_index][ii] = output_f_pixels[ii]; } } } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -10, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, input_f_status); free(input_f); free(interpolation_type); free(output_f); fclose(dispersion_solutions_f); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); return 1; } } // 6. Create [LOREBIN_OUTPUTF_REBIN_WAVFITS_FILE] output file and print // a few parameters FILE *outputfile; outputfile = fopen(LOREBIN_OUTPUTF_REBIN_WAVFITS_FILE, FILE_WRITE_ACCESS); if (!outputfile) { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -11, "Status flag for L2 frrebin routine", ERROR_CODES_FILE_WRITE_ACCESS); free(input_f); free(interpolation_type); free(output_f); fclose(dispersion_solutions_f); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); return 1; } char timestr [80]; memset(timestr, '\0', sizeof(char)*80); find_time(timestr); fprintf(outputfile, "#### %s ####\n\n", LOREBIN_OUTPUTF_REBIN_WAVFITS_FILE); fprintf(outputfile, "# Rebinning wavelength fit parameters.\n\n"); fprintf(outputfile, "# Run Datetime:\t\t%s\n\n", timestr); fprintf(outputfile, "# Target Filename:\t%s\n\n", input_f); fprintf(outputfile, "# Starting Wavelength:\t%.2f\n", bin_wavelengths[0]); fprintf(outputfile, "# Dispersion:\t\t%.2f\n", dispersion); fprintf(outputfile, "%d", EOF); // 7. Write these values to the [ADDITIONAL_KEYS_FILE] file write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CTYPE1", "Wavelength", "Type of co-ordinate on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CUNIT1", "Angstroms", "Units for axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CRVAL1", bin_wavelengths[0], "[pixel] Value at ref. pixel on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CDELT1", dispersion, "[pixel] Pixel scale on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CRPIX1", 1.0, "[pixel] Reference pixel on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CTYPE2", "a2", "Type of co-ordinate on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CUNIT2", "Pixels", "Units for axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CRVAL2", 1, "[pixel] Value at ref. pixel on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CDELT2", 1, "[pixel] Pixel scale on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "LSS_CALIBRATION", "CRPIX2", 1, "[pixel] Reference pixel on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CTYPE1", "Wavelength", "Type of co-ordinate on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CUNIT1", "Angstroms", "Units for axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CRVAL1", bin_wavelengths[0], "[pixel] Value at ref. pixel on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CDELT1", dispersion, "[pixel] Pixel scale on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CRPIX1", 1.0, "[pixel] Reference pixel on axis 1", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CTYPE2", "a2", "Type of co-ordinate on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_str(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CUNIT2", "Pixels", "Units for axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CRVAL2", 1, "[pixel] Value at ref. pixel on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CDELT2", 1, "[pixel] Pixel scale on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); write_additional_key_to_file_dbl(ADDITIONAL_KEYS_FILE, "SPEC_CALIBRATION", "CRPIX2", 1, "[pixel] Reference pixel on axis 2", ADDITIONAL_KEYS_FILE_WRITE_ACCESS); // *********************************************************************** // Set output frame parameters fitsfile *output_f_ptr; int output_f_status = 0; long output_f_naxes [2] = {num_bins,nyelements}; long output_f_fpixel = 1; // *********************************************************************** // Create [output_frame_values_1D] array to hold the output data in the // correct format double output_frame_values_1D [num_bins*nyelements]; memset(output_frame_values_1D, 0, sizeof(double)*num_bins*nyelements); int kk; for (ii=0; ii<nyelements; ii++) { jj = ii * num_bins; for (kk=0; kk<num_bins; kk++) { output_frame_values_1D[jj] = output_frame_values[ii][kk]; jj++; } } // *********************************************************************** // Create and write [output_frame_values_1D] to output file (ARG 5) 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, num_bins * nyelements, output_frame_values_1D, &output_f_status)) { } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -12, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, output_f_status); free(input_f); free(interpolation_type); free(output_f); fclose(dispersion_solutions_f); fclose(outputfile); 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)); return 1; } } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -13, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, output_f_status); free(input_f); free(interpolation_type); free(output_f); fclose(dispersion_solutions_f); fclose(outputfile); 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)); return 1; } } else { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -14, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error(stdout, output_f_status); free(input_f); free(interpolation_type); free(output_f); fclose(dispersion_solutions_f); fclose(outputfile); if(fits_close_file(input_f_ptr, &input_f_status)) fits_report_error (stdout, input_f_status); return 1; } // *********************************************************************** // Clean up heap memory free(input_f); free(interpolation_type); free(output_f); // *********************************************************************** // Close input file (ARG 1), output file (ARG 7) and // [FRARCFIT_OUTPUTF_WAVFITS_FILE] file if (fclose(dispersion_solutions_f)) { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -15, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); fclose(outputfile); 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)); return 1; } if (fclose(outputfile)) { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -16, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); 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)); return 1; } if(fits_close_file(input_f_ptr, &input_f_status)) { write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", -17, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error (stdout, input_f_status); if(fits_close_file(output_f_ptr, &output_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, "L2STATRE", -18, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); fits_report_error (stdout, output_f_status); return 1; } // *********************************************************************** // Write success to [ERROR_CODES_FILE] write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATRE", RETURN_FLAG, "Status flag for L2 lorebin routine", ERROR_CODES_FILE_WRITE_ACCESS); return 0; } }
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[]) { fitsfile *fptr; long fpixel=1, nelements, naxes[2]; dc1394camera_t *camera; int grab_n_frames; struct timeval start_time, end_time; int i, j, status; unsigned int max_height, max_width; 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; unsigned char *buffer; float *average; grab_n_frames = atoi(argv[1]); filename = argv[2]; status = 0; width = 320; height = 240; naxes[0] = width; naxes[1] = height; nelements = naxes[0]*naxes[1]; 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"); 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"); err = dc1394_format7_set_roi (camera, DC1394_VIDEO_MODE_FORMAT7_1, DC1394_COLOR_CODING_MONO8, // 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"); // 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, 100.0); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set framerate"); // 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, 1.0e-2); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set shutter"); // 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, 200); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set gain"); // 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, 50); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set brightness"); 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"); // err = dc1394_feature_set_value (camera, DC1394_FEATURE_GAIN, 24); //DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "Error setting gain"); err = dc1394_capture_setup(camera, 16, DC1394_CAPTURE_FLAGS_DEFAULT); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "Error capturing"); /*----------------------------------------------------------------------- * 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); } /* allocate the buffers */ if (!(buffer = malloc(nelements*sizeof(char)))) { printf("Couldn't Allocate Image Buffer\n"); exit(-1); } if (!(average = calloc(nelements, sizeof(float)))) { printf("Couldn't Allocate Average Image Buffer\n"); 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, FLOAT_IMG, 2, 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); } memcpy(buffer, frame->image, nelements*sizeof(char)); // release buffer dc1394_capture_enqueue(camera,frame); for (j=0; j<nelements; j++) { average[j] += (1.0/grab_n_frames)*(buffer[j]); } } gettimeofday(&end_time, NULL); printf("End capture.\n"); /*----------------------------------------------------------------------- * stop data transmission *-----------------------------------------------------------------------*/ 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, TFLOAT, fpixel, naxes[0]*naxes[1], average, &status); fits_close_file(fptr, &status); fits_report_error(stderr, status); free(buffer); free(average); printf("wrote: %s\n", filename); printf("Readout 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; }