Exemplo n.º 1
0
int FitsFile::GetHDUCount()
{
	CheckOpen();
	int hdunum = 0, status = 0;
	fits_get_num_hdus(_fptr, &hdunum, &status);
	CheckStatus(status);
	return hdunum;
}
Exemplo n.º 2
0
int main(int argc, char *argv[]) {
  fitsfile *fitsFilePtr;         
  char card[FLEN_CARD]; 
  int status, numKey, numHDU, curKey, curHDU, hduType;

  status = 0; /* Must initialize status before use */

  if(argc < 2) {
    printf("ERROR\n");
    exit(11);
  }

  /* Open the fits file */
  fits_open_file(&fitsFilePtr, argv[1], READONLY, &status);
  reportAndExitOnFITSerror(status);

  /* Get the number of HDUs -- usually only one */
  fits_get_num_hdus(fitsFilePtr, &numHDU, &status);
  reportAndExitOnFITSerror(status);
  printf("Number of headers in file: %d\n", numHDU);

  /* Get the current HDU number.  This first one is '1', not '0'. */
  fits_get_hdu_num(fitsFilePtr, &curHDU);
  reportAndExitOnFITSerror(status);
  printf("Working on header number: %d\n", curHDU);

  fits_get_hdu_type(fitsFilePtr,  &hduType, &status);
  reportAndExitOnFITSerror(status);
  switch(hduType) {
    case IMAGE_HDU : printf("HDU Type: IMAGE\n");        break;
    case ASCII_TBL : printf("HDU Type: ASCII Table\n");  break;
    case BINARY_TBL: printf("HDU Type: Binary Table\n"); break;
    default        : printf("HDU Type: UNKNOWN\n");      break;
  }

  /* Get the size (number of keys) of the header space */
  fits_get_hdrspace(fitsFilePtr, &numKey, NULL, &status);
  reportAndExitOnFITSerror(status);
  printf("Number of keys in current HDU: %d\n", numKey);

  /* One can traverse all the lines like this: */
  for(curKey = 1; curKey <= numKey; curKey++)  { 
    /* read the current keyword */
    fits_read_record(fitsFilePtr, curKey, card, &status); 
    reportAndExitOnFITSerror(status);
    printf("%5d: %s\n", curKey, card);
  }
  printf("END\n\n");

  /* We are done.  Close the file. */
  fits_close_file(fitsFilePtr, &status);
  reportAndExitOnFITSerror(status);

  /* If we get here, everything worked! */
  return 0;
}
Exemplo n.º 3
0
Arquivo: hdu.c Projeto: rforge/rfitsio
/* Wrapper to fits_get_num_hdus */
SEXP
cfitsio_get_num_hdus (SEXP fits_object)
{
    fits_file_t * fits = R_ExternalPtrAddr (fits_object);

    if (NULL != fits && NULL != fits->cfitsio_ptr)
    {
	int hdu_num;

	fits_get_num_hdus (fits->cfitsio_ptr, &hdu_num, &(fits->status));
	return ScalarInteger (hdu_num);
    }
    else
	return ScalarInteger (-1);
}
Exemplo n.º 4
0
int fitsNHDU ( fitsfile *fp ) {
  int nhdu;
  int status = 0;
  
  // the internal function of cfitsio does the "right thing" and simply
  // scans through the file to see how many HDU's there are
  
  fits_get_num_hdus(fp, &nhdu, &status);
  
  if (status) {
    nhdu = 0;
  }
  
  return nhdu;
}
Exemplo n.º 5
0
QMap<QString, QString> fitsKeys( fitsfile *fp, int HDU ) {
  
  QMap<QString, QString> keyMap;
  
  int ret = 0;
  int nHDU;
  int hduType;
  // try to seek to the desired HDU
  if (fits_get_num_hdus(fp, &nHDU, &ret)) {
    return keyMap;
  }
  if (HDU > nHDU) {
    return keyMap;
  } else {
    if (fits_movabs_hdu(fp, HDU, &hduType, &ret)) {
      return keyMap;
    }
  }
  
  // reset keyword pointer to beginning of HDU
  int rec = 0;
  char card[FLEN_CARD];
  if (fits_read_record(fp, rec, card, &ret)) {
    return keyMap;
  } 
  
  // go through all keys and add to the QMap
  QString theKey;
  QString theVal;
  char keyval[FLEN_VALUE];
  char keycom[FLEN_COMMENT];
  char keyname[FLEN_KEYWORD];
  int keylen;
  while (!fits_find_nextkey(fp, NULL, 1, NULL, 0, card, &ret)) {
    fits_get_keyname(card, keyname, &keylen, &ret);
    fits_parse_value(card, keyval, keycom, &ret);
    theKey = keyname;
    theVal = keyval;
    keyMap.insert(theKey, theVal);
  }
  
  return keyMap;
}
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
	fitsfile *fptr;
	int i, j, status, dataok, hduok, hdunum, hdutype;
	char *hdustr, *datastr;

	for (i=1; i<argc; i++) {

		fits_open_file(&fptr, argv[i], READONLY, &status);
		if (status) { 
			fits_report_error(stderr, status);
			exit(-1); 
		}

		fits_get_num_hdus(fptr, &hdunum, &status);
		if (status) { 
			fprintf(stderr, "Bad get_num_hdus status for '%s' = %d", 
				argv[i], status);
			exit(-1); 
		}

		for (j=0; j<hdunum; j++) {
			fits_movabs_hdu(fptr, hdunum, &hdutype, &status);
			if (status) { 
				fprintf(stderr, "Bad movabs status for '%s[%d]' = %d.", 
					argv[i], j, status);
				exit(-1);
			}
			fits_verify_chksum(fptr, &dataok, &hduok, &status);
			if (status) { 
				fprintf(stderr, "Bad verify status for '%s[%d]' = %d.", 
					argv[i], j, status);
				exit(-1);
			}
			datastr = verify_status(dataok);
			hdustr = verify_status(hduok);
			printf("Verifying '%s[%d]'  data='%s'   hdu='%s'.\n",
			       argv[i], j, datastr, hdustr);
		}
	}
}
Exemplo n.º 7
0
fitsfile* fits_init(char *filename, int iomode, int *nrelhdu, int *status) {
  *status = 0;
  fitsfile *fptr;
  if (fits_open_file(&fptr, filename, iomode, status)) {
    fits_print_error(*status);
    return 0;
  }

  /* Get the current HDU position and number of HDUs*/
  int hdupos, nhdu;
  fits_get_hdu_num (fptr, &hdupos);
  fits_get_num_hdus(fptr, &nhdu, status);

  /* will process only a single header if a specific extension was given, 
     otherwise all HDUs */ 
  if  (hdupos != 1 || strchr(filename, '[') || nhdu == 1) 
    *nrelhdu = 0;
  else *nrelhdu = nhdu-hdupos;

  return fptr;
}
Exemplo n.º 8
0
// Function which determines if file is of type spSpec, spPlate
int SDSS_filetype(char *infile, int *nspec){
	// return value:
	// 0 = spSpec
	// 1 = spPlate
	// 2 = spec
	int val = 0;
	int hdunum_exp = 0;

	fitsfile *infits;
	int status = 0, hdunum = 0;
	//printf("Name of File: %s\n", infile);
	fits_open_file(&infits, infile, READONLY, &status);
	fits_get_num_hdus(infits, &hdunum, &status);
	//printf("HDUNumber: %i\n\n", hdunum);


	// Number of HDUs not necessarily 9. In some cases might be different
	if( strstr(infile, "spSpec") != NULL ){
		val = 0;
		hdunum_exp = 7;
		//if(hdunum != hdunum_exp) warnmsg("Number of HDUs is not %d as expected from spSpec", hdunum_exp);
	}
	if( strstr(infile, "spPlate") != NULL ){
		val = 1;
		hdunum_exp = 9;
		//if(hdunum != hdunum_exp) warnmsg("Number of HDUs is not %d as expected from spPlate", hdunum_exp);
		fits_read_key(infits, TINT, "NAXIS2", nspec, NULL, &status);
	}
	if( strstr(infile, "spec-") != NULL ){
		val = 2;
		hdunum_exp = 14;
		//if(hdunum != hdunum_exp) warnmsg("Number of HDUs is not %d as expected from spec", hdunum_exp);
	}

	// report Error. TODO: Decide if want to use errormsg instead.
	fits_close_file(infits, &status);
	fits_report_error(stderr, status);

	return val;
}
Exemplo n.º 9
0
int DoIt(){
 
    /* Variable declarations */

    /* Generic use variables */

    int i,j,k;					/* Generic loop counters */

    /* DRMS/JSOC variables */

	char *harpnum,*time_range;					/* SHARPs ID and time range from module_args[] */
	char *drms_query;							/* The DRMS query we are going to send */
	double umb_sig, pen_sig;					/* Cutoffs for sunspots */
	int num_query_chars;						/* Number of characters in total query for malloc definition */
	CmdParams_t *params=&cmdparams;				/* For the module_args stuff */
	DRMS_RecordSet_t *drms_ids;					/* Holds the id structure of the records */
	DRMS_Record_t *drms_record;					/* Holds specific record information */
	DRMS_Segment_t *drms_segment;				/* Segment information */
	int drms_status;							/* Status variable */
	int num_records;							/* Number of records and variables to get the segment locations we need */
	
	/* cfitsio-related variables */

    fitsfile *c_ptr,*i_ptr;				/* Pointers for FITS files */
    int c_status, i_status;				/* Status checker for opening files */
    int hdu_pos,num_hdus;				/* HDU number and location */
    int needed_hdu;						/* The HDU we want to be on */
    int any_nulls;						/* Nonzero if there are null values in data */
    char i_filename[DRMS_MAXPATHLEN+1],c_filename[DRMS_MAXPATHLEN+1];	/* Containers for the filenames */
    double nulval;							/* Container for what null values in data should be set to */
	

    /* Needed FITS keywords */

    int naxis1,naxis2,naxis;			/* Length of axes */
    double crpix1,crpix2;				/* SHARPs CRPIX is the center of the sun relative to the lower left (fortran: 1,1) of patch */
    double cdelt1		;				/* HMI pixel sizes in as */
    double rsun_obs;					/* Radius of the sun, observed at t_obs */
    double blank;						/* Values of bad data */
    TIME t_obs;							/* Observation time, ZULU */
    char **t_obs_s;						/* String version of observation time */
    long *quality;						/* QUALITY keyword */
    
    /* Data-related variables */
    
    double **con_dat, **inc_dat;			/* Data arrays, size defined once naxis1/2 are known */
    int **p_mask, **n_mask;					/* Mask for each polarity of umbrae within continuum data */ 
    double *c_pixel_strip;					/* Strip of pixels read from the continuum data */
    double *i_pixel_strip;					/* Strip of pixels read from the inclination data */
    long fpixel[2];							/* Holds the location of pixel to be read */
    LONGLONG nelements;						/* Number of elements in a strip to be read (naxis2) */
    FILE *outptr,*bad_outptr;				/* Pointer to the outfile */
    char outfile_name[29];					/* Name of the outfile */
    char bad_outfile_name[24];				/* Name of the outfile for bad quality*/    
    
    /* Variables related to the actual task */
    
    double rllx,rlly;				/* Disk center, patch coordinates */
    double **radius;				/* Array to hold where the Sun's boundaries are, column major order */
    double rsun_pix,xx,yy,r;		/* Variables associated with radial boundaries */
    double umb,pen;					/* Intensity cutoffs for the umbra and penumbra */
    double num_good;				/* The number of nonzero continuum values in a sunspot region */
    double *p_spots,*n_spots;		/* Number of sunspots of each polarity within an active region */
    double mu;						/* Angle from solar center */
    long *t_secs;					/* T_OBS time converted to seconds since UNIX epoch */
    int noaa_ar;					/* Active region number */
    
    /* Initialise variables that need it */

    i=j=k=0;
    drms_status=0;

	/* Grab values from module_args[] */

	harpnum=strdup(params_get_str(params,"harpnum"));
	time_range=strdup(params_get_str(params,"time_range"));
	umb_sig=params_get_double(params,"umb_sig");
	pen_sig=params_get_double(params,"pen_sig");

	/* Now we start the main program. The rough layout is as follows: 
	   
	   1. Query drms. Based on what we learn, either exit or grab what we need from it.
	   2. Loop through the files, determining the number of sunspots in each polarity.
	   3. Print out a table of values at the end.				   */
	
	/* Forge the DRMS query. */
	
	num_query_chars=16+strlen(harpnum);		/* hmi.sharp_720s[] is 16 characters */
	
	if (time_range!="[]"){
		
		num_query_chars+=strlen(time_range);
		
	}
	
	drms_query=calloc(num_query_chars,sizeof(char));
	strcat(drms_query,"hmi.sharp_720s[");
	strcat(drms_query,harpnum);
	strcat(drms_query,"]");
	
	if (time_range!="[]"){
	
		strcat(drms_query,time_range);
		
	}
	
	/* Query DRMS for the records. */
	
	printf("Querying DRMS. This may take some time.\n");
	
	if (!(drms_ids=drms_open_records(drms_env,drms_query,&drms_status))){
		
		printf("No record sets match your criteria. Check your SHARPs ID and your time range.\n");
		drms_close_records(drms_ids,DRMS_FREE_RECORD);
		free(drms_query);
		return 0;
		
	}

	free(drms_query);

	num_records=drms_ids->n;
	printf("%d records match. Checking to make sure we have the needed data segments.\n",num_records);

	drms_record=drms_ids->records[0];

	if (!(drms_segment_lookup(drms_record,"continuum"))){
		
		printf("Continuum segment not present! Exiting.\n");
		drms_close_records(drms_ids,DRMS_FREE_RECORD);
		return 0;
	
	}

	if (!(drms_segment_lookup(drms_record,"inclination"))){
		
		printf("Inclination segment not present! Exiting.\n");
		drms_close_records(drms_ids,DRMS_FREE_RECORD);
		return 0;
	
	}
	
	/* Now we can start. We loop over all records, get the keyword information we need, get the data, and then calculate. */
	
	/* First set the size of some of the pointers that are intended to be arrays. */
	
	/* Data-related arrays */
	p_spots=malloc(num_records*sizeof(double));
	n_spots=malloc(num_records*sizeof(double));
	
	/* Time-related arrays */
	
	t_secs=malloc(num_records*sizeof(long));
	t_obs_s=malloc(num_records*sizeof(char *));
	
	for (i=0;i<num_records;i++){
		
		t_obs_s[i]=malloc(T_OBS_LENGTH*sizeof(char));
		
	}
	
	/* Quality */
	
	quality=malloc(num_records*sizeof(long));
		
	for (k=0;k<num_records;k++){ 

		drms_record=drms_ids->records[k];
		
		/* Check to see if we have data for a particular observation time */
		
		if (!(t_obs=drms_getkey_time(drms_record,"T_OBS",&drms_status))){
					
			printf("Keyword %s not present! Exiting.\n","T_OBS");
			drms_close_records(drms_ids,DRMS_FREE_RECORD);
			return 0;
		
		}
		
		if (time_is_invalid(t_obs)){
			
			printf("Bad record, skipping.\n");
			
		} else {

			if (k == 0){
				
				/* Get active region number for pregame info */
			
				if (!(noaa_ar=drms_getkey_int(drms_record,"NOAA_AR",&drms_status))){
					
					printf("Keyword %s not present! Exiting.\n","NOAA_AR");
					drms_close_records(drms_ids,DRMS_FREE_RECORD);
					return 0;
		
				}
				
				/* Create data output filename */
			
				sprintf(outfile_name,"AR%d.spotcount-output.dat",noaa_ar);
				sprintf(bad_outfile_name,"AR%d.bad-quality.dat",noaa_ar);
				
				/* Print out some stats before we run */
			
				printf("Pre-analysis details:\n");
				printf("Analyzing: HARP Number: %s\t NOAA AR: %d\n",harpnum,noaa_ar);
				printf("Output file: %s\n",outfile_name);
			
				if (time_range == "[]"){
				
					printf("We are covering the entire data set.\n");
			
				} else {
				
					printf("Time range: %s\n",time_range);
			
				}

					printf("\n\n");
			
			}
			
			printf("Processing record %d of %d.\n",k+1,num_records);
		
			/* Fill keywords */
			
			if (!(quality[k]=drms_getkey_longlong(drms_record,"QUALITY",&drms_status))){
			
				quality[k]=0;
		
			}
	
			if (!(crpix1=drms_getkey_double(drms_record,"CRPIX1",&drms_status))){
			
				printf("Keyword %s not present! Exiting.\n","CRPIX1");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
			
			if (!(crpix2=drms_getkey_double(drms_record,"CRPIX2",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","CRPIX2");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
		
			if (!(cdelt1=drms_getkey_double(drms_record,"CDELT1",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","CDELT1");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
		
			if (!(rsun_obs=drms_getkey_double(drms_record,"RSUN_OBS",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","RSUN_OBS");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
		
			if (!(blank=drms_getkey_double(drms_record,"BLANK",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","BLANK");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
		
			sprint_ut(t_obs_s[k],t_obs);		/* Convert to string */
			
			if (quality[k] == 0){
		
				/* Ok, now we get the file locations for the data from DRMS. Originally I attempted
				* to pull the data directly from DRMS but there were vague free() and malloc() issues
				* possibly due to icc and multithreading. */
		
				if (!(drms_segment=drms_segment_lookup(drms_record,"continuum"))){
			
					printf("Problem opening the continuum segment! Exiting.\n");
					drms_close_records(drms_ids,DRMS_FREE_RECORD);
					return 0;
			
				}
		
				drms_segment_filename(drms_segment,c_filename);
			
				/* naxis1 and naxis2 we get from segment information */
		
				naxis1=(int)drms_segment->axis[0];
				naxis2=(int)drms_segment->axis[1];
		
				if (!(drms_segment=drms_segment_lookup(drms_record,"inclination"))){
			
					printf("Problem opening the inclination segment! Exiting.\n");
					drms_close_records(drms_ids,DRMS_FREE_RECORD);
					return 0;
			
				}
		
				drms_segment_filename(drms_segment,i_filename);
		
				/* Now open the FITS files and get to work. */
	
				c_status=i_status=0;

				if (fits_open_file(&c_ptr,c_filename,READONLY,&c_status)){
				
					printf("Cannot open %s! Exiting.\n",c_filename);
					exit(0);

				}

				if (fits_open_file(&i_ptr,i_filename,READONLY,&i_status)){
				
					printf("Cannot open %s! Exiting.\n",i_filename);
					fits_close_file(c_ptr,&c_status);
					exit(0);

				}

				printf(" Opening FITs files.\n");

				/* Walk through the HDUs until we get to one with NAXIS=2 */

				/* Number of headers and which one we are on */

				fits_get_num_hdus(c_ptr,&num_hdus,&c_status);
				fits_get_hdu_num(c_ptr,&hdu_pos);

				/* Find the one with two naxes */

				naxis=0;
			
				for (i=1;i<=num_hdus;i++){
				
					fits_movabs_hdu(c_ptr,i,NULL,&c_status);
					fits_read_key(c_ptr,TINT,"NAXIS",&naxis,NULL,&c_status);
				
					if (naxis == 2){
	
						needed_hdu=i;
	
					}
				}

				/* Set all to the needed HDU */

				if (naxis == 0){
		
					printf("HDU problems: can't find one with the required number of axes.\n");
					fits_close_file(c_ptr,&c_status);
					fits_close_file(i_ptr,&i_status);
					exit(0);

				} else {

					fits_movabs_hdu(c_ptr,needed_hdu,NULL,&c_status);
					fits_movabs_hdu(i_ptr,needed_hdu,NULL,&i_status);

				}

				/* Now set some definite boundaries on arrays to help with memory usage. Arrays are called as con_dat[y][x]. */
	
				p_mask=malloc(naxis2*sizeof(int *));
				n_mask=malloc(naxis2*sizeof(int *));
				con_dat=malloc(naxis2*sizeof(double *));
				inc_dat=malloc(naxis2*sizeof(double *));
				radius=malloc(naxis2*sizeof(double *));
				
				c_pixel_strip=calloc(naxis1,sizeof(double));
				i_pixel_strip=calloc(naxis1,sizeof(double));
	
				for (j=0;j<naxis2;j++){
		
					p_mask[j]=calloc(naxis1,sizeof(int));
					n_mask[j]=calloc(naxis1,sizeof(int));
					con_dat[j]=calloc(naxis1,sizeof(double));
					inc_dat[j]=calloc(naxis1,sizeof(double));
					radius[j]=calloc(naxis1,sizeof(double));
		
				}
    
				/* Next, put data in the arrays, clear out blank values and NaNs from the data */
	
				fpixel[0]=1;		/* cfitsio uses fortran reference instead of c when accessing data */
				nelements=naxis1;
				nulval=0;
				any_nulls=0;
    
				for (j=0;j<naxis2;j++){
		
					fpixel[1]=j+1;	/* Add 1 to account for fortran FITS indexing */
					fits_read_pix(c_ptr,TDOUBLE,fpixel,nelements,&nulval,c_pixel_strip,&any_nulls,&c_status);
					fits_read_pix(i_ptr,TDOUBLE,fpixel,nelements,&nulval,i_pixel_strip,&any_nulls,&i_status);
		
					for (i=0;i<naxis1;i++){
			
						/* Kill blank values if present, if not assign to the correct place in array */
			
						if (c_pixel_strip[i] == blank){
				
							con_dat[j][i]=0.0;
					
						} else {
					
							con_dat[j][i]=c_pixel_strip[i];
			
						}
			
						if (i_pixel_strip[i] == blank){
				
							inc_dat[j][i]=0.0;
				
						} else {
					
							inc_dat[j][i]=i_pixel_strip[i];
			
						}
					
					}
				}
		
				printf(" Analyzing data.\n");
	
				/* We now have filled arrays of data about the SHARPs patch and all of the needed keywords. */
	
				/* Coordinate variable definitions for future use. See the declaration section */
				/* at the front of the code to understand what these refer to. */
	
				rllx=(crpix1-1);
				rlly=(crpix2-1);
	
				/* Fill the radius array, handle limb darkening, find max value in patch. */
	
				rsun_pix=rsun_obs/cdelt1;
	
				for (i=0;i<naxis1;i++){
		
					for (j=0;j<naxis2;j++){
			
						xx=(double)i-rllx;
						yy=(double)j-rlly;
						r=sqrt(xx*xx+yy*yy);
				
						if (r <= rsun_pix){
				
							radius[j][i]=r;
							mu=sqrt(1-pow(r/rsun_pix,2.0));
							con_dat[j][i]=con_dat[j][i]/limb_darken(mu);
					
						}
					}
				}
	
				/* Create the actual masks for sunspot counting */
			
				spotbounds(con_dat,naxis1,naxis2,&umb,&pen,umb_sig,pen_sig);

				num_good=0;
	
				for (i=0;i<naxis1;i++){
		
					for (j=0;j<naxis2;j++){
		
						if ((radius[j][i] > 0)&&(con_dat[j][i] <= pen)&&(con_dat[j][i] > 0)){
				
							num_good++;
			
						}
					}
				}

				p_spots[k]=n_spots[k]=0.0;
	
				if (num_good > 0){
		
					/* We have a region. */
		
					for (i=0;i<naxis1;i++){
					
						for (j=0;j<naxis2;j++){
				
							/* On the solar disk, with continuum values at or below the cutoff for
							* the penumbra */
				
							if ((radius[j][i] > 0)&&(con_dat[j][i] <= umb)&&(con_dat[j][i] > 0)){
						
								/* "Positive" sunspot polarities. */
							
								if (inc_dat[j][i] < 90){
							
									p_mask[j][i]=1;
					
								}
					
								/* "Negative" sunspot polarities. */
					
								if (inc_dat[j][i] > 90){
							
									n_mask[j][i]=1;
					
								}
							}
						}
					}
				
					/* Now find the number of unique spots */
				
					p_spots[k]=connected_component_detect(p_mask,naxis1,naxis2);
					n_spots[k]=connected_component_detect(n_mask,naxis1,naxis2);
			
				}

			
				/* Free up dynamic arrays and close the files for the next iteration. */

				for (i=0;i<naxis2;i++){

					free(p_mask[i]);
					free(n_mask[i]);
					free(con_dat[i]);
					free(inc_dat[i]);
					free(radius[i]);
				
				}

				free(p_mask);
				free(n_mask);
				free(con_dat);
				free(inc_dat);
				free(radius);

				free(c_pixel_strip);
				free(i_pixel_strip);
				
				fits_close_file(c_ptr,&c_status);
				fits_close_file(i_ptr,&i_status);

			}
	
		}
		printf(" Completed run %d of %d.\n",k+1,num_records);
	}
	
	/* Output the results to a text file. */
	
	/* First, convert t_obs to a more reasonable product. */
	
	for (i=0;i<num_records;i++){			
	
		t_secs[i]=isotime(t_obs_s[i]);

	}

	printf("Writing to file %s.\n",outfile_name);
	
	outptr=fopen(outfile_name,"w");
	bad_outptr=fopen(bad_outfile_name,"w");
	
	fprintf(outptr,"Active Region: %d\n",noaa_ar);
	fprintf(outptr,"Full UT Time            time(s)  num pos  num neg\n");
	fprintf(outptr,"----------------------  -------  -------  -------\n");
	
	fprintf(bad_outptr,"Active Region: AR%d\n",noaa_ar);
	fprintf(bad_outptr,"Full UT Time            quality  time(s)  number\n");
	fprintf(bad_outptr,"----------------------  -------  -------  ------\n");
	
	for (i=0;i<num_records;i++){
		
		/* Make times relative to the first recorded one. */
		
		if (quality[i] == 0){
		
			fprintf(outptr,"%s  %7ld  %6.2lf  %6.2lf\n",t_obs_s[i],t_secs[i]-t_secs[0],p_spots[i],n_spots[i]);
	
		} else {
			
			fprintf(bad_outptr,"%s  0x%08lX  %7ld  %d\n",t_obs_s[i],quality[i],t_secs[i],i+1);
			
		}
	}
	
	fclose(outptr);
	fclose(bad_outptr);
	
	printf("Done!\n");
	
	/* Free memory associated with dynamic arrays. */
    
	free(p_spots);
	free(n_spots);

	free(t_secs);
	free(t_obs_s);
	
	free(quality);
	
	/* Close the drms records connection */
	
	drms_close_records(drms_ids,DRMS_FREE_RECORD);
    
	/* Done! */
    
	return 0;
}
Exemplo n.º 10
0
image_str *image_create_from_fits(char *filename)
{
    fitsfile *fits;
    char buf[FLEN_CARD];
    image_str *image = NULL;

    int status = 0;  /* Error code for CFITSIO library */
    int Ndims = 0;
    int bitpix = 0;
    long Npixels = 0;
    long firstpix[2] = {1, 1};
    long fits_dims[2] = {1, 1};

    if(!filename || !file_exists_and_normal(filename))
        return NULL;

    fits_open_file(&fits, filename, READONLY, &status);

    do {
        /* read dimensions */
        fits_get_img_dim(fits, &Ndims, &status);
        fits_get_img_size(fits, 2, fits_dims, &status);
        fits_get_img_type(fits, &bitpix, &status);

        if(Ndims < 2){
            int Nhdus = 0;
            int hdu = 0;
            int type = 0;

            fits_get_num_hdus(fits, &Nhdus, &status);
            fits_get_hdu_num(fits, &hdu);

            if(hdu < Nhdus){
                /* dprintf("Moving to HDU %d of %d\n", hdu + 1, Nhdus); */
                fits_movabs_hdu(fits, hdu + 1, &type, &status);
            } else {
                /* dprintf("Error: FITS images with less than 2 dimensions are not supported\n"); */
                /* fits_close_file(fits, &status); */
                /* return NULL; */
                break;
            }
        }
    } while(Ndims < 2);

    if(status || Ndims > 2){
        if(Ndims > 2)
            dprintf("Error: FITS images with more than 2 dimensions are not supported\n");
        fits_close_file(fits, &status);

        return image;
    }

    Npixels = fits_dims[0]*fits_dims[1];

    if(bitpix == DOUBLE_IMG || bitpix == FLOAT_IMG){
        double *data = (double *) malloc(Npixels * sizeof(double));

        fits_read_pix(fits, TDOUBLE, firstpix, Npixels, NULL, data, NULL, &status);
        image = image_create_with_data(fits_dims[0], fits_dims[1], (u_int16_t *)data);
        image->type = IMAGE_DOUBLE;
    } else {
        u_int16_t *data = (u_int16_t *) malloc(Npixels * sizeof(u_int16_t));

        fits_read_pix(fits, TUSHORT, firstpix, Npixels, NULL, data, NULL, &status);
        image = image_create_with_data(fits_dims[0], fits_dims[1], data);
    }

    /* Read all keywords we may need */
    image_keywords_from_fits(image, fits);
    /* Rewind the header */
    fits_read_record(fits, 0, buf, &status);

    image->coords = image_keyword_get_coords(image);
    if(image->coords.ra0 == 0 && image->coords.dec0 == 0){
        image->coords.ra0 = 15.0*image_keyword_get_sexagesimal(image, "RA");
        image->coords.dec0 = image_keyword_get_sexagesimal(image, "DEC");
    }
    image->time = time_str_from_date_time(image_keyword_get_string(image, "TIME"));

    fits_close_file(fits, &status);

    return image;
}
Exemplo n.º 11
0
bool usImage::Load(const wxString& fname)
{
    bool bError = false;

    try
    {
        if (!wxFileExists(fname))
        {
            pFrame->Alert(_("File does not exist - cannot load ") + fname);
            throw ERROR_INFO("File does not exist");
        }

        int status = 0;  // CFITSIO status value MUST be initialized to zero!
        fitsfile *fptr;  // FITS file pointer
        if (!PHD_fits_open_diskfile(&fptr, fname, READONLY, &status))
        {
            int hdutype;
            if (fits_get_hdu_type(fptr, &hdutype, &status) || hdutype != IMAGE_HDU)
            {
                pFrame->Alert(_("FITS file is not of an image: ") + fname);
                throw ERROR_INFO("Fits file is not an image");
            }

            // Get HDUs and size
            int naxis = 0;
            fits_get_img_dim(fptr, &naxis, &status);
            long fsize[3];
            fits_get_img_size(fptr, 2, fsize, &status);
            int nhdus = 0;
            fits_get_num_hdus(fptr, &nhdus, &status);
            if ((nhdus != 1) || (naxis != 2)) {
                pFrame->Alert(_("Unsupported type or read error loading FITS file ") + fname);
                throw ERROR_INFO("unsupported type");
            }
            if (Init((int) fsize[0], (int) fsize[1]))
            {
                pFrame->Alert(_("Memory allocation error loading FITS file ") + fname);
                throw ERROR_INFO("Memory Allocation failure");
            }
            long fpixel[3] = { 1, 1, 1 };
            if (fits_read_pix(fptr, TUSHORT, fpixel, (int)(fsize[0] * fsize[1]), NULL, ImageData, NULL, &status)) { // Read image
                pFrame->Alert(_("Error reading data from FITS file ") + fname);
                throw ERROR_INFO("Error reading");
            }

            char *key = const_cast<char *>("EXPOSURE");
            float exposure;
            status = 0;
            fits_read_key(fptr, TFLOAT, key, &exposure, NULL, &status);
            if (status == 0)
                ImgExpDur = (int) (exposure * 1000.0);

            key = const_cast<char *>("STACKCNT");
            int stackcnt;
            status = 0;
            fits_read_key(fptr, TINT, key, &stackcnt, NULL, &status);
            if (status == 0)
                ImgStackCnt = (int) stackcnt;

            PHD_fits_close_file(fptr);
        }
        else
        {
            pFrame->Alert(_("Error opening FITS file ") + fname);
            throw ERROR_INFO("error opening file");
        }
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);
        bError = true;
    }

    return bError;
}
Exemplo n.º 12
0
void print_spectra_info(struct spectra_info *s)
// Output a spectra_info structure in human readable form
{
    char ctmp[40];

    psrdatatype_description(ctmp, s->datatype);
    printf("From the %s file '%s':\n", ctmp, s->filenames[0]);
    if (strcmp(s->telescope, "unset")!=0)
        printf("                  Telescope = %s\n", s->telescope);
    if (strcmp(s->observer, "unset")!=0)
        printf("                   Observer = %s\n", s->observer);
    if (strcmp(s->source, "unset")!=0)
        printf("                Source Name = %s\n", s->source);
    if (strcmp(s->frontend, "unset")!=0)
        printf("                   Frontend = %s\n", s->frontend);
    if (strcmp(s->backend, "unset")!=0)
        printf("                    Backend = %s\n", s->backend);
    if (strcmp(s->project_id, "unset")!=0)
        printf("                 Project ID = %s\n", s->project_id);
    if (strcmp(s->date_obs, "unset")!=0)
        printf("            Obs Date String = %s\n", s->date_obs);
    if (s->datatype==PSRFITS) {
        int itmp;
        double dtmp;
        DATEOBS_to_MJD(s->date_obs, &itmp, &dtmp);
        sprintf(ctmp, "%.14f", dtmp);
        printf("  MJD start time (DATE-OBS) = %5i.%14s\n", itmp, ctmp+2);
        printf("     MJD start time (STT_*) = %19.14Lf\n", s->start_MJD[0]);
    } else {
        printf("             MJD start time = %19.14Lf\n", s->start_MJD[0]);
    }
    printf("                   RA J2000 = %s\n", s->ra_str);
    printf("             RA J2000 (deg) = %-17.15g\n", s->ra2000);
    printf("                  Dec J2000 = %s\n", s->dec_str);
    printf("            Dec J2000 (deg) = %-17.15g\n", s->dec2000);
    printf("                  Tracking? = %s\n", s->tracking ? "True" : "False");
    printf("              Azimuth (deg) = %-.7g\n", s->azimuth);
    printf("           Zenith Ang (deg) = %-.7g\n", s->zenith_ang);
    if (strcmp(s->poln_type, "unset")!=0)
        printf("          Polarization type = %s\n", s->poln_type);
    if (s->num_polns>=2 && !s->summed_polns)
        printf("            Number of polns = %d\n", s->num_polns);
    else if (s->summed_polns)
        printf("            Number of polns = 2 (summed)\n");
    else 
        printf("            Number of polns = 1\n");
    if (strcmp(s->poln_order, "unset")!=0)
        printf("         Polarization order = %s\n", s->poln_order);
    printf("           Sample time (us) = %-17.15g\n", s->dt * 1e6);
    printf("         Central freq (MHz) = %-17.15g\n", s->fctr);
    printf("          Low channel (MHz) = %-17.15g\n", s->lo_freq);
    printf("         High channel (MHz) = %-17.15g\n", s->hi_freq);
    printf("        Channel width (MHz) = %-17.15g\n", s->df);
    printf("         Number of channels = %d\n", s->num_channels);
    if (s->chan_dm != 0.0) {
        printf("   Orig Channel width (MHz) = %-17.15g\n", s->orig_df);
        printf("    Orig Number of channels = %d\n", s->orig_num_chan);
        printf("    DM used for chan dedisp = %-17.15g\n", s->chan_dm);
    }
    printf("      Total Bandwidth (MHz) = %-17.15g\n", s->BW);
    if (s->num_beams > 0)
        printf("                       Beam = %d of %d\n", s->beamnum, s->num_beams);
    printf("            Beam FWHM (deg) = %.3f\n", s->beam_FWHM);
    printf("         Spectra per subint = %d\n", s->spectra_per_subint);
    printf("            Starting subint = %d\n", s->start_subint[0]);
    printf("           Subints per file = %d\n", s->num_subint[0]);
    printf("           Spectra per file = %lld\n", s->num_spec[0]);
    printf("      Time per subint (sec) = %-.12g\n", s->time_per_subint);
    printf("        Time per file (sec) = %-.12g\n", s->num_spec[0]*s->dt);
    printf("            bits per sample = %d\n", s->bits_per_sample);
    printf("          bytes per spectra = %d\n", s->bytes_per_spectra);
    printf("        samples per spectra = %d\n", s->samples_per_spectra);
    printf("           bytes per subint = %d\n", s->bytes_per_subint);
    printf("         samples per subint = %d\n", s->samples_per_subint);
    printf("                zero offset = %-17.15g\n", s->zero_offset);
    printf("           Invert the band? = %s\n", (s->apply_flipband>0) ? "True" : "False");
    if (s->header_offset!=NULL)
        printf("       bytes in file header = %d\n", s->header_offset[0]);
    if (s->datatype==PSRFITS) {
        int ii, numhdus, hdutype, status = 0;
        char comment[120];
        printf("  PSRFITS Specific info:\n");
        fits_get_num_hdus(s->fitsfiles[0], &numhdus, &status);
        printf("                       HDUs = primary, ");
        for (ii = 2 ; ii < numhdus + 1 ; ii++) {
            fits_movabs_hdu(s->fitsfiles[0], ii, &hdutype, &status);
            fits_read_key(s->fitsfiles[0], TSTRING, "EXTNAME", ctmp, comment, &status);
            printf("%s%s", ctmp, (ii < numhdus) ? ", " : "\n");
        }
        printf("              FITS typecode = %d\n", s->FITS_typecode);
        printf("                DATA column = %d\n", s->data_col);
        printf("             Apply scaling? = %s\n", s->apply_scale ? "True" : "False");
        printf("             Apply offsets? = %s\n", s->apply_offset ? "True" : "False");
        printf("             Apply weights? = %s\n", s->apply_weight ? "True" : "False");
    }
}
Exemplo n.º 13
0
str FITSattach(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci)
{
	mvc *m = NULL;
	sql_trans *tr;
	sql_schema *sch;
	sql_table *fits_tp, *fits_fl, *fits_tbl, *fits_col, *tbl = NULL;
	sql_column *col;
	str msg = MAL_SUCCEED;
	str fname = *(str*)getArgReference(stk, pci, 1);
	fitsfile *fptr;  /* pointer to the FITS file */
	int status = 0, i, j, hdutype, hdunum = 1, cnum = 0, bitpixnumber = 0;
	oid fid, tid, cid, rid = oid_nil;
	char tname[BUFSIZ], *tname_low = NULL, *s, bname[BUFSIZ], stmt[BUFSIZ];
	long tbcol;
	char cname[BUFSIZ], tform[BUFSIZ], tunit[BUFSIZ], tnull[BUFSIZ], tdisp[BUFSIZ];
	double tscal, tzero;
	char xtensionname[BUFSIZ] = "", stilversion[BUFSIZ] = "";
	char stilclass[BUFSIZ] = "", tdate[BUFSIZ] = "", orig[BUFSIZ] = "", comm[BUFSIZ] = "";

	msg = getSQLContext(cntxt, mb, &m, NULL);
	if (msg)
		return msg;

	if (fits_open_file(&fptr, fname, READONLY, &status)) {
		msg = createException(MAL, "fits.attach", "Missing FITS file %s.\n", fname);
		return msg;
	}

	tr = m->session->tr;
	sch = mvc_bind_schema(m, "sys");

	fits_fl = mvc_bind_table(m, sch, "fits_files");
	if (fits_fl == NULL)
		FITSinitCatalog(m);

	fits_fl = mvc_bind_table(m, sch, "fits_files");
	fits_tbl = mvc_bind_table(m, sch, "fits_tables");
	fits_col = mvc_bind_table(m, sch, "fits_columns");
	fits_tp = mvc_bind_table(m, sch, "fits_table_properties");

	/* check if the file is already attached */
	col = mvc_bind_column(m, fits_fl, "name");
	rid = table_funcs.column_find_row(m->session->tr, col, fname, NULL);
	if (rid != oid_nil) {
		fits_close_file(fptr, &status);
		msg = createException(SQL, "fits.attach", "File %s already attached\n", fname);
		return msg;
	}

	/* add row in the fits_files catalog table */
	col = mvc_bind_column(m, fits_fl, "id");
	fid = store_funcs.count_col(tr, col, 1) + 1;
	store_funcs.append_col(m->session->tr,
		mvc_bind_column(m, fits_fl, "id"), &fid, TYPE_int);
	store_funcs.append_col(m->session->tr,
		mvc_bind_column(m, fits_fl, "name"), fname, TYPE_str);

	col = mvc_bind_column(m, fits_tbl, "id");
	tid = store_funcs.count_col(tr, col, 1) + 1;

	if ((s = strrchr(fname, DIR_SEP)) == NULL)
		s = fname;
	else
		s++;
	strcpy(bname, s);
	s = strrchr(bname, '.');
	if (s) *s = 0;

	fits_get_num_hdus(fptr, &hdunum, &status);
	for (i = 1; i <= hdunum; i++) {
		fits_movabs_hdu(fptr, i, &hdutype, &status);
		if (hdutype != ASCII_TBL && hdutype != BINARY_TBL)
			continue;

		/* SQL table name - the name of FITS extention */
		fits_read_key(fptr, TSTRING, "EXTNAME", tname, NULL, &status);
		if (status) {
			snprintf(tname, BUFSIZ, "%s_%d", bname, i);
			tname_low = toLower(tname);
			status = 0;
		}else  { /* check table name for existence in the fits catalog */
			tname_low = toLower(tname);
			col = mvc_bind_column(m, fits_tbl, "name");
			rid = table_funcs.column_find_row(m->session->tr, col, tname_low, NULL);
			/* or as regular SQL table */
			tbl = mvc_bind_table(m, sch, tname_low);
			if (rid != oid_nil || tbl) {
				snprintf(tname, BUFSIZ, "%s_%d", bname, i);
				tname_low = toLower(tname);
			}
		}

		fits_read_key(fptr, TSTRING, "BITPIX", &bitpixnumber, NULL, &status);
		if (status) {
			status = 0;
		}
		fits_read_key(fptr, TSTRING, "DATE-HDU", tdate, NULL, &status);
		if (status) {
			status = 0;
		}
		fits_read_key(fptr, TSTRING, "XTENSION", xtensionname, NULL, &status);
		if (status) {
			status = 0;
		}
		fits_read_key(fptr, TSTRING, "STILVERS", stilversion, NULL, &status);
		if (status) {
			status = 0;
		}
		fits_read_key(fptr, TSTRING, "STILCLAS", stilclass, NULL, &status);
		if (status) {
			status = 0;
		}
		fits_read_key(fptr, TSTRING, "ORIGIN", orig, NULL, &status);
		if (status) {
			status = 0;
		}
		fits_read_key(fptr, TSTRING, "COMMENT", comm, NULL, &status);
		if (status) {
			status = 0;
		}

		fits_get_num_cols(fptr, &cnum, &status);

		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tbl, "id"), &tid, TYPE_int);
		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tbl, "name"), tname_low, TYPE_str);
		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tbl, "columns"), &cnum, TYPE_int);
		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tbl, "file_id"), &fid, TYPE_int);
		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tbl, "hdu"), &i, TYPE_int);
		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tbl, "date"), tdate, TYPE_str);
		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tbl, "origin"), orig, TYPE_str);
		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tbl, "comment"), comm, TYPE_str);

		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tp, "table_id"), &tid, TYPE_int);
		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tp, "xtension"), xtensionname, TYPE_str);
		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tp, "bitpix"), &bitpixnumber, TYPE_int);
		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tp, "stilvers"), stilversion, TYPE_str);
		store_funcs.append_col(m->session->tr,
			mvc_bind_column(m, fits_tp, "stilclas"), stilclass, TYPE_str);

		/* read columns description */
		s = stmt;
		col = mvc_bind_column(m, fits_col, "id");
		cid = store_funcs.count_col(tr, col, 1) + 1;
		for (j = 1; j <= cnum; j++, cid++) {
			fits_get_acolparms(fptr, j, cname, &tbcol, tunit, tform, &tscal, &tzero, tnull, tdisp, &status);
			snprintf(stmt, BUFSIZ, FITS_INS_COL, (int)cid, cname, tform, tunit, j, (int)tid);
			msg = SQLstatementIntern(cntxt, &s, "fits.attach", TRUE, FALSE);
			if (msg != MAL_SUCCEED) {
				fits_close_file(fptr, &status);
				return msg;
			}
		}
		tid++;
	}
	fits_close_file(fptr, &status);

	return MAL_SUCCEED;
}
Exemplo n.º 14
0
bool PLANCKIDEFSource::initFile( )
{
  bool bRetVal = true;
  int iResult = 0;

  _numFrames = 0;

  if( !_filename.isNull( ) && !_filename.isEmpty( ) )
  {
    QString   str;
    fitsfile* ffits;
    int       iStatus = 0;

    iResult = fits_open_file( &ffits, _filename.ascii( ), READONLY, &iStatus );
    if( iResult == 0 )
    {
      int iNumHeaderDataUnits;

      if( fits_get_num_hdus( ffits, &iNumHeaderDataUnits, &iStatus ) == 0 )
      {
        long lNumRows;
        int iHDUType;
        int i;

        //
        // determine the number of frames...
        //
        if( iNumHeaderDataUnits > 1 )
        {
          if( fits_movabs_hdu( ffits, 2, &iHDUType, &iStatus ) == 0 )
          {
            if( fits_get_hdu_type( ffits, &iHDUType, &iStatus ) == 0 )
            {
              if( iHDUType == BINARY_TBL )
              {
                iResult = fits_get_num_rows( ffits, &lNumRows, &iStatus );
                if( iResult == 0 )
                {
                  _numFrames = lNumRows;
                }
              }
            }
          }
        }

        if( _numFrames > 0 )
        {
          fits_movabs_hdu( ffits, 1, &iHDUType, &iStatus );

          field *fld = new field;

          fld->table = 0;
          fld->column = 0;

          _fields.insert( "INDEX", fld );
          _fieldList.append( "INDEX" );

          //
          // add the fields and metadata...
          //
          for( i=0; i<iNumHeaderDataUnits-1; i++ )
          {
            if( iStatus == 0 )
            {
              addToMetadata( ffits, iStatus );

              //
              // the first table never contains data...
              //
              if( i > 0 )
              {
                //
                // create the time entries if necessary...
                //
                if( _fields.find( "TIME_ABSOLUTE" ) == 0L &&
                    _fields.find( "TIME_RELATIVE" ) == 0L )
                {
                  char comment[FLEN_COMMENT];
                  int iStatusDelta = 0;
                  int iStatusZero = 0;

                  fits_read_key( ffits, TDOUBLE, "DELTA_T", &_dTimeDelta, comment, &iStatusDelta );
                  fits_read_key( ffits, TDOUBLE, "TIMEZERO", &_dTimeZero, comment, &iStatusZero );

                  if( iStatusDelta == 0 )
                  {
                    if( iStatusZero == 0 )
                    {
                      field *fld = new field;

                      fld->table = 0;
                      fld->column = 0;

                      _fields.insert( "TIME_ABSOLUTE", fld );
                      _fieldList.append( "TIME_ABSOLUTE" );
                    }
                    else
                    {
                      field *fld = new field;

                      fld->table = 0;
                      fld->column = 0;

                      _fields.insert( "TIME_RELATIVE", fld );
                      _fieldList.append( "TIME_RELATIVE" );
                    }
                  }
                }

                //
                // create the field entries...
                //
                fits_get_hdu_type( ffits, &iHDUType, &iStatus );
                if( iStatus == 0 )
                {
                  if( iHDUType == BINARY_TBL || iHDUType == ASCII_TBL )
                  {
                    int iNumCols;

                    iResult = fits_get_num_cols( ffits, &iNumCols, &iStatus );
                    if( iResult == 0 )
                    {
                      iResult = fits_get_num_rows( ffits, &lNumRows, &iStatus );
                      if( iResult == 0 )
                      {
                        addToFieldList( ffits, iNumCols, iStatus );
                      }
                    }
                  }
                }
              }

              fits_movrel_hdu( ffits, 1, &iHDUType, &iStatus);
            }
          }
        }
      }

      iStatus = 0;

      updateNumFramesScalar( );

      fits_close_file( ffits, &iStatus );
    }
  }

  return bRetVal;
}
Exemplo n.º 15
0
int generateMedianPlane (char *cubepath, char *impath, int iplane,
    int nplane_in, int *startplane, int *endplane, char *errmsg)
{
    struct stat     buf;
    struct FitsHdr  hdr;

    char   str[1024];
    char   cmd[1024];
    
    int    bitpix;
    int    istatus;
    
    int    nhdu, hdutype, hdunum;

    
    long    nelements;
    
    int    naxis3;
    int    l;
    int    i;
    int    j;
    int    jj;

    int    nullcnt;
    
    int    splane;
    int    eplane;
    int    nplane;
    
    
    int    indx;
    int    indx1;
    int    indx2;

    int    npixel;
    int    midpoint; 

    long   fpixel[4];
    long   fpixelo[4];

    double *fitscubebuf;
    double *outbuf;
    double *fitsbuf1d;
    double *wavebuf;


    fitsfile  *infptr;
    fitsfile  *outfptr;

    
    int    debugfile = 1;


/*
     Make a NaN value to use setting blank pixels
*/

    union
    {
        double d;
        char   c[8];
    }
    value;

    double nan;

    for(i=0; i<8; ++i)
        value.c[i] = 255;

    nan = value.d;


    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "\nEnter generateMedianPlane: cubepath= [%s]\n", 
            cubepath);
        fprintf (fp_debug, "impath= [%s]\n", impath);
        fprintf (fp_debug, "iplane= [%d]\n", iplane);
        fprintf (fp_debug, "nplane_in= [%d]\n", nplane_in);
        fflush (fp_debug);
    }

    nplane = nplane_in;

    splane = iplane - nplane/2;
    eplane = splane + nplane - 1;

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "splane= [%d] eplane= [%d]\n", splane, eplane);
        fflush (fp_debug);
    }


