Пример #1
0
static void gfio_text_op(struct fio_client *client, struct fio_net_cmd *cmd)
{
	struct cmd_text_pdu *p = (struct cmd_text_pdu *) cmd->payload;
	struct gfio_client *gc = client->client_data;
	struct gui_entry *ge = gc->ge;
	struct gui *ui = ge->ui;
	GtkTreeIter iter;
	struct tm *tm;
	time_t sec;
	char tmp[64], timebuf[80];

	sec = p->log_sec;
	tm = localtime(&sec);
	strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", tm);
	sprintf(timebuf, "%s.%03ld", tmp, (long) p->log_usec / 1000);

	gdk_threads_enter();

	gtk_list_store_append(ui->log_model, &iter);
	gtk_list_store_set(ui->log_model, &iter, 0, timebuf, -1);
	gtk_list_store_set(ui->log_model, &iter, 1, client->hostname, -1);
	gtk_list_store_set(ui->log_model, &iter, 2, log_get_level(p->level), -1);
	gtk_list_store_set(ui->log_model, &iter, 3, p->buf, -1);

	if (p->level == FIO_LOG_ERR)
		gfio_view_log(ui);

	gdk_threads_leave();
}
Пример #2
0
static gint lua_log_index(lua_State* lua) {
  if (lua_type(lua, 2) == LUA_TSTRING
      && strcmp(lua_tostring(lua, 2), "level") == 0) {
    lua_pushstring(lua, log_level_to_string(log_get_level()));
  } else {
    lua_pushnil(lua);
  }
  return 1;
}
Пример #3
0
static void add_quad(quadbuilder_t* qb, unsigned int* quad, void* token) {
	allquads_t* aq = token;
	if (log_get_level() > LOG_VERB) {
		int k;
		debug("quad: ");
		for (k=0; k<qb->dimquads; k++)
			debug("%-6i ", quad[k]);
		logverb("\n");
	}
	quad_write_const(aq->codes, aq->quads, quad, aq->starkd, qb->dimquads, aq->dimcodes);
}
Пример #4
0
static ssh_bind prepare_ssh(const char *keys_dir, const char *bind_addr, int port)
{
	ssh_bind bind;
	char buffer[PATH_MAX];
	int ssh_log_level;
	ssh_key rsakey = NULL;
	ssh_key ed25519key = NULL;

	ssh_log_level = SSH_LOG_WARNING + max(log_get_level() - LOG_NOTICE, 0);

	ssh_set_log_callback(ssh_log_function);

	bind = ssh_bind_new();
	if (!bind)
		tmate_fatal("Cannot initialize ssh");

	if (bind_addr)
		ssh_bind_options_set(bind, SSH_BIND_OPTIONS_BINDADDR, bind_addr);
	ssh_bind_options_set(bind, SSH_BIND_OPTIONS_BINDPORT, &port);
	ssh_bind_options_set(bind, SSH_BIND_OPTIONS_BANNER, TMATE_SSH_BANNER);
	ssh_bind_options_set(bind, SSH_BIND_OPTIONS_LOG_VERBOSITY, &ssh_log_level);

	sprintf(buffer, "%s/ssh_host_rsa_key", keys_dir);
	ssh_pki_import_privkey_file(buffer, NULL, NULL, NULL, &rsakey);
	ssh_bind_options_set(bind, SSH_BIND_OPTIONS_IMPORT_KEY, rsakey);

	sprintf(buffer, "%s/ssh_host_ed25519_key", keys_dir);
	ssh_pki_import_privkey_file(buffer, NULL, NULL, NULL, &ed25519key);
	ssh_bind_options_set(bind, SSH_BIND_OPTIONS_IMPORT_KEY, ed25519key);

	if (ssh_bind_listen(bind) < 0)
		tmate_fatal("Error listening to socket: %s\n", ssh_get_error(bind));

	tmate_notice("Accepting connections on %s:%d", bind_addr ?: "", port);

	return bind;
}
Пример #5
0
int ert_log_get_log_level(){
  if(logh==NULL)
    ert_log_init_log(1,NULL,true);
  return log_get_level(logh);
}
Пример #6
0
int hpquads(startree_t* starkd,
			codefile_t* codes,
			quadfile_t* quads,
			int Nside,
			double scale_min_arcmin,
			double scale_max_arcmin,
			int dimquads,
			int passes,
			int Nreuses,
			int Nloosen,
			int id,
			anbool scanoccupied,

			void* sort_data,
			int (*sort_func)(const void*, const void*),
			int sort_size,
			
			char** args, int argc) {
	hpquads_t myhpquads;
	hpquads_t* me = &myhpquads;

	int i;
	int pass;
	anbool circle = TRUE;
	double radius2;
	il* hptotry;
	int Nhptotry = 0;
	int nquads;
	double hprad;
	double quadscale;

	int skhp, sknside;

	qfits_header* qhdr;
	qfits_header* chdr;

	int N;
	int dimcodes;
	int quadsize;
	int NHP;

	memset(me, 0, sizeof(hpquads_t));

	if (Nside > HP_MAX_INT_NSIDE) {
		ERROR("Error: maximum healpix Nside = %i", HP_MAX_INT_NSIDE);
		return -1;
	}
	if (Nreuses > 255) {
		ERROR("Error, reuse (-r) must be less than 256");
		return -1;
	}

	me->Nside = Nside;
	me->dimquads = dimquads;
	NHP = 12 * Nside * Nside;
	dimcodes = dimquad2dimcode(dimquads);
	quadsize = sizeof(unsigned int) * dimquads;

	logmsg("Nside=%i.  Nside^2=%i.  Number of healpixes=%i.  Healpix side length ~ %g arcmin.\n",
		   me->Nside, me->Nside*me->Nside, NHP, healpix_side_length_arcmin(me->Nside));

	me->sort_data = sort_data;
	me->sort_func = sort_func;
	me->sort_size = sort_size;

	tic();
	me->starkd = starkd;
	N = startree_N(me->starkd);
	logmsg("Star tree contains %i objects.\n", N);

	// get the "HEALPIX" header from the skdt...
	skhp = qfits_header_getint(startree_header(me->starkd), "HEALPIX", -1);
	if (skhp == -1) {
		if (!qfits_header_getboolean(startree_header(me->starkd), "ALLSKY", FALSE)) {
			logmsg("Warning: skdt does not contain \"HEALPIX\" header.  Code and quad files will not contain this header either.\n");
		}
	}
    // likewise "HPNSIDE"
	sknside = qfits_header_getint(startree_header(me->starkd), "HPNSIDE", 1);

    if (sknside && Nside % sknside) {
        logerr("Error: Nside (-n) must be a multiple of the star kdtree healpixelisation: %i\n", sknside);
		return -1;
    }

	if (!scanoccupied && (N*(skhp == -1 ? 1 : sknside*sknside*12) < NHP)) {
		logmsg("\n\n");
		logmsg("NOTE, your star kdtree is sparse (has only a fraction of the stars expected)\n");
		logmsg("  so you probably will get much faster results by setting the \"-E\" command-line\n");
		logmsg("  flag.\n");
		logmsg("\n\n");
	}

	quads->dimquads = me->dimquads;
	codes->dimcodes = dimcodes;
	quads->healpix = skhp;
	codes->healpix = skhp;
	quads->hpnside = sknside;
	codes->hpnside = sknside;
	if (id) {
		quads->indexid = id;
		codes->indexid = id;
	}

	qhdr = quadfile_get_header(quads);
	chdr = codefile_get_header(codes);

	add_headers(qhdr, args, argc, startree_header(me->starkd), circle, passes);
	add_headers(chdr, args, argc, startree_header(me->starkd), circle, passes);

    if (quadfile_write_header(quads)) {
        ERROR("Couldn't write headers to quad file");
		return -1;
    }
    if (codefile_write_header(codes)) {
        ERROR("Couldn't write headers to code file");
		return -1;
    }

    quads->numstars = codes->numstars = N;
	me->quad_dist2_upper = arcmin2distsq(scale_max_arcmin);
	me->quad_dist2_lower = arcmin2distsq(scale_min_arcmin);
    codes->index_scale_upper = quads->index_scale_upper = distsq2rad(me->quad_dist2_upper);
    codes->index_scale_lower = quads->index_scale_lower = distsq2rad(me->quad_dist2_lower);
	
	me->nuses = calloc(N, sizeof(unsigned char));

	// hprad = sqrt(2) * (healpix side length / 2.)
	hprad = arcmin2dist(healpix_side_length_arcmin(Nside)) * M_SQRT1_2;
	quadscale = 0.5 * sqrt(me->quad_dist2_upper);
	// 1.01 for a bit of safety.  we'll look at a few extra stars.
	radius2 = square(1.01 * (hprad + quadscale));
	me->radius2 = radius2;

	logmsg("Healpix radius %g arcsec, quad scale %g arcsec, total %g arcsec\n",
		   distsq2arcsec(hprad*hprad),
		   distsq2arcsec(quadscale*quadscale),
		   distsq2arcsec(radius2));

	hptotry = il_new(1024);

	if (scanoccupied) {
		logmsg("Scanning %i input stars...\n", N);
		for (i=0; i<N; i++) {
			double xyz[3];
			int j;
			if (startree_get(me->starkd, i, xyz)) {
				ERROR("Failed to get star %i", i);
				return -1;
			}
			j = xyzarrtohealpix(xyz, Nside);
			il_insert_unique_ascending(hptotry, j);
			if (log_get_level() > LOG_VERB) {
				double ra,dec;
				if (startree_get_radec(me->starkd, i, &ra, &dec)) {
					ERROR("Failed to get RA,Dec for star %i\n", i);
					return -1;
				}
				logdebug("star %i: RA,Dec %g,%g; xyz %g,%g,%g; hp %i\n",
						 i, ra, dec, xyz[0], xyz[1], xyz[2], j);
			}
		}
		logmsg("Will check %zu healpixes.\n", il_size(hptotry));
		if (log_get_level() > LOG_VERB) {
			logdebug("Checking healpixes: [ ");
			for (i=0; i<il_size(hptotry); i++)
				logdebug("%i ", il_get(hptotry, i));
			logdebug("]\n");
		}

	} else {
		if (skhp == -1) {
			// Try all healpixes.
			il_free(hptotry);
			hptotry = NULL;
			Nhptotry = NHP;
		} else {
			// The star kdtree may itself be healpixed
			int starhp, starx, stary;
			// In that case, the healpixes we are interested in form a rectangle
			// within a big healpix.  These are the coords (in [0, Nside)) of
			// that rectangle.
			int x0, x1, y0, y1;
			int x, y;

			healpix_decompose_xy(skhp, &starhp, &starx, &stary, sknside);
			x0 =  starx    * (Nside / sknside);
			x1 = (starx+1) * (Nside / sknside);
			y0 =  stary    * (Nside / sknside);
			y1 = (stary+1) * (Nside / sknside);

			for (y=y0; y<y1; y++) {
				for (x=x0; x<x1; x++) {
					int j = healpix_compose_xy(starhp, x, y, Nside);
					il_append(hptotry, j);
				}
			}
			assert(il_size(hptotry) == (Nside/sknside) * (Nside/sknside));
		}
	}
	if (hptotry)
		Nhptotry = il_size(hptotry);

	me->quadlist = bl_new(65536, quadsize);

	if (Nloosen)
		me->retryhps = il_new(1024);

	for (pass=0; pass<passes; pass++) {
		char key[64];
		int nthispass;

		logmsg("Pass %i of %i.\n", pass+1, passes);
		logmsg("Trying %i healpixes.\n", Nhptotry);

		nthispass = build_quads(me, Nhptotry, hptotry, Nreuses);

		logmsg("Made %i quads (out of %i healpixes) this pass.\n", nthispass, Nhptotry);
		logmsg("Made %i quads so far.\n", (me->bigquadlist ? bt_size(me->bigquadlist) : 0) + (int)bl_size(me->quadlist));

		sprintf(key, "PASS%i", pass+1);
		fits_header_mod_int(chdr, key, nthispass, "quads created in this pass");
		fits_header_mod_int(qhdr, key, nthispass, "quads created in this pass");

		logmsg("Merging quads...\n");
		if (!me->bigquadlist)
			me->bigquadlist = bt_new(quadsize, 256);
		for (i=0; i<bl_size(me->quadlist); i++) {
			void* q = bl_access(me->quadlist, i);
			bt_insert2(me->bigquadlist, q, FALSE, compare_quads, &me->dimquads);
		}
		bl_remove_all(me->quadlist);
	}

	il_free(hptotry);
	hptotry = NULL;

	if (Nloosen) {
		int R;
		for (R=Nreuses+1; R<=Nloosen; R++) {
			il* trylist;
			int nthispass;

			logmsg("Loosening reuse maximum to %i...\n", R);
			logmsg("Trying %zu healpixes.\n", il_size(me->retryhps));
			if (!il_size(me->retryhps))
				break;

			trylist = me->retryhps;
			me->retryhps = il_new(1024);
			nthispass = build_quads(me, il_size(trylist), trylist, R);
			logmsg("Made %i quads (out of %zu healpixes) this pass.\n", nthispass, il_size(trylist));
			il_free(trylist);
			for (i=0; i<bl_size(me->quadlist); i++) {
				void* q = bl_access(me->quadlist, i);
				bt_insert2(me->bigquadlist, q, FALSE, compare_quads, &me->dimquads);
			}
			bl_remove_all(me->quadlist);
		}
	}
	if (me->retryhps)
		il_free(me->retryhps);

	kdtree_free_query(me->res);
	me->res = NULL;
	me->inds = NULL;
	me->stars = NULL;
	free(me->nuses);
	me->nuses = NULL;

	logmsg("Writing quads...\n");

	// add the quads from the big-quadlist
	nquads = bt_size(me->bigquadlist);
	for (i=0; i<nquads; i++) {
		unsigned int* q = bt_access(me->bigquadlist, i);
		quad_write(codes, quads, q, me->starkd, me->dimquads, dimcodes);
	}
	// add the quads that were made during the final round.
	for (i=0; i<bl_size(me->quadlist); i++) {
		unsigned int* q = bl_access(me->quadlist, i);
		quad_write(codes, quads, q, me->starkd, me->dimquads, dimcodes);
	}

	// fix output file headers.
	if (quadfile_fix_header(quads)) {
		ERROR("Failed to fix quadfile headers");
		return -1;
	}
	if (codefile_fix_header(codes)) {
		ERROR("Failed to fix codefile headers");
		return -1;
	}

	bl_free(me->quadlist);
	bt_free(me->bigquadlist);

	toc();
	logmsg("Done.\n");
	return 0;
}
Пример #7
0
int main(int argc, char **argv) {
    int argchar;
	double ra=HUGE_VAL, dec=HUGE_VAL, radius=HUGE_VAL;
	int loglvl = LOG_MSG;
	char** myargs;
	int nmyargs;
	int i;
	char* outfn = NULL;
	fitstable_t* table = NULL;

    while ((argchar = getopt (argc, argv, OPTIONS)) != -1)
        switch (argchar) {
		case 'o':
			outfn = optarg;
			break;
		case 'r':
			ra = atof(optarg);
			break;
		case 'd':
			dec = atof(optarg);
			break;
		case 'R':
			radius = atof(optarg);
			break;
		case 'v':
			loglvl++;
			break;
        case '?':
            fprintf(stderr, "Unknown option `-%c'.\n", optopt);
		case 'h':
		default:
			printHelp(argv[0]);
			return -1;
		}
	log_init(loglvl);
	nmyargs = argc - optind;
	myargs = argv + optind;

	if (nmyargs < 1) {
		printHelp(argv[0]);
		exit(-1);
	}
	if (ra == HUGE_VAL || dec == HUGE_VAL || radius == HUGE_VAL) {
		printHelp(argv[0]);
		exit(-1);
	}

	if (outfn) {
		table = fitstable_open_for_writing(outfn);
		if (!table) {
			ERROR("Failed to open output table");
			exit(-1);
		}
		if (fitstable_write_primary_header(table)) {
			ERROR("Failed to write primary header of output table");
			exit(-1);
		}
	}

	for (i=0; i<nmyargs; i++) {
		char* indexfn = myargs[i];
		index_t index;
		sl* cols;
		int* inds;
		double* radecs;
		int N;
		int j;
		fitstable_t* tagtable = NULL;

		logmsg("Reading index \"%s\"...\n", indexfn);
		if (!index_load(indexfn, 0, &index)) {
			ERROR("Failed to read index \"%s\"", indexfn);
			continue;
		}

		logmsg("Index %s: id %i, healpix %i (nside %i), %i stars, %i quads, dimquads=%i, scales %g to %g arcmin.\n",
			   index.indexname, index.indexid, index.healpix, index.hpnside,
			   index.nstars, index.nquads, index.dimquads,
			   arcsec2arcmin(index.index_scale_lower),
			   arcsec2arcmin(index.index_scale_upper));

		cols = startree_get_tagalong_column_names(index.starkd, NULL);
		{
			char* colstr = sl_join(cols, ", ");
			logmsg("Tag-along columns: %s\n", colstr);
			free(colstr);
		}

		logmsg("Searching for stars around RA,Dec (%g, %g), radius %g deg.\n",
			   ra, dec, radius);
		startree_search_for_radec(index.starkd, ra, dec, radius,
								  NULL, &radecs, &inds, &N);
		logmsg("Found %i stars\n", N);

		if (table) {
			int tagsize;
			int rowsize;
			char* rowbuf = NULL;

			if (i > 0) {
				fitstable_next_extension(table);
				fitstable_clear_table(table);
			}

			tagtable = startree_get_tagalong(index.starkd);
			if (tagtable) {
				fitstable_add_fits_columns_as_struct(tagtable);
				logverb("Input tag-along table:\n");
				if (log_get_level() >= LOG_VERB)
					fitstable_print_columns(tagtable);
				fitstable_copy_columns(tagtable, table);
			}
			tagsize = fitstable_get_struct_size(table);
			debug("tagsize=%i\n", tagsize);
			// Add RA,Dec at the end of the row...
			fitstable_add_write_column_struct(table, fitscolumn_double_type(), 1, tagsize, fitscolumn_double_type(), "RA", "degrees");
			fitstable_add_write_column_struct(table, fitscolumn_double_type(), 1, tagsize + sizeof(double), fitscolumn_double_type(), "DEC", "degrees");
			rowsize = fitstable_get_struct_size(table);
			assert(rowsize == tagsize + 2*sizeof(double));
			debug("rowsize=%i\n", rowsize);
			rowbuf = malloc(rowsize);

			logverb("Output table:\n");
			if (log_get_level() >= LOG_VERB)
				fitstable_print_columns(table);

			if (fitstable_write_header(table)) {
				ERROR("Failed to write header of output table");
				exit(-1);
			}

			for (j=0; j<N; j++) {
				if (tagtable) {
					if (fitstable_read_struct(tagtable, inds[j], rowbuf)) {
						ERROR("Failed to read row %i of tag-along table", inds[j]);
						exit(-1);
					}
				}
				// Add RA,Dec to end of struct...
				memcpy(rowbuf + tagsize, radecs+2*j+0, sizeof(double));
				memcpy(rowbuf + tagsize + sizeof(double), radecs+2*j+1, sizeof(double));
				if (fitstable_write_struct(table, rowbuf)) {
					ERROR("Failed to write row %i of output", j);
					exit(-1);
				}
			}
			free(rowbuf);

			if (fitstable_fix_header(table)) {
				ERROR("Failed to fix header of output table");
				exit(-1);
			}

		}

		sl_free2(cols);
		free(radecs);
		free(inds);

		index_close(&index);
	}

	if (table) {
		if (fitstable_close(table)) {
			ERROR("Failed to close output table");
			exit(-1);
		}
	}

	return 0;
}
Пример #8
0
int main(int argc, char** args) {
    int c;
    char* rdlsfn = NULL;
    char* wcsfn = NULL;
    char* xylsfn = NULL;
    char* rcol = NULL;
    char* dcol = NULL;
    anbool forcetan = FALSE;
    il* fields;
    int ext = 0;
    double ra=HUGE_VAL, dec=HUGE_VAL;
    anbool wcslib = FALSE;
    int loglvl = LOG_MSG;

    fields = il_new(16);

    while ((c = getopt(argc, args, OPTIONS)) != -1) {
        switch (c) {
        case 'v':
            loglvl++;
            break;
        case 'L':
            wcslib = TRUE;
            break;
        case 'r':
            ra = atof(optarg);
            break;
        case 'd':
            dec = atof(optarg);
            break;
        case 'e':
            ext = atoi(optarg);
            break;
        case 'h':
            print_help(args[0]);
            exit(0);
        case 't':
            forcetan = TRUE;
            break;
        case 'o':
            xylsfn = optarg;
            break;
        case 'i':
            rdlsfn = optarg;
            break;
        case 'w':
            wcsfn = optarg;
            break;
        case 'f':
            il_append(fields, atoi(optarg));
            break;
        case 'R':
            rcol = optarg;
            break;
        case 'D':
            dcol = optarg;
            break;
        }
    }

    log_init(loglvl);

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

    if (!(wcsfn && ((rdlsfn && xylsfn) || ((ra != HUGE_VAL) && (dec != HUGE_VAL))))) {
        print_help(args[0]);
        exit(-1);
    }

    if (!rdlsfn) {
        double x,y;
        anwcs_t* wcs = NULL;

        // read WCS.
        if (wcslib) {
            wcs = anwcs_open_wcslib(wcsfn, ext);
        } else if (forcetan) {
            wcs = anwcs_open_tan(wcsfn, ext);
        } else {
            wcs = anwcs_open(wcsfn, ext);
        }
        if (!wcs) {
            ERROR("Failed to read WCS file");
            exit(-1);
        }
        logverb("Read WCS:\n");
        if (log_get_level() >= LOG_VERB) {
            anwcs_print(wcs, log_get_fid());
        }

        // convert immediately.
        if (anwcs_radec2pixelxy(wcs, ra, dec, &x, &y)) {
            ERROR("The given RA,Dec is on the opposite side of the sky.");
            exit(-1);
        }
        printf("RA,Dec (%.10f, %.10f) -> pixel (%.10f, %.10f)\n", ra, dec, x, y);
        anwcs_free(wcs);
        exit(0);
    }


    if (wcs_rd2xy(wcsfn, ext, rdlsfn, xylsfn,
                  rcol, dcol, forcetan, wcslib, fields)) {
        ERROR("wcs-rd2xy failed");
        exit(-1);
    }

    return 0;
}
Пример #9
0
sip_t* wcs_pv2sip_header(qfits_header* hdr,
                         double* xy, int Nxy,
               
                         double stepsize,
                         double xlo, double xhi,
                         double ylo, double yhi,

                         int imageW, int imageH,
                         int order,
                         anbool forcetan,
                         int doshift) {
	double* radec = NULL;
	int rtn = -1;
	tan_t tanwcs;
	double x,y, px,py;
	double* rddist = NULL;
	int i, j;
    int nx, ny;
    double xstep, ystep;
    sip_t* sip = NULL;

    /**
     From http://iraf.noao.edu/projects/mosaic/tpv.html

     p = PV1_

     xi' = p0 +
           p1 * xi + p2 * eta + p3 * r +
           p4 * xi^2 + p5 * xi * eta + p6 * eta^2 +
           p7 * xi^3 + p8 * xi^2 * eta + p9 * xi * eta^2 +
              p10 * eta^3 + p11 * r^3 + 
           p12 * xi^4 + p13 * xi^3 * eta + p14 * xi^2 * eta^2 +
              p15 * xi * eta^3 + p16 * eta^4 +
	       p17 * xi^5 + p18 * xi^4 * eta + p19 * xi^3 * eta^2 +
	          p20 * xi^2 * eta^3 + p21 * xi * eta^4 + p22 * eta^5 + p23 * r^5 +
           p24 * xi^6 + p25 * xi^5 * eta + p26 * xi^4 * eta^2 +
              p27 * xi^3 * eta^3 + p28 * xi^2 * eta^4 + p29 * xi * eta^5 +
              p30 * eta^6
           p31 * xi^7 + p32 * xi^6 * eta + p33 * xi^5 * eta^2 +
              p34 * xi^4 * eta^3 + p35 * xi^3 * eta^4 + p36 * xi^2 * eta^5 +
              p37 * xi * eta^6 + p38 * eta^7 + p39 * r^7

     p = PV2_
     eta' = p0 +
            p1 * eta + p2 * xi + p3 * r +
            p4 * eta^2 + p5 * eta * xi + p6 * xi^2 +
            p7 * eta^3 + p8 * eta^2 * xi + p9 * eta * xi^2 + p10 * xi^3 +
                 p11 * r^3 +
            p12 * eta^4 + p13 * eta^3 * xi + p14 * eta^2 * xi^2 +
                 p15 * eta * xi^3 + p16 * xi^4 +
            p17 * eta^5 + p18 * eta^4 * xi + p19 * eta^3 * xi^2 +
	             p20 * eta^2 * xi^3 + p21 * eta * xi^4 + p22 * xi^5 +
                 p23 * r^5 +
            p24 * eta^6 + p25 * eta^5 * xi + p26 * eta^4 * xi^2 +
                 p27 * eta^3 * xi^3 + p28 * eta^2 * xi^4 + p29 * eta * xi^5 +
                 p30 * xi^6
            p31 * eta^7 + p32 * eta^6 * xi + p33 * eta^5 * xi^2 +
                 p34 * eta^4 * xi^3 + p35 * eta^3 * xi^4 + p36 * eta^2 * xi^5 +
                 p37 * eta * xi^6 + p38 * xi^7 + p39 * r^7

     Note the "cross-over" -- the xi' powers are in terms of xi,eta
     while the eta' powers are in terms of eta,xi.
     */

	//           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, 0, 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, 5, 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;

    char* ct;
    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");
    }

	tan_read_header(hdr, &tanwcs);

    if (log_get_level() >= LOG_VERB) {
        printf("Read TAN header:\n");
        tan_print(&tanwcs);
    }

    if (imageW && (imageW != tanwcs.imagew)) {
        logmsg("Overriding image width %f with user-specified %i\n",
               tanwcs.imagew, imageW);
        tanwcs.imagew = imageW;
    }
    if (imageH && (imageH != tanwcs.imageh)) {
        logmsg("Overriding image height %f with user-specified %i\n",
               tanwcs.imageh, imageH);
        tanwcs.imageh = imageH;
    }

	for (i=0; i<sizeof(pv1)/sizeof(double); i++) {
		char key[10];
        double defaultval;

        if (i == 1) {
            defaultval = 1.0;
        } else {
            defaultval = 0.0;
        }
		sprintf(key, "PV1_%i", i);
		pv1[i] = qfits_header_getdouble(hdr, key, defaultval);
		sprintf(key, "PV2_%i", i);
		pv2[i] = qfits_header_getdouble(hdr, key, defaultval);
	}


    // choose grid for evaluating TAN-PV WCS
    if (xlo == 0 && xhi == 0) {
        xlo = 1.;
        xhi = tanwcs.imagew;
    }
    if (ylo == 0 && yhi == 0) {
        ylo = 1.;
        yhi = tanwcs.imageh;
    }

	assert(xhi >= xlo);
	assert(yhi >= ylo);

	if (stepsize == 0)
        stepsize = 100.;
    nx = MAX(2, round((xhi - xlo)/stepsize));
    ny = MAX(2, round((yhi - ylo)/stepsize));
    xstep = (xhi - xlo) / (double)(nx - 1);
    ystep = (yhi - ylo) / (double)(ny - 1);

	logverb("Stepping from x = %g to %g, steps of %g\n", xlo, xhi, xstep);
	logverb("Stepping from y = %g to %g, steps of %g\n", ylo, yhi, ystep);

    Nxy = nx * ny;

    if (xy == NULL) {
        int k = 0;
        xy = malloc(Nxy * 2 * sizeof(double));
        for (i=0; i<ny; i++) {
            y = ylo + i*ystep;
            for (j=0; j<nx; j++) {
                x = xlo + j*xstep;
                //if (i == 0)
                //printf("x=%f\n", x);
                xy[k] = x;
                k++;
                xy[k] = y;
                k++;
            }
            //printf("y=%f\n", y);
        }
        assert(k == (Nxy*2));
    }

    // distorted RA,Dec
	rddist = malloc(2 * Nxy * sizeof(double));

	for (j=0; j<Nxy; j++) {
        double ix = xy[2*j+0];
		double iy = xy[2*j+1];

		tan_pixelxy2iwc(&tanwcs, ix, iy, &x, &y);
        // "x,y" here are most commonly known as "xi, eta".
		r = sqrt(x*x + y*y);
        // compute powers of x,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]];
            // here's the "cross-over" mentioned above
			py += pv2[i] * ypows[xp[i]] * xpows[yp[i]] * rpows[rp[i]];
		}

        // Note that the PV terms *include* a linear term, so no need
        // to re-add x,y to px,py.
        tan_iwc2radec(&tanwcs, px, py,
                      rddist + 2*j, rddist + 2*j + 1);
	}

    sip = malloc(sizeof(sip_t));
    assert(sip);
    {
        double* starxyz;
        starxyz = malloc(3 * Nxy * sizeof(double));
        for (i=0; i<Nxy; i++)
            radecdegarr2xyzarr(rddist + i*2, starxyz + i*3);
        memset(sip, 0, sizeof(sip_t));
        rtn = fit_sip_coefficients(starxyz, xy, NULL, Nxy,
                                   &tanwcs, order, order, sip);
        assert(rtn == 0);

        if (log_get_level() >= LOG_VERB) {
            printf("Fit SIP:\n");
            sip_print(sip);
        }

        // FIXME? -- use xlo,xhi,ylo,yhi here??  Not clear.
        sip_compute_inverse_polynomials(sip, 0, 0, 0, 0, 0, 0);

        if (log_get_level() >= LOG_VERB) {
            printf("Fit SIP inverse polynomials:\n");
            sip_print(sip);
        }
        free(starxyz);
    }

	free(rddist);
	free(radec);
    return sip;
}
Пример #10
0
sip_t* tweak2(const double* fieldxy, int Nfield,
			  double fieldjitter,
			  int W, int H,
			  const double* indexradec, int Nindex,
			  double indexjitter,
			  const double* quadcenter, double quadR2,
			  double distractors,
			  double logodds_bail,
			  int sip_order,
			  int sip_invorder,
			  const sip_t* startwcs,
			  sip_t* destwcs,
			  int** newtheta, double** newodds,
			  double* crpix,
			  double* p_logodds,
			  int* p_besti,
			  int* testperm,
			  int startorder) {
	int order;
	sip_t* sipout;
	int* indexin;
	double* indexpix;
	double* fieldsigma2s;
	double* weights;
	double* matchxyz;
	double* matchxy;
	int i, Nin=0;
	double logodds = 0;
	int besti = -1;
	int* theta = NULL;
	double* odds = NULL;
	int* refperm = NULL;
	double qc[2];

	memcpy(qc, quadcenter, 2*sizeof(double));

	if (destwcs)
		sipout = destwcs;
	else
		sipout = sip_create();

	indexin = malloc(Nindex * sizeof(int));
	indexpix = malloc(2 * Nindex * sizeof(double));
	fieldsigma2s = malloc(Nfield * sizeof(double));
	weights = malloc(Nfield * sizeof(double));
	matchxyz = malloc(Nfield * 3 * sizeof(double));
	matchxy = malloc(Nfield * 2 * sizeof(double));

	// FIXME --- hmmm, how do the annealing steps and iterating up to
	// higher orders interact?

	assert(startwcs);
	memcpy(sipout, startwcs, sizeof(sip_t));

	logverb("tweak2: starting orders %i, %i\n", sipout->a_order, sipout->ap_order);

	if (!sipout->wcstan.imagew)
		sipout->wcstan.imagew = W;
	if (!sipout->wcstan.imageh)
		sipout->wcstan.imageh = H;

	logverb("Tweak2: starting from WCS:\n");
	if (log_get_level() >= LOG_VERB)
		sip_print_to(sipout, stdout);

	for (order=startorder; order <= sip_order; order++) {
		int step;
		int STEPS = 100;
		// variance growth rate wrt radius.
		double gamma = 1.0;
		//logverb("Starting tweak2 order=%i\n", order);

		for (step=0; step<STEPS; step++) {
			double iscale;
			double ijitter;
			double ra, dec;
			double R2;
			int Nmatch;
			int nmatch, nconf, ndist;
			double pix2;
			double totalweight;

			// clean up from last round (we do it here so that they're
			// valid when we leave the loop)
			free(theta);
			free(odds);
			free(refperm);

			// Anneal
			gamma = pow(0.9, step);
			if (step == STEPS-1)
				gamma = 0.0;
			logverb("Annealing: order %i, step %i, gamma = %g\n", order, step, gamma);
			
			debug("Using input WCS:\n");
			if (log_get_level() > LOG_VERB)
				sip_print_to(sipout, stdout);

			// Project reference sources into pixel space; keep the ones inside image bounds.
			Nin = 0;
			for (i=0; i<Nindex; i++) {
				anbool ok;
				double x,y;
				ra  = indexradec[2*i + 0];
				dec = indexradec[2*i + 1];
				ok = sip_radec2pixelxy(sipout, ra, dec, &x, &y);
				if (!ok)
					continue;
				if (!sip_pixel_is_inside_image(sipout, x, y))
					continue;
				indexpix[Nin*2+0] = x;
				indexpix[Nin*2+1] = y;
				indexin[Nin] = i;
				Nin++;
			}
			logverb("%i reference sources within the image.\n", Nin);
			//logverb("CRPIX is (%g,%g)\n", sip.wcstan.crpix[0], sip.wcstan.crpix[1]);

            if (Nin == 0) {
				sip_free(sipout);
				free(matchxy);
				free(matchxyz);
				free(weights);
				free(fieldsigma2s);
				free(indexpix);
				free(indexin);
                return NULL;
            }

			iscale = sip_pixel_scale(sipout);
			ijitter = indexjitter / iscale;
			//logverb("With pixel scale of %g arcsec/pixel, index adds jitter of %g pix.\n", iscale, ijitter);

			/* CHECK
			 for (i=0; i<Nin; i++) {
			 double x,y;
			 int ii = indexin[i];
			 sip_radec2pixelxy(sipout, indexradec[2*ii+0], indexradec[2*ii+1], &x, &y);
			 logverb("indexin[%i]=%i; (%.1f,%.1f) -- (%.1f,%.1f)\n",
			 i, ii, indexpix[i*2+0], indexpix[i*2+1], x, y);
			 }
			 */

			for (i=0; i<Nfield; i++) {
				R2 = distsq(qc, fieldxy + 2*i, 2);
				fieldsigma2s[i] = (square(fieldjitter) + square(ijitter)) * (1.0 + gamma * R2/quadR2);
			}

			if (order == 1 && step == 0 && TWEAK_DEBUG_PLOTS) {
				TWEAK_DEBUG_PLOT("init", W, H, Nfield, fieldxy, fieldsigma2s,
								 Nin, indexpix, *p_besti, *newtheta,
								 sipout->wcstan.crpix, testperm, qc);
			}

			/*
			 logodds = verify_star_lists(indexpix, Nin,
			 fieldxy, fieldsigma2s, Nfield,
			 W*H, distractors,
			 logodds_bail, HUGE_VAL,
			 &besti, &odds, &theta, NULL,
			 &testperm);
			 */

			pix2 = square(fieldjitter);
			logodds = verify_star_lists_ror(indexpix, Nin,
											fieldxy, fieldsigma2s, Nfield,
											pix2, gamma, qc, quadR2,
											W, H, distractors,
											logodds_bail, HUGE_VAL,
											&besti, &odds, &theta, NULL,
											&testperm, &refperm);

			logverb("Logodds: %g\n", logodds);
			verify_count_hits(theta, besti, &nmatch, &nconf, &ndist);
			logverb("%i matches, %i distractors, %i conflicts (at best log-odds); %i field sources, %i index sources\n", nmatch, ndist, nconf, Nfield, Nin);
			verify_count_hits(theta, Nfield-1, &nmatch, &nconf, &ndist);
			logverb("%i matches, %i distractors, %i conflicts (all sources)\n", nmatch, ndist, nconf);
			if (log_get_level() >= LOG_VERB) {
				matchobj_log_hit_miss(theta, testperm, besti+1, Nfield, LOG_VERB, "Hit/miss: ");
			}

			/*
			 logverb("\nAfter verify():\n");
			 for (i=0; i<Nin; i++) {
			 double x,y;
			 int ii = indexin[refperm[i]];
			 sip_radec2pixelxy(sipout, indexradec[2*ii+0], indexradec[2*ii+1], &x, &y);
			 logverb("indexin[%i]=%i; (%.1f,%.1f) -- (%.1f,%.1f)\n",
			 i, ii, indexpix[i*2+0], indexpix[i*2+1], x, y);
			 }
			 */

			if (TWEAK_DEBUG_PLOTS) {
				char name[32];
				sprintf(name, "o%is%02ipre", order, step);
				TWEAK_DEBUG_PLOT(name, W, H, Nfield, fieldxy, fieldsigma2s,
								 Nin, indexpix, besti, theta,
								 sipout->wcstan.crpix, testperm, qc);
			}

			Nmatch = 0;
			debug("Weights:");
			for (i=0; i<Nfield; i++) {
				double ra,dec;
				if (theta[i] < 0)
					continue;
				assert(theta[i] < Nin);
				int ii = indexin[refperm[theta[i]]];
				assert(ii < Nindex);
				assert(ii >= 0);

				ra  = indexradec[ii*2+0];
				dec = indexradec[ii*2+1];
				radecdeg2xyzarr(ra, dec, matchxyz + Nmatch*3);
				memcpy(matchxy + Nmatch*2, fieldxy + i*2, 2*sizeof(double));
				weights[Nmatch] = verify_logodds_to_weight(odds[i]);
				debug(" %.2f", weights[Nmatch]);
				Nmatch++;

				/*
				 logverb("match img (%.1f,%.1f) -- ref (%.1f, %.1f), odds %g, wt %.3f\n",
				 fieldxy[i*2+0], fieldxy[i*2+1],
				 indexpix[theta[i]*2+0], indexpix[theta[i]*2+1],
				 odds[i],
				 weights[Nmatch-1]);
				 double xx,yy;
				 sip_radec2pixelxy(sipout, ra, dec, &xx, &yy);
				 logverb("check: (%.1f, %.1f)\n", xx, yy);
				 */
			}
			debug("\n");

			if (Nmatch < 2) {
				logverb("No matches -- aborting tweak attempt\n");
				free(theta);
				sip_free(sipout);
				free(matchxy);
				free(matchxyz);
				free(weights);
				free(fieldsigma2s);
				free(indexpix);
				free(indexin);
				return NULL;
			}

			// Update the "quad center" to be the weighted average matched star posn.
			qc[0] = qc[1] = 0.0;
			totalweight = 0.0;
			for (i=0; i<Nmatch; i++) {
				qc[0] += (weights[i] * matchxy[2*i+0]);
				qc[1] += (weights[i] * matchxy[2*i+1]);
				totalweight += weights[i];
			}
			qc[0] /= totalweight;
			qc[1] /= totalweight;
			logverb("Moved quad center to (%.1f, %.1f)\n", qc[0], qc[1]);

            //
            sipout->a_order = sipout->b_order = order;
            sipout->ap_order = sipout->bp_order = sip_invorder;
            logverb("tweak2: setting orders %i, %i\n", sipout->a_order, sipout->ap_order);

            if (crpix) {
                tan_t temptan;
                logverb("Moving tangent point to given CRPIX (%g,%g)\n", crpix[0], crpix[1]);
                fit_tan_wcs_move_tangent_point_weighted(matchxyz, matchxy, weights, Nmatch,
                                                        crpix, &sipout->wcstan, &temptan);
                fit_tan_wcs_move_tangent_point_weighted(matchxyz, matchxy, weights, Nmatch,
                                                        crpix, &temptan, &sipout->wcstan);
            }

            int doshift = 1;
            fit_sip_wcs(matchxyz, matchxy, weights, Nmatch,
                        &(sipout->wcstan), order, sip_invorder,
                        doshift, sipout);

            debug("Got SIP:\n");
            if (log_get_level() > LOG_VERB)
                sip_print_to(sipout, stdout);
            sipout->wcstan.imagew = W;
            sipout->wcstan.imageh = H;
		}
	}

	//logverb("Final logodds: %g\n", logodds);

	// Now, recompute final logodds after turning 'gamma' on again (?)
	// FIXME -- this counts the quad stars in the logodds...
	{
		double gamma = 1.0;
		double iscale;
		double ijitter;
		double ra, dec;
		double R2;
		int nmatch, nconf, ndist;
		double pix2;

		free(theta);
		free(odds);
		free(refperm);
		gamma = 1.0;
		// Project reference sources into pixel space; keep the ones inside image bounds.
		Nin = 0;
		for (i=0; i<Nindex; i++) {
			anbool ok;
			double x,y;
			ra  = indexradec[2*i + 0];
			dec = indexradec[2*i + 1];
			ok = sip_radec2pixelxy(sipout, ra, dec, &x, &y);
			if (!ok)
				continue;
			if (!sip_pixel_is_inside_image(sipout, x, y))
				continue;
			indexpix[Nin*2+0] = x;
			indexpix[Nin*2+1] = y;
			indexin[Nin] = i;
			Nin++;
		}
		logverb("%i reference sources within the image.\n", Nin);

		iscale = sip_pixel_scale(sipout);
		ijitter = indexjitter / iscale;
		for (i=0; i<Nfield; i++) {
			R2 = distsq(qc, fieldxy + 2*i, 2);
			fieldsigma2s[i] = (square(fieldjitter) + square(ijitter)) * (1.0 + gamma * R2/quadR2);
		}

		pix2 = square(fieldjitter);
		logodds = verify_star_lists_ror(indexpix, Nin,
										fieldxy, fieldsigma2s, Nfield,
										pix2, gamma, qc, quadR2,
										W, H, distractors,
										logodds_bail, HUGE_VAL,
										&besti, &odds, &theta, NULL,
										&testperm, &refperm);
		logverb("Logodds: %g\n", logodds);
		verify_count_hits(theta, besti, &nmatch, &nconf, &ndist);
		logverb("%i matches, %i distractors, %i conflicts (at best log-odds); %i field sources, %i index sources\n", nmatch, ndist, nconf, Nfield, Nin);
		verify_count_hits(theta, Nfield-1, &nmatch, &nconf, &ndist);
		logverb("%i matches, %i distractors, %i conflicts (all sources)\n", nmatch, ndist, nconf);
		if (log_get_level() >= LOG_VERB) {
			matchobj_log_hit_miss(theta, testperm, besti+1, Nfield, LOG_VERB,
								  "Hit/miss: ");
		}

		if (TWEAK_DEBUG_PLOTS) {
			TWEAK_DEBUG_PLOT("final", W, H, Nfield, fieldxy, fieldsigma2s,
							 Nin, indexpix, besti, theta,
							 sipout->wcstan.crpix, testperm, qc);
		}
	}


	if (newtheta) {
		// undo the "indexpix" inside-image-bounds cut.
		(*newtheta) = malloc(Nfield * sizeof(int));
		for (i=0; i<Nfield; i++) {
			int nt;
			if (theta[i] < 0)
				nt = theta[i];
			else
				nt = indexin[refperm[theta[i]]];
			(*newtheta)[i] = nt;
		}
	}
	free(theta);
	free(refperm);

	if (newodds)
		*newodds = odds;
	else
		free(odds);

	logverb("Tweak2: final WCS:\n");
	if (log_get_level() >= LOG_VERB)
		sip_print_to(sipout, stdout);

	if (p_logodds)
		*p_logodds = logodds;
	if (p_besti)
		*p_besti = besti;

	free(indexin);
	free(indexpix);
	free(fieldsigma2s);
	free(weights);
	free(matchxyz);
	free(matchxy);

	return sipout;
}
Пример #11
0
int main(int argc, char** args) {
	int c;
	char* rdlsfn = NULL;
	char* wcsfn = NULL;
	char* xylsfn = NULL;
	char* xcol = NULL;
	char* ycol = NULL;
	anbool forcetan = FALSE;
	anbool forcewcslib = FALSE;
	anbool forcewcstools = FALSE;
	anbool printhms = FALSE;
	il* fields;
	int ext = 0;
	double x, y;
	int loglvl = LOG_MSG;

	x = y = HUGE_VAL;
	fields = il_new(16);

    while ((c = getopt(argc, args, OPTIONS)) != -1) {
        switch (c) {
		case 'v':
			loglvl++;
			break;
		case 's':
			printhms = TRUE;
			break;
		case 'L':
			forcewcslib = TRUE;
			break;
		case 'T':
			forcewcstools = TRUE;
			break;
		case 'x':
			x = atof(optarg);
			break;
		case 'y':
			y = atof(optarg);
			break;
		case 'e':
			ext = atoi(optarg);
			break;
        case 'h':
			print_help(args[0]);
			exit(0);
		case 't':
			forcetan = TRUE;
			break;
		case 'o':
			rdlsfn = optarg;
			break;
		case 'i':
			xylsfn = optarg;
			break;
		case 'w':
			wcsfn = optarg;
			break;
		case 'f':
			il_append(fields, atoi(optarg));
			break;
		case 'X':
			xcol = optarg;
			break;
		case 'Y':
			ycol = optarg;
			break;
		}
	}

	log_init(loglvl);

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

	if (!(wcsfn && ((rdlsfn && xylsfn) || ((x != HUGE_VAL) && (y != HUGE_VAL))))) {
		print_help(args[0]);
		exit(-1);
	}

	if (!xylsfn) {
		double ra,dec;
		anwcs_t* wcs = NULL;

		// read WCS.
		if (forcewcslib) {
			wcs = anwcs_open_wcslib(wcsfn, ext);
		} else if (forcewcstools) {
			wcs = anwcs_open_wcstools(wcsfn, ext);
		} else if (forcetan) {
			wcs = anwcs_open_tan(wcsfn, ext);
		} else {
			wcs = anwcs_open(wcsfn, ext);
		}
		if (!wcs) {
			ERROR("Failed to read WCS file \"%s\", extension %i", wcsfn, ext);
			exit(-1);
		}

		logverb("Read WCS:\n");
		if (log_get_level() >= LOG_VERB) {
			anwcs_print(wcs, log_get_fid());
		}

		// convert immediately.
		anwcs_pixelxy2radec(wcs, x, y, &ra, &dec);
		printf("Pixel (%.10f, %.10f) -> RA,Dec (%.10f, %.10f)\n", x, y, ra, dec);
		if (printhms) {
			char str[32];
			ra2hmsstring(ra, str);
			printf("                       RA,Dec (%20s, ", str);
			dec2dmsstring(dec, str);
			printf("%20s)\n", str);
		}
		anwcs_free(wcs);
		exit(0);
	}

    if (wcs_xy2rd(wcsfn, ext, xylsfn, rdlsfn, 
                  xcol, ycol, forcetan, forcewcslib, fields)) {
        ERROR("wcs-xy2rd failed");
        exit(-1);
    }

	return 0;
}
Пример #12
0
/*
 * Write a configuration to the config file.
 */
