Example #1
0
int fitstable_close(fitstable_t* tab) {
    int i;
    int rtn = 0;
    if (!tab) return 0;
	if (is_writing(tab)) {
        if (fclose(tab->fid)) {
            SYSERROR("Failed to close output file %s", tab->fn);
            rtn = -1;
        }
    }
	if (tab->anq) {
		anqfits_close(tab->anq);
	}
	if (tab->readfid) {
		fclose(tab->readfid);
	}
    if (tab->primheader)
        qfits_header_destroy(tab->primheader);
    if (tab->header)
        qfits_header_destroy(tab->header);
    if (tab->table)
        qfits_table_close(tab->table);
    free(tab->fn);
    for (i=0; i<ncols(tab); i++) {
        fitscol_t* col = getcol(tab, i);
        free(col->colname);
        free(col->units);
    }
    bl_free(tab->cols);
    if (tab->br) {
        buffered_read_free(tab->br);
        free(tab->br);
    }
	if (tab->rows) {
		bl_free(tab->rows);
	}
	if (tab->extensions) {
		for (i=0; i<bl_size(tab->extensions); i++) {
			fitsext_t* ext = bl_access(tab->extensions, i);
			if (ext->rows != tab->rows)
				bl_free(ext->rows);
			if (ext->header != tab->header)
				qfits_header_destroy(ext->header);
			if (ext->table != tab->table)
				qfits_table_close(ext->table);
		}
		bl_free(tab->extensions);
	}
    free(tab);
    return rtn;
}
Example #2
0
int main(int argc, char** args) {
	char* outfn = NULL;
	char* infn = NULL;
    int ext;
	int c;
    int loglvl = LOG_MSG;
    qfits_header* hdr;
    sip_t sip;

    while ((c = getopt(argc, args, OPTIONS)) != -1) {
        switch (c) {
		case '?':
        case 'h':
			print_help(args[0]);
			exit(0);
        case 'v':
            loglvl++;
            break;
        }
    }

    log_init(loglvl);

    if (optind != argc-3) {
        print_help(args[0]);
        exit(-1);
    }

    infn = args[optind+0];
    ext = atoi(args[optind+1]);
    outfn = args[optind+2];

    logmsg("Reading extension %i from file \"%s\"\n", ext, infn);
    hdr = anqfits_get_header2(infn, ext);
    if (!hdr) {
        ERROR("Failed to read header from extension %i of file \"%s\"\n", ext, infn);
        exit(-1);
    }

    if (!sip_read_header(hdr, &sip)) {
        ERROR("Failed to read SIP header.\n");
        exit(-1);
    }

    if (sip.a_order > 0) {
        logmsg("Got SIP header.\n");
    } else {
        logmsg("Got TAN header.\n");
    }

    logmsg("Writing to file \"%s\"\n", outfn);
    if (sip_write_to_file(&sip, outfn)) {
        ERROR("Failed to write SIP header to file \"%s\".\n", outfn);
        exit(-1);
    }

    qfits_header_destroy(hdr);

    return 0;
}
Example #3
0
int test_qfitsheader_browse(char * filename)
{
    qfits_header    *    qh ;
    char key[80], val[80], com[80] ;
    int     i ;
    int  err ;

    say("-----> Header browsing test");
    /* Read header from source */
    say("Reading header from file");
    qh = qfits_header_read(filename);
    if (qh==NULL) {
        fail("cannot read test file");
        return 1 ;
    }

    err=0 ;
    for (i=0 ; i<qh->n ; i++) {
        if (qfits_header_getitem(qh, i, key, val, com, NULL)!=0) {
            fail("cannot read header item");
            err++ ;
        }
    }
    qfits_header_destroy(qh);
    return err ;
}
Example #4
0
int test_qfits_header_sort(void)
{
    qfits_header    *    qh ;
    
    /* Create header */
    qh = qfits_header_new();
    qfits_header_append(qh, "EXTEND", "value", "comment", NULL);
    qfits_header_append(qh, "COMMENT", "value", "comment", NULL);
    qfits_header_append(qh, "TFORM", "value", "comment", NULL);
    qfits_header_append(qh, "BITPIX", "value", "comment", NULL);
    qfits_header_append(qh, "NAXIS", "value", "comment", NULL);
    qfits_header_append(qh, "NAXIS2", "value", "comment", NULL);
    qfits_header_append(qh, "NAXIS1", "value", "comment", NULL);

    /* Dump the header */
    qfits_header_dump(qh, NULL) ;

    /* Sort the header */
    qfits_header_sort(&qh) ;

    /* Dump the header */
    qfits_header_dump(qh, NULL) ;
    
    /* Destroy the header */
    qfits_header_destroy(qh) ;
    return 0 ;
}
Example #5
0
int codetree_close(codetree_t* s) {
	if (!s) return 0;
	if (s->inverse_perm)
		free(s->inverse_perm);
	if (s->header)
		qfits_header_destroy(s->header);
	if (s->tree)
		kdtree_fits_close(s->tree);
	free(s);
	return 0;
}
Example #6
0
// Called just before starting to write a new field.
int fitstable_new_table(fitstable_t* t) {
    if (t->table) {
        qfits_table_close(t->table);
    }
    fitstable_create_table(t);
    if (t->header) {
        qfits_header_destroy(t->header);
    }
    t->header = qfits_table_ext_header_default(t->table);
    return 0;
}
Example #7
0
int tan_write_to(const tan_t* tan, FILE* fid) {
	qfits_header* hdr;
	int res;
	hdr = tan_create_header(tan);
	if (!hdr) {
		ERROR("Failed to create FITS header from WCS");
		return -1;
	}
	res = qfits_header_dump(hdr, fid);
	qfits_header_destroy(hdr);
	return res;
}
int fits_guess_scale(const char* infn,
                     sl** p_methods, dl** p_scales) {
	qfits_header* hdr;

	hdr = anqfits_get_header2(infn, 0);
	if (!hdr) {
		ERROR("Failed to read FITS header");
        return -1;
	}
    fits_guess_scale_hdr(hdr, p_methods, p_scales);
    qfits_header_destroy(hdr);
    return 0;
}
Example #9
0
int sip_write_to(const sip_t* sip, FILE* fid) {
	qfits_header* hdr;
	int res;
	if ((sip->a_order == 0) && (sip->b_order == 0) &&
		(sip->ap_order == 0) && (sip->bp_order == 0))
		return tan_write_to(&(sip->wcstan), fid);
	hdr = sip_create_header(sip);
	if (!hdr) {
		ERROR("Failed to create FITS header from WCS");
		return -1;
	}
	res = qfits_header_dump(hdr, fid);
	qfits_header_destroy(hdr);
	return res;
}
Example #10
0
sip_t* sip_from_string(const char* str, int slen, sip_t* dest) {
	qfits_header* hdr;
	sip_t* rtn;
	if (slen == 0) {
		slen = strlen(str);
	}
	hdr = qfits_header_read_hdr_string((const unsigned char*)str, slen);
	if (!hdr) {
		ERROR("Failed to parse a FITS header from the given string");
		return NULL;
	}
	rtn = sip_read_header(hdr, dest);
	qfits_header_destroy(hdr);
	return rtn;
}
Example #11
0
int scamp_write_field(const qfits_header* imageheader,
                      const sip_t* wcs,
                      const starxy_t* xy,
                      const char* filename) {
    scamp_cat_t* scamp;
    qfits_header* hdr;
    int i;

    if (!imageheader)
        hdr = qfits_table_prim_header_default();
    else
        hdr = qfits_header_copy(imageheader);

    sip_add_to_header(hdr, wcs);

    scamp = scamp_catalog_open_for_writing(filename, FALSE);
    if (!scamp) {
        return -1;
    }

    if (scamp_catalog_write_field_header(scamp, hdr)) {
        return -1;
    }
    qfits_header_destroy(hdr);

    for (i=0; i<starxy_n(xy); i++) {
        scamp_obj_t obj;
        obj.x = starxy_getx(xy, i);
        obj.y = starxy_gety(xy, i);
        obj.err_a = 1.0;
        obj.err_b = 1.0;
        obj.err_theta = 0.0;
        if (xy->flux)
            obj.flux = xy->flux[i];
        else
            obj.flux = 1000.0;
        obj.err_flux = 1.0;
        obj.flags = 0;
        if (scamp_catalog_write_object(scamp, &obj)) {
            return -1;
        }
    }

    if (scamp_catalog_close(scamp)) {
        return -1;
    }
    return 0;
}
Example #12
0
int fitstable_open_extension(fitstable_t* tab, int ext) {
	if (in_memory(tab)) {
		fitsext_t* theext;
		if (ext > bl_size(tab->extensions)) {
			ERROR("Table has only %zu extensions, but you requested #%i",
				  bl_size(tab->extensions), ext);
			return -1;
		}
		theext = bl_access(tab->extensions, ext-1);
		tab->table = theext->table;
		tab->header = theext->header;
		tab->rows = theext->rows;
		tab->extension = ext;

	} else {
		if (tab->table) {
			qfits_table_close(tab->table);
            tab->table = NULL;
		}

        assert(tab->anq);
        if (ext >= anqfits_n_ext(tab->anq)) {
            ERROR("Requested FITS extension %i in file %s, but there are only %i extensions.\n", ext, tab->fn, anqfits_n_ext(tab->anq));
            return -1;
        }
        tab->table = anqfits_get_table(tab->anq, ext);

		if (!tab->table) {
			ERROR("FITS extension %i in file %s is not a table (or there was an error opening the file)", ext, tab->fn);
			return -1;
		}
		if (tab->header) {
			qfits_header_destroy(tab->header);
		}

        tab->header = anqfits_get_header(tab->anq, ext);
		if (!tab->header) {
			ERROR("Couldn't get header for FITS extension %i in file %s", ext, tab->fn);
			return -1;
		}
		tab->extension = ext;
	}
    return 0;
}
Example #13
0
/*
 uint64_t startree_get_starid(const startree_t* s, int ind) {
 if (!s->starids)
 return 0;
 return s->starids[ind];
 }
 */