/*
    Open input fits cube 
*/
    istatus = 0;
    if (fits_open_file (&infptr, cubepath, READONLY, &istatus)) {

        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
            fprintf (fp_debug, "istatus= [%d]\n", istatus);
            fflush (fp_debug);
        }

        sprintf (errmsg, "Failed to open FITS file [%s]\n", cubepath);
        return (-1);
    } 


    hdunum = 1; 
    nhdu = 0;
    istatus = 0;
    istatus = fits_get_num_hdus (infptr, &nhdu, &istatus);
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, 
            "returned fits_get_hdu_num: istatus= [%d] nhdu= [%d]\n",
            istatus, nhdu);
        fflush (fp_debug);
    }

    if (hdunum > nhdu) {

        sprintf (errmsg, "fname [%s] doesn't contain any HDU", cubepath);
        return (-1);
    }


/*
    Read fits keywords from the first HDU
*/
    hdutype = 0;
    istatus = 0;
    istatus = fits_movabs_hdu (infptr, hdunum, &hdutype, &istatus);

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, 
            "returned fits_movabs_hdu: istatus= [%d] hdutype= [%d]\n",
            istatus, hdutype);
        fflush (fp_debug);
    }

/*
    Read fits keywords
*/
    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "simple", str, (char *)NULL, 
        &istatus);
    
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword SIMPLE not found in fits header");
        return (-1);
    }
   
    if ((strcmp (str, "T") != 0) && (strcmp (str, "F") != 0)) {
        sprintf (errmsg, "keyword SIMPLE must be T or F");
        return (-1);
    }

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "bitpix", str, (char *)NULL, 
        &istatus);
    
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword BITPIX not found in fits header");
        return (-1);
    }
  
    istatus = str2Integer (str, &bitpix, errmsg);
    if (istatus != 0) {
        sprintf (errmsg, "keyword BITPIX must be an integer");
        return (-1);
    }

    if ((bitpix != 8) &&
        (bitpix != 16) &&
        (bitpix != 32) &&
        (bitpix != 64) &&
        (bitpix != -32) &&
        (bitpix != -64)) {
        
        sprintf (errmsg, 
            "keyword BITPIX value must be 8, 16, 32, 64, -32, -64");
        return (-1);
    }

    hdr.bitpix = bitpix;

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis", str, (char *)NULL, 
        &istatus);
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis not found in fits header");
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }
    istatus = str2Integer (str, &hdr.naxis, errmsg);
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis to integer");
        return (-1);
    }
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "naxis= [%d]\n", hdr.naxis);
        fflush (fp_debug);
    }


    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis1", str, (char *)NULL, 
        &istatus);
        
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", istatus);
        fflush (fp_debug);
    }
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis1 not found in fits header");
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }

    istatus = str2Integer (str, &hdr.ns, errmsg);
    
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis1 string to integer");
        return (-1);
    }
    hdr.naxes[0] = hdr.ns;

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis2", str, 
        (char *)NULL, &istatus);
        
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", istatus);
        fflush (fp_debug);
    }
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis2 not found in fits header");
        return (-1);
    }
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }

    istatus = str2Integer (str, &hdr.nl, errmsg);
    
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis2 string to integer");
        return (-1);
    }
    hdr.naxes[1] = hdr.nl;

    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "ns= [%d] nl= [%d]\n", hdr.ns, hdr.nl);
        fflush (fp_debug);
    }

    hdr.nplane = 1;

    if (hdr.naxis > 2) {
    
        istatus = 0;
        istatus = fits_read_key (infptr, TSTRING, "naxis3", str, 
            (char *)NULL, &istatus);
        
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
            fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", 
                istatus);
            fflush (fp_debug);
        }
        
        if (istatus == KEY_NO_EXIST) {
            sprintf (errmsg, "keyword naxis3 not found in fits header");
            return (-1);
        }
    
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
            fprintf (fp_debug, "str= [%s]\n", str);
            fflush (fp_debug);
        }

        istatus = str2Integer (str, &hdr.naxes[2], errmsg);
    
        if (istatus < 0) {
            sprintf (errmsg, "Failed to convert naxis3 string to integer");
            return (-1);
        }
        hdr.nplane = hdr.naxes[2];
    
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
            fprintf (fp_debug, "naxes[2]= [%d]\n", hdr.naxes[2]);
            fflush (fp_debug);
        }
    }
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "hdr.nplane= [%d]\n", hdr.nplane);
        fflush (fp_debug);
    }


    if (splane < 1)
        splane = 1;
    
    if (eplane > hdr.nplane)
        eplane = hdr.nplane;

    nplane = eplane - splane + 1;

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        
        fprintf (fp_debug, "hdr.nplane= [%d]\n", hdr.nplane);
        fprintf (fp_debug, "splane= [%d] eplane= [%d]\n", splane, eplane);
        fprintf (fp_debug, "nplane= [%d]\n", nplane);
        fflush (fp_debug);
    }