static void write_config(struct config_s *config)
{
#ifdef WINDOWS
    remove(CONFIG_BAK_FILENAME);    // For windows rename() bug.
#endif
    if (rename(CONFIG_FILENAME, CONFIG_BAK_FILENAME) != 0 && errno != ENOENT)
    {
        warning("unable to back-up old configuation file \"%s\" to \"%s\"",
            CONFIG_FILENAME, CONFIG_BAK_FILENAME);
    }
    errno = 0;

    FILE *file = fopen(CONFIG_TMP_FILENAME, "w");
    if (file == NULL)
    {
        warning("unable to open configuration file \"%s\" for writing",
            CONFIG_TMP_FILENAME);
        return;
    }
    fprintf(file, "# %s configuration file\n", PROGRAM_NAME_LONG);
    fputs("# AUTOMATICALLY GENERATED, DO NOT EDIT\n", file);
    fputc('\n', file);
    fprintf(file, "%s = \"%s\"\n", VAR_ENABLED,
        bool_to_string(config->enabled));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP,
        bool_to_string(config->hide_tcp));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_DATA,
        bool_to_string(config->hide_tcp_data));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_SYN,
        enum_to_string(config->hide_tcp_syn, flag_def, DEF_SIZE(flag_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_ACK,
        enum_to_string(config->hide_tcp_ack, flag_def, DEF_SIZE(flag_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_PSH,
        enum_to_string(config->hide_tcp_psh, flag_def, DEF_SIZE(flag_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_FIN,
        enum_to_string(config->hide_tcp_fin, flag_def, DEF_SIZE(flag_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_RST,
        enum_to_string(config->hide_tcp_rst, flag_def, DEF_SIZE(flag_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_UDP,
        bool_to_string(config->hide_udp));
    fprintf(file, "%s = \"%s\"\n", VAR_SPLIT_MODE,
        enum_to_string(config->split, split_def, DEF_SIZE(split_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_LOG_LEVEL,
        enum_to_string((config_enum_t)log_get_level(), log_level_def,
        DEF_SIZE(log_level_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_GHOST_MODE,
        enum_to_string(config->ghost, ghost_def, DEF_SIZE(ghost_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_GHOST_CHECK,
        bool_to_string(config->ghost_check));
    fprintf(file, "%s = \"%s\"\n", VAR_GHOST_SET_TTL,
        bool_to_string(config->ghost_set_ttl));
    fprintf(file, "%s = \"%u\"\n", VAR_GHOST_TTL, config->ghost_ttl);
    fprintf(file, "%s = \"%s\"\n", VAR_FRAG_MODE,
        enum_to_string(config->fragment, frag_def, DEF_SIZE(frag_def)));
    fprintf(file, "%s = \"%u\"\n", VAR_TCP_PORT, config->tcp_port);
    fprintf(file, "%s = \"%s\"\n", VAR_TCP_PROTO,
        protocol_get_name(config->tcp_proto));
    fprintf(file, "%s = \"%u\"\n", VAR_UDP_PORT, config->udp_port);
    fprintf(file, "%s = \"%s\"\n", VAR_UDP_PROTO,
        protocol_get_name(config->udp_proto));
    fprintf(file, "%s = \"%u\"\n", VAR_MTU, config->mtu);
    fprintf(file, "%s = \"%s\"\n", VAR_LAUNCH_UI,
        bool_to_string(config->launch_ui));
    fclose(file);

#ifdef WINDOWS
    remove(CONFIG_FILENAME);
#endif
    if (rename(CONFIG_TMP_FILENAME, CONFIG_FILENAME) != 0)
    {
        warning("unable to move temporary configuration file \"%s\" to \"%s\"",
            CONFIG_TMP_FILENAME, CONFIG_FILENAME);
    }
}
Пример #13
0
/*
 * Call-back from the configuration server; save the configuration state.
 */
void config_callback(struct http_user_vars_s *vars)
{
    bool should_save;
    if (http_user_var_lookup(vars, VAR_POST) == NULL)
    {
        // This is a GET request -- initialise variables:
        char buff[32];
        http_user_var_insert(vars, VAR_ENABLED,
            bool_to_string(config.enabled));
        http_user_var_insert(vars, VAR_HIDE_TCP,
            bool_to_string(config.hide_tcp));
        http_user_var_insert(vars, VAR_HIDE_TCP_DATA,
            bool_to_string(config.hide_tcp_data));
        http_user_var_insert(vars, VAR_HIDE_TCP_SYN,
            enum_to_string(config.hide_tcp_syn, flag_def, DEF_SIZE(flag_def)));
        http_user_var_insert(vars, VAR_HIDE_TCP_ACK,
            enum_to_string(config.hide_tcp_ack, flag_def, DEF_SIZE(flag_def)));
        http_user_var_insert(vars, VAR_HIDE_TCP_PSH,
            enum_to_string(config.hide_tcp_psh, flag_def, DEF_SIZE(flag_def)));
        http_user_var_insert(vars, VAR_HIDE_TCP_FIN,
            enum_to_string(config.hide_tcp_fin, flag_def, DEF_SIZE(flag_def)));
        http_user_var_insert(vars, VAR_HIDE_TCP_RST,
            enum_to_string(config.hide_tcp_rst, flag_def, DEF_SIZE(flag_def)));
        http_user_var_insert(vars, VAR_SPLIT_MODE,
            enum_to_string(config.split, split_def, DEF_SIZE(split_def)));
        http_user_var_insert(vars, VAR_LOG_LEVEL,
            enum_to_string((config_enum_t)log_get_level(), log_level_def,
            DEF_SIZE(log_level_def)));
        http_user_var_insert(vars, VAR_HIDE_UDP,
            bool_to_string(config.hide_udp));
        http_user_var_insert(vars, VAR_GHOST_MODE,
            enum_to_string(config.ghost, ghost_def, DEF_SIZE(ghost_def)));
        http_user_var_insert(vars, VAR_GHOST_CHECK,
            bool_to_string(config.ghost_check));
        http_user_var_insert(vars, VAR_GHOST_SET_TTL,
            bool_to_string(config.ghost_set_ttl));
        snprintf(buff, sizeof(buff)-1, "%u", config.ghost_ttl);
        http_user_var_insert(vars, VAR_GHOST_TTL, buff);
        http_user_var_insert(vars, VAR_FRAG_MODE,
            enum_to_string(config.fragment, frag_def, DEF_SIZE(frag_def)));
        snprintf(buff, sizeof(buff)-1, "%u", config.tcp_port);
        http_user_var_insert(vars, VAR_TCP_PORT, buff);
        http_user_var_insert(vars, VAR_TCP_PROTO,
            protocol_get_name(config.tcp_proto));
        snprintf(buff, sizeof(buff)-1, "%u", config.udp_port);
        http_user_var_insert(vars, VAR_UDP_PORT, buff);
        http_user_var_insert(vars, VAR_UDP_PROTO,
            protocol_get_name(config.udp_proto));
        snprintf(buff, sizeof(buff)-1, "%u", config.mtu);
        http_user_var_insert(vars, VAR_MTU, buff);
        http_user_var_insert(vars, VAR_LAUNCH_UI,
            bool_to_string(config.launch_ui));

    }
    else if (http_get_bool_var(vars, VAR_SAVE, &should_save) && should_save)
    {
        // This is a POST request that wishes to save a new configuration:
        struct config_s config_temp;
        memmove(&config_temp, &config, sizeof(struct config_s));
        load_config(vars, &config_temp);

        // Copy to the global configuration state.
        thread_lock(&config_lock);
        memmove(&config, &config_temp, sizeof(struct config_s));
        thread_unlock(&config_lock);

        // Save the new configuration to disk.
        write_config(&config_temp);

        // Handle add/del of tunnel URLs
        const char *url;
        if (http_get_string_var(vars, VAR_ADD_URL, &url) && url[0] != '\0')
        {
            tunnel_add(url);
        }
        else if (http_get_string_var(vars, VAR_DEL_URL, &url) &&
                    url[0] != '\0')
        {
            tunnel_delete(url);
        }
    }
}
Пример #14
0
int main(int argc, char** args) {
  int ext = 0,c;
  double ra,dec;
  double sol[2];
  const gsl_multiroot_fsolver_type *T;
  gsl_multiroot_fsolver *s;
  int status;
  size_t iter=0;
  const size_t n=2;
  gsl_multiroot_function f={&fvec,n,NULL};
  gsl_vector *x = gsl_vector_alloc(n);
  char *wcsfn1=NULL, *wcsfn2=NULL;
  
  while ((c = getopt(argc, args, OPTIONS)) != -1) {
    switch(c) {
    case 'v':
      loglvl++;
      break;
    case 'h':
      print_help(args[0]);
      exit(0);
    case '1':
      wcsfn1 = optarg;
      break;
    case '2':
      wcsfn2 = optarg;
      break;
    }
  }
  log_init(loglvl);
  if (optind != argc) {
    print_help(args[0]);
    exit(-1);
  }
  if (!(wcsfn1) || !(wcsfn2)) {
    print_help(args[0]);
    exit(-1);
  }
  /* open the two wcs systems */
  wcs1 = anwcs_open(wcsfn1, ext);
  if (!wcs1) {
    ERROR("Failed to read WCS file");
    exit(-1);
  }
  logverb("Read WCS:\n");
  if (log_get_level() >= LOG_VERB) {
    anwcs_print(wcs1, log_get_fid());
  }
  wcs2 = anwcs_open(wcsfn2, ext);
  if (!wcs2) {
    ERROR("Failed to read WCS file");
    exit(-1);
  }
  logverb("Read WCS:\n");
  if (log_get_level() >= LOG_VERB) {
    anwcs_print(wcs2, log_get_fid());
  }
  
  /* setup the solver, start in the middle */

  gsl_vector_set(x,0,anwcs_imagew(wcs1)/2.0);
  gsl_vector_set(x,1,anwcs_imageh(wcs1)/2.0);
  T = gsl_multiroot_fsolver_hybrids;
  s = gsl_multiroot_fsolver_alloc (T,2);
  gsl_multiroot_fsolver_set(s,&f,x);
  print_state(iter,s);
  do {
    iter++;
    status = gsl_multiroot_fsolver_iterate(s);
    print_state(iter,s);
    if (status) break;
    status = gsl_multiroot_test_residual(s->f,1e-7);
  } while (status == GSL_CONTINUE && iter < 1000);
  sol[0]=gsl_vector_get(s->x,0);
  sol[1]=gsl_vector_get(s->x,1);


  /* write some diagnostics on stderr */
  /* transform to ra/dec */
  anwcs_pixelxy2radec(wcs1, sol[0], sol[1], &ra, &dec);
  if (loglvl > LOG_MSG)
    fprintf(stderr,"Pixel (%.10f, %.10f) -> RA,Dec (%.10f, %.10f)\n", 
	    sol[0], sol[1], ra, dec);
  /* transform to x/y with second wcs 
     center of rotation should stay the same x/y */
  anwcs_radec2pixelxy(wcs2, ra, dec, &sol[0], &sol[1]);
  if (loglvl > LOG_MSG)
    fprintf(stderr,"RA,Dec (%.10f, %.10f) -> Pixel (%.10f, %.10f) \n", 
	    ra, dec, sol[0], sol[1]);

  /* write the solution */
  fprintf(stdout,"%f\n",sol[0]); 
  fprintf(stdout,"%f\n",sol[1]);
  
  return(0);
}