int startree_close(startree_t* s) {
	if (!s) return 0;
	if (s->inverse_perm)
		free(s->inverse_perm);
 	if (s->header)
		qfits_header_destroy(s->header);
    if (s->tree) {
        if (s->writing) {
            kdtree_free(s->tree);
			free(s->sweep);
		}
        else
            kdtree_fits_close(s->tree);
    }
	if (s->tagalong)
		fitstable_close(s->tagalong);
	free(s);
	return 0;
}
Example #14
0
static void* read_header_file(const char* fn, int ext, anbool only, void* dest,
							  void* (*readfunc)(const qfits_header*, void*)) {
	qfits_header* hdr;
	void* result;
	if (only) {
	  hdr = anqfits_get_header_only(fn, ext);
	} else {
	  hdr = anqfits_get_header2(fn, ext);
	}
	if (!hdr) {
		ERROR("Failed to read FITS header from file \"%s\" extension %i", fn, ext);
		return NULL;
	}
	result = readfunc(hdr, dest);
	if (!result) {
		ERROR("Failed to parse WCS header from file \"%s\" extension %i", fn, ext);
	}
	qfits_header_destroy(hdr);
	return result;
}
Example #15
0
void fitstable_next_extension(fitstable_t* tab) {
	if (is_writing(tab))
        fits_pad_file(tab->fid);

	if (in_memory(tab)) {
		fitsext_t ext;
		if (!tab->table)
			return;
		// update NAXIS2
		fitstable_fix_header(tab);
		ext.table = tab->table;
		ext.header = tab->header;
		ext.rows = tab->rows;
		bl_append(tab->extensions, &ext);
		tab->rows = NULL;
	} else {
		qfits_table_close(tab->table);
		qfits_header_destroy(tab->header);
	}
    tab->extension++;
    tab->table = NULL;
    tab->header = NULL;
}
Example #16
0
int wcs_pv2sip(const char* wcsinfn, int ext,
			   const char* wcsoutfn,
			   anbool scamp_head_file,
			   double* xy, int Nxy,
			   int imageW, int imageH,
			   anbool forcetan) {
	qfits_header* hdr = NULL;
	double* radec = NULL;
	int rtn = -1;
	tan_t tanwcs;
	double x,y, px,py;
	double xyz[3];

	double* xorig = NULL;
	double* yorig = NULL;
	double* rddist = NULL;
	int i, j;

	//           1  x  y  r x2 xy y2 x3 x2y xy2 y3 r3 x4 x3y x2y2 xy3 y4
	//          x5 x4y x3y2 x2y3 xy4 y5 r5 x6 x5y x4y2, x3y3 x2y4 xy5 y6
	//          x7 x6y x5y2 x4y3 x3y4 x2y5 xy6 y7 r7
	int xp[] = { 0, 1, 0, 0, 2, 1, 0, 3,  2,  1, 0, 0, 4,  3,   2,  1, 0,
				 5,  4,   3,   2,  1, 5, 0, 6,  5,   4,    3,   2,  1, 0,
				 7,  6,   5,   4,   3,   2,  1, 0, 0};
	int yp[] = { 0, 0, 1, 0, 0, 1, 2, 0,  1,  2, 3, 0, 0,  1,   2,  3, 4,
				 0,  1,   2,   3,  4, 0, 0, 0,  1,   2,    3,   4,  5, 6,
				 0,  1,   2,   3,   4,   5,  6, 7, 0};
	int rp[] = { 0, 0, 0, 1, 0, 0, 0, 0,  0,  0, 0, 3, 0,  0,   0,  0, 0,
				 0,  0,   0,   0,  0, 0, 5, 0,  0,   0,    0,   0,  0, 0,
				 0,  0,   0,   0,   0,   0,  0, 0, 7};
	double xpows[8];
	double ypows[8];
	double rpows[8];
	double pv1[40];
	double pv2[40];
	double r;

	if (scamp_head_file) {
		size_t sz = 0;
		char* txt;
		char* prefix;
		int np;
		int nt;
		unsigned char* txthdr;
		sl* lines;
		int i;
		txt = file_get_contents(wcsinfn, &sz, TRUE);
		if (!txt) {
			ERROR("Failed to read file %s", wcsinfn);
			goto bailout;
		}
		lines = sl_split(NULL, txt, "\n");
		prefix =
			"SIMPLE  =                    T / Standard FITS file                             "
			"BITPIX  =                    8 / ASCII or bytes array                           "
			"NAXIS   =                    0 / Minimal header                                 "
			"EXTEND  =                    T / There may be FITS ext                          "
			"WCSAXES =                    2 /                                                ";
		np = strlen(prefix);
		nt = np + FITS_LINESZ * sl_size(lines);
		txthdr = malloc(nt);
		memset(txthdr, ' ', np + FITS_LINESZ * sl_size(lines));
		memcpy(txthdr, prefix, np);
		for (i=0; i<sl_size(lines); i++)
			memcpy(txthdr + np + i*FITS_LINESZ, sl_get(lines, i), strlen(sl_get(lines, i)));
		sl_free2(lines);
		hdr = qfits_header_read_hdr_string(txthdr, nt);
		free(txthdr);
		free(txt);
	} else {
		char* ct;
		hdr = anqfits_get_header2(wcsinfn, ext);

		ct = fits_get_dupstring(hdr, "CTYPE1");
		if ((ct && streq(ct, "RA---TPV")) || forcetan) {
			// http://iraf.noao.edu/projects/ccdmosaic/tpv.html
			logmsg("Replacing CTYPE1 = %s header with RA---TAN\n", ct);
			fits_update_value(hdr, "CTYPE1", "RA---TAN");
		}
		ct = fits_get_dupstring(hdr, "CTYPE2");
		if ((ct && streq(ct, "DEC--TPV")) || forcetan) {
			logmsg("Replacing CTYPE2 = %s header with DEC--TAN\n", ct);
			fits_update_value(hdr, "CTYPE2", "DEC--TAN");
		}
	}
	if (!hdr) {
		ERROR("Failed to read header: file %s, ext %i\n", wcsinfn, ext);
		goto bailout;
	}
	
	tan_read_header(hdr, &tanwcs);

	for (i=0; i<sizeof(pv1)/sizeof(double); i++) {
		char key[10];
		sprintf(key, "PV1_%i", i);
		pv1[i] = qfits_header_getdouble(hdr, key, 0.0);
		sprintf(key, "PV2_%i", i);
		pv2[i] = qfits_header_getdouble(hdr, key, 0.0);
	}

	xorig = malloc(Nxy * sizeof(double));
	yorig = malloc(Nxy * sizeof(double));
	rddist = malloc(2 * Nxy * sizeof(double));

	for (j=0; j<Nxy; j++) {
		xorig[j] = xy[2*j+0];
		yorig[j] = xy[2*j+1];

		tan_pixelxy2iwc(&tanwcs, xorig[j], yorig[j], &x, &y);
		r = sqrt(x*x + y*y);
		xpows[0] = ypows[0] = rpows[0] = 1.0;
		for (i=1; i<sizeof(xpows)/sizeof(double); i++) {
			xpows[i] = xpows[i-1]*x;
			ypows[i] = ypows[i-1]*y;
			rpows[i] = rpows[i-1]*r;
		}
		px = py = 0;
		for (i=0; i<sizeof(xp)/sizeof(int); i++) {
			px += pv1[i] * xpows[xp[i]] * ypows[yp[i]] * rpows[rp[i]];
			py += pv2[i] * ypows[xp[i]] * xpows[yp[i]] * rpows[rp[i]];
		}
		tan_iwc2xyzarr(&tanwcs, px, py, xyz);
		xyzarr2radecdeg(xyz, rddist+2*j, rddist+2*j+1);
	}

	//
	{
		starxy_t sxy;
		tweak_t* t;
		il* imgi;
		il* refi;
		int sip_order = 5;
		int sip_inv_order = 5;

		sxy.N = Nxy;
		sxy.x = xorig;
		sxy.y = yorig;

		imgi = il_new(256);
		refi = il_new(256);
		for (i=0; i<Nxy; i++) {
			il_append(imgi, i);
			il_append(refi, i);
		}

		t = tweak_new();
		t->sip->a_order = t->sip->b_order = sip_order;
		t->sip->ap_order = t->sip->bp_order = sip_inv_order;
		tweak_push_wcs_tan(t, &tanwcs);
		tweak_push_ref_ad_array(t, rddist, Nxy);
		tweak_push_image_xy(t, &sxy);
		tweak_push_correspondence_indices(t, imgi, refi, NULL, NULL);
		tweak_go_to(t, TWEAK_HAS_LINEAR_CD);
		if (imageW)
			t->sip->wcstan.imagew = imageW;
		if (imageH)
			t->sip->wcstan.imageh = imageH;
		sip_write_to_file(t->sip, wcsoutfn);
		tweak_free(t);
	}
	rtn = 0;

 bailout:
	free(xorig);
	free(yorig);
	free(rddist);
	qfits_header_destroy(hdr);
	free(radec);
	return rtn;
}
Example #17
0
// Add FITS keywords
void add_fits_keywords(struct transformation t,char *filename) 
{
  int i,j,k,l,m;
  int naxis1,naxis2,naxis3;
  qfits_header *qh;
  qfitsdumper qd;
  qfitsloader ql;
  char key[FITS_LINESZ+1];
  char val[FITS_LINESZ+1];
  char com[FITS_LINESZ+1];
  char lin[FITS_LINESZ+1];
  FILE *file;
  float *fbuf;

  naxis1=atoi(qfits_query_hdr(filename,"NAXIS1"));
  naxis2=atoi(qfits_query_hdr(filename,"NAXIS2"));
  naxis3=atoi(qfits_query_hdr(filename,"NAXIS3"));

  fbuf=malloc(sizeof(float)*naxis1*naxis2*naxis3);

  // Read header
  qh=qfits_header_read(filename);

  ql.xtnum=0;
  ql.ptype=PTYPE_FLOAT;
  ql.filename=filename;
  for (k=0,l=0;k<naxis3;k++) {
    ql.pnum=k;
    // Initialize load
    if (qfitsloader_init(&ql) != 0) 
      printf("Error initializing data loading\n");

    // Test load
    if (qfits_loadpix(&ql) != 0) 
      printf("Error loading actual data\n");

    for (i=0,m=0;i<naxis1;i++) {
      for (j=0;j<naxis2;j++) {
	fbuf[l]=ql.fbuf[m];
	l++;
	m++;
      }
    }
  }

  qfits_header_add_after(qh,"MJD-OBS","CUNIT2","'deg'"," ",NULL);
  qfits_header_add_after(qh,"MJD-OBS","CUNIT1","'deg'"," ",NULL);
  qfits_header_add_after(qh,"MJD-OBS","CTYPE2","'DEC--TAN'"," ",NULL);
  qfits_header_add_after(qh,"MJD-OBS","CTYPE1","'RA---TAN'"," ",NULL);
  sprintf(val,"%e",t.b[2]/3600.0);
  qfits_header_add_after(qh,"MJD-OBS","CD2_2",val," ",NULL);
  sprintf(val,"%e",t.b[1]/3600.0);
  qfits_header_add_after(qh,"MJD-OBS","CD2_1",val," ",NULL);
  sprintf(val,"%e",t.a[2]/3600.0);
  qfits_header_add_after(qh,"MJD-OBS","CD1_2",val," ",NULL);
  sprintf(val,"%e",t.a[1]/3600.0);
  qfits_header_add_after(qh,"MJD-OBS","CD1_1",val," ",NULL);
  sprintf(val,"%f",t.de0);
  qfits_header_add_after(qh,"MJD-OBS","CRVAL2",val," ",NULL);
  sprintf(val,"%f",t.ra0);
  qfits_header_add_after(qh,"MJD-OBS","CRVAL1",val," ",NULL);
  sprintf(val,"%f",t.y0);
  qfits_header_add_after(qh,"MJD-OBS","CRPIX2",val," ",NULL);
  sprintf(val,"%f",t.x0);
  qfits_header_add_after(qh,"MJD-OBS","CRPIX1",val," ",NULL);

  file=fopen(filename,"w");
  qfits_header_dump(qh,file);
  fclose(file);

  qfits_header_destroy(qh);

  qd.filename=filename;
  qd.npix=naxis1*naxis2*naxis3;
  qd.ptype=PTYPE_FLOAT;
  qd.fbuf=fbuf;
  qd.out_ptype=-32;

  qfits_pixdump(&qd);
  free(fbuf);

  return;
}
Example #18
0
int test_qfitsheader_read(char * filename)
{
    qfits_header    *    qh ;
    char            *    val ;
    int                    err ;
    int                    keytype ;

    err=0 ;
    say("-----> Header reading test");
    /* Read header from source */
    say("Reading header from file");
    qh = qfits_header_read(filename);
    if (qh==NULL) {
        fail("cannot read test file");
        return 1 ;
    }
    say("Querying mandatory keys");
    err += check_key(qh, "SIMPLE", "T");
    err += check_key(qh, "NAXIS", "2");
    err += check_key(qh, "NAXIS1", "11");
    err += check_key(qh, "NAXIS2", "10");
    err += check_key(qh, "BITPIX", "-32");

    say("Querying base keys");
    err += check_key(qh, "KEY01", "value01");
    err += check_key(qh, "KEY02", "2");
    err += check_key(qh, "KEY03", "3.0");
    err += check_key(qh, "KEY04", "4.0 4.2");
    err += check_key(qh, "KEY05", "T");

    say("Checking key types");
    val = qfits_header_getstr(qh, "KEY01");
    keytype = qfits_get_type(val);
    if (keytype!=QFITS_STRING) {
        printf("val=[%s] type is %d\n", val, keytype);
        fail("wrong identified type for KEY01 (string)");
        err++;
    }
    val = qfits_header_getstr(qh, "KEY02");
    keytype = qfits_get_type(val);
    if (keytype!=QFITS_INT) {
        fail("wrong identified type for KEY02 (int)");
        err++;
    }
    val = qfits_header_getstr(qh, "KEY03");
    keytype = qfits_get_type(val);
    if (keytype!=QFITS_FLOAT) {
        fail("wrong identified type for KEY03 (float)");
        err++;
    }
    val = qfits_header_getstr(qh, "KEY04");
    keytype = qfits_get_type(val);
    if (keytype!=QFITS_COMPLEX) {
        fail("wrong identified type for KEY04 (complex)");
        err++;
    }
    val = qfits_header_getstr(qh, "KEY05");
    keytype = qfits_get_type(val);
    if (keytype!=QFITS_BOOLEAN) {
        fail("wrong identified type for KEY05 (boolean)");
        err++;
    }

    say("Querying hierarch keys");
    err += check_key(qh, "HIERARCH ESO PRO A", "0.0");
    err += check_key(qh, "PRO.B", "0.0");
    err += check_key(qh, "pro.c", "0.0");

    err += check_key(qh, "ins.a", "0.0");
    err += check_key(qh, "ins.b", "0.0");
    err += check_key(qh, "ins.c", "0.0");

    err += check_key(qh, "gen.a", "0.0");
    err += check_key(qh, "gen.b", "0.0");
    err += check_key(qh, "gen.c", "0.0");

    err += check_key(qh, "obs.a", "0.0");
    err += check_key(qh, "obs.b", "0.0");
    err += check_key(qh, "obs.c", "0.0");

    err += check_key(qh, "tpl.a", "0.0");
    err += check_key(qh, "tpl.b", "0.0");
    err += check_key(qh, "tpl.c", "0.0");

    err += check_key(qh, "tel.a", "0.0");
    err += check_key(qh, "tel.b", "0.0");
    err += check_key(qh, "tel.c", "0.0");

    err += check_key(qh, "log.a", "0.0");
    err += check_key(qh, "log.b", "0.0");
    err += check_key(qh, "log.c", "0.0");

    err += check_key(qh, "null.a", "0.0");
    err += check_key(qh, "null.b", "0.0");
    err += check_key(qh, "null.c", "0.0");

    say("Removing keys");

    qfits_header_del(qh, "PRO.A");
    qfits_header_del(qh, "pro.b");
    qfits_header_del(qh, "HIERARCH ESO PRO C");

    if (qfits_header_getstr(qh, "HIERARCH ESO PRO A")!=NULL) 
        err ++ ;
    if (qfits_header_getstr(qh, "PRO.B")!=NULL) 
        err ++ ;
    if (qfits_header_getstr(qh, "pro.c")!=NULL) 
        err ++ ;

    say("Modifying keys");

    qfits_header_destroy(qh);
    return err ;
}
int main(int argc, char** args) {
    int argchar;
    kdtree_t* kd;
    int Nleaf = 25;
    char* infn = NULL;
    char* outfn = NULL;
    char* tychofn = NULL;
    char* crossfn = NULL;
	char* progname = args[0];
    FILE* f;

    tycstar_t* tycstars = NULL;
    int Ntyc = 0;

	int exttype  = KDT_EXT_DOUBLE;
	int datatype = KDT_DATA_U32;
	int treetype = KDT_TREE_U32;
	int tt;
	int buildopts = 0;
	int i, N, D;

    dl* ras;
    dl* decs;
    dl* hds;

    fl* mag1s;
    fl* mag2s;
    fl* mag3s;

    int nbad = 0;
    int nox = 0;

    int* hd;
    double* xyz;

    qfits_header* hdr;

    while ((argchar = getopt (argc, args, OPTIONS)) != -1)
        switch (argchar) {
        case 'T':
            tychofn = optarg;
            break;
        case 'X':
            crossfn = optarg;
            break;
        case 'R':
            Nleaf = (int)strtoul(optarg, NULL, 0);
            break;
		case 't':
			treetype = kdtree_kdtype_parse_tree_string(optarg);
			break;
		case 'd':
			datatype = kdtree_kdtype_parse_data_string(optarg);
			break;
		case 'b':
			buildopts |= KD_BUILD_BBOX;
			break;
		case 's':
			buildopts |= KD_BUILD_SPLIT;
			break;
		case 'S':
			buildopts |= KD_BUILD_SPLITDIM;
			break;
        case '?':
            fprintf(stderr, "Unknown option `-%c'.\n", optopt);
        case 'h':
			printHelp(progname);
            return 0;
        default:
            return -1;
        }

    if (optind != argc - 2) {
        printHelp(progname);
        exit(-1);
    }

    infn = args[optind];
    outfn = args[optind+1];

	if (!(buildopts & (KD_BUILD_BBOX | KD_BUILD_SPLIT))) {
		printf("You need bounding-boxes or splitting planes!\n");
		printHelp(progname);
		exit(-1);
	}

    if (tychofn || crossfn) {
        if (!(tychofn && crossfn)) {
            printf("You need both -T <Tycho2> and -X <Crossref> to do cross-referencing.\n");
            exit(-1);
        }
    }

    if (tychofn) {
        int i, N;
        tycho2_fits* tyc;
        FILE* f;
        int nx, nox;
		int lastgrass = 0;

        tyc = tycho2_fits_open(tychofn);
        if (!tyc) {
            ERROR("Failed to open Tycho-2 catalog.");
            exit(-1);
        }
        printf("Reading Tycho-2 catalog...\n");

        N = tycho2_fits_count_entries(tyc);
        tycstars = calloc(N, sizeof(tycstar_t));

        for (i=0; i<N; i++) {
            tycho2_entry* te;
			int grass = (i*80 / N);
			if (grass != lastgrass) {
				printf(".");
				fflush(stdout);
				lastgrass = grass;
			}
			te = tycho2_fits_read_entry(tyc);
            tycstars[i].tyc1 = te->tyc1;
            tycstars[i].tyc2 = te->tyc2;
            tycstars[i].tyc3 = te->tyc3;
            tycstars[i].ra   = te->ra;
            tycstars[i].dec  = te->dec;
            tycstars[i].mag_BT = te->mag_BT;
            tycstars[i].mag_VT = te->mag_VT;
            tycstars[i].mag_HP = te->mag_HP;
        }
        tycho2_fits_close(tyc);

        printf("Sorting...\n");
        qsort(tycstars, N, sizeof(tycstar_t), compare_tycs);
        Ntyc = N;

        f = fopen(crossfn, "rb");
        if (!f) {
            SYSERROR("Failed to open cross-reference file %s", crossfn);
            exit(-1);
        }

        nx = 0;
        nox = 0;
        while (TRUE) {
            char buf[1024];
            int tyc1, tyc2, tyc3, hd, nhd, ntyc;
            char ftyc, sptype0, sptype1, sptype2;
            tycstar_t* s;

            if (!fgets(buf, sizeof(buf), f)) {
                if (ferror(f)) {
                    SYSERROR("Failed to read a line of text from the cross-reference file");
                    exit(-1);
                }
                break;
            }

            if (sscanf(buf, " %d %d %d%c %d %c%c%c %d %d",
                       &tyc1, &tyc2, &tyc3, &ftyc, &hd,
                       &sptype0, &sptype1, &sptype2, &nhd, &ntyc) != 10) {
                ERROR("Failed to parse line: \"%s\"", buf);
            }

            //printf("%i %i %i %i %i %i\n", tyc1, tyc2, tyc3, hd, nhd, ntyc);
            s = find_tycho(tycstars, Ntyc, tyc1, tyc2, tyc3);
            if (!s) {
                ERROR("Failed to find Tycho-2 star %i-%i-%i", tyc1, tyc2, tyc3);
                nox++;
            } else {
                s->hd = hd;
                s->ntyc = ntyc;
            }
            nx++;
        }
        fclose(f);

        printf("Read %i cross-references.\n", nx);
        printf("Failed to find %i cross-referenced Tycho-2 stars.\n", nox);

        printf("Sorting...\n");
        qsort(tycstars, N, sizeof(tycstar_t), compare_hds);
    }

    f = fopen(infn, "rb");
    if (!f) {
        SYSERROR("Failed to open input file %s", infn);
        exit(-1);
    }

    ras = dl_new(1024);
    decs = dl_new(1024);
    hds = il_new(1024);

    mag1s = fl_new(1024);
    mag2s = fl_new(1024);
    mag3s = fl_new(1024);

    printf("Reading HD catalog...\n");
    for (;;) {
        char buf[1024];
        double ra, dec;
        int hd;
        float mag1, mag2, mag3;

        mag1 = mag2 = mag3 = 0.0;

        if (!fgets(buf, sizeof(buf), f)) {
            if (ferror(f)) {
                SYSERROR("Failed to read a line of text from the input file");
                exit(-1);
            }
            break;
        }

        if (buf[0] == '#')
            continue;
        if (buf[0] == '\n')
            continue;

        if (sscanf(buf, " %lf| %lf| %d", &ra, &dec, &hd) < 3) {
            // ignore three invalid lines
            if (nbad > 3) {
                ERROR("Failed to parse line: \"%s\"", buf);
            }
            nbad++;
        } else {

            if (tycstars) {
                tycstar_t* s = find_hd(tycstars, Ntyc, hd);
                if (!s) {
                    //printf("Failed to find cross-ref for HD %i\n", hd);
                    nox++;
                } else {
                    ra = s->ra;
                    dec = s->dec;

                    mag1 = s->mag_VT;
                    mag2 = s->mag_BT;
                    mag3 = s->mag_HP;
                }
            }

            dl_append(ras, ra);
            dl_append(decs, dec);
            il_append(hds, hd);
            fl_append(mag1s, mag1);
            fl_append(mag2s, mag2);
            fl_append(mag3s, mag3);
        }
    }
    fclose(f);

    N = dl_size(ras);
    printf("Read %i entries and %i bad lines.\n", N, nbad);

    if (dl_size(ras) != HD_NENTRIES) {
        printf("WARNING: expected %i Henry Draper catalog entries.\n", HD_NENTRIES);
    }

    if (nox) {
        printf("Found %i HD entries with no cross-reference (expect this to be about 1%%)\n", nox);
    }

    hd = malloc(sizeof(int) * N);
    il_copy(hds, 0, N, hd);
    il_free(hds);
    for (i=0; i<N; i++)
        if (hd[i] != i+1) {
            printf("Line %i is HD %i\n", i+1, hd[i]);
            break;
        }
    // HACK  - don't allocate 'em in the first place...
    free(hd);

    xyz = malloc(sizeof(double) * 3 * N);
    for (i=0; i<N; i++) {
        radecdeg2xyzarr(dl_get(ras, i), dl_get(decs, i), xyz + 3*i);
    }

    dl_free(ras);
    dl_free(decs);

	tt = kdtree_kdtypes_to_treetype(exttype, treetype, datatype);
	D = 3;
	{
		// limits of the kdtree...
        double lo[] = {-1.0, -1.0, -1.0};
        double hi[] = { 1.0,  1.0,  1.0};
        kd = kdtree_new(N, D, Nleaf);
        kdtree_set_limits(kd, lo, hi);
	}
	printf("Building tree...\n");
	kd = kdtree_build(kd, xyz, N, D, Nleaf, tt, buildopts);

    hdr = qfits_header_default();
    qfits_header_add(hdr, "AN_FILE", "HDTREE", "Henry Draper catalog kdtree", NULL);
    BOILERPLATE_ADD_FITS_HEADERS(hdr);
    fits_add_long_history(hdr, "This file was created by the following command-line:");
    fits_add_args(hdr, args, argc);

    if (kdtree_fits_write(kd, outfn, hdr)) {
        ERROR("Failed to write kdtree");
        exit(-1);
    }

    // Write mags as tag-along table.
    {
        fitstable_t* tag;
        tag = fitstable_open_for_appending(outfn);
        if (!tag) {
            ERROR("Failed to open kd-tree file for appending");
            exit(-1);
        }

        fitstable_add_write_column(tag, fitscolumn_float_type(), "MAG_VT", "");
        fitstable_add_write_column(tag, fitscolumn_float_type(), "MAG_BT", "");
        fitstable_add_write_column(tag, fitscolumn_float_type(), "MAG_HP", "");

        if (fitstable_write_header(tag)) {
            ERROR("Failed to write tag-along header");
            exit(-1);
        }

        for (i=0; i<N; i++) {
            fitstable_write_row(tag, fl_get(mag1s, i), fl_get(mag2s, i),
                                fl_get(mag3s, i));
        }
        if (fitstable_fix_header(tag)) {
            ERROR("Failed to fix tag-along header");
            exit(-1);
        }
        if (fitstable_close(tag)) {
            ERROR("Failed to close tag-along data");
            exit(-1);
        }
    }
    fl_free(mag1s);
    fl_free(mag2s);
    fl_free(mag3s);

    printf("Done.\n");

	qfits_header_destroy(hdr);
    free(xyz);
    kdtree_free(kd);
    free(tycstars);

    return 0;
}
Example #20
0
int main(int argc, char** args) {
    int argchar;
	char* infn = NULL;
	char* outfn = NULL;
	unsigned int row;
	int bits;
	FILE* fid = stdin;
	FILE* fout = stdout;
	int loglvl = LOG_MSG;
	char* progname = args[0];
	int bzero = 0;
	int outformat;
	qfits_header* hdr;
	unsigned int plane;
	off_t datastart;
	anbool onepass = FALSE;
	bl* pixcache = NULL;

#if HAVE_NETPBM
	struct pam img;
	tuple * tuplerow;
#else
	void* rowbuf;
#endif
	int W, H, depth, maxval;

    while ((argchar = getopt (argc, args, OPTIONS)) != -1)
        switch (argchar) {
		case '?':
		case 'h':
			printHelp(progname);
			exit(0);
		case 'v':
			loglvl++;
			break;
		case 'q':
			loglvl--;
			break;
		case 'o':
			outfn = optarg;
			break;
		}

	log_init(loglvl);
	log_to(stderr);
	fits_use_error_system();

	if (optind == argc) {
		// ok, stdin to stdout.
	} else if (optind == argc-1) {
		infn = args[optind];
	} else if (optind == argc-2) {
		infn = args[optind];
		outfn = args[optind+1];
	} else {
		printHelp(progname);
		exit(-1);
	}

	if (infn && !streq(infn, "-")) {
		fid = fopen(infn, "rb");
		if (!fid) {
			SYSERROR("Failed to open input file %s", infn);
			exit(-1);
		}
	}
	if (outfn) {
		fout = fopen(outfn, "wb");
		if (!fid) {
			SYSERROR("Failed to open output file %s", outfn);
			exit(-1);
		}
	} else
		outfn = "stdout";

#if HAVE_NETPBM
	pm_init(args[0], 0);
	pnm_readpaminit(fid, &img, 
					// PAM_STRUCT_SIZE isn't defined until Netpbm 10.23 (July 2004)
#if defined(PAM_STRUCT_SIZE)
					PAM_STRUCT_SIZE(tuple_type)
#else
					sizeof(struct pam)
#endif
);
	W = img.width;
	H = img.height;
	depth = img.depth;
	maxval = img.maxval;

	tuplerow = pnm_allocpamrow(&img);
	bits = pm_maxvaltobits(img.maxval); 
	bits = (bits <= 8) ? 8 : 16;

#else // No NETPBM

	if (parse_pnm_header(fid, &W, &H, &depth, &maxval)) {
		ERROR("Failed to parse PNM header from file: %s\n", infn ? infn : "<stdin>");
		exit(-1);
	}
	bits = 8 * maxval_to_bytes(maxval);

	rowbuf = malloc(W * depth * (bits/8));

#endif

	logmsg("Read file %s: %i x %i pixels x %i color(s); maxval %i\n",
		   infn ? infn : "stdin", W, H, depth, maxval);
	if (bits == 8)
		outformat = BPP_8_UNSIGNED;
	else {
		outformat = BPP_16_SIGNED;
		if (maxval >= INT16_MAX)
			bzero = 0x8000;
	}
	logmsg("Using %i-bit output\n", bits);

	hdr = fits_get_header_for_image3(W, H, outformat, depth, NULL);
	if (bzero)
		fits_header_add_int(hdr, "BZERO", bzero, "Number that has been subtracted from pixel values");
	if (qfits_header_dump(hdr, fout)) {
		ERROR("Failed to write FITS header to file %s", outfn);
		exit(-1);
	}
	qfits_header_destroy(hdr);

	datastart = ftello(fid);
	// Figure out if we can seek backward in this input file...
	if ((fid == stdin) ||
		(fseeko(fid, 0, SEEK_SET) ||
		 fseeko(fid, datastart, SEEK_SET)))
		// Nope!
		onepass = TRUE;
	if (onepass && depth > 1) {
		logmsg("Reading in one pass\n");
		pixcache = bl_new(16384, bits/8);
	}

	for (plane=0; plane<depth; plane++) {
		if (plane > 0) {
			if (fseeko(fid, datastart, SEEK_SET)) {
				SYSERROR("Failed to seek back to start of image data");
				exit(-1);
			}
		}
		for (row = 0; row<H; row++) {
			unsigned int column;

#if HAVE_NETPBM
			pnm_readpamrow(&img, tuplerow);
#else
			read_pnm_row(fid, W, depth, maxval, rowbuf);
#endif

			for (column = 0; column<W; column++) {
				int rtn;
				int pixval;

#if HAVE_NETPBM
				pixval = tuplerow[column][plane];
#else
				pixval = (bits == 8 ?
						  ((uint8_t *)rowbuf)[column*depth + plane] :
						  ((uint16_t*)rowbuf)[column*depth + plane]);
#endif
				if (outformat == BPP_8_UNSIGNED)
					rtn = fits_write_data_B(fout, pixval);
				else
					rtn = fits_write_data_I(fout, pixval-bzero, TRUE);
				if (rtn) {
					ERROR("Failed to write FITS pixel");
					exit(-1);
				}
			}
			if (onepass && depth > 1) {
				for (column = 0; column<W; column++) {
					for (plane=1; plane<depth; plane++) {
						int pixval;
#if HAVE_NETPBM
						pixval = tuplerow[column][plane];
#else
						pixval = (bits == 8 ?
								  ((uint8_t *)rowbuf)[column*depth + plane] :
								  ((uint16_t*)rowbuf)[column*depth + plane]);
#endif
						if (outformat == BPP_8_UNSIGNED) {
							uint8_t pix = pixval;
							bl_append(pixcache, &pix);
						} else {
							int16_t pix = pixval - bzero;
							bl_append(pixcache, &pix);
						}
					}
				}
			}
		}
	}
	
#if HAVE_NETPBM
	pnm_freepamrow(tuplerow);
#else
	free(rowbuf);
#endif

	if (pixcache) {
		int i, j;
		int step = (depth - 1);
		logverb("Writing %zu queued pixels\n", bl_size(pixcache));
		for (plane=1; plane<depth; plane++) {
			j = (plane - 1);
			for (i=0; i<(W * H); i++) {
				int rtn;
				if (outformat == BPP_8_UNSIGNED) {
					uint8_t* pix = bl_access(pixcache, j);
					rtn = fits_write_data_B(fout, *pix);
				} else {
					int16_t* pix = bl_access(pixcache, j);
					rtn = fits_write_data_I(fout, *pix, TRUE);
				}
				if (rtn) {
					ERROR("Failed to write FITS pixel");
					exit(-1);
				}
				j += step;
			}
		}
		bl_free(pixcache);
	}

	if (fid != stdin)
		fclose(fid);

	if (fits_pad_file(fout)) {
		ERROR("Failed to pad output file \"%s\"", outfn);
		return -1;
	}

	if (fout != stdout)
		if (fclose(fout)) {
			SYSERROR("Failed to close output file %s", outfn);
			exit(-1);
		}

	return 0;
}
Example #21
0
/*----------------------------------------------------------------------------*/
int qfits_header_sort(qfits_header ** hdr) 
{
    qfits_header    *   sorted;
    keytuple        *   k;
    keytuple        *   kbf;
    keytuple        *   next;
    keytuple        *   last;

    /* Test entries */
    if (hdr == NULL) return -1;
    if (*hdr == NULL) return -1;
    if ((*hdr)->n < 2) return 0;
    
    /* Create the new FITS header */
    sorted = qfits_header_new();

    /* Move the first keytuple to the sorted empty header */
    k = (keytuple*)(*hdr)->first;
    next = k->next;
    sorted->first = sorted->last = k;
    k->next = k->prev = NULL;
    sorted->n = 1;
    
    /* Loop over the other tuples */
    while (next != NULL) {
        k = next;
        next = k->next;

        /* Find k's place in sorted */
        kbf = (keytuple*)sorted->first;
        while (kbf!=NULL) {
            if (k->typ < kbf->typ) break;
            kbf = kbf->next;
        }
        
        /* Hook k into sorted list */
        if (kbf == NULL) {
            /* k is last in sorted */
            last = sorted->last;
            sorted->last = k;
            k->next = NULL;
            k->prev = last;
            last->next = k;
        } else {
            /* k goes just before kbf */
            k->next = kbf;
            k->prev = kbf->prev;
            if (kbf->prev != NULL) (kbf->prev)->next = k;
            else sorted->first = k;
            kbf->prev = k;
        }
        (sorted->n) ++;
    }

    /* Replace the input header by the sorted one */
    (*hdr)->first = (*hdr)->last = NULL;
    qfits_header_destroy(*hdr);
    *hdr = sorted;
    
    return 0;
}
Example #22
0
int new_wcs(const char* infn, int extension,
            const char* wcsfn, const char* outfn,
            anbool copydata) {
    FILE* outfid = NULL;
    int i, N;
    int e;
    regex_t re1[NE1];
    regex_t re2[NE2];
    qfits_header *inhdr=NULL, *outhdr=NULL, *wcshdr=NULL;

    char key[FITS_LINESZ + 1];
    char newkey[FITS_LINESZ + 1];
    char val[FITS_LINESZ + 1];
    char comment[FITS_LINESZ + 1];
    int imatch = -1;
    // how many REs have successfully been compiled.
    int n1=0, n2=0;

    outfid = fopen(outfn, "wb");
    if (!outfid) {
        SYSERROR("Failed to open output file \"%s\"", outfn);
        goto bailout;
    }

    inhdr = anqfits_get_header2(infn, extension);
    if (!inhdr) {
        ERROR("Failed to read FITS header from input file \"%s\" ext %i",
              infn, extension);
        goto bailout;
    }
    wcshdr = anqfits_get_header2(wcsfn, 0);
    if (!wcshdr) {
        ERROR("Failed to read FITS header from WCS file \"%s\"", wcsfn);
        goto bailout;
    }

    outhdr = qfits_header_new();
    if (!outhdr) {
        ERROR("Failed to allocate new output FITS header.");
        goto bailout;
    }

    // Compile regular expressions...
    for (e=0; e<NE1; e++) {
        int errcode;
        errcode = regcomp(re1 + e, exclude_input[e], REG_EXTENDED);
        if (errcode) {
            char err[256];
            regerror(errcode, re1 + e, err, sizeof(err));
            ERROR("Failed to compile regular expression \"%s\": %s", exclude_input[e], err);
            goto bailout;
        }
        n1++;
    }
    for (e=0; e<NE2; e++) {
        int errcode;
        errcode = regcomp(re2 + e, exclude_wcs[e], REG_EXTENDED);
        if (errcode) {
            char err[256];
            regerror(errcode, re2 + e, err, sizeof(err));
            ERROR("Failed to compile regular expression \"%s\": %s", exclude_wcs[e], err);
            goto bailout;
        }
        n2++;
    }

    logverb("Reading input file FITS headers...\n");

    if (extension) {
        // Copy the primary header unchanged
        qfits_header* phdr = anqfits_get_header2(infn, 0);
        if (!phdr) {
            ERROR("Failed to read primary FITS header from input file \"%s\n",
                  infn);
            goto bailout;
        }
        if (qfits_header_dump(phdr, outfid) ||
            fits_pad_file(outfid)) {
            SYSERROR("Failed to write primary header to file %s", outfn);
            goto bailout;
        }
        qfits_header_destroy(phdr);
    }
    
    N = qfits_header_n(inhdr);
    for (i=0; i<N; i++) {
        anbool added_newkey = FALSE;
        char line[FITS_LINESZ + 1];
        if (qfits_header_getitem(inhdr, i, key, val, comment, line)) {
            ERROR("Failed to read FITS header card %i from input file", i);
            goto bailout;
        }
        logverb("Read input header line: \"%s\"\n", line);

        if (key_matches(key, re1, exclude_input, NE1, &imatch)) {
            logverb("Regular expression matched: \"%s\", key \"%s\".\n", exclude_input[imatch], key);
            snprintf(newkey, FITS_LINESZ+1, "Original key: \"%s\"", key);
            qfits_header_append(outhdr, "COMMENT", newkey, NULL, NULL);
            // Completely skip the END card, since _ND is not a valid line.
            if (streq(key, "END"))
                continue;
            snprintf(newkey, FITS_LINESZ+1, "_%.7s", key+1);
            logverb("New key: \"%s\"\n", newkey);
            strcpy(key, newkey);
            line[0] = '_';
            added_newkey = TRUE;
        }
        // If the header already contains this new (starting-with-"_")
        // key, add three comment cards instead.
        if (starts_with(key, "_") &&
            (qfits_header_getstr(inhdr, key) ||
             qfits_header_getstr(outhdr, key))) {
            logverb("Key \"%s\" already exists; adding COMMENT cards for value and comment instead\n", key);
            if (!added_newkey) {
                snprintf(newkey, FITS_LINESZ+1, "Original key: \"%s\"", key);
                qfits_header_append(outhdr, "COMMENT", newkey, NULL, NULL);
            }
            snprintf(newkey, FITS_LINESZ+1, " = %s", val);
            qfits_header_append(outhdr, "COMMENT", newkey, NULL, NULL);
            snprintf(newkey, FITS_LINESZ+1, " / %s", comment);
            qfits_header_append(outhdr, "COMMENT", newkey, NULL, NULL);
            continue;
        }

        qfits_header_append(outhdr, key, val, comment, line);
    }
    qfits_header_destroy(inhdr);
    inhdr = NULL;

    logverb("Reading WCS file FITS headers...\n");

    qfits_header_append(outhdr, "COMMENT", "", NULL, NULL);
    qfits_header_append(outhdr, "COMMENT", "--Start of Astrometry.net WCS solution--", NULL, NULL);
    qfits_header_append(outhdr, "COMMENT", "--Put in by the new-wcs program--", NULL, NULL);
    qfits_header_append(outhdr, "COMMENT", "", NULL, NULL);

    N = qfits_header_n(wcshdr);
    for (i=0; i<N; i++) {
        char line[FITS_LINESZ + 1];
        if (qfits_header_getitem(wcshdr, i, key, val, comment, line)) {
            ERROR("Failed to read FITS header card %i from WCS file.", i);
            goto bailout;
        }

        if (key_matches(key, re2, exclude_wcs, NE2, &imatch)) {
            logverb("Regular expression matched: \"%s\", key \"%s\".\n", exclude_wcs[imatch], key);
            // These don't really need to appear in the output file...
            /*
             snprintf(newkey, FITS_LINESZ+1, "Original WCS key: \"%s\"", key);
             qfits_header_append(outhdr, "COMMENT", newkey, NULL, NULL);
             snprintf(newkey, FITS_LINESZ+1, "_%.7s", key);
             strcpy(key, newkey);
             */
            continue;
        }
        if (streq(key, "DATE") && qfits_header_getstr(outhdr, key)) {
            // If the input header already had a DATE card,
            snprintf(newkey, FITS_LINESZ+1, "Original WCS key: \"%s\"", key);
            qfits_header_append(outhdr, "COMMENT", newkey, NULL, NULL);
            snprintf(newkey, FITS_LINESZ+1, "_%.7s", key);
            strcpy(key, newkey);
            line[0] = '_';
        }

        qfits_header_append(outhdr, key, val, comment, line);
    }
    qfits_header_destroy(wcshdr);
    wcshdr = NULL;

    qfits_header_append(outhdr, "COMMENT", "", NULL, NULL);
    qfits_header_append(outhdr, "COMMENT", "--End of Astrometry.net WCS--", NULL, NULL);
    qfits_header_append(outhdr, "COMMENT", "--(Put in by the new-wcs program)--", NULL, NULL);
    qfits_header_append(outhdr, "COMMENT", "", NULL, NULL);


    qfits_header_append(outhdr, "END", NULL, NULL, NULL);

    if (qfits_header_dump(outhdr, outfid) ||
        fits_pad_file(outfid)) {
        SYSERROR("Failed to write output header to file %s", outfn);
        goto bailout;
    }
    qfits_header_destroy(outhdr);
    outhdr = NULL;

    if (copydata) {
        int datsize, datstart;
        FILE* infid = NULL;
        anqfits_t* anq = NULL;
        anq = anqfits_open(infn);
        if (!anq) {
            ERROR("Failed to open file \"%s\"", infn);
            goto bailout;
        }
        datstart = anqfits_data_start(anq, extension);
        datsize  = anqfits_data_size (anq, extension);
        infid = fopen(infn, "rb");
        if (!infid) {
            SYSERROR("Failed to open input file \"%s\"", infn);
            anqfits_close(anq);
            goto bailout;
        }
        logverb("Copying from offset %i to offset %i (length %i) of the input file to the output.\n",
                datstart, datstart + datsize, datsize);
        if (pipe_file_offset(infid, datstart, datsize, outfid)) {
            ERROR("Failed to copy the data block");
            fclose(infid);
            anqfits_close(anq);
            goto bailout;
        }
        fclose(infid);
        if (fits_pad_file(outfid)) {
            ERROR("Failed to pad FITS file \"%s\"", outfn);
            anqfits_close(anq);
            goto bailout;
        }
        anqfits_close(anq);
        anq = NULL;
    }
    
    if (fclose(outfid)) {
        SYSERROR("Failed to close output file \"%s\"", outfn);
        goto bailout;
    }


    // Free regular expressions...
    for (e=0; e<NE1; e++)
        regfree(re1 + e);
    for (e=0; e<NE2; e++)
        regfree(re2 + e);
    return 0;

 bailout:
    if (outfid)
        fclose(outfid);
    if (inhdr)
        qfits_header_destroy(inhdr);
    if (outhdr)
        qfits_header_destroy(outhdr);
    if (wcshdr)
        qfits_header_destroy(wcshdr);
    for (i=0; i<n1; i++)
        regfree(re1 + i);
    for (i=0; i<n2; i++)
        regfree(re2 + i);
    return -1;
}
Example #23
0
int test_qfits_filecreate(char * filename)
{
    qfits_header    *    qh ;
    FILE            *    out ;
    qfitsdumper            qd ;
    int                    i ;

    say("-----> Header creation");
    say("Creating blank header");
    qh = qfits_header_new();
    if (qh==NULL) {
        fail("qfits_header_new() failed");
        return 1 ;
    }
    say("Destroying blank header");
    /* Destroy header now */
    qfits_header_destroy(qh);

    /* Create minimal header (SIMPLE/END) */
    say("Creating minimal header");
    qh = qfits_header_default();
    if (qh==NULL) {
        fail("qfits_header_default() failed");
        return 1 ;
    }

    say("Inserting primary keywords");
    /* Insert XTENSION marker */
    qfits_header_add(qh, "EXTEND", "T", "xtension might be present", NULL);

    /* Insert a string */
    qfits_header_add(qh, "KEY01", "value01", "comment 01", NULL);
    /* Insert an int */
    qfits_header_add(qh, "KEY02", "2", "comment 02", NULL);
    /* Insert a double */
    qfits_header_add(qh, "KEY03", "3.0", "comment 03", NULL);
    /* Insert a complex */
    qfits_header_add(qh, "KEY04", "4.0 4.2", "comment 04", NULL);
    /* Insert a boolean */
    qfits_header_add(qh, "KEY05", "T", "comment 05", NULL);


    say("Inserting history keywords");
    /* Insert HISTORY keys */
    qfits_header_add(qh, "HISTORY", "1 history field", NULL, NULL);
    qfits_header_add(qh, "HISTORY", "2 history field", NULL, NULL);
    qfits_header_add(qh, "HISTORY", "3 history field", NULL, NULL);
    qfits_header_add(qh, "HISTORY", "4 history field", NULL, NULL);

    say("Inserting comment keywords");
    /* Insert COMMENT keys */
    qfits_header_add(qh, "COMMENT", "1 comment field", NULL, NULL);
    qfits_header_add(qh, "COMMENT", "2 comment field", NULL, NULL);
    qfits_header_add(qh, "COMMENT", "3 comment field", NULL, NULL);
    qfits_header_add(qh, "COMMENT", "4 comment field", NULL, NULL);

    say("Inserting hierarch keywords");
    /* Insert HIERARCH ESO keys in reverse DICB order */
    qfits_header_add(qh, "HIERARCH ESO NULL A", "0.0", "not DICB", NULL);
    qfits_header_add(qh, "HIERARCH ESO NULL B", "0.0", "not DICB", NULL);
    qfits_header_add(qh, "HIERARCH ESO NULL C", "0.0", "not DICB", NULL);

    qfits_header_add(qh, "PRO.A", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "PRO.B", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "PRO.C", "0.0", "DICB compliant", NULL);

    qfits_header_add(qh, "HIERARCH ESO LOG A", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "HIERARCH ESO LOG B", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "HIERARCH ESO LOG C", "0.0", "DICB compliant", NULL);

    qfits_header_add(qh, "INS.A", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "INS.B", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "INS.C", "0.0", "DICB compliant", NULL);

    qfits_header_add(qh, "HIERARCH ESO TEL A", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "HIERARCH ESO TEL B", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "HIERARCH ESO TEL C", "0.0", "DICB compliant", NULL);

    qfits_header_add(qh, "GEN.A", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "GEN.B", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "GEN.C", "0.0", "DICB compliant", NULL);

    qfits_header_add(qh, "HIERARCH ESO TPL A", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "HIERARCH ESO TPL B", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "HIERARCH ESO TPL C", "0.0", "DICB compliant", NULL);

    qfits_header_add(qh, "OBS.A", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "OBS.B", "0.0", "DICB compliant", NULL);
    qfits_header_add(qh, "OBS.C", "0.0", "DICB compliant", NULL);

    say("Inserting mandatory keywords");
    /* Insert mandatory keys in reverse order */
    qfits_header_add(qh, "NAXIS2", "10", "NAXIS2 comment", NULL);
    qfits_header_add(qh, "NAXIS1", "11", "NAXIS1 comment", NULL);
    qfits_header_add(qh, "NAXIS",  "2", "NAXIS comment", NULL);
    qfits_header_add(qh, "BITPIX",  "-32", "BITPIX comment", NULL);

    /* Dump header to file */
    say("Opening file for output");
    out = fopen(filename, "w");
    if (out==NULL) {
        fail("cannot create test file");
        qfits_header_destroy(qh);
        return 1 ;
    }
    say("Dumping header to file");
    if (qfits_header_dump(qh, out)!=0) {
        fail("cannot dump header");
        qfits_header_destroy(qh);
        return 1 ;
    }
    say("Destroying built header");
    qfits_header_destroy(qh);
    fclose(out);

    say("-----> Dumping pixels");
    /* Allocate data segment and save it to FITS file */
    qd.fbuf = qfits_malloc(11 * 10 * sizeof(float));
    for (i=0 ; i<(11*10) ; i++) {
        qd.fbuf[i]=i*0.2 ;
    }

    qd.filename  = filename ;
    qd.npix      = 11 * 10 ;
    qd.ptype     = PTYPE_FLOAT ;
    qd.out_ptype = -32 ;

    if (qfits_pixdump(&qd)!=0) {
        fail("cannot save data to test file");
        qfits_free(qd.fbuf);
        return 1 ;
    }
    qfits_free(qd.fbuf);

    /* Zero-pad the output file */
    qfits_zeropad(filename);
    return 0 ;
}
Example #24
0
int test_qfits_filecreate_ext(char * filename)
{
    qfits_header*    qh ;
    qfitsdumper        qd ;
    FILE        *    out ;
    const char  *    sig ;

    say("-----> File with multiple extensions");
    /* Create minimal FITS header for main */
    say("Creating default header");
    qh = qfits_header_default() ;
    if (qh==NULL) {
        fail("cannot create default header");
        return 1 ;
    }
    qfits_header_add(qh, "BITPIX", "8", "no data in main section", NULL);
    qfits_header_add(qh, "NAXIS", "0", "no data in main section", NULL);
    qfits_header_add(qh, "EXTEND", "T", "Extensions are present", NULL);

    say("Dumping header to test file");
    out = fopen(filename, "w");
    if (out==NULL) {
        fail("cannot create test file");
        qfits_header_destroy(qh);
        return 1 ;
    }
    qfits_header_dump(qh, out);
    fclose(out);
    qfits_header_destroy(qh);

    say("Creating first extension with float pixels");
    qh = qfits_header_new();
    if (qh==NULL) {
        fail("cannot create extension header 1");
        return 1 ;
    }
    qfits_header_append(qh, "XTENSION", "T", "Ext 1", NULL);
    qfits_header_append(qh, "BITPIX", "-32", "bpp", NULL);
    qfits_header_append(qh, "NAXIS", "2", "axes", NULL);
    qfits_header_append(qh, "NAXIS1", "6", "size in x", NULL);
    qfits_header_append(qh, "NAXIS2", "2", "size in y", NULL);
    qfits_header_append(qh, "END", NULL, NULL, NULL);

    say("Dumping ext header 1 to test file");
    out = fopen(filename, "a");
    if (out==NULL) {
        fail("cannot append to test file");
        qfits_header_destroy(qh);
        return 1 ;
    }
    qfits_header_dump(qh, out);
    fclose(out);
    qfits_header_destroy(qh);

    say("Dumping float array");

    qd.filename = filename ;
    qd.npix      = 12 ;
    qd.ptype     = PTYPE_FLOAT ;
    qd.out_ptype = -32 ;
    qd.fbuf         = float_array_orig ;

    if (qfits_pixdump(&qd)!=0) {
        fail("cannot save data to test file");
        qfits_free(qd.fbuf);
        return 1 ;
    }
    /* Zero-pad the output file */
    qfits_zeropad(filename);

    say("Creating second extension with int pixels");
    qh = qfits_header_new();
    if (qh==NULL) {
        fail("cannot create extension header 1");
        return 1 ;
    }
    qfits_header_append(qh, "XTENSION", "T", "Ext 1", NULL);
    qfits_header_append(qh, "BITPIX", "32", "bpp", NULL);
    qfits_header_append(qh, "NAXIS", "2", "axes", NULL);
    qfits_header_append(qh, "NAXIS1", "6", "size in x", NULL);
    qfits_header_append(qh, "NAXIS2", "2", "size in y", NULL);
    qfits_header_append(qh, "END", NULL, NULL, NULL);

    say("Dumping ext header 2 to test file");
    out = fopen(filename, "a");
    if (out==NULL) {
        fail("cannot append to test file");
        qfits_header_destroy(qh);
        return 1 ;
    }
    qfits_header_dump(qh, out);
    fclose(out);
    qfits_header_destroy(qh);

    say("Dumping int array");

    qd.filename = filename ;
    qd.npix      = 12 ;
    qd.ptype     = PTYPE_INT ;
    qd.out_ptype = 32 ;
    qd.ibuf         = int_array_orig ;

    if (qfits_pixdump(&qd)!=0) {
        fail("cannot save data to test file");
        qfits_free(qd.fbuf);
        return 1 ;
    }
    /* Zero-pad the output file */
    qfits_zeropad(filename);

    say("Creating third extension with double pixels");
    qh = qfits_header_new();
    if (qh==NULL) {
        fail("cannot create extension header 3");
        return 1 ;
    }
    qfits_header_append(qh, "XTENSION", "T", "Ext 1", NULL);
    qfits_header_append(qh, "BITPIX", "-64", "bpp", NULL);
    qfits_header_append(qh, "NAXIS", "2", "axes", NULL);
    qfits_header_append(qh, "NAXIS1", "6", "size in x", NULL);
    qfits_header_append(qh, "NAXIS2", "2", "size in y", NULL);
    qfits_header_append(qh, "END", NULL, NULL, NULL);

    say("Dumping ext header 3 to test file");
    out = fopen(filename, "a");
    if (out==NULL) {
        fail("cannot append to test file");
        qfits_header_destroy(qh);
        return 1 ;
    }
    qfits_header_dump(qh, out);
    fclose(out);
    qfits_header_destroy(qh);

    say("Dumping double array");

    qd.filename = filename ;
    qd.npix      = 12 ;
    qd.ptype     = PTYPE_DOUBLE ;
    qd.out_ptype = -64 ;
    qd.dbuf         = double_array_orig ;

    if (qfits_pixdump(&qd)!=0) {
        fail("cannot save data to test file");
        qfits_free(qd.fbuf);
        return 1 ;
    }
    /* Zero-pad the output file */
    qfits_zeropad(filename);

    /* Get MD5 for the test file */
    sig = qfits_datamd5(filename);
    if (strcmp(sig, REFSIG)) {
        fail("test file signature does not match");
        return 1 ;
    }
    say("File DATAMD5 signature is Ok");

    return 0 ;
}
Example #25
0
int main(int argc, char *argv[]) {
    int argchar;
	char* infn = NULL;
	char* outfn = NULL;
	FILE* fout;
	anbool tostdout = FALSE;
    anqfits_t* anq;
    int W, H;
	qfits_header* hdr;
    const anqfits_image_t* animg;
	float* img;
	int loglvl = LOG_MSG;
	int scale = 2;
	int winw;
	int winh;
	int plane;
	int out_bitpix = -32;
	float* outimg;
	int outw, outh;
	int edge = EDGE_TRUNCATE;
	int ext = 0;
	int npixout = 0;

    while ((argchar = getopt (argc, argv, OPTIONS)) != -1)
        switch (argchar) {
		case 'v':
			loglvl++;
			break;
		case 's':
			scale = atoi(optarg);
			break;
		case 'e':
			ext = atoi(optarg);
			break;
        case '?':
        case 'h':
			printHelp(argv[0]);
            return 0;
        default:
            return -1;
        }

	log_init(loglvl);
	log_to(stderr);
	errors_log_to(stderr);
	fits_use_error_system();

	if (argc - optind != 2) {
		logerr("Need two arguments: input and output files.\n");
		printHelp(argv[0]);
		exit(-1);
	}

	infn = argv[optind];
	outfn = argv[optind+1];

	if (streq(outfn, "-")) {
		tostdout = TRUE;
		fout = stdout;
	} else {
		fout = fopen(outfn, "wb");
		if (!fout) {
			SYSERROR("Failed to open output file \"%s\"", outfn);
			exit(-1);
		}
	}

    anq = anqfits_open(infn);
    if (!anq) {
        ERROR("Failed to open input file \"%s\"", infn);
        exit(-1);
    }
    animg = anqfits_get_image_const(anq, ext);
    
    W = (int)animg->width;
    H = (int)animg->height;
    if (!animg) {
        ERROR("Failde to read image from \"%s\"", infn);
        exit(-1);
    }

    /*
	if (tostdout)
		dump.filename = "STDOUT";
	else
		dump.filename = outfn;
	dump.ptype = PTYPE_FLOAT;
	dump.out_ptype = out_bitpix;
     */

	get_output_image_size(W % scale, H % scale,
						  scale, edge, &outw, &outh);
	outw += (W / scale);
	outh += (H / scale);
    
	hdr = qfits_header_default();
    fits_header_add_int(hdr, "BITPIX", out_bitpix, "bits per pixel");
	if (animg->planes > 1)
		fits_header_add_int(hdr, "NAXIS", 3, "number of axes");
	else
		fits_header_add_int(hdr, "NAXIS", 2, "number of axes");
    fits_header_add_int(hdr, "NAXIS1", outw, "image width");
    fits_header_add_int(hdr, "NAXIS2", outh, "image height");
	if (animg->planes > 1)
		fits_header_add_int(hdr, "NAXIS3", animg->planes, "number of planes");

	if (qfits_header_dump(hdr, fout)) {
		ERROR("Failed to write FITS header to \"%s\"", outfn);
		exit(-1);
	}
	qfits_header_destroy(hdr);

	winw = W;
	winh = (int)ceil(ceil(1024*1024 / (float)winw) / (float)scale) * scale;

	outimg = malloc((int)ceil(winw/scale)*(int)ceil(winh/scale) * sizeof(float));
			
	logmsg("Image is %i x %i x %i\n", W, H, (int)animg->planes);
	logmsg("Output will be %i x %i x %i\n", outw, outh, (int)animg->planes);
	logverb("Reading in blocks of %i x %i\n", winw, winh);
	for (plane=0; plane<animg->planes; plane++) {
		int bx, by;
		int nx, ny;
		for (by=0; by<(int)ceil(H / (float)winh); by++) {
			for (bx=0; bx<(int)ceil(W / (float)winw); bx++) {
                int i;
				int lox, loy, hix, hiy, outw, outh;
				nx = MIN(winw, W - bx*winw);
				ny = MIN(winh, H - by*winh);
				lox = bx*winw;
				loy = by*winh;
				hix = lox + nx;
				hiy = loy + ny;
				logverb("  reading %i,%i + %i,%i\n", lox, loy, nx, ny);

                img = anqfits_readpix(anq, ext, lox, hix, loy, hiy, plane,
                                      PTYPE_FLOAT, NULL, &W, &H);
                if (!img) {
                    ERROR("Failed to load pixel window: x=[%i, %i), y=[%i,%i), plane %i\n",
                          lox, hix, loy, hiy, plane);
                    exit(-1);
                }

				average_image_f(img, nx, ny, scale, edge,
								&outw, &outh, outimg);
                free(img);

				logverb("  writing %i x %i\n", outw, outh);
				if (outw * outh == 0)
					continue;

                for (i=0; i<outw*outh; i++) {
                    int nbytes = abs(out_bitpix)/8;
                    char buf[nbytes];
                    if (qfits_pixel_ctofits(PTYPE_FLOAT, out_bitpix,
                                            outimg + i, buf)) {
                        ERROR("Failed to convert pixel to FITS type\n");
                        exit(-1);
                    }
                    if (fwrite(buf, nbytes, 1, fout) != 1) {
                        ERROR("Failed to write pixels\n");
                        exit(-1);
                    }
                }
				npixout += outw*outh;
			}
		}
	}
	free(outimg);
    anqfits_close(anq);

	if (tostdout) {
		// pad.
		int N;
		char pad[2880];
		N = (npixout * (abs(out_bitpix) / 8)) % 2880;
		memset(pad, 0, 2880);
		fwrite(pad, 1, N, fout);
	} else {
		if (fits_pad_file(fout)) {
			ERROR("Failed to pad output file");
			exit(-1);
		}
        if (fclose(fout)) {
            SYSERROR("Failed to close output file");
            exit(-1);
        }
    }
	logverb("Done!\n");
	return 0;
}
Example #26
0
int main(int argc, char *argv[]) {
    int argchar;

	char* infn = NULL;
	char* outfn = NULL;
	FILE* fin = NULL;
	FILE* fout = NULL;
	pl* cols;
	char* progname = argv[0];
	int nextens;
	int ext;
	int NC;
	int start, size;
    anqfits_t* anq = NULL;

	qfits_table* outtable;
	unsigned char* buffer;

	cols = pl_new(16);

    while ((argchar = getopt (argc, argv, OPTIONS)) != -1)
        switch (argchar) {
        case 'c':
			pl_append(cols, optarg);
            break;
        case 'i':
			infn = optarg;
			break;
        case 'o':
			outfn = optarg;
			break;
        case '?':
        case 'h':
			printHelp(progname);
            return 0;
        default:
            return -1;
        }

	if (!infn || !outfn || !pl_size(cols)) {
		printHelp(progname);
		exit(-1);
	}

    fin = fopen(infn, "rb");
    if (!fin) {
        ERROR("Failed to open input file %s: %s\n", infn, strerror(errno));
        exit(-1);
    }

    fout = fopen(outfn, "wb");
    if (!fout) {
        ERROR("Failed to open output file %s: %s\n", outfn, strerror(errno));
        exit(-1);
    }

	// copy the main header exactly.
    anq = anqfits_open(infn);
    if (!anq) {
        ERROR("Failed to read \"%s\"", infn);
        exit(-1);
    }
    start = anqfits_header_start(anq, 0);
    size  = anqfits_header_size (anq, 0);
    if (pipe_file_offset(fin, start, size, fout)) {
        ERROR("Failed to copy primary header.\n");
        exit(-1);
    }

	NC = pl_size(cols);
	nextens = anqfits_n_ext(anq);
	printf("Translating %i extensions.\n", nextens);
	buffer = NULL;
	for (ext=1; ext<nextens; ext++) {
		int c2, c;
		int columns[NC];
		int sizes[NC];
		int offsets[NC];
		int offset = 0;
		int off, n;
		int totalsize = 0;
		const int BLOCK=1000;
		qfits_table* table;
		qfits_header* header;
		qfits_header* tablehdr;

		if (ext%100 == 0) {
			printf("Extension %i.\n", ext);
			fflush(stdout);
		}

		if (!anqfits_is_table(anq, ext)) {
			ERROR("extention %i isn't a table.\n", ext);
			// HACK - just copy it.
			return -1;
		}
		table = anqfits_get_table(anq, ext);
		if (!table) {
			ERROR("failed to open table: file %s, extension %i.\n", infn, ext);
			return -1;
		}
        header = anqfits_get_header(anq, ext);
		if (!header) {
			ERROR("failed to read header: extension %i\n", ext);
			exit(-1);
		}

		outtable = qfits_table_new(outfn, QFITS_BINTABLE, 0, NC, table->nr);
		outtable->tab_w = 0;
		
		for (c=0; c<pl_size(cols); c++) {
			columns[c] = -1;
		}
		for (c=0; c<pl_size(cols); c++) {
			char* colname = pl_get(cols, c);
			qfits_col* col;
			c2 = fits_find_column(table, colname);
			if (c2 == -1) {
				ERROR("Extension %i: failed to find column named %s\n",
						ext, colname);
				exit(-1);
			}
			col = table->col + c2;
			columns[c] = c2;
			sizes[c] = col->atom_nb * col->atom_size;
			offsets[c] = offset;
			offset += sizes[c];

			qfits_col_fill(outtable->col + c,
						   col->atom_nb, col->atom_dec_nb,
						   col->atom_size, col->atom_type,
						   col->tlabel, col->tunit,
						   col->nullval, col->tdisp,
						   col->zero_present,
						   col->zero,
						   col->scale_present,
						   col->scale,
						   outtable->tab_w);
			outtable->tab_w += sizes[c];
		}
		totalsize = offset;

		tablehdr = qfits_table_ext_header_default(outtable);
		// add any headers from the original table that aren't part of the BINTABLE extension.
        fits_copy_non_table_headers(tablehdr, header);
		qfits_header_dump(tablehdr, fout);
		qfits_header_destroy(tablehdr);
		
		buffer = realloc(buffer, totalsize * BLOCK);

		for (off=0; off<table->nr; off+=n) {
			if (off + BLOCK > table->nr)
				n = table->nr - off;
			else
				n = BLOCK;
			for (c=0; c<pl_size(cols); c++)
				qfits_query_column_seq_to_array_no_endian_swap
					(table, columns[c], off, n, buffer + offsets[c], totalsize);
			if (fwrite(buffer, totalsize, n, fout) != n) {
				ERROR("Error writing a block of data: ext %i: %s\n", ext, strerror(errno));
				exit(-1);
			}
		}

		qfits_table_close(outtable);
		fits_pad_file(fout);
		qfits_header_destroy(header);
		qfits_table_close(table);
	}
	free(buffer);

	if (fclose(fout)) {
		ERROR("Error closing output file: %s\n", strerror(errno));
	}
	fclose(fin);

    anqfits_close(anq);

	pl_free(cols);
	return 0;
}
Example #27
0
int main(int argc, char** args) {
    int argchar;
	char* progname = args[0];

	char* outfn = NULL;
	char* outwcsfn = NULL;
	int outwcsext = 0;

	anwcs_t* outwcs;

	sl* inimgfns = sl_new(16);
	sl* inwcsfns = sl_new(16);
	sl* inwtfns = sl_new(16);
	il* inimgexts = il_new(16);
	il* inwcsexts = il_new(16);
	il* inwtexts = il_new(16);

	int i;
	int loglvl = LOG_MSG;
	int order = 3;

	coadd_t* coadd;
	lanczos_args_t largs;

	double sigma = 0.0;
	anbool nearest = FALSE;
	anbool divweight = FALSE;

	int plane = 0;

    while ((argchar = getopt(argc, args, OPTIONS)) != -1)
        switch (argchar) {
		case '?':
        case 'h':
			printHelp(progname);
			exit(0);
		case 'D':
			divweight = TRUE;
			break;
		case 'p':
			plane = atoi(optarg);
			break;
		case 'N':
			nearest = TRUE;
			break;
		case 's':
			sigma = atof(optarg);
			break;
		case 'v':
			loglvl++;
			break;
		case 'e':
			outwcsext = atoi(optarg);
			break;
		case 'w':
			outwcsfn = optarg;
			break;
		case 'o':
			outfn = optarg;
			break;
		case 'O':
			order = atoi(optarg);
			break;
		}

	log_init(loglvl);
	fits_use_error_system();

	args += optind;
	argc -= optind;
	if (argc == 0 || argc % 6) {
		printHelp(progname);
		exit(-1);
	}

	for (i=0; i<argc/6; i++) {
		sl_append(inimgfns, args[6*i+0]);
		il_append(inimgexts, atoi(args[6*i+1]));
		sl_append(inwtfns, args[6*i+2]);
		il_append(inwtexts, atoi(args[6*i+3]));
		sl_append(inwcsfns, args[6*i+4]);
		il_append(inwcsexts, atoi(args[6*i+5]));
	}

	logmsg("Reading output WCS file %s\n", outwcsfn);
	outwcs = anwcs_open(outwcsfn, outwcsext);
	if (!outwcs) {
		ERROR("Failed to read WCS from file: %s ext %i\n", outwcsfn, outwcsext);
		exit(-1);
	}

	logmsg("Output image will be %i x %i\n", (int)anwcs_imagew(outwcs), (int)anwcs_imageh(outwcs));

	coadd = coadd_new(anwcs_imagew(outwcs), anwcs_imageh(outwcs));

	coadd->wcs = outwcs;

	if (nearest) {
		coadd->resample_func = nearest_resample_f;
		coadd->resample_token = NULL;
	} else {
		coadd->resample_func = lanczos_resample_f;
		largs.order = order;
		coadd->resample_token = &largs;
	}

	for (i=0; i<sl_size(inimgfns); i++) {
        anqfits_t* anq;
        anqfits_t* wanq;
		float* img;
		float* wt = NULL;
		anwcs_t* inwcs;
		char* fn;
		int ext;
		float overallwt = 1.0;
        int W, H;

		fn = sl_get(inimgfns, i);
		ext = il_get(inimgexts, i);
		logmsg("Reading input image \"%s\" ext %i\n", fn, ext);

        anq = anqfits_open(fn);
        if (!anq) {
            ERROR("Failed to open file \"%s\"\n", fn);
            exit(-1);
        }

        img = anqfits_readpix(anq, ext, 0, 0, 0, 0, plane,
                              PTYPE_FLOAT, NULL, &W, &H);
        if (!img) {
            ERROR("Failed to read image from ext %i of %s\n", ext, fn);
            exit(-1);
        }
        anqfits_close(anq);
		logmsg("Read image: %i x %i.\n", W, H);

		if (sigma > 0.0) {
			int k0, nk;
			float* kernel;
			logmsg("Smoothing by Gaussian with sigma=%g\n", sigma);
			kernel = convolve_get_gaussian_kernel_f(sigma, 4, &k0, &nk);
			convolve_separable_f(img, W, H, kernel, k0, nk, img, NULL);
			free(kernel);
		}

		fn = sl_get(inwcsfns, i);
		ext = il_get(inwcsexts, i);
		logmsg("Reading input WCS file \"%s\" ext %i\n", fn, ext);

		inwcs = anwcs_open(fn, ext);
		if (!inwcs) {
			ERROR("Failed to read WCS from file \"%s\" ext %i\n", fn, ext);
			exit(-1);
		}
		if (anwcs_pixel_scale(inwcs) == 0) {
			ERROR("Pixel scale from the WCS file is zero.  Usually this means the image has no valid WCS header.\n");
			exit(-1);
		}
		if (anwcs_imagew(inwcs) != W || anwcs_imageh(inwcs) != H) {
			ERROR("Size mismatch between image and WCS!");
			exit(-1);
		}

		fn = sl_get(inwtfns, i);
		ext = il_get(inwtexts, i);
		if (streq(fn, "none")) {
			logmsg("Not using weight image.\n");
			wt = NULL;
		} else if (file_exists(fn)) {
			logmsg("Reading input weight image \"%s\" ext %i\n", fn, ext);
            wanq = anqfits_open(fn);
            if (!wanq) {
                ERROR("Failed to open file \"%s\"\n", fn);
                exit(-1);
            }
            int wtW, wtH;
            wt = anqfits_readpix(anq, ext, 0, 0, 0, 0, 0,
                              PTYPE_FLOAT, NULL, &wtW, &wtH);
            if (!wt) {
                ERROR("Failed to read image from ext %i of %s\n", ext, fn);
                exit(-1);
            }
            anqfits_close(wanq);
			logmsg("Read image: %i x %i.\n", wtW, wtH);
			if (wtW != W || wtH != H) {
				ERROR("Size mismatch between image and weight!");
				exit(-1);
			}
		} else {
			char* endp;
			overallwt = strtod(fn, &endp);
			if (endp == fn) {
				ERROR("Weight: \"%s\" is neither a file nor a double.\n", fn);
				exit(-1);
			}
			logmsg("Parsed weight value \"%g\"\n", overallwt);
		}

		if (divweight && wt) {
			int j;
			logmsg("Dividing image by weight image...\n");
			for (j=0; j<(W*H); j++)
				img[j] /= wt[j];
		}

		coadd_add_image(coadd, img, wt, overallwt, inwcs);

		anwcs_free(inwcs);
        free(img);
		if (wt)
			free(wt);
	}

	//
	logmsg("Writing output: %s\n", outfn);

	coadd_divide_by_weight(coadd, 0.0);

	/*
	 if (fits_write_float_image_hdr(coadd->img, coadd->W, coadd->H, outfn)) {
	 ERROR("Failed to write output image %s", outfn);
	 exit(-1);
	 }
	 */
	/*
	 if (fits_write_float_image(coadd->img, coadd->W, coadd->H, outfn)) {
	 ERROR("Failed to write output image %s", outfn);
	 exit(-1);
	 }
	 */
	{
		qfitsdumper qoutimg;
		qfits_header* hdr;
		hdr = anqfits_get_header2(outwcsfn, outwcsext);
		if (!hdr) {
			ERROR("Failed to read WCS file \"%s\" ext %i\n", outwcsfn, outwcsext);
			exit(-1);
		}
		fits_header_mod_int(hdr, "NAXIS", 2, NULL);
		fits_header_set_int(hdr, "NAXIS1", coadd->W, "image width");
		fits_header_set_int(hdr, "NAXIS2", coadd->H, "image height");
		fits_header_modf(hdr, "BITPIX", "-32", "32-bit floats");
		memset(&qoutimg, 0, sizeof(qoutimg));
		qoutimg.filename = outfn;
		qoutimg.npix = coadd->W * coadd->H;
		qoutimg.fbuf = coadd->img;
		qoutimg.ptype = PTYPE_FLOAT;
		qoutimg.out_ptype = BPP_IEEE_FLOAT;
		if (fits_write_header_and_image(NULL, &qoutimg, coadd->W)) {
			ERROR("Failed to write FITS image to file \"%s\"", outfn);
			exit(-1);
		}
		qfits_header_destroy(hdr);
	}

	coadd_free(coadd);
	sl_free2(inimgfns);
	sl_free2(inwcsfns);
	sl_free2(inwtfns);
	il_free(inimgexts);
	il_free(inwcsexts);
	il_free(inwtexts);
	anwcs_free(outwcs);


	return 0;
}
Example #28
0
/**
 Evaluates the given TAN-TPV WCS header on a grid of points,
 fitting a SIP distortion solution to it.

 The grid can be specified by either:

 double* xy, int Nxy

 double stepsize=100, double xlo=0, double xhi=0, double ylo=0, double yhi=0

 xlo and xhi, if both 0, default to 1. and the WCS width
 ylo and yhi, if both 0, default to 1. and the WCS height

 The number of steps is chosen to be the closest step size to split the range
 xlo to xhi into an integer number of steps.

 imageW and imageH, if non-zero, override the image width read from the WCS,
 and ALSO the WCS width/height mentioned above.

 */