/*
    malloc arrays for reading data
*/
    fitscubebuf  
    = (double *)malloc(hdr.ns*hdr.nl*nplane*sizeof(double));
    
    outbuf  = (double *)malloc(hdr.ns*hdr.nl*sizeof(double));
    
    wavebuf  = (double *)malloc(nplane*sizeof(double));
    
    fitsbuf1d  = (double *)malloc(hdr.ns*sizeof(double));

    nelements = hdr.ns;

    npixel = hdr.ns*hdr.nl;
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "npixel= [%d]\n", npixel);
        fflush (fp_debug);
    }


/*
    Read cube data to fitscubebuf
*/
    fpixel[0] = 1;
    fpixel[3] = 1;
    
    indx = 0;
    for (l=splane; l<=eplane; l++)
    {
       
        indx2 = hdr.nl*hdr.ns*(l-splane); 

        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
            fprintf (fp_debug, "l= [%d]\n", l);
            fflush (fp_debug);
        }


        fpixel[1] = 1;
        fpixel[2] = l;
        
        for (j=0; j<hdr.nl; j++)
        {
            indx1 = hdr.ns*j; 

            if (fits_read_pix (infptr, TDOUBLE, fpixel, nelements, &nan,
                fitsbuf1d, &nullcnt, &istatus)) {
                break;
            }

            for (i=0; i<nelements; i++) {
                
                fitscubebuf[indx2+indx1+i] = fitsbuf1d[i];
                
                if ((debugfile) && (fp_debug != (FILE *)NULL)) {
                    
                    if ((i == 30) && (j == 25)) {
                        fprintf (fp_debug, "i=[%d] j=[%d] l=[%d] pixel=[%lf]\n",
                            i, j, l, fitscubebuf[indx2+indx1+i]);
                        fflush (fp_debug);
                    }
                }


            }

            fpixel[1]++;
        }
   }

/*
    istatus = 0;
    if (fits_close_file (infptr, &istatus)) {
        sprintf (errmsg, "Failed to close cubepath [%s]\n", cubepath);
        return (-1); 
    }
*/


/*
    Extract wave axis and compute median values
*/
    midpoint = nplane / 2;
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "midpint= [%d]\n", midpoint);
        fflush (fp_debug);
    }

    for (j=0; j<hdr.nl; j++) {
        
        indx1 = hdr.ns*j;

        for (i=0; i<hdr.ns; i++) {
        
            for (l=0; l<nplane; l++) {
                
                indx = npixel*l + indx1 + i;

                wavebuf[l] = fitscubebuf[indx];
                    
                if ((debugfile) && (fp_debug != (FILE *)NULL)) {
                    
                    if ((i == 30) && (j == 25)) {
                        fprintf (fp_debug, "i=[%d] j=[%d] l=[%d] pixel=[%lf]\n",
                            i, j, l, wavebuf[l]);
                        fflush (fp_debug);
                    }
                }
            }

            sort (wavebuf, nplane);
                
            if ((debugfile) && (fp_debug != (FILE *)NULL)) {
                    
                
                if ((i == 30) && (j == 25)) {
                    
                    fprintf (fp_debug, "after qsort\n");
                    for (l=0; l<nplane; l++) {
                        fprintf (fp_debug, "l=[%d] pixel=[%lf]\n", 
                            l, wavebuf[l]);
                    }
                    fflush (fp_debug);
                }
            }

            outbuf[indx1+i] = wavebuf[midpoint];
            
            if ((debugfile) && (fp_debug != (FILE *)NULL)) {
                if ((i == 30) && (j == 25)) {
                    fprintf (fp_debug, "outbuf= [%lf]\n", outbuf[indx1+i]);
                    fflush (fp_debug);
                }
            }

        }
    }



/*
    Create output fits file
*/
    istatus = stat (impath, &buf);
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "impath exists? : istatus= [%d]\n", istatus);
        fflush (fp_debug); 
    }

    if (istatus >= 0) {
        sprintf (cmd, "unlink %s", impath);
        istatus = system (cmd);
    }        


    istatus = 0;
    if (fits_create_file (&outfptr, impath, &istatus)) {
            
        sprintf (errmsg, "Failed to create output fitsfile [%s]\n", 
            impath);
        
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
            fprintf (fp_debug, "err: [%s]\n", errmsg);
            fflush (fp_debug);
        }
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "outptr created\n");
        fflush (fp_debug);
    }


/* 
    Copy input fits header to output fitsfile
*/
    istatus = 0;
    if (fits_copy_header (infptr, outfptr, &istatus)) {

        strcpy (errmsg, "Failed to copy fitshdr\n");
        
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {
            fprintf (fp_debug, "err: [%s]\n", errmsg);
            fflush (fp_debug);
        }
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "header copied\n");
        fflush (fp_debug);
    }



/*
    Update header keyword NAXIS3
*/
    naxis3 = 1;
    istatus = 0;
    if (fits_update_key_lng(outfptr, "NAXIS3", naxis3, (char *)NULL, 
        &istatus)) {
        
        strcpy (errmsg, "Failed to update keyword NAXIS3\n");
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "naxis3 updated\n");
        fflush (fp_debug);
    }


