image_t *readimage(const char *filename) { char errmsg[80]; image_t *image = NULL; // open the FITS file int status = 0; fitsfile *fits = NULL; if (fits_open_file(&fits, filename, READONLY, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot read fits file %s: %s\n", filename, errmsg); return NULL; } // find dimensions of pixel array int igt; int naxis; long naxes[3]; if (fits_get_img_param(fits, 3, &igt, &naxis, naxes, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot read fits file info: %s\n", errmsg); goto bad; } image = (image_t *)malloc(sizeof(image_t)); image->width = naxes[0]; image->height = naxes[1]; // read the pixel data long npixels = image->width * image->height; image->data = (double *)malloc(npixels * sizeof(double)); long firstpixel[3] = { 1, 1, 1 }; if (fits_read_pix(fits, TDOUBLE, firstpixel, npixels, NULL, image->data, NULL, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot read pixel data: %s\n", errmsg); goto bad; } // close the file if (fits_close_file(fits, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot close fits file %s: %s\n", filename, errmsg); goto bad; } // return the image return image; bad: if (image) { if (image->data) { free(image->data); } free(image); } if (fits) { fits_close_file(fits, &status); } return NULL; }
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); }
/*--------------------------------------------------------------------------*/ void printerror( int status) { /*****************************************************/ /* Print out cfitsio error messages and exit program */ /*****************************************************/ char status_str[FLEN_STATUS], errmsg[FLEN_ERRMSG]; if (status) fprintf(stderr, "\n*** Error occurred during program execution ***\n"); fits_get_errstatus(status, status_str); /* get the error description */ fprintf(stderr, "\nstatus = %d: %s\n", status, status_str); /* get first message; null if stack is empty */ if ( fits_read_errmsg(errmsg) ) { fprintf(stderr, "\nError message stack:\n"); fprintf(stderr, " %s\n", errmsg); while ( fits_read_errmsg(errmsg) ) /* get remaining messages */ fprintf(stderr, " %s\n", errmsg); } exit( status ); /* terminate the program, returning error status */ }
/** Opens a FITS file. * \param[in] fileName The name of the file to open. * \param[in] openMode Mask defining how the file should be opened; bits are * NDFileModeRead, NDFileModeWrite, NDFileModeAppend, NDFileModeMultiple * \param[in] pArray A pointer to an NDArray; this is used to determine the array and attribute properties. */ asynStatus NDFileFITS::openFile(const char *fileName, NDFileOpenMode_t openMode, NDArray *pArray) { static const char *functionName = "openFile"; // We don't support reading yet if (openMode & NDFileModeRead) return(asynError); // We don't support opening an existing file for appending yet if (openMode & NDFileModeAppend) return(asynError); // At present only 16 bits unsigned images are valid. if (pArray->dataType != NDUInt16) return(asynError); //>>>>>>>>>>>>>>if (FITSType != 0) return(asynError); fitsStatus = 0; if(fits_create_file(&fitsFilePtr, fileName, &fitsStatus)) {// create new FITS file // get the error description fits_get_errstatus(fitsStatus, fits_status_str); asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s::%s error opening file %s error=%s\n", driverName, functionName, fileName, fits_status_str); fits_clear_errmsg(); return (asynError); } return(asynSuccess); }
void FITSTab::saveFile() { int err_status; char err_text[FLEN_STATUS]; KUrl backupCurrent = currentURL; QString currentDir = Options::fitsDir(); if (currentURL.path().contains("/tmp/")) currentURL.clear(); // If no changes made, return. if( mDirty == false && !currentURL.isEmpty()) return; if (currentURL.isEmpty()) { currentURL = KFileDialog::getSaveUrl( currentDir, "*.fits |Flexible Image Transport System"); // if user presses cancel if (currentURL.isEmpty()) { currentURL = backupCurrent; return; } if (currentURL.path().contains('.') == 0) currentURL.setPath(currentURL.path() + ".fits"); if (QFile::exists(currentURL.path())) { int r = KMessageBox::warningContinueCancel(0, i18n( "A file named \"%1\" already exists. " "Overwrite it?", currentURL.fileName() ), i18n( "Overwrite File?" ), KGuiItem(i18n( "&Overwrite" )) ); if(r==KMessageBox::Cancel) return; } } if ( currentURL.isValid() ) { if ( (err_status = saveFITS('!' + currentURL.path())) < 0) { fits_get_errstatus(err_status, err_text); // Use KMessageBox or something here KMessageBox::error(0, i18n("FITS file save error: %1", QString::fromUtf8(err_text)), i18n("FITS Save")); return; } //statusBar()->changeItem(i18n("File saved."), 3); emit newStatus(i18n("File saved."), FITS_MESSAGE); modifyFITSState(); } else { QString message = i18n( "Invalid URL: %1", currentURL.url() ); KMessageBox::sorry( 0, message, i18n( "Invalid URL" ) ); } }
/** 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); }
void mShrink_printFitsError(int status) { char status_str[FLEN_STATUS]; fits_get_errstatus(status, status_str); strcpy(montage_msgstr, status_str); }
static void vips_fits_error( int status ) { char buf[80]; fits_get_errstatus( status, buf ); vips_error( "fits", "%s", buf ); }
void fits_error(const char* filename, int status) { char err_text[32]; fits_get_errstatus(status, err_text); errorf(filename, 0, "%s", err_text); }
static void CheckErrors(int status) { if(status) { char err_text[32]; fits_get_errstatus(status, err_text); printf("Error: %s\n",err_text); } }
int FITSerror(int status) { char status_str[FLEN_STATUS]; fits_get_errstatus(status, status_str); fprintf(fstatus, "[struct stat=\"ERROR\", status=%d, msg=\"%s\"]\n", status, status_str); exit(1); }
void montage_printFitsError(int status) { char status_str[FLEN_STATUS]; fits_get_errstatus(status, status_str); fprintf(fstatus, "[struct stat=\"ERROR\", flag=%d, msg=\"%s\"]\n", status, status_str); exit(1); }
void writeimage(const image_t *image, const char *filename) { if (debug) { fprintf(stderr, "%s:%d: writing image %s\n", __FILE__, __LINE__, filename); } char errmsg[80]; int status = 0; fitsfile *fits = NULL; if (fits_create_file(&fits, filename, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot create fits file %s: %s\n", filename, errmsg); return; } // find dimensions of pixel array int naxis = 2; long naxes[2] = { image->width, image->height }; if (fits_create_img(fits, DOUBLE_IMG, naxis, naxes, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot create image: %s\n", errmsg); goto bad; } // read the pixel data long npixels = image->width * image->height; long firstpixel[3] = { 1, 1, 1 }; if (fits_write_pix(fits, TDOUBLE, firstpixel, npixels, image->data, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot write pixel data: %s\n", errmsg); } bad: // close the file if (fits_close_file(fits, &status)) { fits_get_errstatus(status, errmsg); fprintf(stderr, "cannot close fits file %s: %s\n", filename, errmsg); goto bad; } }
static void err_FITS(GError **error, gint status) { gchar buf[31]; /* Max length is specified as 30. */ fits_get_errstatus(status, buf); buf[sizeof(buf)-1] = '\0'; g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_SPECIFIC, _("CFITSIO error while reading the FITS file: %s."), buf); }
void Fits2D::printerror(int status){ if(status){ char status_str[200]; fits_get_errstatus(status, status_str); std::string str(status_str); BOOST_LOG_SEV(logger, fail) << "CFITSIO ERROR : " << status << " -> " << str; cout << "CFITSIO ERROR : " << status << " -> " << str << endl; } }
char * get_fitsio_error_message(void) { if(fitsio_status == 0) return NULL; else { char string[80]; fits_get_errstatus(fitsio_status, string); fitsio_status = 0; return strdup(string); } }
/** Closes the FITS file. */ asynStatus NDFileFITS::closeFile() { static const char *functionName = "closeFile"; if(fits_close_file(fitsFilePtr, &fitsStatus)) { fits_get_errstatus(fitsStatus, fits_status_str); asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s::%s error closing fits image file: error=%s\n", driverName, functionName, fits_status_str); fits_clear_errmsg(); return asynError; } return asynSuccess; }
void FITSTab::headerFITS() { QString recordList; int nkeys; int err_status; char err_text[FLEN_STATUS]; FITSImage *image_data = image->getImageData(); if ( (err_status = image_data->getFITSRecord(recordList, nkeys)) < 0) { fits_get_errstatus(err_status, err_text); KMessageBox::error(0, i18n("FITS record error: %1", QString::fromUtf8(err_text)), i18n("FITS Header")); return; } //FIXME: possible crash! Must use QPointer<...>! QDialog fitsHeaderDialog; Ui::fitsHeaderDialog header; header.setupUi(&fitsHeaderDialog); header.tableWidget->setRowCount(nkeys); for(int i = 0; i < nkeys; i++) { QString record = recordList.mid(i*80, 80); // I love regexp! QStringList properties = record.split(QRegExp("[=/]")); QTableWidgetItem* tempItem = new QTableWidgetItem(properties[0].simplified()); tempItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); header.tableWidget->setItem(i, 0, tempItem); if (properties.size() > 1) { tempItem = new QTableWidgetItem(properties[1].simplified()); tempItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); header.tableWidget->setItem(i, 1, tempItem); } if (properties.size() > 2) { tempItem = new QTableWidgetItem(properties[2].simplified()); tempItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); header.tableWidget->setItem(i, 2, tempItem); } } header.tableWidget->resizeColumnsToContents(); fitsHeaderDialog.exec(); }
void fits_print_error(int status) { if (!status) return; static char status_str[FLEN_STATUS]; static char errmsg[FLEN_ERRMSG]; /* get the error description */ fits_get_errstatus(status, status_str); fprintf(stderr, " Error: cfitsio %d: %s\n", status, status_str); /* get error stack messages */ while (fits_read_errmsg(errmsg)) fprintf(stderr, " %s\n", errmsg); }
void FitsFile::CheckStatus(int status) const { if(status) { /* fits_get_errstatus returns at most 30 characters */ char err_text[31]; fits_get_errstatus(status, err_text); char err_msg[81]; std::stringstream errMsg; errMsg << "CFITSIO reported error when performing IO on file '" << _filename << "':" << err_text << " ("; while(fits_read_errmsg(err_msg)) errMsg << err_msg; errMsg << ')'; throw FitsIOException(errMsg.str()); } }
void __fastcall TForm1::printerror( int status) { char status_str[FLEN_STATUS], errmsg[FLEN_ERRMSG]; char aux[300]; if (status) Memo1->Lines->Add("\n*** Error occurred during program execution ***\n"); fits_get_errstatus(status, status_str); // get the error description wsprintf(aux, "\nstatus = %d: %s\n", status, status_str); Memo1->Lines->Add(aux); if ( fits_read_errmsg(errmsg) )//get first message; null if stack is empty { Memo1->Lines->Add( "\nError message stack:\n"); Memo1->Lines->Add( errmsg); while ( fits_read_errmsg(errmsg) ) // get remaining messages Memo1->Lines->Add( errmsg); } }
void printFitsError(int status) { char status_str[FLEN_STATUS], errmsg[FLEN_ERRMSG]; if(status) fprintf(stderr, "\n*** Error occurred during program execution ***\n"); fits_get_errstatus(status, status_str); fprintf(stderr, "\nstatus = %d: %s\n", status, status_str); if(fits_read_errmsg(errmsg)) { fprintf(stderr, "\nError message stack:\n"); fprintf(stderr, " %s\n", errmsg); while(fits_read_errmsg(errmsg)) fprintf(stderr, " %s\n", errmsg); } exit(status); }
/* copy image section from input to putput, with binning */ int copyImageSection(fitsfile *ifptr, fitsfile *ofptr, int *dims, double *cens, int bin, char *slice, int *status) { void *buf; char card[FLEN_CARD]; char tbuf[SZ_LINE]; int numkeys, nkey, bitpix, dtype; int start[2]; int end[2]; int naxis = 2; long nelements; long naxes[2]; long fpixel[2] = {1,1}; buf = getImageToArray(ifptr, dims, cens, bin, slice, start, end, &bitpix, status); if( !buf || *status ){ fits_get_errstatus(*status, tbuf); fprintf(stderr, "ERROR: could not create section for output image: %s\n", tbuf); return *status; } /* get image size and total number of elements */ naxes[0] = (int)((end[0] - start[0] + 1) / bin); naxes[1] = (int)((end[1] - start[1] + 1) / bin); nelements = naxes[0] * naxes[1]; /* convert bitpix to cfitio data type */ switch(bitpix){ case 8: dtype = TBYTE; break; case 16: dtype = TSHORT; break; case -16: dtype = TUSHORT; break; case 32: dtype = TINT; break; case 64: dtype = TLONGLONG; break; case -32: dtype = TFLOAT; break; case -64: dtype = TDOUBLE; break; default: fprintf(stderr, "ERROR: unknown data type for image section\n"); return -1; } /* this code is modeled after cfitsio/cfileio.c/fits_copy_image_section() */ fits_create_img(ofptr, bitpix, naxis, naxes, status); /* copy all other non-structural keywords from the input to output file */ fits_get_hdrspace(ifptr, &numkeys, NULL, status); for(nkey=4; nkey<=numkeys; nkey++) { fits_read_record(ifptr, nkey, card, status); if (fits_get_keyclass(card) > TYP_CMPRS_KEY){ /* write the record to the output file */ fits_write_record(ofptr, card, status); } } if( *status > 0 ){ fprintf(stderr, "ERROR: can't copy header from input image to output section"); return(*status); } /* write image to FITS file */ fits_write_pix(ofptr, dtype, fpixel, nelements, buf, status); /* update LTM/TLV values in header */ updateLTM(ifptr, ofptr, (int)((end[0] + start[0]) / 2), (int)((end[1] + start[1]) / 2), (int)(end[0] - start[0] + 1), (int)(end[1] - start[1] + 1), bin, 1); /* free up space */ if( buf ){ free(buf); } /* return status */ return *status; }
int main(int argc, char **argv) { int i, j, indx, n_file, special_key, knul=0, anynull, hdutype, status=0; int LastSlashIndex; int NDump, NChan, NumHDU; long nrows=0; double ChanFreq, BW, CentFreq, DM; double TDump, StartTime, DumpMiddleSecs, ScanLen; char KeyValue[32], err_text[256]; char cur_file[256], cur_file_short[64]; char HdrVer[16]; char aspoutstr[11], dumprefstr[11]; fitsfile *Fin; Cmdline *Cmd; /* Get command line variables */ Cmd = parseCmdline(argc, argv); /* Normally use this somewhere, and not showOptionValues */ Cmd->tool = Cmd->tool; /* InfileP = (argc > 1); printf("InfileP = %d\n", InfileP); InfileC = (argc - 1); printf("InfileC = %d\n", InfileC); Infile = (char **)malloc(InfileC); for (i=0; i<InfileC; i++) { Infile[i] = (char *)malloc(256); if (strlen(argv[i+1]) > 255) { fprintf(stderr, "Error: argument %d is too long.\n", i+1); exit(1); } else{ strcpy(Infile[i], argv[i+1]); } printf("Argument %d: %s = %s\n", i+1, Infile[i], argv[i+1]); } */ /************* Keyword list output **************/ if (Cmd->ListP) { if (argc > 2) { fprintf(stderr,"\n-list option must be used alone. Exiting...\n"); exit(1); } else{ printf("\nSome available keywords/info options useable with the "); printf("-key flag:\n"); printf("\nObserving frequency-related options:\n"); printf("\nNCHAN: No. of channels\n"); printf("CFRQ: Centre frequecy\n"); printf("BW: Bandwidth\n"); printf("STARTCHAN: First (0th) frequency channel\n"); printf("ENDCHAN: Last (NCHAN-th) frequency channel\n"); printf("ALLCHAN: List all channels (ALLCHAN keyword output does\n"); printf(" not follow convention of -col flag)\n"); printf("\nIntegration-related options:\n"); printf("\nNDUMP: No. of integrations\n"); printf("TDUMP: Individual integration time (s)\n"); printf("SCANLEN: Full scan length of input file (s)\n"); printf("NPTSPROF: No. of bins in integrated profiles\n"); printf("\nOther options:\n"); printf("\nSRC_NAME: Source Name\n"); printf("DM: Dispersion measure\n"); printf("OBS_MODE: PSR/CAL -- normal or calibration scan\n"); printf("OBSVTY: Observatory code\n"); printf("FD_POLN: Polarisation basis (e.g. L or C for linear or\n"); printf(" circular, respectively)\n"); printf("RA: Right ascension of source\n"); printf("DEC: Declination of source\n"); printf("\nNote that all -key arguments are NOT case-sensitive.\n"); } } else if(Cmd->TDiffP) { if (Cmd->KeywordP) { fprintf(stderr,"\n-tdiff option must be used alone. Exiting...\n"); exit(1); } } else{ if(!Cmd->KeywordP){ printf("Must use -key option with appropriate arguments if not\n"); printf("using -list or -tdiff flag\n"); exit(1); } if(!Cmd->InfileP){ printf("Must use -infile option with input file arguments if not\n"); printf("using -list or -tdiff flag\n"); exit(1); } } /*************************************************/ /* Print header line */ if(Cmd->KeywordP && Cmd->ColumnP) { printf("%s ","File"); for(i=0;i<Cmd->KeywordC;i++) printf("%s ",Cmd->Keyword[i]); printf("\n"); } else if(Cmd->TDiffP){ // for Tdiff printf("File Source MJD TDIFF [ns]\n"); } for(n_file=0;n_file<Cmd->InfileC;n_file++){ strcpy(cur_file,Cmd->Infile[n_file]); /* Open fits file */ if(fits_open_file(&Fin, cur_file, READONLY, &status)){ printf("\nError opening FITS file %s\n", cur_file); fits_get_errstatus(status, err_text); printf("FITS Error status %d: %s\n",status,err_text); exit(1); } status=0; /* get rid of everthing before and including last forward slash in the filename for printing to screen: */ LastSlashIndex = -1; for(i=strlen(cur_file)-1;i>0;i--){ if(!strncasecmp(&cur_file[i],"/",1)){ LastSlashIndex = i; break; } } strncpy(cur_file_short,&cur_file[LastSlashIndex+1],strlen(cur_file)-LastSlashIndex); if(Cmd->TDiffP){ /******************** TDIFF ***********************/ int i_dump; int IMJDStart, SMJDStart; double StartMJD, MJD, TDiff; char ObsCode[4], psr[12]; /* Check this is Nancay data */ fits_read_key(Fin, TSTRING, "OBSVTY", ObsCode, NULL, &status); if(strncmp(ObsCode,"f",1)) { printf("\nError: File %s does not contain Nancay data (obs code = %s).", cur_file_short,ObsCode); printf(" Cannot extract TDIFF from this file. Exiting.\n"); exit(2); } /* Get pulsar name */ fits_read_key(Fin, TSTRING, "SRC_NAME", psr, NULL, &status); /* Calculate start MJD */ fits_read_key(Fin, TINT, "STT_IMJD", &(IMJDStart),NULL, &status); status = 0; fits_read_key(Fin, TINT, "STT_SMJD", &(SMJDStart),NULL, &status); status = 0; StartMJD = (double)IMJDStart + (double)SMJDStart/86400.; /* Find nuber of dumps in this file */ fits_get_num_hdus(Fin, &NumHDU, &status); NDump = NumHDU-3; // Nancay data is always Ver1.0 /* Loop through each dump and pick out time stamp and phase */ fits_movnam_hdu(Fin, BINARY_TBL, "ASPOUT0", 0, &status); for (i_dump=0;i_dump<NDump;i_dump++){ fits_movrel_hdu(Fin, 1, NULL, &status); fits_read_key(Fin, TDOUBLE, "DUMPMIDSECS", &(DumpMiddleSecs),NULL, &status); status = 0; fits_read_key(Fin, TDOUBLE, "DUMPTDIFF", &(TDiff),NULL, &status); status = 0; MJD = StartMJD + DumpMiddleSecs/86400.; printf("%s ",cur_file_short); printf("%s ",psr); printf("%14.8lf ",MJD); printf("%7.3lf \n",TDiff); } } // else if(Cmd->ColumnP) printf("%s ",cur_file_short); else printf("\nKeywords in %s:\n\n", cur_file_short); /* For each keyword requested... */ for(i=0;i<Cmd->KeywordC;i++){ special_key=0; /* Clear Keyword */ strcpy(KeyValue,"\0"); /**************** Channel-based keywords: *****************/ if(!strcasecmp(Cmd->Keyword[i],"NChan") || // # of channels !strncasecmp(Cmd->Keyword[i],"CFRQ",4) || // centre frequency !strncasecmp(Cmd->Keyword[i],"BW",2) || // bandwidth in MHz !strcasecmp(Cmd->Keyword[i],"StartChan") || // first channel (MHz) !strcasecmp(Cmd->Keyword[i],"EndChan") || // last channel (MHz) !strcasecmp(Cmd->Keyword[i],"AllChan")){ // all channels (MHz) /* move to channel table */ fits_movnam_hdu(Fin, ASCII_TBL, "BECONFIG", 0, &status); ffgnrw(Fin, &nrows, &status); indx = 1; fits_read_col(Fin, TINT, indx++, 1, 1, 1, &knul, &NChan, &anynull, &status); /* Write heading for AllChans keyword if requested */ if (!strcasecmp(Cmd->Keyword[i],"AllChan")) printf("\nAll Channels:\n"); /* Read NChans number, copy to keyword */ if (!strcasecmp(Cmd->Keyword[i],"NChan")) sprintf(KeyValue,"%d",NChan); /* Initialize BW and CentFreq variables */ BW=CentFreq=0.; for (j=0; j<NChan; j++) { /* read each channel in succession */ fits_read_col(Fin, TDOUBLE, indx++, 1, 1, 1, NULL, &ChanFreq, &anynull, &status); /* Take not of first channel if StartChan keyword is requested */ if (!strcasecmp(Cmd->Keyword[i],"StartChan") && j==0) sprintf(KeyValue,"%6.1lf",ChanFreq); /* Calculate bandwidth or centre frequency using first and last channels */ if((!strncasecmp(Cmd->Keyword[i],"BW",2) || !strncasecmp(Cmd->Keyword[i],"CFRQ",4))){ if (j==0) BW = CentFreq = ChanFreq; if (j==NChan-1) { /* +4 because we are subtracting centres of channels, so this includes the edges... */ BW = fabs(ChanFreq-BW)+4.; CentFreq = 0.5*(CentFreq + ChanFreq); } } /* Print each channel separately if AllChans keyword is requestes */ if (!strcasecmp(Cmd->Keyword[i],"AllChan")) printf("%6.1lf ",ChanFreq); } /* Take note of last channel if requested */ if (!strcasecmp(Cmd->Keyword[i],"EndChan")) sprintf(KeyValue,"%6.1lf",ChanFreq); /* Copy centre frequency and bandwidth keywords to keyword variable if requested */ if (!strncasecmp(Cmd->Keyword[i],"CFRQ",4)) sprintf(KeyValue,"%6.1lf",CentFreq); if(!strncasecmp(Cmd->Keyword[i],"BW",2)) sprintf(KeyValue,"%6.1lf",BW); /* If AllChans is requested, print newline */ if (!strcasecmp(Cmd->Keyword[i],"AllChan")) { special_key=1; printf("\n"); } /* Move file pointer back to beginning of file */ fits_movrel_hdu(Fin, -1, NULL, &status); /**************** End channel-based keywords: *****************/ } /**************** DM keyword: *****************/ else if(!strcasecmp(Cmd->Keyword[i],"DM")) { // special_key=1; fits_movnam_hdu(Fin, ASCII_TBL, "COHDDISP", 0, &status); ffgnrw(Fin, &nrows, &status); indx = 1; fits_read_col(Fin, TDOUBLE, indx, 1, 1, 1, NULL, &DM, &anynull, &status); sprintf(KeyValue,"%8.5lf",DM); fits_movrel_hdu(Fin, -2, NULL, &status); /**************** End DM keyword: *****************/ } /**************** NDUMPS or SCANLEN keyword: *****************/ else if(!strcasecmp(Cmd->Keyword[i],"NDUMP") || // # of dumps !strcasecmp(Cmd->Keyword[i],"NDUMPS") || !strcasecmp(Cmd->Keyword[i],"TDUMP") || // dump length in secs !strcasecmp(Cmd->Keyword[i],"SCANLEN")){ // length of scans in secs /* Get the number of dumps. this depensd on version of asp file code */ fits_get_num_hdus(Fin, &NumHDU, &status); fits_read_key(Fin, TSTRING, "HDRVER", HdrVer, NULL, &status); status=0; if(!strcasecmp(HdrVer,"Ver1.0")){ /* divided by 2 since half the tables are phase/period vs. freq before each data table */ NDump = NumHDU-3; } else if(!strcasecmp(HdrVer,"Ver1.0.1")){ /* the "3" is temporary, depending on how many non-data tables we will be using */ NDump = (NumHDU-3)/2; } else{ printf("Do not recognize FITS file version number in header.\n"); printf("This header %s. Exiting...\n",HdrVer); exit(3); } if (!strncasecmp(Cmd->Keyword[i],"NDUMP",4)) { // covers NDUMPS also... sprintf(KeyValue,"%d",NDump); } // if need TDUMP or Total Scan Length (SCANLEN): if (!strcasecmp(Cmd->Keyword[i],"TDUMP") || // dump length in secs !strcasecmp(Cmd->Keyword[i],"SCANLEN")) { /* Get time between successive scans */ /* Get start time */ fits_read_key(Fin, TDOUBLE, "STT_SMJD", &StartTime, NULL, &status); if (NDump > 1) { sprintf(aspoutstr,"ASPOUT%d",NDump-2); sprintf(dumprefstr,"DUMPREF%d",NDump-2); // printf ("\n%s %s\n",aspoutstr,dumprefstr); /* Move to first data table , get central time stamp */ if(!strcasecmp(HdrVer,"Ver1.0")) { fits_movnam_hdu(Fin, BINARY_TBL, "ASPOUT0", 0, &status); fits_read_key(Fin, TDOUBLE, "DUMPMIDSECS", &(DumpMiddleSecs),NULL, &status); status = 0; } else if (!strcasecmp(HdrVer,"Ver1.0.1")) { fits_movnam_hdu(Fin, ASCII_TBL, "DUMPREF0", 0, &status); fits_read_key(Fin, TDOUBLE, "MIDSECS", &(DumpMiddleSecs), NULL, &status); status = 0; } TDump = DumpMiddleSecs; /* Move to second data table , get central time stamp */ sprintf(aspoutstr,"ASPOUT%d",234); sprintf(dumprefstr,"DUMPREF%d",234); // printf ("\n%s %s\n",aspoutstr,dumprefstr); if(!strcasecmp(HdrVer,"Ver1.0")) { fits_movnam_hdu(Fin, BINARY_TBL, "ASPOUT1", 0, &status); fits_read_key(Fin, TDOUBLE, "DUMPMIDSECS", &(DumpMiddleSecs),NULL, &status); status = 0; } else if (!strcasecmp(HdrVer,"Ver1.0.1")) { fits_movnam_hdu(Fin, ASCII_TBL, "DUMPREF1", 0, &status); fits_read_key(Fin, TDOUBLE, "MIDSECS", &(DumpMiddleSecs), NULL, &status); status = 0; } if(DumpMiddleSecs < TDump) DumpMiddleSecs += 86400.; // printf("First = %lf, Second = %lf\n", TDump, DumpMiddleSecs); TDump = DumpMiddleSecs - TDump; } else { /* We may have switched over to the next MJD, so take care of this if it's the case */ if (DumpMiddleSecs < StartTime) DumpMiddleSecs += 86400.; /* TDump is twice the difference between the middle time stamp and the start time */ TDump = 2.* ((double)floor(DumpMiddleSecs) - StartTime); } if (!strncasecmp(Cmd->Keyword[i],"TDUMP",4)) { sprintf(KeyValue,"%9.3lf",TDump); } if (!strcasecmp(Cmd->Keyword[i],"SCANLEN")) { ScanLen = NDump*TDump; sprintf(KeyValue,"%7.1lf",ScanLen); } /* Move back to first HDU again */ fits_movabs_hdu(Fin,1,&hdutype,&status);status = 0; } } /**************** Other keywords: *****************/ else{ fits_read_key(Fin, TSTRING, Cmd->Keyword[i], KeyValue, NULL, &status); if(status == VALUE_UNDEFINED || !strcasecmp(KeyValue,"")) { sprintf(KeyValue,"<not_found>"); } /**************** End other keywords: *****************/ } /* The only special keyword is AllChans. If it's not, do the following */ if(!special_key){ /* Column format */ if(Cmd->ColumnP) { printf("%s ",KeyValue); if(i==Cmd->KeywordC-1 && n_file<Cmd->InfileC-1) printf("\n"); } /* Non-column format */ else { printf("%15s: %s\n",Cmd->Keyword[i],KeyValue); } } } status=0; fits_close_file(Fin, &status); } printf("\n"); fflush(stdout); exit(0); }
void readFITS(const std::string& fitsname, cv::Mat& cvImage) { fitsfile *fptr = nullptr; int status(0); char err_text[100]; //READONLY, READWRITE fits_open_file(&fptr, fitsname.c_str(), READONLY, &status); if (status) { fits_report_error(stdout, status); fits_get_errstatus(status,err_text); fptr = nullptr; std::cout << "readFITS: Unable to open the fits file." << std::endl; throw CustomException("readFITS: Unable to open the fits file."); } //turn off scaling so we read the raw pixel value double bscale_ = 1.0, bzero_ = 0.0; fits_set_bscale(fptr, bscale_, bzero_, &status); int bitpix, naxis; int maxdim(3); long naxes[] = {1,1, 1}; fits_get_img_param(fptr, maxdim, &bitpix, &naxis, naxes, &status); if (status) { fits_report_error(stdout, status); fits_get_errstatus(status,err_text); fptr = nullptr; std::cout << "readFITS: Unable to get params from FITS." << std::endl; throw CustomException("readFITS: Unable to get params from FITS."); } if(naxis == 2) { // TBYTE, TSBYTE, TSHORT, TUSHORT, TINT, TUINT, TLONG, TLONGLONG, TULONG, TFLOAT, TDOUBLE long fpixel[] = {1, 1}; long lpixel[] = {naxes[0], naxes[1]}; long inc[] = {1, 1}; long nelements = naxes[0] * naxes[1]; double *array = new double[nelements]; fits_read_subset(fptr, TDOUBLE, fpixel, lpixel, inc, nullptr, array, nullptr, &status); if (status) { fits_report_error(stdout, status); fits_get_errstatus(status,err_text); fptr = nullptr; delete[] array; throw CustomException("readFITS: Unable to read the fits file."); } //it seems cfitsio interprets image axes in the oppsite way of opencv cvImage = cv::Mat(naxes[1], naxes[0], cv::DataType<double>::type, array); fits_close_file(fptr, &status); if (status) { fits_report_error(stdout, status); fits_get_errstatus(status,err_text); fptr = nullptr; delete[] array; throw CustomException("readFITS: Cannot close fits file."); } } if(naxis == 3) { // TBYTE, TSBYTE, TSHORT, TUSHORT, TINT, TUINT, TLONG, TLONGLONG, TULONG, TFLOAT, TDOUBLE long layer = 29; //Only consider the first layer long fpixel[] = {1, 1, layer}; long lpixel[] = {naxes[0], naxes[1], layer}; long inc[] = {1, 1, 1}; long nelements = naxes[0] * naxes[1]; double *array = new double[nelements]; fits_read_subset(fptr, TDOUBLE, fpixel, lpixel, inc, nullptr, array, nullptr, &status); if (status) { fits_report_error(stdout, status); fits_get_errstatus(status,err_text); fptr = nullptr; delete[] array; throw CustomException("readFITS: Unable to read the fits file."); } //it seems cfitsio interprets image axes in the oppsite way of opencv cvImage = cv::Mat(naxes[1], naxes[0], cv::DataType<double>::type, array); fits_close_file(fptr, &status); if (status) { fits_report_error(stdout, status); fits_get_errstatus(status,err_text); fptr = nullptr; delete[] array; throw CustomException("readFITS: Cannot close fits file."); } } }
int SDSS_sortredshift(spectrum *spec,int nspec) { int i=0,*nqso=NULL; int comp_pair(const void *x1, const void *x2); char comment[32]="\0"; spectrum *pspec=NULL,tspec; pair *dpair=NULL; extern FILE *stream; extern setblock set; /* FITS DECLERATIONS */ int fitstatus=0; fitsfile *infits=NULL; /* Read in Redshifts */ for(i=0;i<nspec;i++) { /* Just the completion counter */ if( rint(100.0*i/nspec) > rint(100.0*(i-1)/nspec)) fprintf(stream,"\b\b\b%2i%%",(int) 100*i/nspec); fits_open_file(&infits,spec[i].file,READONLY,&fitstatus); fits_read_key(infits,TDOUBLE,"Z",&(spec[i].zem),comment,&fitstatus); fits_read_key(infits,TDOUBLE,"CRVAL1",&(spec[i].beginwl),comment,&fitstatus); fits_read_key(infits,TDOUBLE,"CD1_1",&(spec[i].deltwl),comment,&fitstatus); fits_read_key(infits,TINT,"NAXIS1",&(spec[i].np),comment,&fitstatus); fits_close_file(infits,&fitstatus); if(fitstatus) { fits_get_errstatus(fitstatus,comment); errormsg("%s",comment); } } fprintf(stream,"\b\b\b"); /* Then sort in redshift */ qsort(spec,nspec,sizeof(spectrum),comp_red); if(set.optsort==0) return 0; else if(set.optsort<0) { for(i=0;i<nspec;i++) { SPECSWAP(spec[i],spec[nspec-1-i]); } } else { /* Allocate Memory */ dpair=(pair *) malloc(nspec*sizeof(pair)); pspec=(spectrum *)malloc(nspec*sizeof(spectrum)); /* Initialize data pairs for sorting */ for(i=0;i<nspec;i++) { dpair[i].idx=i; if(set.optsort>0){ pspec[i]=spec[i]; dpair[i].value=fabs(set.optsort-spec[i].zem); } } qsort(dpair,nspec,sizeof(pair),comp_pair); for(i=0;i<nspec;i++){ spec[i]=pspec[dpair[i].idx]; } free(pspec);free(dpair); } return 0; }
/* process this command */ static int ProcessCmd(char *cmd, char **args, int node, int tty) { int ip=0; char tbuf[SZ_LINE]; Finfo finfo, tfinfo; #if HAVE_CFITSIO int x0, x1, y0, y1, bin; int xcolnum, ycolnum, hdunum, hdutype; int status=0, status2=0; int dims[2]; double cens[2]; char *cols[2] = {"X", "Y"}; char *ofile=NULL; char *omode=NULL; fitsfile *ifptr, *ofptr, *tfptr; #endif switch(*cmd){ case 'f': if( !strcmp(cmd, "fitsFile") ){ if( args && word(args[0], tbuf, &ip) ){ if( !(tfinfo=FinfoLookup(tbuf)) ){ fprintf(stderr, NOIMAGE, tbuf); return 1; } } else if( !(tfinfo=FinfoGetCurrent()) ){ fprintf(stderr, NOFINFO, cmd); return 1; } if( tfinfo->fitsfile ){ if( node ) fprintf(stdout, "fitsFile\r"); fprintf(stdout, "%s %s\n", tfinfo->fname, tfinfo->fitsfile); fflush(stdout); } return 0; } break; break; case 'i': if( !strcmp(cmd, "image") ){ if( !args || !word(args[0], tbuf, &ip) ){ fprintf(stderr, WRONGARGS, cmd, 1, 0); return 1; } /* new image */ if( !(finfo = FinfoNew(tbuf)) ){ fprintf(stderr, NONEW, cmd); return 1; } /* make it current */ FinfoSetCurrent(finfo); if( node ) fprintf(stdout, "image\r"); /* return the FITS file name, if possible */ fprintf(stdout, "%s %s\n", finfo->fname, finfo->fitsfile ? finfo->fitsfile : "?"); fflush(stdout); return 0; } else if( !strcmp(cmd, "image_") ){ if( !args || !word(args[0], tbuf, &ip) ){ fprintf(stderr, WRONGARGS, cmd, 1, 0); return 1; } /* new image */ if( !(finfo = FinfoNew(tbuf)) ){ fprintf(stderr, NONEW, cmd); return 1; } /* make it current */ FinfoSetCurrent(finfo); /* no output! */ return 0; } else if( !strcmp(cmd, "imsection") ){ #if HAVE_CFITSIO if( !(finfo=FinfoGetCurrent()) ){ fprintf(stderr, NOFINFO, cmd); return 1; } ifptr = openFITSFile(finfo->fitsfile, EXTLIST, &hdutype, &status); if( status ){ fprintf(stderr, "ERROR: can't open FITS file '%s'\n", finfo->fitsfile); return 1; } if( !args || !parseSection(args[0], &x0, &x1, &y0, &y1, &bin) ){ fprintf(stderr, "ERROR: can't parse section for '%s' [%s]\n", finfo->fitsfile, (args && args[1]) ? args[1] : "NONE"); return 1; } if( args[1] ){ omode = args[1]; } else { omode = "native"; } ofile = "stdout"; // create image if ifile is an image or omode is not native if( (hdutype == IMAGE_HDU) || strcmp(omode, "native") ){ fits_create_file(&ofptr, ofile, &status); if( status ){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't open output FITS file to section '%s' [%s]\n", finfo->fitsfile, tbuf); return 1; } switch(hdutype){ case IMAGE_HDU: if( bin != 1 ){ fprintf(stderr, "ERROR: imsection of an image must use bin 1 for '%s'\n", finfo->fitsfile); return 1; } snprintf(tbuf, SZ_LINE-1, "%d:%d,%d:%d", x0, x1, y0, y1); fits_copy_image_section(ifptr, ofptr, tbuf, &status); break; default: dims[0] = x1 - x0 + 1; dims[1] = y1 - y0 + 1; cens[0] = (x0 + x1) / 2; cens[1] = (y0 + y1) / 2; tfptr = filterTableToImage(ifptr, NULL, cols, dims, cens, bin, &status); if( status ){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't create image from table for '%s' [%s]\n", finfo->fitsfile, tbuf); return 1; } fits_copy_image_section(tfptr, ofptr, "*,*", &status); closeFITSFile(tfptr, &status2); break; } if( status ){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't write section FITS file for '%s' [%s]\n", finfo->fitsfile, tbuf); closeFITSFile(ofptr, &status); return 1; } closeFITSFile(ofptr, &status); } else { // extract (native) table snprintf(tbuf, SZ_LINE-1, "x >= %d && x <= %d && y >= %d && y <= %d", x0, x1, y0, y1); // ffselect_table(&ifptr, ofile, tbuf, &status); // copied from cfileio.c/ffselect_table() /* create new empty file to hold copy of the image */ if (ffinit(&ofptr, ofile, &status) > 0) { fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't init section file for '%s' [%s]\n", finfo->fitsfile, tbuf); return 1; } /* save current HDU number in input file */ fits_get_hdu_num(ifptr, &hdunum); /* copy the primary array */ fits_movabs_hdu(ifptr, 1, NULL, &status); if( fits_copy_hdu(ifptr, ofptr, 0, &status) > 0){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't copy primary for section file '%s' [%s]\n", finfo->fitsfile, tbuf); fits_close_file(ofptr, &status); return 1; } /* back to current hdu */ fits_movabs_hdu(ifptr, hdunum, NULL, &status); /* copy all the header keywords from the input to output file */ if (fits_copy_header(ifptr, ofptr, &status) > 0){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't copy header for section file '%s' [%s]\n", finfo->fitsfile, tbuf); fits_close_file(ofptr, &status); return 1; } /* set number of rows = 0 */ /* warning: start of cfitsio black magic */ fits_modify_key_lng(ofptr, "NAXIS2", 0, NULL, &status); (ofptr->Fptr)->numrows = 0; (ofptr->Fptr)->origrows = 0; /* force the header to be scanned */ if (ffrdef(ofptr, &status) > 0){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't rdef for section file '%s' [%s]\n", finfo->fitsfile, tbuf); fits_close_file(ofptr, &status); return 1; } /* warning: end of cfitsio black magic */ /* select filtered rows and write to output file */ if (fits_select_rows(ifptr, ofptr, tbuf, &status) > 0){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't select rows for section file '%s' [%s]\n", finfo->fitsfile, tbuf); fits_close_file(ofptr, &status); return 1; } /* update params for this section */ if( (fits_get_colnum(ofptr, CASEINSEN, "X", &xcolnum, &status) > 0) || (fits_get_colnum(ofptr, CASEINSEN, "Y", &ycolnum, &status) > 0) ){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't find X,Y cols for section file '%s' [%s]\n", finfo->fitsfile, tbuf); fits_close_file(ofptr, &status); return 1; } /* we can ignore errors here */ status = 0; snprintf(tbuf, SZ_LINE-1, "TALEN%d", xcolnum); fits_modify_key_lng(ofptr, tbuf, x1-x0, NULL, &status); status = 0; snprintf(tbuf, SZ_LINE-1, "TALEN%d", ycolnum); fits_modify_key_lng(ofptr, tbuf, y1-y0, NULL, &status); status = 0; snprintf(tbuf, SZ_LINE-1, "TLMIN%d", xcolnum); fits_modify_key_flt(ofptr, tbuf, x0, 6, NULL, &status); status = 0; snprintf(tbuf, SZ_LINE-1, "TLMAX%d", xcolnum); fits_modify_key_flt(ofptr, tbuf, x1, 6, NULL, &status); status = 0; snprintf(tbuf, SZ_LINE-1, "TLMIN%d", ycolnum); fits_modify_key_flt(ofptr, tbuf, y0, 6, NULL, &status); status = 0; snprintf(tbuf, SZ_LINE-1, "TLMAX%d", ycolnum); fits_modify_key_flt(ofptr, tbuf, y1, 6, NULL, &status); /* close the output file */ status = 0; fits_close_file(ofptr, &status); } closeFITSFile(ifptr, &status); return 0; #else fprintf(stderr, "ERROR: for section support, build js9helper with cfitsio\n"); return 1; #endif } else if( !strcmp(cmd, "info") ){ if( tty ){ if( !(finfo=FinfoGetCurrent()) ){ fprintf(stderr, NOFINFO, cmd); return 1; } /* make sure we have a wcs */ fprintf(stdout, "fname:\t%s\n", finfo->fname); fprintf(stdout, "fits:\t%s\n", finfo->fitsfile?finfo->fitsfile:"N/A"); fflush(stdout); } return 0; } break; case 'l': /* list all images */ if( !strcmp(cmd, "list") ){ FinfoList(stdout); return 0; } break; case 's': if( !strcmp(cmd, "setDataPath") ){ if( args && word(args[0], tbuf, &ip) ){ setenv("JS9_DATAPATH", tbuf, 1); if( node ) fprintf(stdout, "setDataPath\r"); fprintf(stdout, "%s\n", getenv("JS9_DATAPATH")); fflush(stdout); } else { fprintf(stderr, WRONGARGS, cmd, 1, 0); return 1; } return 0; } break; case 'u': if( !strcmp(cmd, "unimage") ){ if( !args || !word(args[0], tbuf, &ip) ){ fprintf(stderr, WRONGARGS, cmd, 1, 0); return 1; } /* close this image */ FinfoFree(tbuf); return 0; } break; case '#': case '\0': return 0; default: break; } /* if we reached here, we did not recognize the command */ fprintf(stderr, "ERROR: unknown command '%s'\n", cmd); /* return the news */ return 2; }
/* process this command */ static int ProcessCmd(char *cmd, char **args, int narg, int node, int tty) { char tbuf[SZ_LINE]; Finfo finfo, tfinfo; #if HAVE_CFITSIO int xlims[2], ylims[2], bin, got, hdutype, hdunum, ncard; int status=0, tstatus=0; int dims[2]; double cens[2]; char extname[FLEN_CARD]; char *cols[2] = {"X", "Y"}; char *ofile="stdout"; char *section=NULL; char *filter=NULL; char *slice=NULL; char *cardstr=NULL; void *tcens=NULL; fitsfile *ifptr, *ofptr, *tfptr; #endif switch(*cmd){ case 'f': if( !strcmp(cmd, "fitsFile") ){ if( narg ){ if( !(tfinfo=FinfoLookup(args[0])) ){ fprintf(stderr, NOIMAGE, args[0]); return 1; } } else if( !(tfinfo=FinfoGetCurrent()) ){ fprintf(stderr, NOFINFO, cmd); return 1; } if( tfinfo->fitsfile ){ if( node ) fprintf(stdout, "fitsFile\r"); fprintf(stdout, "%s %s\n", tfinfo->fname, tfinfo->fitsfile); fflush(stdout); } return 0; } break; break; case 'i': if( !strcmp(cmd, "image") ){ if( !narg ){ fprintf(stderr, WRONGARGS, cmd, 1, 0); return 1; } /* new image */ if( !(finfo = FinfoNew(args[0])) ){ return 1; } /* make it current */ FinfoSetCurrent(finfo); if( node ) fprintf(stdout, "image\r"); /* return the FITS file name, if possible */ fprintf(stdout, "%s %s\n", finfo->fname, finfo->fitsfile ? finfo->fitsfile : "?"); fflush(stdout); return 0; } else if( !strcmp(cmd, "image_") ){ if( !narg ){ fprintf(stderr, WRONGARGS, cmd, 1, 0); return 1; } /* new image */ if( !(finfo = FinfoNew(args[0])) ){ return 1; } /* make it current */ FinfoSetCurrent(finfo); /* no output! */ return 0; } else if( !strcmp(cmd, "imsection") ){ #if HAVE_CFITSIO if( !(finfo=FinfoGetCurrent()) ){ fprintf(stderr, NOFINFO, cmd); return 1; } if( narg < 2 ){ fprintf(stderr, WRONGARGS2, cmd, 2); return 1; } ifptr = openFITSFile(finfo->fitsfile, READONLY, EXTLIST, &hdutype, &status); if( status ){ fprintf(stderr, "ERROR: can't open FITS file '%s'\n", finfo->fitsfile); return 1; } /* process args */ ofile = args[0]; section = args[1]; if( narg >= 3 && args[2] ){ filter = args[2]; } if( narg >= 4 && args[3] ){ slice = args[3]; } if( !section || !(got = parseSection(ifptr, hdutype, section, xlims, ylims, dims, cens, &bin)) ){ fprintf(stderr, "ERROR: can't parse section for '%s' [%s]\n", finfo->fitsfile, (args && args[0]) ? args[0] : "NONE"); return 1; } /* output image */ fits_create_file(&ofptr, ofile, &status); if( status ){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't open output FITS file to section '%s' [%s]\n", finfo->fitsfile, tbuf); return 1; } switch(hdutype){ case IMAGE_HDU: /* image: let cfitsio make a section */ if( copyImageSection(ifptr, ofptr, dims, cens, bin, slice, &status) ){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't copy image section for '%s' [%s]\n", finfo->fitsfile, tbuf); return 1; } break; default: /* table: let jsfitsio create an image section by binning the table */ tfptr = filterTableToImage(ifptr, filter, cols, dims, cens, 1, &status); if( status ){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't create image from table for '%s' [%s]\n", finfo->fitsfile, tbuf); return 1; } fits_read_key(tfptr, TSTRING, "CTYPE1", tbuf, NULL, &status); if( status == 0 ){ if( strstr(tbuf, "--HPX") || strstr(tbuf, "--hpx") ){ tcens = cens; } } status = 0; /* copy section to new image */ if( copyImageSection(tfptr, ofptr, dims, tcens, bin, NULL, &status) ){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't copy image section for '%s' [%s]\n", finfo->fitsfile, tbuf); return 1; } tstatus = 0; closeFITSFile(tfptr, &tstatus); break; } if( status ){ fits_get_errstatus(status, tbuf); fprintf(stderr, "ERROR: can't create section FITS file for '%s' [%s]\n", finfo->fitsfile, tbuf); closeFITSFile(ofptr, &status); return 1; } // return a json object with info about original data fprintf(stdout, "{\"file\":\"%s\"", finfo->fitsfile); fprintf(stdout, ",\"type\":%d", hdutype); ffghdn(ifptr, &hdunum); fprintf(stdout, ",\"extnum\":%d", hdunum-1); tstatus=0; ffgky(ifptr, TSTRING, "EXTNAME", extname, NULL, &tstatus); if( !tstatus ){ fprintf(stdout, ",\"extname\":\"%s\"", extname); } fprintf(stdout, ",\"hdus\":"); _listhdu(finfo->fitsfile, NULL); tstatus=0; getHeaderToString(ifptr, &cardstr, &ncard, &tstatus); if( cardstr ){ fprintf(stdout, ",\"ncard\":%d",ncard); fprintf(stdout, ",\"cardstr\":\"%s\"",cardstr); free(cardstr); } fprintf(stdout, "}\n"); fflush(stdout); tstatus=0; closeFITSFile(ifptr, &tstatus); tstatus=0; closeFITSFile(ofptr, &tstatus); return 0; #else fprintf(stderr, "ERROR: for section support, build js9helper with cfitsio\n"); return 1; #endif } else if( !strcmp(cmd, "info") ){ if( tty ){ if( !(finfo=FinfoGetCurrent()) ){ fprintf(stderr, NOFINFO, cmd); return 1; } /* make sure we have a wcs */ fprintf(stdout, "fname:\t%s\n", finfo->fname); fprintf(stdout, "fits:\t%s\n", finfo->fitsfile?finfo->fitsfile:"N/A"); fflush(stdout); } return 0; } break; case 'l': /* list all images */ if( !strcmp(cmd, "list") ){ FinfoList(stdout); return 0; #if HAVE_CFITSIO } else if( !strcmp(cmd, "listhdus") ){ if( !(finfo=FinfoGetCurrent()) ){ fprintf(stderr, NOFINFO, cmd); return 1; } _listhdu(finfo->fitsfile, NULL); fflush(stdout); return 0; #endif } break; case 's': if( !strcmp(cmd, "setDataPath") ){ if( narg ){ setenv("JS9_DATAPATH", args[0], 1); if( node ) fprintf(stdout, "setDataPath\r"); fprintf(stdout, "%s\n", getenv("JS9_DATAPATH")); fflush(stdout); } else { fprintf(stderr, WRONGARGS, cmd, 1, 0); return 1; } return 0; } break; case 'u': if( !strcmp(cmd, "unimage") ){ if( !narg ){ fprintf(stderr, WRONGARGS, cmd, 1, 0); return 1; } /* close this image */ FinfoFree(args[0]); return 0; } break; case '#': case '\0': return 0; default: break; } /* if we reached here, we did not recognize the command */ fprintf(stderr, "ERROR: unknown command '%s'\n", cmd); /* return the news */ return 2; }
bool FITSImage::loadFITS ( const QString &inFilename, QProgressDialog *progress ) { int status=0, nulval=0, anynull=0; long fpixel[2], nelements, naxes[2]; char error_status[512]; qDeleteAll(starCenters); starCenters.clear(); if (mode == FITS_NORMAL && progress) { progress->setLabelText(i18n("Please hold while loading FITS file...")); progress->setWindowTitle(i18n("Loading FITS")); } if (mode == FITS_NORMAL && progress) progress->setValue(30); if (fptr) { fits_close_file(fptr, &status); if (tempFile) QFile::remove(filename); } filename = inFilename; if (filename.contains("/tmp/")) tempFile = true; else tempFile = false; filename.remove("file://"); if (fits_open_image(&fptr, filename.toAscii(), READONLY, &status)) { fits_report_error(stderr, status); fits_get_errstatus(status, error_status); if (progress) KMessageBox::error(0, i18n("Could not open file %1 (fits_get_img_param). Error %2", filename, QString::fromUtf8(error_status)), i18n("FITS Open")); return false; } if (mode == FITS_NORMAL && progress) if (progress->wasCanceled()) return false; if (mode == FITS_NORMAL && progress) progress->setValue(40); if (fits_get_img_param(fptr, 2, &(stats.bitpix), &(stats.ndim), naxes, &status)) { fits_report_error(stderr, status); fits_get_errstatus(status, error_status); if (progress) KMessageBox::error(0, i18n("FITS file open error (fits_get_img_param): %1", QString::fromUtf8(error_status)), i18n("FITS Open")); return false; } if (stats.ndim < 2) { if (progress) KMessageBox::error(0, i18n("1D FITS images are not supported in KStars."), i18n("FITS Open")); return false; } if (fits_get_img_type(fptr, &data_type, &status)) { fits_report_error(stderr, status); fits_get_errstatus(status, error_status); if (progress) KMessageBox::error(0, i18n("FITS file open error (fits_get_img_type): %1", QString::fromUtf8(error_status)), i18n("FITS Open")); return false; } if (mode == FITS_NORMAL && progress) if (progress->wasCanceled()) return false; if (mode == FITS_NORMAL && progress) progress->setValue(60); stats.dim[0] = naxes[0]; stats.dim[1] = naxes[1]; delete (image_buffer); image_buffer = NULL; image_buffer = new float[stats.dim[0] * stats.dim[1]]; if (image_buffer == NULL) { qDebug() << "Not enough memory for image_buffer"; return false; } if (mode == FITS_NORMAL && progress) { if (progress->wasCanceled()) { delete (image_buffer); return false; } } if (mode == FITS_NORMAL && progress) progress->setValue(70); nelements = stats.dim[0] * stats.dim[1]; fpixel[0] = 1; fpixel[1] = 1; qApp->processEvents(); if (fits_read_2d_flt(fptr, 0, nulval, naxes[0], naxes[0], naxes[1], image_buffer, &anynull, &status)) { fprintf(stderr, "fits_read_pix error\n"); fits_report_error(stderr, status); return false; } if (mode == FITS_NORMAL && progress) { if (progress->wasCanceled()) { delete (image_buffer); return false; } } calculateStats(); if (mode == FITS_NORMAL && progress) progress->setValue(80); //currentWidth = stats.dim[0]; // currentHeight = stats.dim[1]; qApp->processEvents(); if (mode == FITS_NORMAL) { checkWCS(); if (progress) progress->setValue(90); } if (mode == FITS_NORMAL && progress) { if (progress->wasCanceled()) { delete (image_buffer); return false; } } if (mode == FITS_NORMAL && progress) progress->setValue(100); starsSearched = false; return true; }
std::string FitsFileResource::getStatus() const { char pBuf[31]; fits_get_errstatus(mStatus, pBuf); return std::string(pBuf); }