Beispiel #1
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;
}
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;
}
Beispiel #3
0
fitstable_t* fitstable_open_for_appending(const char* fn) {
	fitstable_t* tab = open_for_writing(fn, "r+b", NULL);
	if (!tab)
		return tab;
	if (fseeko(tab->fid, 0, SEEK_END)) {
		SYSERROR("Failed to seek to end of file");
		fitstable_close(tab);
		return NULL;
	}
    tab->primheader = anqfits_get_header2(fn, 0);
    if (!tab->primheader) {
        ERROR("Failed to read primary FITS header from %s", fn);
		fitstable_close(tab);
		return NULL;
    }
	return tab;
}
Beispiel #4
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;
}
Beispiel #5
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;
}
/**
 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;
}
Beispiel #7
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;
}
Beispiel #8
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;
}
Beispiel #9
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);
		}
	}
}