int wcs_pv2sip(const char* wcsinfn, int ext,
			   const char* wcsoutfn,
			   anbool scamp_head_file,

			   double* xy, int Nxy,
               
               double stepsize,
               double xlo, double xhi,
               double ylo, double yhi,

			   int imageW, int imageH,
               int order,
			   anbool forcetan,
               int doshift) {

	qfits_header* hdr = NULL;
    sip_t* sip = NULL;
    int rtn = -1;

	if (scamp_head_file) {
		size_t sz = 0;
		char* txt;
		char* prefix;
		int np;
		int nt;
		unsigned char* txthdr;
		sl* lines;
		int i;
		txt = file_get_contents(wcsinfn, &sz, TRUE);
		if (!txt) {
			ERROR("Failed to read file %s", wcsinfn);
			goto bailout;
		}
		lines = sl_split(NULL, txt, "\n");
		prefix =
			"SIMPLE  =                    T / Standard FITS file                             "
			"BITPIX  =                    8 / ASCII or bytes array                           "
			"NAXIS   =                    0 / Minimal header                                 "
			"EXTEND  =                    T / There may be FITS ext                          "
			"WCSAXES =                    2 /                                                ";
		np = strlen(prefix);
		nt = np + FITS_LINESZ * sl_size(lines);
		txthdr = malloc(nt);
		memset(txthdr, ' ', np + FITS_LINESZ * sl_size(lines));
		memcpy(txthdr, prefix, np);
		for (i=0; i<sl_size(lines); i++)
			memcpy(txthdr + np + i*FITS_LINESZ, sl_get(lines, i), strlen(sl_get(lines, i)));
		sl_free2(lines);
		hdr = qfits_header_read_hdr_string(txthdr, nt);
		free(txthdr);
		free(txt);
	} else {
		hdr = anqfits_get_header2(wcsinfn, ext);
    }
	if (!hdr) {
		ERROR("Failed to read header: file %s, ext %i\n", wcsinfn, ext);
		goto bailout;
	}

    sip = wcs_pv2sip_header(hdr, xy, Nxy, stepsize, xlo, xhi, ylo, yhi,
                            imageW, imageH, order, forcetan, doshift);
    if (!sip) {
        goto bailout;
    }
    sip_write_to_file(sip, wcsoutfn);

	rtn = 0;

 bailout:
	qfits_header_destroy(hdr);
	return rtn;
}
Example #29
0
// This runs after "astrometry-engine" is run on the file.
static void after_solved(augment_xylist_t* axy,
						 solve_field_args_t* sf,
						 anbool makeplots,
						 const char* me,
						 anbool verbose,
						 const char* tempdir,
						 sl* tempdirs,
						 sl* tempfiles,
						 double plotscale,
						 const char* bgfn) {
	sip_t wcs;
	double ra, dec, fieldw, fieldh;
	char rastr[32], decstr[32];
	char* fieldunits;

	// print info about the field.
	logmsg("Field: %s\n", axy->imagefn ? axy->imagefn : axy->xylsfn);
	if (file_exists(axy->wcsfn)) {
		double orient;
		if (axy->wcs_last_mod) {
			time_t t = file_get_last_modified_time(axy->wcsfn);
			if (t == axy->wcs_last_mod) {
				logmsg("Warning: there was already a WCS file, and its timestamp has not changed.\n");
			}
		}
		if (!sip_read_header_file(axy->wcsfn, &wcs)) {
			ERROR("Failed to read WCS header from file %s", axy->wcsfn);
			exit(-1);
		}
		sip_get_radec_center(&wcs, &ra, &dec);
		sip_get_radec_center_hms_string(&wcs, rastr, decstr);
		sip_get_field_size(&wcs, &fieldw, &fieldh, &fieldunits);
		orient = sip_get_orientation(&wcs);
		logmsg("Field center: (RA,Dec) = (%3.6f, %3.6f) deg.\n", ra, dec);
		logmsg("Field center: (RA H:M:S, Dec D:M:S) = (%s, %s).\n", rastr, decstr);
		logmsg("Field size: %g x %g %s\n", fieldw, fieldh, fieldunits);
		logmsg("Field rotation angle: up is %g degrees E of N\n", orient);
	} else {
		logmsg("Did not solve (or no WCS file was written).\n");
	}

	// create new FITS file...
	if (axy->fitsimgfn && sf->newfitsfn && file_exists(axy->wcsfn)) {
		logmsg("Creating new FITS file \"%s\"...\n", sf->newfitsfn);
		if (new_wcs(axy->fitsimgfn, axy->wcsfn, sf->newfitsfn, TRUE)) {
			ERROR("Failed to create FITS image with new WCS headers");
			exit(-1);
		}
	}

	// write list of index stars in image coordinates
	if (sf->indxylsfn && file_exists(axy->wcsfn) && file_exists(axy->rdlsfn)) {
		assert(axy->wcsfn);
		assert(axy->rdlsfn);
		// index rdls to xyls.
		if (wcs_rd2xy(axy->wcsfn, 0, axy->rdlsfn, sf->indxylsfn,
					  NULL, NULL, FALSE, FALSE, NULL)) {
			ERROR("Failed to project index stars into field coordinates using wcs-rd2xy");
			exit(-1);
		}
	}

	if (makeplots && file_exists(sf->indxylsfn) && file_readable(axy->matchfn) && file_readable(axy->wcsfn)) {
		logmsg("Creating index object overlay plot...\n");
		if (plot_index_overlay(axy, me, sf->indxylsfn, sf->redgreenfn, plotscale, bgfn)) {
			ERROR("Plot index overlay failed.");
		}
	}

	if (makeplots && file_readable(axy->wcsfn)) {
		logmsg("Creating annotation plot...\n");
		if (plot_annotations(axy, me, verbose, sf->ngcfn, plotscale, bgfn)) {
			ERROR("Plot annotations failed.");
		}
	}

	if (axy->imagefn && sf->kmzfn && file_exists(axy->wcsfn)) {
		logmsg("Writing kmz file...\n");
		if (write_kmz(axy, sf->kmzfn, tempdir, tempdirs, tempfiles)) {
			ERROR("Failed to write KMZ.");
			exit(-1);
		}
	}

	if (sf->scampfn && file_exists(axy->wcsfn)) {
		//char* hdrfile = NULL;
		qfits_header* imageheader = NULL;
		starxy_t* xy;
		xylist_t* xyls;

		xyls = xylist_open(axy->axyfn);
		if (!xyls) {
			ERROR("Failed to read xylist to write SCAMP catalog");
			exit(-1);
		}
		if (axy->xcol)
			xylist_set_xname(xyls, axy->xcol);
		if (axy->ycol)
			xylist_set_yname(xyls, axy->ycol);
		//xylist_set_include_flux(xyls, FALSE);
		xylist_set_include_background(xyls, FALSE);
		xy = xylist_read_field(xyls, NULL);
		xylist_close(xyls);

		if (axy->fitsimgfn) {
			//hdrfile = axy->fitsimgfn;
			imageheader = anqfits_get_header2(axy->fitsimgfn, 0);
		}
		if (axy->xylsfn) {
			char val[32];
			//hdrfile = axy->xylsfn;
			imageheader = anqfits_get_header2(axy->xylsfn, 0);
			// Set NAXIS=2, NAXIS1=IMAGEW, NAXIS2=IMAGEH
			fits_header_mod_int(imageheader, "NAXIS", 2, NULL);
			sprintf(val, "%i", axy->W);
			qfits_header_add_after(imageheader, "NAXIS",  "NAXIS1", val, "image width", NULL);
			sprintf(val, "%i", axy->H);
			qfits_header_add_after(imageheader, "NAXIS1", "NAXIS2", val, "image height", NULL);
			//fits_header_add_int(imageheader, "NAXIS1", axy->W, NULL);
			//fits_header_add_int(imageheader, "NAXIS2", axy->H, NULL);
			logverb("Using NAXIS 1,2 = %i,%i\n", axy->W, axy->H);
		}

		if (scamp_write_field(imageheader, &wcs, xy, sf->scampfn)) {
			ERROR("Failed to write SCAMP catalog");
			exit(-1);
		}
		starxy_free(xy);
		if (imageheader)
			qfits_header_destroy(imageheader);
	}

	if (sf->scampconfigfn) {
		if (scamp_write_config_file(axy->scampfn, sf->scampconfigfn)) {
			ERROR("Failed to write SCAMP config file snippet to %s", sf->scampconfigfn);
			exit(-1);
		}
	}
}