/*
    Write to output fitsfile
*/
    nelements = hdr.ns;
    fpixelo[0] = 1;
    fpixelo[1] = 1;
    fpixelo[2] = 1;
    fpixelo[3] = 1;
       
    for (j=0; j<hdr.nl; j++) {
    
        jj = hdr.ns*j;
        for (i=0; i<hdr.ns; i++) {
                
            fitsbuf1d[i] = outbuf[jj+i];
        }

        if (fits_write_pix (outfptr, TDOUBLE, fpixelo, nelements,
             (void *)fitsbuf1d, &istatus)) {

            sprintf (errmsg, "fits write error: l= [%d] j= [%d]\n", l, j);
            return (-1);
        }

        fpixelo[1]++;
    }

        
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "here2\n");
        fflush (fp_debug);
    }


    istatus = 0;
    if (fits_close_file (infptr, &istatus)) {
        sprintf (errmsg, "Failed to close cubepath [%s]\n", cubepath);
        return (-1); 
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "here3\n");
        fflush (fp_debug);
    }


    istatus = 0;
    if (fits_close_file (outfptr, &istatus)) {
        sprintf (errmsg, "Failed to close impath [%s]\n", impath);
        return (-1); 
    }

    *startplane = splane;
    *endplane = eplane;


    return (0);
}
Exemplo n.º 16
0
std::string read_image(std::string pathname, float *&array, int &naxis, long *&naxes) {
  TRACE_ENTER();
  // open FITS image file in READONLY mode
  fitsfile *fptr;
  int status = 0;
  fits_open_image(&fptr, pathname.c_str(), READONLY, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // read number of HDUs in the file
  int nhdus = 0;
  fits_get_num_hdus(fptr, &nhdus, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // we expect only one HDU in the file
  if (nhdus != 1) {
    std::ostringstream exit_oss;
    exit_oss << "nhdus is " << nhdus << ", not 1";
    TRACE_ERROR(exit_oss.str());
    return exit_oss.str();
  }
  // read the type of the HDU
  int hdutype = 0;
  fits_movabs_hdu(fptr, nhdus, &hdutype, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // we expect the HDU to be an image
  if (hdutype != IMAGE_HDU) {
    std::ostringstream exit_oss;
    exit_oss << "hdutype is " << hdutype << ", not IMAGE_HDU";
    TRACE_ERROR(exit_oss.str());
    return exit_oss.str();
  }
  // read the type of data in the HDU
  int bitpix = 0;
  fits_get_img_type (fptr, &bitpix, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // we expect the data to be floats
  if (bitpix != FLOAT_IMG) {
    std::ostringstream exit_oss;
    exit_oss << "bitpix is " << bitpix << ", not FLOAT_IMG";
    TRACE_ERROR(exit_oss.str());
    return exit_oss.str();
  }
  // get the number of dimensions in the image
  naxis = 0;
  fits_get_img_dim (fptr, &naxis, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // we expect 2 or 3 dimensions in the image
  if ((naxis < 2) || (naxis > 3)) {
    std::ostringstream exit_oss;
    exit_oss << "naxis is " << naxis << ", neither 2 nor 3";
    TRACE_ERROR(exit_oss.str());
    return exit_oss.str();
  }
  // get the size of each dimension in the image
  naxes = new long[naxis];
  int maxdim = naxis;
  fits_get_img_size(fptr, maxdim, naxes, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // fits_read_subset
  long *fpixel = new long[naxis];
  for (int i = 0; i < naxis; i++) {
    fpixel[i] = 1;
  }
  long *lpixel = new long[naxis];
  for (int i = 0; i < naxis; i++) {
    lpixel[i] = naxes[i];
  }
  long *inc = new long[naxis];
  for (int i = 0; i < naxis; i++) {
    inc[i] = 1;
  }
  float nulval = 0;
  long nelements = 1;
  for (int i = 0; i < naxis; i++) {
    nelements = nelements * naxes[i];
  }
  array = new float[nelements];
  int anynul = 0;
  fits_read_subset(fptr, TFLOAT, fpixel, lpixel, inc, &nulval, array, &anynul, &status);
  delete [] inc;
  delete [] lpixel;
  delete [] fpixel;
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // close the FITS image file
  fits_close_file(fptr, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  return "READ_OK";
}
Exemplo n.º 17
0
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);
}
Exemplo n.º 18
0
bool Camera_INDIClass::ReadFITS(usImage& img, bool takeSubframe, const wxRect& subframe)
{
    int xsize, ysize;
    fitsfile *fptr;  // FITS file pointer
    int status = 0;  // CFITSIO status value MUST be initialized to zero!
    int hdutype, naxis;
    int nhdus=0;
    long fits_size[2];
    long fpixel[3] = {1,1,1};
    size_t bsize = static_cast<size_t>(cam_bp->bloblen);

    // load blob to CFITSIO
    if (fits_open_memfile(&fptr,
                          "",
                          READONLY,
                          &(cam_bp->blob),
                          &bsize,
                          0,
                          NULL,
                          &status) )
    {
        pFrame->Alert(_("Unsupported type or read error loading FITS file"));
        return true;
    }
    if (fits_get_hdu_type(fptr, &hdutype, &status) || hdutype != IMAGE_HDU) {
        pFrame->Alert(_("FITS file is not of an image"));
        PHD_fits_close_file(fptr);
        return true;
    }

    // Get HDUs and size
    fits_get_img_dim(fptr, &naxis, &status);
    fits_get_img_size(fptr, 2, fits_size, &status);
    xsize = (int) fits_size[0];
    ysize = (int) fits_size[1];
    fits_get_num_hdus(fptr,&nhdus,&status);
    if ((nhdus != 1) || (naxis != 2)) {
        pFrame->Alert(_("Unsupported type or read error loading FITS file"));
        PHD_fits_close_file(fptr);
        return true;
    }
    if (takeSubframe) {
        if (img.Init(FullSize)) {
            pFrame->Alert(_("Memory allocation error"));
            PHD_fits_close_file(fptr);
            return true;
        }
        img.Clear();
        img.Subframe = subframe;
        unsigned short *rawdata = new unsigned short[xsize*ysize];
        if (fits_read_pix(fptr, TUSHORT, fpixel, xsize*ysize, NULL, rawdata, NULL, &status) ) {
            pFrame->Alert(_("Error reading data"));
            PHD_fits_close_file(fptr);
            return true;
        }
        int i = 0;
        for (int y = 0; y < subframe.height; y++)
        {
            unsigned short *dataptr = img.ImageData + (y + subframe.y) * img.Size.GetWidth() + subframe.x;
            memcpy(dataptr, &rawdata[i], subframe.width * sizeof(unsigned short));
            i += subframe.width;
        }
        delete[] rawdata;
    }
    else {
        if (img.Init(xsize,ysize)) {
            pFrame->Alert(_("Memory allocation error"));
            PHD_fits_close_file(fptr);
            return true;
        }
        // Read image
        if (fits_read_pix(fptr, TUSHORT, fpixel, xsize*ysize, NULL, img.ImageData, NULL, &status) ) {
            pFrame->Alert(_("Error reading data"));
            PHD_fits_close_file(fptr);
            return true;
        }
    }

    PHD_fits_close_file(fptr);
    return false;
}
Exemplo n.º 19
0
int read_kpvt(
      char *input_file_name,
      char *aux_file,
      int verbose_flag,
      int minmax_flag)
{

   int status = 0;

   /*
    * If the Compiler macro FITS is not defined, that means the makefile
    * determined that libcfitsio.a was not available.  Instead of shutting down
    * the entire converter Lets just disable any read routines thatt depend on
    * the FITS library
    *
    */

#ifdef FITS

   extern int linear_minmax_search(float *, int, float *, float *);

   fitsfile *fits_filePtr;
   char header_buffer[FLEN_CARD ];

   float operand1;

   int i, j;
   int number_of_fits_header_keys;
   int number_of_fits_hdus;
   int hdu_type;
   int bit_pix;
   long naxes[10];
   int maxdim = 10;
   long fpixel[10];
   float missing_val = 256*256*256;
   int anynul;
   float net_flux_2d_static[180][360];
   float net_flux_2d_static_flat[64800];
   float total_flux_2d_static[180][360];
   float total_flux_2d_static_flat[64800];
   float weights_2d_static[180][360];
   float weights_2d_static_flat[64800];

   /** open fits file **/

   fits_open_file( &fits_filePtr, input_file_name, READONLY, &status);

   /** get number_of_fits_header_keys **/

   fits_get_hdrspace(fits_filePtr, &number_of_fits_header_keys, NULL, &status);

   /** get the number of hdu's in the current file **/

   fits_get_num_hdus(fits_filePtr, &number_of_fits_hdus, &status);

   printf("FITS File: %s has %d hdu's\n", input_file_name, number_of_fits_hdus);

   /** for every hdu **/

   for (i=0; i<number_of_fits_hdus; i++)
   {
      /** select hdu by number **/

      fits_movabs_hdu(fits_filePtr, number_of_fits_hdus, &hdu_type, &status);

      /** there are three type of hdu's
       * IMAGE_HDU
       * ACSII_TBL
       * BINARY_TBL
       * ********************************/

      if (hdu_type == IMAGE_HDU)
      {
         printf("Current HDU Type is IMAGE\n");

         /*** get general info about the current image file ***/

         fits_get_img_param(
               fits_filePtr,
               maxdim,
               &bit_pix,
               &naxis,
               naxes,
               &status);

         printf("bitpix = %d\nnaxis = %d\n", bit_pix, naxis);

         if (DEBUG_FLAG)
         {
            for (i = 0; i<naxis; i++)
               printf("naxis[%d] = %ld\n", i, naxes[i]);
         }

         naxis1 = naxes[0];
         naxis2 = naxes[1];

         number_of_elements = naxis1 * naxis2;

         /** dynamically allocate space for the image grid **/

         carrington_longitiude = malloc(naxis1 * sizeof(float));
         carrington_sine_latitude = malloc(naxis2 * sizeof(float));

         /** dynamically allocate space for the flat variable arrays **/

         net_flux = malloc(number_of_elements * sizeof(float));
         total_flux = malloc(number_of_elements * sizeof(float));
         weights = malloc(number_of_elements * sizeof(float));

         /** manually insert sequential grid values from 1 - naxes[*] **/

         operand1 = 2.0 / naxis2;
         if (DEBUG_FLAG)
         {
            printf(
                  "\n\n\n\n\n\nWTF: operand1 = %f\nnaxis2 = %d\n",
                  operand1,
                  naxis2);
         }

         for (i=0; i < naxis2; i++)
         {

            /** convert to sine latidude **/
            /*
             carrington_sine_latitude[i] = i+1;
             */
            carrington_sine_latitude[i] = (-1.0)
                  + (operand1 * ( (i + 1 ) - .5 ) );

            if (DEBUG_FLAG)
               printf("%d deg = %f\n", i+1, carrington_sine_latitude[i]);

         }

         for (i=0; i < naxis1; i++)
         {
            carrington_longitiude[i] = i+1;

            if (DEBUG_FLAG)
               printf("%d deg = %f deg\n", i+1, carrington_longitiude[i]);
         }

         /** print position values **/

         for (i=0; i<naxis2; i+=30)
         {
            for (j=0; j<naxis1; j+=30)
            {
               if (DEBUG_FLAG)
               {
                  printf(
                        "position[%f][%f]\n",
                        carrington_sine_latitude[i],
                        carrington_longitiude[j]);
               }
            }
         }

         /** print c_lon values **/

         for (i=0; i<naxis1; i++)
         {

            if( DEBUG_FLAG ) printf("c_lon[%d] = %f  ", i, carrington_longitiude[i]);

         }

         /** print c_sine_lat values **/

         for (i=0; i<naxis2; i++)
         {

            if( DEBUG_FLAG ) printf("c_sine_lat[%d] = %f  ", i, carrington_sine_latitude[i]);

         }

         /** dynamically allocate memory for the three image slices that we
          * expect - we must reverse the majority since the fits api expects
          * array[column][row] **/

         net_flux_2d = malloc(naxis1 * sizeof(float *));
         for (i=0; i< naxis1; i++)
         {
            net_flux_2d[i] = malloc(naxis2 * sizeof(float));
         }

         total_flux_2d = malloc(naxis2 * sizeof(float *));
         for (i=0; i< naxis2; i++)
         {
            total_flux_2d[i] = malloc(naxis1 * sizeof(float));
         }

         weights_2d = malloc(naxis2 * sizeof(float *));
         for (i=0; i< naxis2; i++)
         {
            weights_2d[i] = malloc(naxis1 * sizeof(float));
         }

         /*** read in the image data ***/

         /** this is the starting point for the read - slice one - net flux **/

         fpixel[0] = fpixel[1] = fpixel[2]= 1;
         if( DEBUG_FLAG ) printf(
               "\nfpixel[0] = %ld\nfpixel[1] = %ld\nfpixel[2] = %ld\nnumber_of_elements = %ld\n\n",
               fpixel[0],
               fpixel[1],
               fpixel[2],
               number_of_elements);
         /*
          fits_read_pix( fits_filePtr, TFLOAT, fpixel, number_of_elements,
          &missing_val, *net_flux_2d, &anynul, &status );
          */
         fits_read_pix(
               fits_filePtr,
               TFLOAT,
               fpixel,
               number_of_elements,
               &missing_val,
               net_flux_2d_static,
               &anynul,
               &status);

         /** this is the starting point for the read - slice two - total flux */

         fpixel[2] = 2;
         if( DEBUG_FLAG )  printf(
               "fpixel[0] = %ld\nfpixel[1] = %ld\nfpixel[2] = %ld\nnumber_of_elements = %ld\n\n",
               fpixel[0],
               fpixel[1],
               fpixel[2],
               number_of_elements);
         /*
          * fits_read_pix( fits_filePtr, TFLOAT, fpixel, number_of_elements,
          * &missing_val, *total_flux_2d, &anynul, &status );
          *
          */

         fits_read_pix(
               fits_filePtr,
               TFLOAT,
               fpixel,
               number_of_elements,
               &missing_val,
               total_flux_2d_static,
               &anynul,
               &status);

         /** this is the starting point for the read - slice three - weights **/

         fpixel[2] = 3;
         if( DEBUG_FLAG )printf(
               "fpixel[0] = %ld\nfpixel[1] = %ld\nfpixel[2] = %ld\nnumber_of_elements = %ld\n\n",
               fpixel[0],
               fpixel[1],
               fpixel[2],
               number_of_elements);
         /*
          * fits_read_pix( fits_filePtr, TFLOAT, fpixel, number_of_elements,
          * &missing_val, *weights_2d, &anynul, &status );
          *
          */

         fits_read_pix(
               fits_filePtr,
               TFLOAT,
               fpixel,
               number_of_elements,
               &missing_val,
               weights_2d_static,
               &anynul,
               &status);

         /** flatten out arrays **/

         for (i=0; i<naxis2; i++)
         {
            for (j=0; j<naxis1; j++)
            {
               /*
                net_flux[ i * naxis1 + j] = net_flux_2d_static[i][j];
                total_flux[ i * naxis1 + j] = total_flux_2d[i][j];
                weights[ i * naxis1 + j] = weights_2d[i][j];
                */
               net_flux[ i * naxis1 + j] = net_flux_2d_static[i][j];
               total_flux[ i * naxis1 + j] = total_flux_2d_static[i][j];
               weights[ i * naxis1 + j] = weights_2d_static[i][j];

            }
         }

         /*** DEBUG PRINT OUT OF VALUES ***/

         /*
          for( i=0;i<naxis2;i+=20)
          {
          for( j=0;j<naxis1;j+=20)
          {

          printf( "net_flux[%d][%d] = %f\n", i,j, net_flux[i * naxis1 + j] );
          printf( "net_flux_2d[%d][%d] = %f\n", i,j, net_flux_2d[i][j] );
          printf( "net_flux_2d_static[%d][%d] = %f\n", i,j, net_flux_2d_static[i][j] );
          printf( "net_flux_2d_static_flat[%d][%d] = %f\n", i,j, net_flux_2d_static_flat[i * naxis1 + j] );
          printf( "total_flux[%d][%d] = %f\n", i,j, total_flux[i * naxis1 + j] );
          printf( "total_flux_2d[%d][%d] = %f\n", i,j, total_flux_2d[i][j] );
          printf( "weights[%d][%d] = %f\n", i,j, weights[i * naxis1 + j] );
          printf( "weights_2d[%d][%d] = %f\n\n", i,j, weights_2d[i][j] );


          }
          }
          */

      }
      else if (hdu_type == ASCII_TBL)
      {
         printf("Current HDU Type is ACSII TABLE\n");
      }
      else if (hdu_type == BINARY_TBL)
      {
         printf("Current HDU Type is BINARY TABLE\n");
      }

      /*** get the header info for the current hdu ***/

      for (i = 0; i < number_of_fits_header_keys; i++)
      {
         fits_read_record(fits_filePtr, i, header_buffer, &status);
         printf("%s\n", header_buffer);
      }

   }

   /** close fits file **/

   fits_close_file(fits_filePtr, &status);

   if (status)
   {
      fits_report_error( stderr, status);
   }

   /*
    * calcluate actual min/max values for each ariable unless -nominmax flag was
    * specified
    *
    */

   /** add more error handling for each linear_minmax_search function call **/

   /*** if -nominmax option was NOT specified ***/

   if ( !minmax_flag)
   {

      if (verbose_flag)
      {
         printf("\ncalculating actual minimum & maximum values for each variable ...\n");
      }

      if (verbose_flag)
      {
         printf("%-25s%-25s%-25s\n", "", "min", "max");
      }

      linear_minmax_search(
            carrington_longitiude,
            naxis1,
            &carrington_longitiude_actual_min,
            &carrington_longitiude_actual_max);
      if (verbose_flag)
      {
         printf(
               "%-25s%-25g%-25g\n",
               "c_lon",
               carrington_longitiude_actual_min,
               carrington_longitiude_actual_max);
      }

      linear_minmax_search(
            carrington_sine_latitude,
            naxis2,
            &carrington_sine_latitude_actual_min,
            &carrington_sine_latitude_actual_max);
      if (verbose_flag)
      {
         printf(
               "%-25s%-25g%-25g\n",
               "c_sine_lat",
               carrington_sine_latitude_actual_min,
               carrington_sine_latitude_actual_max);
      }

      linear_minmax_search(
            net_flux,
            number_of_elements,
            &net_flux_actual_min,
            &net_flux_actual_max);
      if (verbose_flag)
      {
         printf(
               "%-25s%-25g%-25g\n",
               "net_flux",
               net_flux_actual_min,
               net_flux_actual_max);
      }

      linear_minmax_search(
            total_flux,
            number_of_elements,
            &total_flux_actual_min,
            &total_flux_actual_max);
      if (verbose_flag)
      {
         printf(
               "%-25s%-25g%-25g\n",
               "total_flux",
               total_flux_actual_min,
               total_flux_actual_max);
      }

      linear_minmax_search(
            weights,
            number_of_elements,
            &weights_actual_min,
            &weights_actual_max);
      if (verbose_flag)
      {
         printf(
               "%-25s%-25g%-25g\n",
               "weights",
               weights_actual_min,
               weights_actual_max);
      }

   }

#endif

#ifndef FITS
   printf("\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
   printf("!! WARNING: from %s line [%d]. Conversion Software was not compiled and linked with netCDF libraries ( libcfitsio.a ).  No .fts FITS files will be ingested... \n", __FILE__, __LINE__ );
   return EXIT_FAILURE;
#endif

   return status;

}
int get_num_of_hdus(fitsfile * fptr)
{
    int result = 0;
    fits_get_num_hdus(fptr, &result, &fitsio_status);
    return result;
}
Exemplo n.º 21
0
int DoIt(){
 
    /* Variable declarations */

    /* Generic use variables */

    int i,j,k,l,n;								/* Generic loop counters */

    /* DRMS/JSOC variables */

	char *harpnum,*time_range;					/* SHARPs ID and time range from module_args[] */
	double umb_sig, pen_sig;					/* Cutoffs for sunspots */
	int num_divs;								/* Number of divisions to break a data strip into for trend removal */
	char *drms_query;							/* The DRMS query we are going to send */
	int num_query_chars;						/* Number of characters in total query for malloc definition */
	CmdParams_t *params=&cmdparams;				/* For the module_args stuff */
	DRMS_RecordSet_t *drms_ids;					/* Holds the id structure of the records */
	DRMS_Record_t *drms_record;					/* Holds specific record information */
	DRMS_Segment_t *drms_segment;				/* Segment information */
	int drms_status;							/* Status variable */
	int num_records;							/* Number of records and variables to get the segment locations we need */
	
	/* cfitsio-related variables */

    fitsfile *v_ptr,*i_ptr,*c_ptr;		/* Pointers for FITS files */
    fitsfile *info_ptr;		
    int v_status,i_status,c_status;		/* Status checker for opening files */
    int info_status;					
    int hdu_pos,num_hdus;				/* HDU number and location */
    int needed_hdu;						/* The HDU we want to be on */
    int any_nulls;						/* Nonzero if there are null values in data */
    char i_filename[DRMS_MAXPATHLEN+1],v_filename[DRMS_MAXPATHLEN+1];		/* Containers for the filenames */
	char c_filename[DRMS_MAXPATHLEN+1],info_filename[DRMS_MAXPATHLEN+1];
	double nulval;							/* Container for what null values in data should be set to */
	long l_nulval;

    /* Needed FITS keywords */

    int naxis1,naxis2,naxis;			/* Length of axes */
    double crpix1,crpix2;				/* SHARPs CRPIX is the center of the Sun relative to the lower left of the patch (fortranL 1,1) */
    double imcrpix1,imcrpix2;			/* SHARPs IMCRPIX is the center of the Sun in full plate coordinates (fortran) */
    double cdelt1,cdelt2;				/* HMI pixel sizes in as */    double blank;						/* Values of bad data */
    double crota2,crln_obs,crlt_obs;	/* Rotation, carrington observer location */
    double dsun_obs,rsun_obs;			/* Distance to and radius of the sun, observed at t_obs */
    double obs_vr,obs_vw,obs_vn;		/* Satellite velocity keywords */
    TIME t_obs;							/* Observation time, ZULU */
    char **t_obs_s;						/* String version of observation time */
    long *quality;						/* Data quality keyword */
    
    /* Data-related variables */
    
    double **vlos_dat, **inc_dat;			/* Data arrays, size defined once naxis1/2 are known */
    double **con_dat;
    long **info_dat;
    double *v_pixel_strip;					/* Strip of pixels read from the field data */
    double *i_pixel_strip;					/* Strip of pixels read from the inclination data */
    double *c_pixel_strip;					/* Strip of pixels read from the continuum data */
    long *info_pixel_strip;					/* Strip of pixels read from the continuum data */
    long fpixel[2];							/* Holds the location of pixel to be read */
    LONGLONG nelements;						/* Number of elements in a strip to be read (naxis2) */
    FILE *outptr,*bad_outptr;				/* Pointer to the outfile */
    char outfile_name[25];					/* Name of the outfile */
    char bad_outfile_name[24];				/* Name of the outfile for bad quality*/
    
    /* Variables related to the actual task */
    
    double rscx,rscy;				/* Disk center, plate coordinates */
    double rllx,rlly;				/* Disk center, patch coordinates */
    double rpllx,rplly;				/* Lower left of patch, plate coordinates */
    double **radius;				/* Array to hold where the Sun's boundaries are, column major order */
	double umb,pen;					/* Intensity cutoffs for the umbra and penumbra */
    double num_good;				/* The number of nonzero continuum values in a sunspot region */
    double mu;						/* Angle from solar center */
    double rsun_pix,xx,yy,r;		/* Variables associated with radial boundaries */
    long *t_secs;					/* T_OBS time converted to seconds since UNIX epoch */
    double *umb_p_vel,*umb_n_vel;	/* Umbral LOS velocities */
    double *pen_p_vel,*pen_n_vel;	/* Penumbral LOS velocities */
    double umb_p_counter,umb_n_counter;	/* Counters for averages */
    double pen_p_counter,pen_n_counter;
    double vr,vn,vw,vt;				/* Various LOS velocities due to satellite motion and solar rotation */
    double vlos;					/* VLOS after removing all of the satellite motion and solar rotation */
    double **y_axis;				/* Array to be looped over wrt naxis2 to remove trends */
    double **y_error;				/* Error on y axis, taken as 1 */
    double **x_axis;				/* Array to be looped over that holds naxis1 information for fitting */
    double x,y;						/* Pixel location on the solar disk */
    double ttx,tty,tx,ty,zz;		/* Intermediate variables for coordinate conversions */
    double lat,lon;					/* Carrington coordinate latitude and longitude */
    double p,t;						/* Spherical phi and theta coordinates */
	int noaa_ar;					/* Active region number */
	mp_result result;				/* Fitting result structure */
	mp_config config;				/* Configuration options for fitting structure */
	double perror[2];				/* Error on fitting coefficients */
	double fit_params[2];			/* Fitting coefficients */
	struct vars_struct v;			/* Private data, shared between main and functions */
	int fit_status;					/* Fitting returned status */
	int inv_len;					/* Interval length for breaking data up */
	
       
    /* Initialise variables that need it */

    drms_status=0;
    
	memset(&result,0,sizeof(result));
	memset(&config,0,sizeof(config));
	
	/* Set the error stuff for cmfit */
	
	result.xerror=perror;
	
	/* Set the default options for cmfit */
	
	config.ftol=1.49012e-08;
	config.xtol=1.49012e-08;
	config.gtol=0.0;
	config.maxfev=0;
    
	/* Grab values from module_args[] */

	harpnum=strdup(params_get_str(params,"harpnum"));
	time_range=strdup(params_get_str(params,"time_range"));
	umb_sig=params_get_double(params,"umb_sig");
	pen_sig=params_get_double(params,"pen_sig");
	num_divs=params_get_int(params,"num_divs");
	
	/* Now we start the main program. The rough layout is as follows: 
	   
	   1. Query drms. Based on what we learn, either exit or grab what we need from it.
	   2. Loop through the files, calculate field stuff.
	   3. Print out a table of values at the end.				   */
	
	/* Forge the DRMS query. */
	
	num_query_chars=16+strlen(harpnum);		/* hmi.sharp_720s[] is 16 characters */
	
	if (time_range!="[]"){
		
		num_query_chars+=strlen(time_range);
		
	}
	
	drms_query=calloc(num_query_chars,sizeof(char));
	strcat(drms_query,"hmi.sharp_720s[");
	strcat(drms_query,harpnum);
	strcat(drms_query,"]");
	
	if (time_range!="[]"){
	
		strcat(drms_query,time_range);
		
	}
	
	/* Query DRMS for the records. */
	
	printf("Querying DRMS. This may take some time.\n");
	
	if (!(drms_ids=drms_open_records(drms_env,drms_query,&drms_status))){
		
		printf("No record sets match your criteria. Check your SHARPs ID and your time range.\n");
		drms_close_records(drms_ids,DRMS_FREE_RECORD);
		free(drms_query);
		return 0;
		
	}

	free(drms_query);

	num_records=drms_ids->n;
	printf("%d records match. Checking to make sure we have the needed data segments.\n",num_records);

	drms_record=drms_ids->records[0];

	if (!(drms_segment_lookup(drms_record,"vlos_mag"))){
		
		printf("vlos_mag segment not present! Exiting.\n");
		drms_close_records(drms_ids,DRMS_FREE_RECORD);
		return 0;
	
	}

	if (!(drms_segment_lookup(drms_record,"inclination"))){
		
		printf("Inclination segment not present! Exiting.\n");
		drms_close_records(drms_ids,DRMS_FREE_RECORD);
		return 0;
	
	}

	if (!(drms_segment_lookup(drms_record,"continuum"))){
		
		printf("Continuum segment not present! Exiting.\n");
		drms_close_records(drms_ids,DRMS_FREE_RECORD);
		return 0;
	
	}

	if (!(drms_segment_lookup(drms_record,"info_map"))){
		
		printf("Info_map segment not present! Exiting.\n");
		drms_close_records(drms_ids,DRMS_FREE_RECORD);
		return 0;

	}

	/* Now we can start. We loop over all records, get the keyword information we need, get the data, and then calculate. */
	
	/* First set the size of some of the pointers that are intended to be arrays. */
	
	/* Time-related arrays */
	
	t_secs=malloc(num_records*sizeof(long));
	t_obs_s=malloc(num_records*sizeof(char *));
	
	for (i=0;i<num_records;i++){
		
		t_obs_s[i]=malloc(T_OBS_LENGTH*sizeof(char));
		
	}
	
	/* Data-related arrays */
	
	umb_p_vel=malloc(num_records*sizeof(double));
	pen_p_vel=malloc(num_records*sizeof(double));
	umb_n_vel=malloc(num_records*sizeof(double));
	pen_n_vel=malloc(num_records*sizeof(double));

	/* Record quality */
	
	quality=malloc(num_records*sizeof(long));
	
	for (k=0;k<num_records;k++){ 

		drms_record=drms_ids->records[k];
		
		/* Check to see if we have data for a particular observation time */
		
		if (!(t_obs=drms_getkey_time(drms_record,"T_OBS",&drms_status))){
					
			printf("Keyword %s not present! Exiting.\n","T_OBS");
			drms_close_records(drms_ids,DRMS_FREE_RECORD);
			return 0;
		
		}
		
		if (time_is_invalid(t_obs)){
			
			printf("Bad record, skipping.\n");
			
		} else {
			
			if (k == 0){
				
				/* Get active region number for pregame info */
			
				if (!(noaa_ar=drms_getkey_int(drms_record,"NOAA_AR",&drms_status))){
					
					printf("Keyword %s not present! Exiting.\n","NOAA_AR");
					drms_close_records(drms_ids,DRMS_FREE_RECORD);
					return 0;
		
				}
				
				/* Create data output filename */
			
				sprintf(outfile_name,"AR%d.fvlos-output.dat",noaa_ar);
				sprintf(bad_outfile_name,"AR%d.bad-quality.dat",noaa_ar);
							
				/* Print out some stats before we run */
			
				printf("Pre-analysis details:\n");
				printf("Analyzing: HARP Number: %s\t NOAA AR: %d\n",harpnum,noaa_ar);
				printf("Output file: %s\n",outfile_name);
			
				if (time_range == "[]\0"){
				
					printf("We are covering the entire data set.\n");
			
				} else {
				
					printf("Time range: %s\n",time_range);
			
				}

				printf("\n\n");	
			}
			
			printf("Processing record %d of %d.\n",k+1,num_records);
		
			/* Fill keywords */
			
			if (!(quality[k]=drms_getkey_longlong(drms_record,"QUALITY",&drms_status))){
			
				quality[k]=0;
		
			}
	
			if (!(crpix1=drms_getkey_double(drms_record,"CRPIX1",&drms_status))){
			
				printf("Keyword %s not present! Exiting.\n","CRPIX1");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
			
			if (!(crpix2=drms_getkey_double(drms_record,"CRPIX2",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","CRPIX2");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
		
		
			if (!(cdelt1=drms_getkey_double(drms_record,"CDELT1",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","CDELT1");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
			
			if (!(cdelt2=drms_getkey_double(drms_record,"CDELT2",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","CDELT2");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
		
			if (!(imcrpix1=drms_getkey_double(drms_record,"IMCRPIX1",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","IMCRPIX1");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
		
			if (!(imcrpix2=drms_getkey_double(drms_record,"IMCRPIX2",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","IMCRPIX2");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
		
			if (!(rsun_obs=drms_getkey_double(drms_record,"RSUN_OBS",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","RSUN_OBS");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}

			if (!(dsun_obs=drms_getkey_double(drms_record,"DSUN_OBS",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","DSUN_OBS");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
			
			if (!(obs_vr=drms_getkey_double(drms_record,"OBS_VR",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","OBS_VR");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}

			if (!(obs_vn=drms_getkey_double(drms_record,"OBS_VN",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","OBS_VN");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
			
			if (!(obs_vw=drms_getkey_double(drms_record,"OBS_VW",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","OBS_VW");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}

			if (!(crota2=drms_getkey_double(drms_record,"CROTA2",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","CROTA2");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
		
			if (!(crln_obs=drms_getkey_double(drms_record,"CRLN_OBS",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","CRLN_OBS");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
		
			if (!(crlt_obs=drms_getkey_double(drms_record,"CRLT_OBS",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","CRLT_OBS");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}

			if (!(blank=drms_getkey_double(drms_record,"BLANK",&drms_status))){
					
				printf("Keyword %s not present! Exiting.\n","BLANK");
				drms_close_records(drms_ids,DRMS_FREE_RECORD);
				return 0;
		
			}
		
			sprint_ut(t_obs_s[k],t_obs);		/* Convert to string */
		
			printf(" Checking quality.\n");
			
			if (quality[k] == 0){
		
				/* Ok, now we get the file locations for the data from DRMS. Originally I attempted
				* to pull the data directly from DRMS but there were vague free() and malloc() issues
				* possibly due to icc and multithreading, or library problems. */
		
				if (!(drms_segment=drms_segment_lookup(drms_record,"vlos_mag"))){
			
					printf("Problem opening the vlos_mag segment! Exiting.\n");
					drms_close_records(drms_ids,DRMS_FREE_RECORD);
					return 0;
			
				}
		
				drms_segment_filename(drms_segment,v_filename);
			
				if (!(drms_segment=drms_segment_lookup(drms_record,"continuum"))){
				
					printf("Problem opening the continuum segment! Exiting.\n");
					drms_close_records(drms_ids,DRMS_FREE_RECORD);
					return 0;
			
				}
		
				drms_segment_filename(drms_segment,c_filename);
			
				/* naxis1 and naxis2 we get from segment information */
		
				naxis1=(int)drms_segment->axis[0];
				naxis2=(int)drms_segment->axis[1];
		
				if (!(drms_segment=drms_segment_lookup(drms_record,"inclination"))){
			
					printf("Problem opening the inclination segment! Exiting.\n");
					drms_close_records(drms_ids,DRMS_FREE_RECORD);
					return 0;
			
				}
		
				drms_segment_filename(drms_segment,i_filename);
			
				if (!(drms_segment=drms_segment_lookup(drms_record,"info_map"))){
			
					printf("Problem opening the info_map segment! Exiting.\n");
					drms_close_records(drms_ids,DRMS_FREE_RECORD);
					return 0;
			
				}
			
				drms_segment_filename(drms_segment,info_filename);
			
				printf(" Opening FITs files.\n");
		
				/* Now open the FITS files and get to work. */
	
				v_status=0;
				i_status=0;
				c_status=0;
				info_status=0;
				any_nulls=0;

				if (fits_open_file(&v_ptr,v_filename,READONLY,&v_status)){
				
					printf("Cannot open %s! Exiting.\n",v_filename);
					exit(0);

				}

				if (fits_open_file(&i_ptr,i_filename,READONLY,&i_status)){
				
					printf("Cannot open %s! Exiting.\n",i_filename);
					fits_close_file(i_ptr,&i_status);
					exit(0);

				}
			
				if (fits_open_file(&c_ptr,c_filename,READONLY,&c_status)){
				
					printf("Cannot open %s! Exiting.\n",c_filename);
					fits_close_file(c_ptr,&c_status);
					exit(0);

				}
			
				if (fits_open_file(&info_ptr,info_filename,READONLY,&info_status)){
				
					printf("Cannot open %s! Exiting.\n",info_filename);
					fits_close_file(info_ptr,&info_status);
					exit(0);

				}
				
				
				/* Walk through the HDUs until we get to one with NAXIS=2 */

				/* Number of headers and which one we are on */

				fits_get_num_hdus(v_ptr,&num_hdus,&v_status);
				fits_get_hdu_num(v_ptr,&hdu_pos);

				/* Find the one with two naxes */

				naxis=0;

				for (i=1;i<=num_hdus;i++){
				
					fits_movabs_hdu(v_ptr,i,NULL,&v_status);
					fits_read_key(v_ptr,TINT,"NAXIS",&naxis,NULL,&v_status);
				
					if (naxis == 2){
	
						needed_hdu=i;
	
					}
				}


				/* Set all to the needed HDU */

				if (naxis == 0){
		
					printf("HDU problems: can't find one with the required number of axes.\n");
					fits_close_file(v_ptr,&v_status);
					fits_close_file(i_ptr,&i_status);
					fits_close_file(c_ptr,&c_status);
					fits_close_file(info_ptr,&info_status);
					exit(0);

				} else {

					fits_movabs_hdu(v_ptr,needed_hdu,NULL,&v_status);
					fits_movabs_hdu(i_ptr,needed_hdu,NULL,&i_status);
					fits_movabs_hdu(c_ptr,needed_hdu,NULL,&c_status);
					fits_movabs_hdu(info_ptr,needed_hdu,NULL,&info_status);

				}


				/* Now set some definite boundaries on arrays to help with memory usage. Arrays are called as con_dat[y][x]. */
				
				inv_len=naxis1/num_divs;
				
				vlos_dat=malloc(naxis2*sizeof(double *));
				inc_dat=malloc(naxis2*sizeof(double *));
				con_dat=malloc(naxis2*sizeof(double *));
				radius=malloc(naxis2*sizeof(double *));
				info_dat=malloc(naxis2*sizeof(long *));
				y_axis=malloc(num_divs*sizeof(double *));
				y_error=malloc(num_divs*sizeof(double *));
				x_axis=malloc(num_divs*sizeof(double *));
			
				v_pixel_strip=calloc(naxis1,sizeof(double));
				i_pixel_strip=calloc(naxis1,sizeof(double));
				c_pixel_strip=calloc(naxis1,sizeof(double));
				info_pixel_strip=calloc(naxis1,sizeof(long));
	
				for (j=0;j<naxis2;j++){
		
					vlos_dat[j]=calloc(naxis1,sizeof(double));
					inc_dat[j]=calloc(naxis1,sizeof(double));
					con_dat[j]=calloc(naxis1,sizeof(double));
					radius[j]=calloc(naxis1,sizeof(double));
					info_dat[j]=calloc(naxis1,sizeof(long));
		
				}
				
				for (j=0;j<(num_divs-1);j++){
					
					x_axis[j]=calloc((inv_len),sizeof(double));
					y_axis[j]=calloc((inv_len),sizeof(double));
					y_error[j]=calloc((inv_len),sizeof(double));
					
				}
				
				x_axis[num_divs-1]=calloc((inv_len + naxis1%num_divs),sizeof(double));
				y_axis[num_divs-1]=calloc((inv_len + naxis1%num_divs),sizeof(double));
				y_error[num_divs-1]=calloc((inv_len + naxis1%num_divs),sizeof(double));
				
				/* Next, put data in the arrays, clear out blank values and NaNs from the data */
	
				fpixel[0]=1;		/* cfitsio uses fortran reference instead of c when accessing data */
				nelements=naxis1;
				nulval=0;
				l_nulval=0;
				any_nulls=0;
    
				for (j=0;j<naxis2;j++){
		
					fpixel[1]=j+1;	/* Add 1 to account for fortran FITS indexing */
					fits_read_pix(v_ptr,TDOUBLE,fpixel,nelements,&nulval,v_pixel_strip,&any_nulls,&v_status);
					fits_read_pix(i_ptr,TDOUBLE,fpixel,nelements,&nulval,i_pixel_strip,&any_nulls,&i_status);
					fits_read_pix(c_ptr,TDOUBLE,fpixel,nelements,&nulval,c_pixel_strip,&any_nulls,&c_status);
					fits_read_pix(info_ptr,TLONG,fpixel,nelements,&l_nulval,info_pixel_strip,&any_nulls,&info_status);
		
					for (i=0;i<naxis1;i++){
			
						/* Kill blank values if present, if not assign to the correct place in array */
			
						if (v_pixel_strip[i] == blank){
				
							vlos_dat[j][i]=0.0;
					
						} else {
				
							vlos_dat[j][i]=v_pixel_strip[i];
			
						}
			
						if (i_pixel_strip[i] == blank){
				
							inc_dat[j][i]=0.0;
				
						} else {
					
							inc_dat[j][i]=i_pixel_strip[i];
			
						}

						if (c_pixel_strip[i] == blank){
				
							con_dat[j][i]=0.0;
			
						} else {
					
							con_dat[j][i]=c_pixel_strip[i];
			
						}
					
						info_dat[j][i]=info_pixel_strip[i];
					
					}
				}
				
		
				printf(" Analyzing data.\n");
	
				/* Coordinate variable definitions for future use. See the declaration section */
				/* at the front of the code to understand what these refer to. */
	
				rscx=(imcrpix1-1.0);
				rscy=(imcrpix2-1.0);
				rllx=(crpix1-1.0);
				rlly=(crpix2-1.0);
				rpllx=(rscx-rllx);
				rplly=(rscy-rlly);
	
				/* Fill the radius array, handle limb darkening */
	
				rsun_pix=rsun_obs/cdelt1;
	
				for (i=0;i<naxis1;i++){
		
					for (j=0;j<naxis2;j++){
			
						xx=(double)i-rllx;
						yy=(double)j-rlly;
						r=sqrt(xx*xx+yy*yy);
				
						if (r <= rsun_pix){
				
							radius[j][i]=r;
							mu=sqrt(1-pow(r/rsun_pix,2.0));
							con_dat[j][i]=con_dat[j][i]/limb_darken(mu);
					
						}
					}
				}
			
				/* Determine if we actually have an active region here. */
			
				spotbounds(con_dat,naxis1,naxis2,&umb,&pen,umb_sig,pen_sig);
			
				num_good=0;
	
				for (i=0;i<naxis1;i++){
		
					for (j=0;j<naxis2;j++){
		
						if ((radius[j][i] > 0)&&(con_dat[j][i] <= pen)&&(con_dat[j][i] > 0)){
				
							num_good++;
			
						}
					}
				}
	
				/* Now find the average LOS velocities. */
			
				umb_p_vel[k]=0;
				pen_p_vel[k]=0;
				umb_n_vel[k]=0;
				pen_n_vel[k]=0;
				
				umb_p_counter=0.0;
				umb_n_counter=0.0;
				pen_p_counter=0.0;
				pen_n_counter=0.0;
			
				if (num_good > 0){
					
					/* We're going to do these loops twice - first to remove any satellite and differential 
					 * rotation effects, then again to fit and remove trends. */
			
					/* First the satellite motion and the differential rotation */
			
					for (i=0;i<naxis1;i++){
				
						for (j=0;j<naxis2;j++){
							
							if ((radius[j][i] > 0)&&(good_pixel(info_dat[j][i]))){
								
								/* Get the pixel location in HPL coordinates */
							
								x=rpllx+(double)i;
								y=rplly+(double)j;
								
								/* Stonyhurst/carrington needed for photospheric velocity calcs */
							
								pixel2hpl(x,y,crota2,imcrpix1,imcrpix2,cdelt1,cdelt2,&tx,&ty);	
								hpl2stony(tx,ty,dsun_obs,crln_obs,crlt_obs,&lat,&lon);
								
								/* Photospheric rotation removal */
								
								vt=v_t(lat,0,0,0)*along_phi(t,p,dsun_obs); /*0's are for default coefficients */
							
								/* Convert to spherical with no rotation to account for sat orientation and handle LOS stuff */
							
								pixel2hpl(x,y,0.0,imcrpix1,imcrpix2,cdelt1,cdelt2,&tx,&ty);
								hpl2hpc(tx,ty,&ttx,&tty);
								hpc2hcc(ttx,tty,dsun_obs,&xx,&yy,&zz);
								hcc2sphere(xx,yy,zz,&t,&p);
							
								/* LOS satellite velocity components */
							
								vr=obs_vr*along_obs(t,p,dsun_obs);
								vn=obs_vn*along_north(t,p,dsun_obs);
								vw=obs_vw*along_west(t,p,dsun_obs);
								
								/* vlos after removing all of the doppler effects. The 
								 * division by 100 is to convert cm/s to m/s. */
								
								vlos_dat[j][i]=(vlos_dat[j][i]/100)-vr-vn-vw-vt;
								
							}
						}
					}
					
					/* Next we fit a function across x, not including points that would be in a sunspot or off-disk points.
					 * Then we subtract this trend from the remaining data. */
					 
					for (j=0;j<naxis2;j++){
				
						/* Fill the arrays along x */
				
						for (i=0;i<num_divs;i++){
							
							if (i < (num_divs-1)){
								
								/* There are a total of num_divs segments in a data strip.
								 * To handle remainders when determining how many points to 
								 * place in a segment, we first do the remainderless ones.
								 * The last may or may not have a remainder, but that's where
								 * one would go if it did, so we do it separately. */
							
								for (l=0;l<inv_len;l++){
									
									n=i*inv_len+l;
									y_error[i][l]=1;
									x_axis[i][l]=(double)n;
									
							
									if ((radius[j][n] > 0)&&(con_dat[j][n] > pen)&&(good_pixel(info_dat[j][n]))){
								
										y_axis[i][l]=vlos_dat[j][n];
								
									} else {
								
										y_axis[i][l]=0.0;
								
									}
						
								}
								
							} else {
								
								/* Handle the one that might have a remainder */
								
								for (l=0;l<(inv_len + naxis1%num_divs);l++){
									
									n=(num_divs-1)*inv_len+l;
									y_error[num_divs-1][l]=1;
									x_axis[num_divs-1][l]=(double)n;
									
							
									if ((radius[j][n] > 0)&&(con_dat[j][n] > pen)&&(good_pixel(info_dat[j][n]))){
								
										y_axis[num_divs-1][l]=vlos_dat[j][n];
								
									} else {
								
										y_axis[num_divs-1][l]=0.0;
								
									}
						
								}
								
							}
							
						}
						
						/* Now we fit, but in strips determined by num_divs */
						
						for (i=0;i<num_divs;i++){
							
							if (i < (num_divs-1)){
									
								v.x=x_axis[i];
								v.y=y_axis[i];
								v.ey=y_error[i];
	
								fit_status=mpfit(fit_me,inv_len,2,fit_params,0,&config,(void *)&v,&result);
								
								for (l=0;l<inv_len;l++){
									
									n=i*inv_len+l;
									vlos_dat[j][n]=vlos_dat[j][n]-(fit_params[0]*x_axis[i][l]+fit_params[1]);	/* Subtract trend */
									
								}
								
							} else {
								
								v.x=x_axis[num_divs-1];
								v.y=y_axis[num_divs-1];
								v.ey=y_error[num_divs-1];
	
								fit_status=mpfit(fit_me,inv_len + naxis1%num_divs,2,fit_params,0,&config,(void *)&v,&result);
							
								for (l=0;l<(inv_len + naxis1%num_divs);l++){
									
									n=(num_divs-1)*inv_len+l;
									vlos_dat[j][n]=vlos_dat[j][n]-(fit_params[0]*x_axis[num_divs-1][l]+fit_params[1]);	/* Subtract trend */
									
								}
								
							}
						}	
								
					}
					
					/* Finally, we have a clean data set. Now get to work on it. */
					 
					 
					for (i=0;i<naxis1;i++){
				
						for (j=0;j<naxis2;j++){
							
							if ((radius[j][i] > 0)&&(con_dat[j][i] < pen)&&(good_pixel(info_dat[j][i]))){
						
								/* "Positive" sunspot polarities. */
								
								vlos=vlos_dat[j][i];
							
								if (inc_dat[j][i] < 90){
								
									if (con_dat[j][i] <= umb){
									
										umb_p_vel[k]+=vlos;
										umb_p_counter++;
								
									}
								
									if (con_dat[j][i] > umb){
									
										pen_p_vel[k]+=vlos;
										pen_p_counter++;
									
									}
								
					
								}
					
								/* "Negative" sunspot polarities. */
					
								if (inc_dat[j][i] > 90){
							
								
									if (con_dat[j][i] <= umb){
									
										umb_n_vel[k]+=vlos;
										umb_n_counter++;
								
									}
								
									if (con_dat[j][i] > umb){
									
										pen_n_vel[k]+=vlos;
										pen_n_counter++;
									
									}
					
								}
							
							}
						}
					}
				
				}
				
				if (umb_p_counter > 0){
					
					umb_p_vel[k]/=umb_p_counter;
					
				} else {
					
					umb_p_vel[k]=0;
					
				}
			
				if (umb_n_counter > 0){
					
					umb_n_vel[k]/=umb_n_counter;
					
				} else {
					
					umb_n_vel[k]=0;
					
				}
				
				if (pen_p_counter > 0){
					
					pen_p_vel[k]/=pen_p_counter;
					
				} else {
					
					pen_p_vel[k]=0;
					
				}

				if (pen_n_counter > 0){
					
					pen_n_vel[k]/=pen_n_counter;
					
				} else {
					
					pen_n_vel[k]=0;
					
				}
				
			
				/* Free up dynamic arrays and close the files for the next iteration. */
				
				for (i=0;i<naxis2;i++){
				
					free(vlos_dat[i]);
					free(inc_dat[i]);
					free(con_dat[i]);
					free(radius[i]);
					free(info_dat[i]);
					
				}
				
				free(vlos_dat);
				free(inc_dat);
				free(con_dat);
				free(radius);
				free(info_dat);
				
				
				free(v_pixel_strip);
				free(i_pixel_strip);
				free(c_pixel_strip);
				free(info_pixel_strip);
				
				free(x_axis);
				free(y_axis);
				free(y_error);
			
				fits_close_file(v_ptr,&v_status);
				fits_close_file(i_ptr,&i_status);
				fits_close_file(c_ptr,&c_status);
				fits_close_file(info_ptr,&info_status);

			}
	
		}
	
		printf(" Completed run %d of %d.\n",k+1,num_records);
		
	}
	
	/* Output the results to a text file. */
	
	/* First, convert t_obs to a more reasonable product. */
	
	for (i=0;i<num_records;i++){			
	
		t_secs[i]=isotime(t_obs_s[i]);

	}

	printf("Writing to file %s.\n",outfile_name);
	
	outptr=fopen(outfile_name,"w");
	bad_outptr=fopen(bad_outfile_name,"w");
	
	fprintf(outptr,"Active Region: %d\tVelocities are in m/s, fvlos is scaled to remove limb effects.\n",noaa_ar);
	fprintf(outptr,"Full UT Time            time(s)  vlos pumb  vlos ppen  vlos numb  vlos npen\n");
	fprintf(outptr,"----------------------  -------  ---------  ---------  ---------  ---------\n");

	fprintf(bad_outptr,"Active Region: AR%d\n",noaa_ar);
	fprintf(bad_outptr,"Full UT Time            quality  time(s)  number\n");
	fprintf(bad_outptr,"----------------------  -------  -------  ------\n");
	
	for (i=0;i<num_records;i++){
		
		/* Make times relative to the first recorded one. */
		
		if (quality[i] == 0){
		
			fprintf(outptr,"%s  %7ld  %6.2lf  %6.2lf  %6.2lf  %6.2lf\n",t_obs_s[i],t_secs[i]-t_secs[0],umb_p_vel[i],pen_p_vel[i],umb_n_vel[i],pen_n_vel[i]);
		
		} else {
			
			fprintf(bad_outptr,"%s  0x%08lX  %7ld  %d\n",t_obs_s[i],quality[i],t_secs[i],i+1);		
		
		}

	}
	
	fclose(outptr);
	fclose(bad_outptr);
	
	printf("Done!\n");
	
	/* Free memory associated with dynamic arrays. */

	free(t_secs);
	free(t_obs_s);
	
	free(umb_p_vel);
	free(pen_p_vel);
	free(umb_n_vel);
	free(pen_n_vel);
	
	free(quality);
	
	
	/* Close the drms records connection */
	
	drms_close_records(drms_ids,DRMS_FREE_RECORD);
    
	/* Done! */
    
	return 0;
}
Exemplo n.º 22
0
int main(int argc, char **argv)
{

  int             i_file,i_scan,i_chan,i_bin,n_omit,status=0;
  int             NFirstTable, NumHDU, NDumps, TotDumps=0, hdutype;
  // int             OutChans;
  int             spk;
  int             got_bins=0, got_mjd1=0; //, zeroed_outprofs=0;
  long            NPtsProf=0, FirstNPtsProf=0;
  float           Weight=1.0, TotWeight=0.;
  // int             ProfSum=0;
  double          x, ptype;
  double          MJD_first=0., MJD_last=0., MJD_mid;
  double          IMJDMid, MJDSecsMid;
  double          SBase,Srms,Duty,SPeak,FinalMask[NBINMAX];
  double          OutFreq;
  char            ProgName[32];
  char            Outfile[128];
  char            Header[256];  
  struct ASPHdr   *Hdr;
  struct SubHdr   Subhdr;
  struct StdProfs *InProfile, OutProfile;
  struct RunVars  RunMode;
  fitsfile        **Fin;
  FILE            *Fout, *Fcheck;
  Cmdline         *Cmd;


  /* Get command line variables */
  Cmd = parseCmdline(argc, argv);  

  /* Normally use this somewhere, and not showOptionValues */
  Cmd->tool = Cmd->tool;

  strcpy(ProgName, argv[0]);

  Fin = (fitsfile **)malloc(Cmd->InfileC*sizeof(fitsfile));
  Hdr = (struct ASPHdr *)malloc(Cmd->InfileC*sizeof(struct ASPHdr));

  /* Dynamically allocate RunMode variables */
  if (AllocRunMode(&RunMode) < 0){
    printf("Could not allocate RunMode structure.  Exiting...\n");
    exit(2);
  }
  strcpy(RunMode.Infile,Cmd->Infile); 
  

 //    if(!zeroed_outprofs) {
      /*     if(Cmd->SortChansP){
	     OutChans=Hdr[0].obs.NChan;
	     } 
	     else{ */
  // OutChans=1;
  // }
  // OutProfile=(struct StdProfs *)malloc(OutChans*sizeof(struct StdProfs));
  // TotWeight=(float *)malloc(OutChans*sizeof(float));
  
  /* Zero out profiles */
  //     for(i_chan=0;i_chan<OutChans;i_chan++){
  FZero(OutProfile.rstds,NBINMAX);
  FZero(OutProfile.rstdq,NBINMAX);
  FZero(OutProfile.rstdu,NBINMAX);
  FZero(OutProfile.rstdv,NBINMAX);
  // }
  //zeroed_outprofs=1;
      //    }

  /* Create an output file to check omissions if in vebose mode */
  if (Cmd->VerboseP || Cmd->CheckOmitP){
    if((Fcheck = fopen("check_omit.dat","w")) == 0)
       { printf("Cannot open %s. Exiting...\n",Outfile); exit(1); }   
  }


  /* read in all input files and add each to the final profile */

  /* read in all input file headers */
  NPtsProf=0;
  for (i_file=0;i_file<Cmd->InfileC;i_file++){
    n_omit=0;
    status=0;    
    if(fits_open_file(&Fin[i_file], Cmd->Infile[i_file], READONLY, &status)){
      printf("Error opening FITS file %s !!!\n", Cmd->Infile[i_file]);
      exit(1);
    }
    if(ReadASPHdr(&Hdr[i_file], Fin[i_file]) < 0){
      printf("%s> Unable to read Header from file %s.  Exiting...\n",
	     ProgName,Cmd->Infile[i_file]);
      exit(1);
    }

    /* Write file name in verbose-mode omit check file */
    if(Cmd->VerboseP || Cmd->CheckOmitP) 
      fprintf(Fcheck, "\n%s\n",Cmd->Infile[i_file]);


    /* for now just check if all files have same number of channels */
    /* if(Cmd->SortChansP)
        if(i_file>0 && Hdr[i_file].obs.NChan!=Hdr[0].obs.NChan){
        fprintf(stderr,"%s> Different numbers of channels in different files:\n\n",
        ProgName);
        fprintf(stderr,"%s: %d channels,  %s: %d channels\n",
	Cmd->Infile[0],Hdr[0].obs.NChan,
	Cmd->Infile[i_file],Hdr[i_file].obs.NChan);
	} */
    
    /* now find the number of dumps in the file */    
    fits_get_num_hdus(Fin[i_file], &NumHDU, &status);
    if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0")){
      NDumps = NumHDU-3;  /* the "3" is temporary, depending on how 
				   many non-data tables we will be using */
    }
    else if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0.1")){
      NDumps = (NumHDU-3)/2;
    }
    else{
      fprintf(stderr,"%s> Do not recognize FITS file version in header.\n",
	      ProgName);
      fprintf(stderr,"This header is %s. Exiting...\n",Hdr[i_file].gen.HdrVer);
      exit(1);
    }

    printf("File %s:\n",Cmd->Infile[i_file]);
    printf("     Number of channels:  %d\n",Hdr[i_file].obs.NChan) ;
    printf("     Number of dumps:     %d\n",NDumps);

    /* Move to the first data table HDU in the fits file */
    if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0"))
      fits_movnam_hdu(Fin[i_file], BINARY_TBL, "STOKES0", 0, &status);
    else if (!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0.1"))
      fits_movnam_hdu(Fin[i_file], ASCII_TBL, "DUMPREF0", 0, &status);

    /* Get the current HDU number */
    fits_get_hdu_num(Fin[i_file], &NFirstTable);

    /* Set up Profile structure size */


    for(i_scan=0;i_scan<NDumps;i_scan++){
      
      InProfile=(struct StdProfs *)malloc(Hdr[i_file].obs.NChan*
					sizeof(struct StdProfs));
     /* move to next dump's data */
      if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0")){
	fits_movabs_hdu(Fin[i_file], NFirstTable+i_scan, &hdutype, &status); 
      }
      else if(!strcmp(Hdr[i_file].gen.HdrVer,"Ver1.0.1")){
	/* if we've reached the end of the FITS file then increase FileNo */
	fits_movabs_hdu(Fin[i_file],NFirstTable+(i_scan%MAXDUMPS)*2+1,&hdutype,
			&status);
	fits_get_num_rows(Fin[i_file], &NPtsProf, &status);status=0; 
	fits_movrel_hdu(Fin[i_file], -1, NULL, &status);
      }
      
      /* IF not done so, use number of bins from first file to compare to 
	 the rest of the files */
      if(got_bins==0){
	FirstNPtsProf=NPtsProf;  
	got_bins=1;
      }

      /**********  FIX:  SKIP THIS WITHOUT DOING THE OMIT THING ***********/
      /**********         AND DON'T ADD TO NUMBER COUNT  ************/
      if(NPtsProf != FirstNPtsProf) {
	fprintf(stderr,"Warning: Skipping scan %d (%ld bins ",
		i_scan,NPtsProf);
	fprintf(stderr,"vs. %ld bins in others).\n",FirstNPtsProf);
		
	n_omit += Hdr[i_file].obs.NChan;
      }
      else{
	
	/* find NPtsProf */
	ReadASPStokes(&Hdr[i_file], &Subhdr, Fin[i_file], NPtsProf, 
		      InProfile, i_scan, Cmd->VerboseP);
	
	
	/* Add this profile onto running output profile */
	
	for(i_chan=0;i_chan<Hdr[i_file].obs.NChan;i_chan++){
	  
	  /* Bad scans are zeroed so if summ of the profile is zero, it's 
	     not to be used in summation */
	  //	  ProfSum = FSum(&InProfile[i_chan].rstds[0], NPtsProf);
	  //	  ProfSum = 0;
	  // ProfSum = ArrayZero(InProfile[i_chan].rstds, NPtsProf);
	  //	  if(ProfSum != 0.0) { // i.e. good data
	  /* Test that all bins in current profile are not zeroed */
	  if(!ArrayZero(InProfile[i_chan].rstds, NPtsProf)) { // i.e. good data
	    //	  if(InProfile[i_chan].rstds[0] > -99998.) { // i.e. good data
	    
	    /* If first MJD has not been registered, then do so since this 
	       would be the first non-omitted scan */
	    if (got_mjd1==0) {
	      MJD_first = (double)Hdr[i_file].obs.IMJDStart + 
		Subhdr.DumpMiddleSecs/86400.;
	      got_mjd1=1;
	    }
	    if (i_scan==NDumps-1) {
	      /* Just keep overwriting MJD_last every i_file -- that way we 
		 ensure getting the last MJD of the FINAL non-omitted scan 
		 used */
	      MJD_last = (double)Hdr[i_file].obs.IMJDStart + 
		Subhdr.DumpMiddleSecs/86400.;
	    }

	    /* Get SNR for each Profile if we want to use weighting; 
	       otherwise weights will all be 1.0 */
	    if(Cmd->WeightP) {
	      Duty = DutyLookup(Hdr[i_file].target.PSRName);
	      BMask(InProfile[i_chan].rstds,&Hdr[i_file].redn.RNBinTimeDump,
		    &Duty,FinalMask);
	      Baseline(InProfile[i_chan].rstds,FinalMask,
		       &Hdr[i_file].redn.RNBinTimeDump,&SBase,&Srms);
	      SPeak =  FindPeak(InProfile[i_chan].rstds,
				&Hdr[i_file].redn.RNBinTimeDump,&spk);
	      InProfile[i_chan].SNR = SPeak*Srms;
	      //	      Weight = InProfile[i_chan].SNR;
	      Weight = Srms; // which is actually 1/RMS.
	    }
	    // printf("SNR %d = %lf\n",i_chan,InProfile[i_chan].SNR);
	    
	    /* Need to figure out how to organize input channels to match 
	     *  output channels */
	    /* if(Cmd->SortChansP){
	          for(i_bin=0;i_bin<NPtsProf;i_bin++) {
	             OutProfile[i_chan].rstds[i_bin] +=
		     Weight*InProfile[i_chan].rstds[i_bin];
		     OutProfile[i_chan].rstdq[i_bin] +=
		     Weight*InProfile[i_chan].rstdq[i_bin];
		     OutProfile[i_chan].rstdu[i_bin] +=
		     Weight*InProfile[i_chan].rstdu[i_bin];
		     OutProfile[i_chan].rstdv[i_bin] +=
		     Weight*InProfile[i_chan].rstdv[i_bin];
		  }
	       } 
	       else{ */
	    for(i_bin=0;i_bin<NPtsProf;i_bin++) {
	      OutProfile.rstds[i_bin] += 
		Weight*InProfile[i_chan].rstds[i_bin];
	      OutProfile.rstdq[i_bin] += 
		Weight*InProfile[i_chan].rstdq[i_bin];
	      OutProfile.rstdu[i_bin] += 
		Weight*InProfile[i_chan].rstdu[i_bin];
	      OutProfile.rstdv[i_bin] += 
		Weight*InProfile[i_chan].rstdv[i_bin];  
	      //   printf("%f\n",OutProfile[0].rstds[i_bin]);fflush(stdout);
	    }
	    //  }
	    TotWeight += Weight;  // for now keep at zero index
	    /* Print profile weights for each scan, for each channel */
	    if(RunMode.Verbose) {
	      if(i_chan==0) printf("Profile weights -- scan %d: \n   ",i_scan);
	      printf("%6.2f  ",Weight);
	      if(i_chan==Hdr[i_file].obs.NChan-1) printf("\n");fflush(stdout);
	    }
	  }
	  else {
	    n_omit++;
	    if(Cmd->VerboseP || Cmd->CheckOmitP){
	      fprintf(Fcheck, "%6d     %.1lf\n",
		      i_scan,Hdr[i_file].obs.ChanFreq[i_chan]);
	 /* printf("File %d, Dump %d, Channel %d (%lf MHz) were found to be\n",
		   i_file,i_scan,i_chan,Hdr[i_file].obs.ChanFreq[i_chan]);
	    printf("  zeroed and so are not included.\n");fflush(stdout); */
	    }
	  }
	  //    if(i_chan==0) {for(i=0;i<50;i++) printf("%lf  ",OutProfile[0].rstds[i]);printf("\n\n");fflush(stdout);};
	}
	
	/*****************/
	
	/*     }  */
	
	
      } /* else from positive check on NPtsProf */
     free(InProfile);
    }    
    /****** maybe bring this inside the ELSE where entire scans aren't being omitted ******/
    /* if (Cmd->SortChansP) 
      TotDumps += (NDumps - n_omit);
      else */ 
    TotDumps += (NDumps*Hdr[i_file].obs.NChan - n_omit); 
    //free(InProfile);
    
    printf("Reading of file %s complete and successful.\n",
	     Cmd->Infile[i_file]);
    printf("%d scans omitted.\n\n",n_omit);fflush(stdout);
  }

  if(Cmd->VerboseP || Cmd->CheckOmitP) fclose(Fcheck);

  /* Appease the format of the MakePol routine by making up these RunMode 
     structure members */
  strcpy(RunMode.Source,Hdr[0].target.PSRName);
  RunMode.Verbose = Cmd->VerboseP;
  RunMode.FlipPA = 0;
  RunMode.NoBase = Cmd->NoBaseP;
  /* divide out total number of dumps to get the average */
  // for(i_chan=0;i_chan<OutChans;i_chan++){
   
  printf("Totdumps = %d\n",TotDumps);
  fflush(stdout);
  
  for(i_bin=0;i_bin<NPtsProf;i_bin++) {
    OutProfile.rstds[i_bin] /= TotWeight;
    OutProfile.rstdq[i_bin] /= TotWeight;
    OutProfile.rstdu[i_bin] /= TotWeight;
    OutProfile.rstdv[i_bin] /= TotWeight;
  }
  
  MakePol(&RunMode, (int)NPtsProf, &OutProfile);
  /* Open file for writing */
  sprintf(Outfile,"AddProf.out");
  
  /* now write the output ascii added profile */
  if ((Fout = fopen(Outfile,"w")) == 0)
    { printf("Cannot open %s. Exiting...\n",Outfile); exit(1); }
  
  /* take average MJD of first to last scan */
  MJD_mid = (MJD_first + MJD_last)/2.;
  IMJDMid = floor(MJD_mid);
  MJDSecsMid = (MJD_mid - IMJDMid)*86400.;
  
  printf("MJD_mid = %lf, IMJDMid = %lf, MJDSecsMid = %lf\n",MJD_mid,IMJDMid,MJDSecsMid);fflush(stdout); 

  /* to choose a channel to put in the header for now, ust use the average 
     of the first datafile's channels */ 
  OutFreq=0.;
  for(i_chan=0; i_chan<Hdr[0].obs.NChan; i_chan++){
    OutFreq += Hdr[0].obs.ChanFreq[i_chan];
  }
  OutFreq /= Hdr[0].obs.NChan;

  /* Create and print header line for output file(s) */
  sprintf(Header,"# %.1f %.7f %.10f %ld %.3f %.3f %d %s %d %9s %.10f",
	  IMJDMid, 
	  MJDSecsMid, 
	  //	  Subhdr.DumpRefPeriod[i_chan],
	  0.,
	  (long)1, OutFreq,
	  //	    Hdr[0].obs.DM, Hdr[i_file].redn.RNBinTimeDump,
	  Hdr[0].obs.DM, (int)NPtsProf,
	  Hdr[0].obs.ObsvtyCode, 1, Hdr[0].target.PSRName, 
	  0.);             
  //	  Subhdr.DumpRefPhase[i_chan]);             
  fprintf(Fout,"%s\n",Header);
  
  for(i_bin=0;i_bin<NPtsProf;i_bin++) {
    /* see how strong the linear polarization is */
    x = OutProfile.stdlin[i_bin]*OutProfile.Srms; 
    ptype = 43.1;
    if (x > 1.) ptype=43.2;
    if (x > 2.) ptype=43.3;
    if (x > 3.) ptype=43.4;
    if (x > 4.) ptype=43.5;
    if (x > 5.) ptype=43.6;
    fprintf(Fout,"%5d%15.7f%15.7f%15.7f%15.7f%15.7f%15.7f%15.7f%6.1f\n",i_bin,
	    OutProfile.rstds[i_bin],OutProfile.rstdq[i_bin],
	    OutProfile.rstdu[i_bin],
	    OutProfile.rstdv[i_bin],
	    /* phi in degrees */
	    OutProfile.stdlin[i_bin],
	    OutProfile.stdphi[i_bin]*180.0/TWOPI, 
	    OutProfile.stdphierr[i_bin]*180.0/TWOPI,ptype);
  }
  printf("Created output file %s\n",Outfile);
  fclose(Fout);
  // }
  
  /* Write all this to file */
  
  
  printf("\nCompleted successfully.\n\n");fflush(stdout);
  
  exit(0);

}
Exemplo n.º 23
0
std::string read_image_3D(std::string pathname_3D, float *&array_2D_real, float *&array_2D_imag, int &naxis_2D, long *&naxes_2D) {
  TRACE_ENTER();
  // open FITS image file in READONLY mode
  fitsfile *fptr;
  int status = 0;
  fits_open_image(&fptr, pathname_3D.c_str(), READONLY, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // read number of HDUs in the file
  int nhdus = 0;
  fits_get_num_hdus(fptr, &nhdus, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // we expect only one HDU in the file
  if (nhdus != 1) {
    std::ostringstream exit_oss;
    exit_oss << "nhdus is " << nhdus << ", not 1";
    TRACE_ERROR(exit_oss.str());
    return exit_oss.str();
  }
  // read the type of the HDU
  int hdutype = 0;
  fits_movabs_hdu(fptr, nhdus, &hdutype, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // we expect the HDU to be an image
  if (hdutype != IMAGE_HDU) {
    std::ostringstream exit_oss;
    exit_oss << "hdutype is " << hdutype << ", not IMAGE_HDU";
    TRACE_ERROR(exit_oss.str());
    return exit_oss.str();
  }
  // read the type of data in the HDU
  int bitpix = 0;
  fits_get_img_type (fptr, &bitpix, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // we expect the data to be floats
  if (bitpix != FLOAT_IMG) {
    std::ostringstream exit_oss;
    exit_oss << "bitpix is " << bitpix << ", not FLOAT_IMG";
    TRACE_ERROR(exit_oss.str());
    return exit_oss.str();
  }
  // get the number of dimensions in the image
  int naxis_3D = 0;
  fits_get_img_dim (fptr, &naxis_3D, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  naxis_2D = naxis_3D-1;
  // we expect 3 dimensions in the image
  if (naxis_3D != 3) {
    std::ostringstream exit_oss;
    exit_oss << "naxis_3D is " << naxis_3D << ", not 3";
    TRACE_ERROR(exit_oss.str());
    return exit_oss.str();
  }
  // get the size of each dimension in the image
  long *naxes_3D = new long[naxis_3D];
  int maxdim = naxis_3D;
  fits_get_img_size(fptr, maxdim, naxes_3D, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  naxes_2D = new long[naxis_2D];
  for (int i = 0; i < naxis_2D; i++) {
    naxes_2D[i] = naxes_3D[i];
  }
  // we expect two sub-images in the third dimension
  if (naxes_3D[2] != 2) {
    std::ostringstream exit_oss;
    exit_oss << "naxes_2D[2] is " << naxes_2D[2] << ", not 2";
    TRACE_ERROR (exit_oss.str());
    return exit_oss.str();
  }
  // fits_read_subset
  long *fpixel = new long[naxis_3D];
  for (int i = 0; i < naxis_3D; i++) {
    fpixel[i] = 1;
  }
  long *lpixel = new long[naxis_3D];
  for (int i = 0; i < naxis_3D; i++) {
    lpixel[i] = naxes_3D[i];
  }
  long *inc = new long[naxis_3D];
  for (int i = 0; i < naxis_3D; i++) {
    inc[i] = 1;
  }
  float nulval = 0;
  long nelements_2D = 1;
  for (int i = 0; i < naxis_2D; i++) {
    nelements_2D = nelements_2D*naxes_2D[i];
  }
  int anynul = 0;
  // read array_2D_real
  array_2D_real = new float[nelements_2D];
  fpixel[2] = 1;
  lpixel[2] = 1;
  fits_read_subset(fptr, TFLOAT, fpixel, lpixel, inc, &nulval, array_2D_real, &anynul, &status);
  // read array_2D_imag
  array_2D_imag = new float[nelements_2D];
  fpixel[2] = 2;
  lpixel[2] = 2;
  fits_read_subset(fptr, TFLOAT, fpixel, lpixel, inc, &nulval, array_2D_imag, &anynul, &status);
  // free arrays
  delete [] inc;
  delete [] lpixel;
  delete [] fpixel;
  // test read result
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  // close the FITS image file
  fits_close_file(fptr, &status);
  if (status != 0) {
    return FORMAT_STATUS(status);
  }
  return "READ_OK";
}
Exemplo n.º 24
0
bool WMAPSource::initFile( )
{
  bool bRetVal = true;
  int iResult = 0;

  _numFrames = 0;

  if( !_filename.isNull( ) && !_filename.isEmpty( ) )
  {
    QString   str;
    fitsfile* ffits;
    int       iStatus = 0;

    iResult = fits_open_file( &ffits, _filename.ascii( ), READONLY, &iStatus );
    if( iResult == 0 )
    {
      int iNumHeaderDataUnits;

      if( fits_get_num_hdus( ffits, &iNumHeaderDataUnits, &iStatus ) == 0 )
      {
        long lNumBaseRows = 0;
        long lNumRows;
        int iHDUType;
        int i;

        //
        // determine the number of frames...
        //
        for( i=0; i<iNumHeaderDataUnits-1; i++ )
        {
          if( iStatus == 0 )
          {
            fits_get_hdu_type( ffits, &iHDUType, &iStatus );
            if( iHDUType == BINARY_TBL || iHDUType == ASCII_TBL )
            {
              iResult = fits_get_num_rows( ffits, &lNumRows, &iStatus );
              if( iResult == 0 )
              {
                if( lNumBaseRows == 0 )
                {
                  lNumBaseRows = lNumRows;
                }
                else if( lNumRows != 1 )
                {
                  if( lNumRows < lNumBaseRows )
                  {
                    lNumBaseRows = lNumRows;
                  }
                }
              }
            }

            fits_movrel_hdu( ffits, 1, &iHDUType, &iStatus );
          }
        }

        fits_movabs_hdu( ffits, 1, &iHDUType, &iStatus);

        field *fld = new field;

        fld->table = 0;
        fld->column = 0;
        fld->entry = 0;
        fld->entries = 0;
        fld->numSamplesPerFrame = 1;
        fld->numFrames = lNumBaseRows;

        _fields.insert( "INDEX", fld );
        _fieldList.append( "INDEX" );

        //
        // add the fields and metadata...
        //
        for( i=0; i<iNumHeaderDataUnits-1; i++ )
        {
          if( iStatus == 0 )
          {
            addToMetadata( ffits, iStatus );

            //
            // create the field entries...
            //
            fits_get_hdu_type( ffits, &iHDUType, &iStatus );
            if( iStatus == 0 )
            {
              if( iHDUType == BINARY_TBL || iHDUType == ASCII_TBL )
              {
                int iNumCols;
  
                iResult = fits_get_num_cols( ffits, &iNumCols, &iStatus );
                if( iResult == 0 )
                {
                  iResult = fits_get_num_rows( ffits, &lNumRows, &iStatus );
                  if( iResult == 0 )
                  {
                    if( lNumRows > 1 )
                    {
                      addToFieldList( ffits, iNumCols, lNumRows, lNumBaseRows, iStatus );
                    }
                    else if( lNumRows == 1 )
                    {
                      addToMetadata( ffits, iNumCols, iStatus );
                    }
                  }
                }
              }
            }

            fits_movrel_hdu( ffits, 1, &iHDUType, &iStatus);
          }
        }
      }

      iStatus = 0;

      updateNumFramesScalar( );

      fits_close_file( ffits, &iStatus );
    }
  }

  return bRetVal;
}
Exemplo n.º 25
0
int extractAvePlane (char *cubepath, char *impath, int iplane, int nplaneave,
    int *splaneave, int *eplaneave, char *errmsg)
{
    struct stat     buf;
    struct FitsHdr  hdr;

    char   str[1024];
    char   cmd[1024];
    
    int    bitpix;
    int    istatus;
    
    int    nhdu, hdutype, hdunum;

    int    nelements;
   
    int    naxis3;
    int    l;
    int    j;
    int    i;
    int    jj;
    int    nullcnt;

    int    splane;
    int    eplane;

    long   fpixel[4];
    long   fpixelo[4];

    double *fitsbuf;
    double *imbuff;
    
    fitsfile  *infptr;
    fitsfile  *outfptr;

    
    int    debugfile = 1;
    int    debugfile1 = 0;


/*
     Make a NaN value to use setting blank pixels
 */

    union
    {
        double d;
        char   c[8];
    }
    value;

    double nan;

    for(i=0; i<8; ++i)
        value.c[i] = 255;

    nan = value.d;


    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	fprintf (fp_debug, "\nEnter extractAvePlane: cubepath= [%s]\n", 
	    cubepath);
	fprintf (fp_debug, "iplane= [%d]\n", iplane);
	fprintf (fp_debug, "nplaneave= [%d]\n", nplaneave);
	fprintf (fp_debug, "impath= [%s]\n", impath);
        fflush (fp_debug);
    }

    splane = iplane - nplaneave/2;
    eplane = splane + nplaneave - 1;

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	fprintf (fp_debug, "splane= [%d] eplane= [%d]\n", splane, eplane);
        fflush (fp_debug);
    }

    istatus = 0;
    if (fits_open_file (&infptr, cubepath, READONLY, &istatus)) {

        if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	    fprintf (fp_debug, "istatus= [%d]\n", istatus);
            fflush (fp_debug);
	}

	sprintf (errmsg, "Failed to open FITS file [%s]\n", cubepath);
	return (-1);
    } 
   
    hdunum = 1; 
    nhdu = 0;
    istatus = 0;
    istatus = fits_get_num_hdus (infptr, &nhdu, &istatus);
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	fprintf (fp_debug, 
	    "returned fits_get_hdu_num: istatus= [%d] nhdu= [%d]\n",
	    istatus, nhdu);
        fflush (fp_debug);
    }

    if (hdunum > nhdu) {

        sprintf (errmsg, "fname [%s] doesn't contain any HDU", cubepath);
	return (-1);
    }


/*
    Read fits keywords from the first HDU
*/
    hdutype = 0;
    istatus = 0;
    istatus = fits_movabs_hdu (infptr, hdunum, &hdutype, &istatus);

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	fprintf (fp_debug, 
	    "returned fits_movabs_hdu: istatus= [%d] hdutype= [%d]\n",
	    istatus, hdutype);
        fflush (fp_debug);
    }

/*
    Read fits keywords
*/
    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "simple", str, (char *)NULL, 
        &istatus);
    
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword SIMPLE not found in fits header");
        return (-1);
    }
   
    if ((strcmp (str, "T") != 0) && (strcmp (str, "F") != 0)) {
        sprintf (errmsg, "keyword SIMPLE must be T or F");
        return (-1);
    }

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "bitpix", str, (char *)NULL, 
        &istatus);
    
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword BITPIX not found in fits header");
        return (-1);
    }
  
    istatus = str2Integer (str, &bitpix, errmsg);
    if (istatus != 0) {
        sprintf (errmsg, "keyword BITPIX must be an integer");
        return (-1);
    }

    if ((bitpix != 8) &&
        (bitpix != 16) &&
        (bitpix != 32) &&
        (bitpix != 64) &&
        (bitpix != -32) &&
        (bitpix != -64)) {
        
	sprintf (errmsg, 
	    "keyword BITPIX value must be 8, 16, 32, 64, -32, -64");
        return (-1);
    }

    hdr.bitpix = bitpix;

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis", str, (char *)NULL, 
        &istatus);
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis not found in fits header");
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }
    istatus = str2Integer (str, &hdr.naxis, errmsg);
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis to integer");
        return (-1);
    }
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "naxis= [%d]\n", hdr.naxis);
        fflush (fp_debug);
    }


    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis1", str, (char *)NULL, 
        &istatus);
        
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", istatus);
        fflush (fp_debug);
    }
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis1 not found in fits header");
        return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }

    istatus = str2Integer (str, &hdr.ns, errmsg);
    
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis1 string to integer");
        return (-1);
    }
    hdr.naxes[0] = hdr.ns;

    istatus = 0;
    istatus = fits_read_key (infptr, TSTRING, "naxis2", str, 
        (char *)NULL, &istatus);
        
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", istatus);
        fflush (fp_debug);
    }
        
    if (istatus == KEY_NO_EXIST) {
        sprintf (errmsg, "keyword naxis2 not found in fits header");
        return (-1);
    }
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "str= [%s]\n", str);
        fflush (fp_debug);
    }

    istatus = str2Integer (str, &hdr.nl, errmsg);
    
    if (istatus < 0) {
        sprintf (errmsg, "Failed to convert naxis2 string to integer");
        return (-1);
    }
    hdr.naxes[1] = hdr.nl;

    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "ns= [%d] nl= [%d]\n", hdr.ns, hdr.nl);
        fflush (fp_debug);
    }

    hdr.nplane = 1;

    if (hdr.naxis > 2) {
    
        istatus = 0;
        istatus = fits_read_key (infptr, TSTRING, "naxis3", str, 
            (char *)NULL, &istatus);
        
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {

            fprintf (fp_debug, "returned fits_read_key: istatus= [%d]\n", 
	        istatus);
            fflush (fp_debug);
        }
        
        if (istatus == KEY_NO_EXIST) {
            sprintf (errmsg, "keyword naxis3 not found in fits header");
            return (-1);
        }
    
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {

            fprintf (fp_debug, "str= [%s]\n", str);
            fflush (fp_debug);
        }

        istatus = str2Integer (str, &hdr.naxes[2], errmsg);
    
        if (istatus < 0) {
            sprintf (errmsg, "Failed to convert naxis3 string to integer");
            return (-1);
        }
        hdr.nplane = hdr.naxes[2];
    
        if ((debugfile) && (fp_debug != (FILE *)NULL)) {

            fprintf (fp_debug, "naxes[2]= [%d]\n", hdr.naxes[2]);
            fflush (fp_debug);
        }
    }
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

        fprintf (fp_debug, "nplane= [%d]\n", hdr.nplane);
        fflush (fp_debug);
    }


    istatus = stat (impath, &buf);
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
        fprintf (fp_debug, "impath exists? : istatus= [%d]\n", istatus);
        fflush (fp_debug); 
    }

    if (istatus >= 0) {
        sprintf (cmd, "unlink %s", impath);
	istatus = system (cmd);
    }	

/*
    Create output fits file
*/
    istatus = 0;
    if (fits_create_file (&outfptr, impath, &istatus)) {
	    
        sprintf (errmsg, "Failed to create output fitsfile [%s]\n", impath);
        
	if ((debugfile) && (fp_debug != (FILE *)NULL)) {
            fprintf (fp_debug, "err: [%s]\n", errmsg);
	    fflush (fp_debug);
        }
	return (-1);
    }

    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
	fprintf (fp_debug, "outptr created\n");
        fflush (fp_debug);
    }


/* 
    Copy input fits header to output fitsfile
*/
    istatus = 0;
    if (fits_copy_header (infptr, outfptr, &istatus)) {

        strcpy (errmsg, "Failed to copy fitshdr\n");
        
	if ((debugfile) && (fp_debug != (FILE *)NULL)) {
            fprintf (fp_debug, "err: [%s]\n", errmsg);
	    fflush (fp_debug);
        }
	return (-1);
    }

/*
    Update header keyword NAXIS3
*/
    naxis3 = 1;
    istatus = 0;
    if (fits_update_key_lng(outfptr, "NAXIS3", naxis3, (char *)NULL, 
        &istatus)) {
	
        strcpy (errmsg, "Failed to update keyword NAXIS3\n");
	return (-1);
    }

    istatus = 0;
    if (fits_close_file (infptr, &istatus)) {
        sprintf (errmsg, "Failed to close cubepath [%s]\n", cubepath);
        return (-1); 
    }
    
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {
	        
	fprintf (fp_debug, "cubepath= [%s]\n", cubepath);
        fflush (fp_debug);
    }

    istatus = 0;
    if (fits_open_file (&infptr, cubepath, READONLY, &istatus)) {

        if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	    fprintf (fp_debug, "istatus= [%d]\n", istatus);
            fflush (fp_debug);
	}

	sprintf (errmsg, "Failed to open FITS file [%s]\n", cubepath);
	return (-1);
    } 
  
/*
    Create imbuff for average image
*/
    imbuff = (double *)malloc (hdr.ns*hdr.nl*sizeof(double));
    for (i=0; i<hdr.nl*hdr.ns; i++) {
        imbuff[i] = 0.;
    }


/*
    Read data from nth plane and write to output fitsfile
*/
    nelements = hdr.ns;
       
    if ((debugfile) && (fp_debug != (FILE *)NULL)) {

	fprintf (fp_debug, "iplane= [%d]\n", iplane);
        fflush (fp_debug);
    }

    fitsbuf  = (double *)malloc(hdr.ns*sizeof(double));

    if (splane < 1)
        splane = 1;
    
    if (eplane > hdr.nplane)
        eplane = hdr.nplane;

    for (l=splane; l<=eplane; l++) { 
    
        fpixel[0] = 1;
        fpixel[1] = 1;
        fpixel[2] = l;
        fpixel[3] = 1;

        for (j=0; j<hdr.nl; j++) {

	    if (j == 0) {
	        if ((debugfile1) && (fp_debug != (FILE *)NULL)) {
	        
	            fprintf (fp_debug, "l= [%d] fpixel[2]= [%ld]\n", 
		        l, fpixel[2]);
                    fflush (fp_debug);
	        }
            }

	    if (fits_read_pix (infptr, TDOUBLE, fpixel, nelements, &nan,
                fitsbuf, &nullcnt, &istatus)) {
	        break;
	    }
            
	    if (j == 10) {
	        if ((debugfile1) && (fp_debug != (FILE *)NULL)) {
                    for (i=0; i<hdr.ns; i++) {
	                fprintf (fp_debug, "j= [%d] i= [%d] fitsbuf= [%lf]\n",
	                    j, i, fitsbuf[i]);
	                fprintf (fp_debug, "fitsbuf/nplaneave= [%lf]\n",
	                    fitsbuf[i]/nplaneave);
		    }
                    fflush (fp_debug);
	        }
            }         

/*
    Copy data to imbuff for plane averaging
*/
            jj = hdr.ns*j;
	    if ((debugfile1) && (fp_debug != (FILE *)NULL)) {
	        fprintf (fp_debug, "jj= [%d]\n", jj);
                fflush (fp_debug);
	    }
	        
            for (i=0; i<hdr.ns; i++) {
		imbuff[jj+i] += fitsbuf[i]/nplaneave; 
            }         
 
            if (j == 10) {
	        if ((debugfile1) && (fp_debug != (FILE *)NULL)) {
	        
                    for (i=0; i<hdr.ns; i++) {
	                fprintf (fp_debug, "j= [%d] i= [%d] imbuff= [%lf]\n",
	                    j, i, imbuff[jj+i]);
		    }
                    fflush (fp_debug);
	        }
            }         
            fpixel[1]++;
        }
    }

/*
    Write averaged image to output FITS file
*/
    fpixelo[0] = 1;
    fpixelo[1] = 1;
    fpixelo[2] = 1;
    fpixelo[3] = 1;
    
    for (j=0; j<hdr.nl; j++) {

        jj = hdr.ns*j;
        for (i=0; i<hdr.ns; i++) {
	    fitsbuf[i] = imbuff[jj+i]; 
        }
            
	if (j == 10) {
	    if ((debugfile1) && (fp_debug != (FILE *)NULL)) {
	        
                for (i=0; i<hdr.ns; i++) {
	            fprintf (fp_debug, "j= [%d] i= [%d] fitsbuf= [%lf]\n", 
		        j, i, fitsbuf[i]);
		}
                fflush (fp_debug);
	    }
        }         

        
	if (fits_write_pix (outfptr, TDOUBLE, fpixelo, nelements,
			 (void *)fitsbuf, &istatus)) {

            sprintf (errmsg, "fits write error: l= [%d]\n", l);
            return (-1);
        }

        fpixelo[1]++;
    }   


    istatus = 0;
    if (fits_close_file (infptr, &istatus)) {
        sprintf (errmsg, "Failed to close cubepath [%s]\n", cubepath);
        return (-1); 
    }
    
    istatus = 0;
    if (fits_close_file (outfptr, &istatus)) {
        sprintf (errmsg, "Failed to close impath [%s]\n", impath);
        return (-1); 
    }

    *splaneave = splane;
    *eplaneave = eplane;

    return (0);
}
Exemplo n.º 26
0
  int understands_wmap( KConfig*, const QString& filename )
  {
    fitsfile* ffits;
    int       iStatus = 0;
    int       iRetVal = 0;

    //
    // determine if it is a WMAP file...
    //
    if( fits_open_file( &ffits, filename.ascii( ), READONLY, &iStatus ) == 0 )
    {
      int iNumHeaderDataUnits;

      if( fits_get_num_hdus( ffits, &iNumHeaderDataUnits, &iStatus ) == 0 )
      {
        if( iNumHeaderDataUnits == 6 )
        {
          char  value[FLEN_VALUE];
          char  comment[FLEN_COMMENT];
          int   iHDUType;
          int   iColNum;
          int   i;
          int   j;

          for( i=0; i<iNumKeywords; ++i )
          {
            if( iStatus == 0 )
            {
              fits_read_keyword( ffits, keywords[i], value, comment, &iStatus );
            }
            else  
            {
              break;
            }
          }

          if( iStatus == 0 )
          {
            char **entries = metaDataHeaders;
            int iNumEntries = iNumMetaDataHeaders;

            for( i=0; i<iNumHeaderDataUnits-1; i++ )
            {
              switch (i)
              {
                case 0:
                  iNumEntries = iNumMetaDataHeaders;
                  entries = metaDataHeaders;
                  break;
                case 1:
                  iNumEntries = iNumScienceDataHeaders;
                  entries = scienceDataHeaders;
                  break;
                case 2:
                  iNumEntries = iNumAIHKDataHeaders;
                  entries = AIHKDataHeaders;
                  break;
                case 3:
                  iNumEntries = iNumDIHKDataHeaders;
                  entries = DIHKDataHeaders;
                  break;
                case 4:
                  iNumEntries = iNumLOSDataHeaders;
                  entries = LOSDataHeaders;
                  break;
                default:
                  iNumEntries = iNumMetaDataHeaders;
                  entries = metaDataHeaders;
                  break;
              }

              fits_movrel_hdu( ffits, 1, &iHDUType, &iStatus);
              if( iStatus == 0 && iHDUType == BINARY_TBL )
              {
                for( j=0; j<iNumEntries; ++j )
                {
                  if( iStatus == 0 )
                  {
                    fits_get_colnum( ffits, 0, entries[j], &iColNum, &iStatus );
                    if( strchr( entries[j], '#' ) != 0L &&  iStatus == COL_NOT_UNIQUE )
                    {
                      iStatus = 0;
                    }
                  }
                  else  
                  {
                    break;
                  }
                }
              }
            }
          }

          if( iStatus == 0 )
          {
            iRetVal = 99;
          }
        }
      }

      iStatus = 0;

      fits_close_file( ffits, &iStatus );
    }
    else
    {
      //
      // failed to open the file, so we can't understand it...
      //
    }

    return iRetVal;
  }
Exemplo n.º 27
0
/* Print all the extension informations. */
void
fits_print_extension_info(struct fitsparams *p)
{
  uint16_t *ui16;
  fitsfile *fptr;
  gal_data_t *cols=NULL, *tmp;
  char **tstra, **estra, **sstra;
  size_t i, numext, *dsize, ndim;
  int j, nc, numhdu, hdutype, status=0, type;
  char *msg, *tstr=NULL, sstr[1000], extname[FLEN_VALUE];


  /* Open the FITS file and read the first extension type, upon moving to
     the next extension, we will read its type, so for the first we will
     need to do it explicitly. */
  fptr=gal_fits_hdu_open(p->filename, "0", READONLY);
  if (fits_get_hdu_type(fptr, &hdutype, &status) )
    gal_fits_io_error(status, "reading first extension");


  /* Get the number of HDUs. */
  if( fits_get_num_hdus(fptr, &numhdu, &status) )
    gal_fits_io_error(status, "finding number of HDUs");
  numext=numhdu;


  /* Allocate all the columns (in reverse order, since this is a simple
     linked list). */
  gal_list_data_add_alloc(&cols, NULL, GAL_TYPE_STRING, 1, &numext, NULL, 1,
                          p->cp.minmapsize, "HDU_SIZE", "name", "Size of "
                          "image or table number of rows and columns.");
  gal_list_data_add_alloc(&cols, NULL, GAL_TYPE_STRING, 1, &numext, NULL, 1,
                          p->cp.minmapsize, "HDU_TYPE", "name", "Image "
                          "data type or `table' format (ASCII or binary).");
  gal_list_data_add_alloc(&cols, NULL, GAL_TYPE_STRING, 1, &numext, NULL, 1,
                          p->cp.minmapsize, "EXTNAME", "name",
                          "Extension name of this HDU (EXTNAME in FITS).");
  gal_list_data_add_alloc(&cols, NULL, GAL_TYPE_UINT16, 1, &numext, NULL, 1,
                          p->cp.minmapsize, "HDU_INDEX", "count", "Index "
                          "(starting from zero) of each HDU (extension).");


  /* Keep pointers to the array of each column for easy writing. */
  ui16  = cols->array;
  estra = cols->next->array;
  tstra = cols->next->next->array;
  sstra = cols->next->next->next->array;

  cols->next->disp_width=15;
  cols->next->next->disp_width=15;


  /* Fill in each column. */
  for(i=0;i<numext;++i)
    {
      /* Work based on the type of the extension. */
      switch(hdutype)
        {
        case IMAGE_HDU:
          gal_fits_img_info(fptr, &type, &ndim, &dsize, NULL, NULL);
          tstr=gal_type_name(type , 1);
          break;

        case ASCII_TBL:
        case BINARY_TBL:
          ndim=2;
          tstr = hdutype==ASCII_TBL ? "table_ascii" : "table_binary";
          dsize=gal_data_malloc_array(GAL_TYPE_SIZE_T, 2, __func__, "dsize");
          gal_fits_tab_size(fptr, dsize+1, dsize);
          break;

        default:
          error(EXIT_FAILURE, 0, "%s: a bug! the `hdutype' code %d not "
                "recognized", __func__, hdutype);
        }


      /* Read the extension name*/
      fits_read_keyword(fptr, "EXTNAME", extname, NULL, &status);
      switch(status)
        {
        case 0:
          gal_fits_key_clean_str_value(extname);
          break;

        case KEY_NO_EXIST:
          sprintf(extname, "%s", GAL_BLANK_STRING);
          status=0;
          break;

        default:
          gal_fits_io_error(status, "reading EXTNAME keyword");
        }
      status=0;


      /* Write the size into a string. `sprintf' returns the number of
         written characters (excluding the `\0'). So for each dimension's
         size that is written, we add to `nc' (the number of
         characters). Note that FITS allows blank extensions, in those
         cases, return "0". */
      if(ndim>0)
        {
          nc=0;
          for(j=ndim-1;j>=0;--j)
            nc += sprintf(sstr+nc, "%zux", dsize[j]);
          sstr[nc-1]='\0';
          free(dsize);
        }
      else
        {
          sstr[0]='0';
          sstr[1]='\0';
        }


      /* Write the strings into the columns. */
      j=0;
      for(tmp=cols; tmp!=NULL; tmp=tmp->next)
        {
          switch(j)
            {
            case 0: ui16[i]=i;                                    break;
            case 1: gal_checkset_allocate_copy(extname, estra+i); break;
            case 2: gal_checkset_allocate_copy(tstr, tstra+i);    break;
            case 3: gal_checkset_allocate_copy(sstr, sstra+i);    break;
            }
          ++j;
        }


      /* Move to the next extension if we aren't on the last extension. */
      if( i!=numext-1 && fits_movrel_hdu(fptr, 1, &hdutype, &status) )
        {
          asprintf(&msg, "moving to hdu %zu", i+1);
          gal_fits_io_error(status, msg);
        }
    }


  /* Print the resutls. */
  if(!p->cp.quiet)
    {
      printf("%s\nRun on %s-----\n", PROGRAM_STRING, ctime(&p->rawtime));
      printf("HDU (extension) information: `%s'.\n", p->filename);
      printf(" Column 1: Index (counting from 0, usable with `--hdu').\n");
      printf(" Column 2: Name (`EXTNAME' in FITS standard, usable with "
             "`--hdu').\n");
      printf(" Column 3: Image data type or `table' format (ASCII or "
             "binary).\n");
      printf(" Column 4: Size of data in HDU.\n");
      printf("-----\n");
    }
  gal_table_write(cols, NULL, GAL_TABLE_FORMAT_TXT, NULL, NULL);
  gal_list_data_free(cols);
}
Exemplo n.º 28
0
int get_header(fitsfile *fptr, struct uvf_header *header)
{
  int status = 0;
  int error;
  int i, k, hdunum, hdutype, bitpix, naxis, group;
  long pcount, gcount, naxes[MAX_DIM];
  char extname[68];
  int extver;
  char object[FLEN_VALUE];
  char telescop[FLEN_VALUE];
  char instrume[FLEN_VALUE];
  char ctype[FLEN_VALUE];
  char datobs[FLEN_VALUE], bunit[FLEN_VALUE], radecsys[FLEN_VALUE];
  char keyctype[FLEN_KEYWORD], keycrval[FLEN_KEYWORD];
  char keycdelt[FLEN_KEYWORD], keycrpix[FLEN_KEYWORD];
  char observer[FLEN_KEYWORD];
  double crval, cdelt, crpix;
  double equinox, obsra, obsdec, ra, dec, freq, bw;
  double min_date, max_date;
  int stokes[MAX_STOKES], nstokes, delta_stokes;
  int nc, nif, nval;
  struct uvf_sample sample;

  /* Read the standard header keywords */

  fits_read_imghdr(fptr, MAX_DIM, NULL, &bitpix, &naxis,
		   naxes, &pcount, &gcount, NULL, &status);
  fprintf(stderr, "  bitpix = %d, gcount=%ld\n", bitpix, gcount);
  fits_report_error(stderr, status);

  /* Check for UVF */

  if (status || gcount <= 1  || naxes[0] != 0) {
    fprintf(stderr, "This is not UV-FITS file\n");
    return 1;
  }

  /* Look for the keywords that we know about */

  fits_read_key(fptr, TSTRING, "OBJECT",   object,   NULL, &status);
  if (status == 202) {status = 0; object[0] = '\0';}
  fits_read_key(fptr, TSTRING, "TELESCOP", telescop, NULL, &status);
  if (status == 202) {status = 0; telescop[0] = '\0';}
  fits_read_key(fptr, TSTRING, "INSTRUME", instrume, NULL, &status);
  if (status == 202) {status = 0; instrume[0] = '\0';}
  fits_read_key(fptr, TSTRING, "DATE-OBS", datobs,   NULL, &status);
  if (status == 202) {status = 0; datobs[0] = '\0';}
  fits_read_key(fptr, TSTRING, "BUNIT",    bunit,    NULL, &status);
  if (status == 202) {status = 0; bunit[0] = '\0';}
  fits_read_key(fptr, TSTRING, "RADECSYS", radecsys, NULL, &status);
  if (status == 202) {status = 0; radecsys[0] = '\0';}
  fits_read_key(fptr, TSTRING, "OBSERVER", observer, NULL, &status);
  if (status == 202) {status = 0; observer[0] = '\0';}
  fits_read_key(fptr, TDOUBLE, "EQUINOX",  &equinox, NULL, &status);
  if (status == 202) { /* EQUINOX not found; use EPOCH */
    status = 0;
    /* fprintf(stderr, "Warning: EQUINOX keyword missing\n"); */
    fits_read_key(fptr, TDOUBLE, "EPOCH",  &equinox, NULL, &status);
  }
  fits_read_key(fptr, TDOUBLE, "OBSRA",  &obsra, NULL, &status);
  if (status == 202) {status = 0; obsra = 0.0;}
  fits_read_key(fptr, TDOUBLE, "OBSDEC", &obsdec, NULL, &status);
  if (status == 202) {status = 0; obsdec = 0.0;}
  fprintf(stderr, "  %s,%s,%s,%s,%s,%s,%s,%.2f,%s,%s\n", 
	  object, telescop, instrume, observer, datobs, bunit, radecsys,
	  equinox, ra_string(obsra*RPDEG), dec_string(obsdec*RPDEG));

  /* Look at the axis descriptions */

  error = 0;
  nc = 0;
  nstokes = 0;
  nif = 0;
  ra = dec = freq = bw = 0.0;
  stokes[0] = 0;
  delta_stokes = 0;
  fprintf(stderr, "  Axes (%d): ", naxis-1);
  for (i=1; i<naxis; i++) {
    status = 0;
    fits_make_keyn("CTYPE", i+1, keyctype, &status);
    fits_make_keyn("CRVAL", i+1, keycrval, &status);
    fits_make_keyn("CDELT", i+1, keycdelt, &status);
    fits_make_keyn("CRPIX", i+1, keycrpix, &status);
    fits_read_key(fptr, TSTRING, keyctype, ctype, NULL, &status);
    fits_read_key(fptr, TDOUBLE, keycrval, &crval, NULL, &status);
    fits_read_key(fptr, TDOUBLE, keycdelt, &cdelt, NULL, &status);
    fits_read_key(fptr, TDOUBLE, keycrpix, &crpix, NULL, &status);
    if (status)
      fits_report_error(stderr, status);
    if (i>1) fprintf(stderr, ",");
    fprintf(stderr, "%s(%ld)", ctype, naxes[i]);
    if (strcmp(ctype, "RA") == 0) {
      ra = crval;
      error += (naxes[i] != 1);
    } else if (strcmp(ctype, "DEC") == 0) {
      dec = crval;
      error += (naxes[i] != 1);
    } else if (strcmp(ctype, "COMPLEX") == 0) {
      nc = naxes[i];
      error += (nc != 3);
      error += (crval != 1.0);
    } else if (strcmp(ctype, "STOKES") == 0) {
      nstokes = naxes[i];
      error += (nstokes < 1 || nstokes > MAX_STOKES);
      delta_stokes = cdelt;
      for (k=0; k < MAX_STOKES; k++) {
	stokes[k] = crval + (1+k-crpix)*cdelt;
      }
      error += (nc == 0); /* COMPLEX must be an earlier axis than STOKES */
    } else if (strcmp(ctype, "FREQ") == 0) {
      freq = crval;
      bw = cdelt;
      error += (naxes[i] != 1);
    } else if (strcmp(ctype, "IF") == 0) {
      nif = naxes[i];
      error += (nif < 1);
      error += (crval != 1.0);
      error += (nstokes == 0); /* STOKES must be an earlier axis than IF */
      error += (nc == 0); /* COMPLEX must be an earlier axis than IF */
    } else {
      error += 1;
    }
  }
  fprintf(stderr, "\n");
  if (error > 0) {
    fprintf(stderr, "This is not an acceptable UV-FITS file\n");
    return 1;
  }
  fprintf(stderr, "  RA=%s, Dec=%s, Stokes=",
	  ra_string(ra*RPDEG), dec_string(dec*RPDEG));
  for (k = 0; k < nstokes; k++)
    fprintf(stderr,"%s,", stokes_label(stokes[k]));
  fprintf(stderr, " Freq=%.6g, BW=%.6g\n", freq, bw);
  nval = nc*nif; /* Number of data values at each uv point */

  /* Look at the parameter descriptions */

  header->index_u = -1;
  header->index_v = -1;
  header->index_w = -1;
  header->index_baseline = -1;
  header->index_date1 = -1;
  header->index_date2 = -1;
  header->index_inttim = -1;
  fprintf(stderr, "  Parameters (%ld): ", pcount);
  for (i=0; i<pcount; i++) {
    status = 0;
    fits_make_keyn("PTYPE", i+1, keyctype, &status);
    fits_read_key(fptr, TSTRING, keyctype, ctype, NULL, &status);
    fits_make_keyn("PSCAL", i+1, keyctype, &status);
    fits_read_key(fptr, TDOUBLE, keyctype, &header->pscal[i], NULL, &status);
    fits_make_keyn("PZERO", i+1, keyctype, &status);
    fits_read_key(fptr, TDOUBLE, keyctype, &header->pzero[i], NULL, &status);
    if (status)
      fits_report_error(stderr, status);
    if (i>0) fprintf(stderr, ",");
    fprintf(stderr, "%s", ctype);
    if (strcmp("UU---SIN", ctype) == 0 ||
	strcmp("UU",       ctype) == 0)
      header->index_u = i;
    else if (strcmp("VV---SIN", ctype) == 0 ||
	     strcmp("VV",       ctype) == 0)
      header->index_v = i;
    else if (strcmp("WW---SIN", ctype) == 0 ||
	     strcmp("WW",       ctype) == 0)
      header->index_w = i;
    else if (strcmp("BASELINE", ctype) == 0)
      header->index_baseline = i;
    else if (strcmp("INTTIM", ctype) == 0)
      header->index_inttim = i; /* optional */
    else if (strcmp("DATE", ctype) == 0) {
      if (header->index_date1 == -1)
	header->index_date1 = i;
      else
	header->index_date2 = i;
    } else {
      fprintf(stderr, "\nIgnoring unknown parameter \"%s\"\n", ctype);
    }      
  }
  fprintf(stderr, "\n");

  if (header->index_u < 0 || header->index_v < 0 || header->index_w < 0 ||
      header->index_baseline < 0 || header->index_date1 < 0) {
    fprintf(stderr, "A required parameter is missing\n");
    return 1;
  }

  if (pcount > MAX_PAR) {
    fprintf(stderr, "Too many group parameters in UVF file\n");
    return 1;
  }
  if (DEBUG) {
    for (i=0; i < pcount; i++)
      fprintf(stderr,"%g %g\n", header->pscal[i], header->pzero[i]);
  }

  /* Save header */

  strcpy(header->object, object);
  strcpy(header->telescop, telescop);
  strcpy(header->instrume, instrume);
  strcpy(header->bunit, bunit);
  strcpy(header->radecsys, radecsys);
  strcpy(header->observer, observer);
  header->equinox = equinox;
  header->obsra = obsra;
  header->obsdec = obsdec;
  header->ra = ra;
  header->dec = dec;
  header->freq = freq;
  header->bw = bw;
  header->nstokes = nstokes;
  header->delta_stokes = delta_stokes;
  for (k = 0; k < nstokes; k++)
    header->stokes[k] = stokes[k];
  header->nif = nif;
  header->nchan = nif*nstokes;
  header->nsamp = gcount;
  header->pcount = pcount;
  header->n_antennas = 0;

  /* Read the data to find the time range */

  max_date = 0.0;
  min_date = 1e20;
  for (group=1; group <= gcount; group++) {
    get_sample(fptr, header, group, &sample); 
    if (sample.date < min_date) min_date = sample.date;
    if (sample.date > max_date) max_date = sample.date;
  }
  header->start_jd = min_date;
  header->end_jd = max_date;
  fprintf(stderr, "  Time range: MJD %.8f to %.8f\n", min_date, max_date);

  /* Find the extensions */

  fits_get_num_hdus(fptr, &hdunum, &status);
  for (i=1; i < hdunum; i++) {
    fits_movabs_hdu(fptr, i+1, &hdutype, &status);
    if (hdutype == BINARY_TBL || hdutype == ASCII_TBL) {
      fits_read_key(fptr, TSTRING, "EXTNAME", extname, NULL, &status);
      fits_read_key(fptr, TINT, "EXTVER", &extver, NULL, &status);
      fprintf(stderr, "  Extension %d is %s version %d (%s table)\n", i,
	      extname, extver, hdutype == BINARY_TBL ? "binary" : "ascii");
      if (hdutype == BINARY_TBL && strcmp(extname, "AIPS AN") == 0)
	get_antable(fptr, i+1, header);
      if (hdutype == BINARY_TBL && strcmp(extname, "AIPS FQ") == 0)
	get_fqtable(fptr, i+1, header);
    } else {
      fprintf(stderr, "  Skipping unknown extension of type %d\n", hdutype);
    }
  }

  return status ? 1 : 0;
}