Exemplo n.º 1
0
void sat_bruteforce(sat_t *sat) {
	state_t *state_best = state_init(sat->vars_cnt, STATE_ALL_0);
	state_t *state = state_init(sat->vars_cnt, STATE_ALL_0);

	sat_bruteforce_inner(sat, state, state_best, sat->vars_cnt);

	fprintf(stderr, "bf= %u ", cost_main(sat, state_best));

	state_free(state);
	state_free(state_best);
}
Exemplo n.º 2
0
Arquivo: main.c Projeto: beoran/eruta
/* The real main loop of the Eruta engine. Most of the work happens in state.c,
 * and the main.rb script, though. */
int real_main(void) {
  Image    * border   = NULL;
  Image    * sheet    = NULL;
  Tileset  * tileset  = NULL;
  Tile     * tile     = NULL;
  State    * state    = NULL;
  Camera   * camera   = NULL;
  Tilepane * tilepane = NULL;
  Tilemap  * map      = NULL;
  Thing    * actor    = NULL;
  Tracker  * tracker          = NULL;
  Tracker  * maptracker       = NULL;
  Sprite   * sprite           = NULL;
  SpriteState * spritestate   = NULL;
  AlpsShower shower;
  int        actor_id         = -1;
  int        sprite_id        = -1;
  int        npc1_id          = -1;
  int        npc2_id          = -1;
  
  
  React    react;
  ALLEGRO_COLOR myblack = {0.0, 0.0, 0.0, 1.0};
    
  state = state_alloc();
  state_set(state); 
  if((!(state)) || (!state_init(state, FALSE))) {
    perror(state_errmsg(state));
    return 1;
  }
  
  alpsshower_init(&shower, state_camera(state), 100, 1.0, bevec(10.0, 10000.0));

  /* Initializes the reactor, the game state is it's data. */
  react_initempty(&react, state);
  react.keyboard_key_up   = main_react_key_up;
  react.keyboard_key_down = main_react_key_down;
  
  puts_standard_path(ALLEGRO_EXENAME_PATH, "ALLEGRO_EXENAME_PATH:");

  camera  = state_camera(state);

  /* Finally initialize ruby and call the ruby startup function. */
  rh_load_main();
  callrb_on_start();
    
  /* Main game loop, controlled by the State object. */  
  while(state_busy(state)) { 
      Point spritenow = bevec(100, 120); 
      react_poll(&react, state);
      alpsshower_update(&shower, state_frametime(state));
      state_update(state);
      state_draw(state);
      /* alpsshower_draw(&shower, camera); */ 
      state_flip_display(state);
   }
   state_done(state);
   state_free(state); 
   return 0;
}
Exemplo n.º 3
0
/* Parse the given disk state and set a newly allocated state. On success,
 * return that state else NULL. */
static sr_state_t *
disk_state_parse(const sr_disk_state_t *new_disk_state)
{
  sr_state_t *new_state = state_new(default_fname, time(NULL));

  tor_assert(new_disk_state);

  new_state->version = new_disk_state->Version;
  new_state->valid_until = new_disk_state->ValidUntil;
  new_state->valid_after = new_disk_state->ValidAfter;

  /* Set our current phase according to the valid-after time in our disk
   * state. The disk state we are parsing contains everything for the phase
   * starting at valid_after so make sure our phase reflects that. */
  new_state->phase = get_sr_protocol_phase(new_state->valid_after);

  /* Parse the shared random values. */
  if (disk_state_parse_sr_values(new_state, new_disk_state) < 0) {
    goto error;
  }
  /* Parse the commits. */
  if (disk_state_parse_commits(new_state, new_disk_state) < 0) {
    goto error;
  }
  /* Great! This new state contains everything we had on disk. */
  return new_state;

 error:
  state_free(new_state);
  return NULL;
}
Exemplo n.º 4
0
static void
state_allocate(struct State * state, struct Query * query, struct Target * target)
{
  int i;

  state->height      = query->len;
  state->width       = target->n_bits;
  state->n_bytes     = target->n_bytes;
  state->res_counter = 0;

  if(state->max_length < query->len * target->n_bytes){

    if(state->max_length != 0){
      printf("state->free called   max_length : %d\n", state->max_length);
      state_free(state);
    }

    state->mat = (long *)talloc((query->len + 2) *// Depth
				target->n_bytes * // Width
				state->height *   // Height
				sizeof(long));    // sizeof(long)

    state->res_max_len = (query->len + 2) *// Depth
      target->n_bytes * // Width
      state->height *   // Height
      sizeof(long) * 100;
    state->res = (long *)talloc(state->res_max_len);    // sizeof(long)
    state->max_length = query->len * target->n_bytes;
  }
  state->length = query->len * target->n_bytes;
  state->depth = -1;

  for(i = 0 ; i < state->length ; i++){ state->mat[i] = 0;}
}
Exemplo n.º 5
0
static VALUE
mol_by_mol(VALUE self, VALUE q_mol, VALUE t_mol)
{
  struct Query  query;
  struct Target target;
  struct State  state;
  VALUE result;

  target.max_length = 0;
  state.max_length = 0;

  query_setup(  q_mol, & query  );
  target_setup( t_mol, & target );

  state_allocate(& state, & query, & target);

  if(rb_block_given_p() == Qtrue){
    state_setup_block(& state);
  }
  else{
    state_setup(& state, & query, & target);
  }

  search_by_ullmann(& state, & query, & target);
  result = state_get_result(& state);

  query_free(& query);
  target_free(& target);
  state_free(& state);

  return result;
}
Exemplo n.º 6
0
/* Set our global state pointer with the one given. */
static void
state_set(sr_state_t *state)
{
  tor_assert(state);
  if (sr_state != NULL) {
    state_free(sr_state);
  }
  sr_state = state;
}
Exemplo n.º 7
0
/* Cleanup and free our disk and memory state. */
void
sr_state_free_all(void)
{
  state_free(sr_state);
  disk_state_free(sr_disk_state);
  /* Nullify our global state. */
  sr_state = NULL;
  sr_disk_state = NULL;
}
Exemplo n.º 8
0
int main( int argc, char **argv )
{
    struct state *s = parse( argv[1] );
#ifdef DEBUG
    state_print( s );
#endif
    state_free( s );
    return 0;
}
Exemplo n.º 9
0
void run_code_event(struct state *state, struct event *event,
			    const char *text)
{
	DEBUGP("%d: run code event\n", event->line_number);

	char *error = NULL, *script_path = NULL;

	/* Wait for the right time before firing off this event. */
	wait_for_event(state);

	if (state->socket_under_test == NULL) {
		asprintf(&error, "no socket to use for code");
		goto error_out;
	}
	int fd = state->socket_under_test->live.fd;
	struct code_state *code = state->code;

	void *data = NULL;
	int  data_len = 0;
	if (code->data_type == DATA_NONE) {
		/* First time: try various getsockopt calls until one works. */
#if HAVE_TCP_INFO
		if (data == NULL) {
			code->data_type = DATA_TCP_INFO;
			data = get_data(fd, code->data_type, &data_len);
		}
#endif  /* HAVE_TCP_INFO */
		if (data == NULL) {
			asprintf(&error,
				 "can't find getsockopt to get TCP info");
			goto error_out;
		}
	} else {
		/* Run the getsockopt we already picked above. */
		data = get_data(fd, code->data_type, &data_len);
		if (!data) {
			asprintf(&error, "can't get info for socket");
			goto error_out;
		}
	}
	assert(code->data_type != DATA_NONE);
	assert(data != NULL);

	append_data(code, code->data_type, data, data_len);
	append_text(code, state->config->script_path, event->line_number,
		    strdup(text));

	return;

error_out:
	script_path = strdup(state->config->script_path);
	state_free(state);
	die("%s:%d: runtime error in code: %s\n",
	    script_path, event->line_number, error);
	free(script_path);
	free(error);
}
Exemplo n.º 10
0
Profile *
tracker_create_profile (tracker_t *tracker)
{
    uint8_t *end = tracker->events + tracker->n_event_bytes;
    StackStash *resolved_stash;
    Profile *profile;
    state_t *state;
    uint8_t *event;

    state = state_new ();
    resolved_stash = stack_stash_new (g_free);

    event = tracker->events;
    while (event < end)
    {
	event_type_t type = GET_TYPE (*(uint32_t *)event);

	switch (type)
	{
	case NEW_PROCESS:
	    create_process (state, (new_process_t *)event);
	    event += sizeof (new_process_t);
	    break;

	case NEW_MAP:
	    create_map (state, (new_map_t *)event);
	    event += sizeof (new_map_t);
	    break;

	case FORK:
	    process_fork (state, (fork_t *)event);
	    event += sizeof (fork_t);
	    break;

	case EXIT:
	    process_exit (state, (exit_t *)event);
	    event += sizeof (exit_t);
	    break;

	case SAMPLE:
	    process_sample (state, resolved_stash, (sample_t *)event);
	    event += sizeof (sample_t);
	    break;
	}
    }
    
    profile = profile_new (resolved_stash);

    state_free (state);
    stack_stash_unref (resolved_stash);

    return profile;
}
Exemplo n.º 11
0
/** forward declare machine */
static void state_on_ops_off(struct state *state, struct machine *fsm)
{
	struct state_off *off;

	_MY_TRACE_STR("state_on::off()\n");

	off = malloc(sizeof(*off));
	state_off_init(off);
	machine_set_state(fsm, &off->state);

	state_free(state);
}
Exemplo n.º 12
0
/* Run the given packet event; print warnings/errors, and exit on error. */
static void run_local_packet_event(struct state *state, struct event *event,
				   struct packet *packet)
{
	char *error = NULL;
	int result = STATUS_OK;

	result = run_packet_event(state, event, packet, &error);
	if (result == STATUS_WARN) {
		fprintf(stderr, "%s", error);
		free(error);
	} else if (result == STATUS_ERR) {
		state_free(state);
		die("%s\n", error);
	}
}
Exemplo n.º 13
0
static void
db_load(struct CompoundDB * db, struct Query * query){

  int new_n_bits;
  int new_n_bytes;
  int mat_ptr;

  struct Target target;
  struct State state;
  struct Record record;

  int i, j;

  target.n_bits  = 0;
  target.n_bytes = 0;
  target.max_length = 0;
  state.max_length = 0;

  for(;;){
    if(feof(db->idx) || feof(db->mat) || feof(db->mat)){
      printf("Database broken!\n");
      return;
    }

    fread(& record, sizeof(struct Record), 1, db->idx);
    if(record.n_bits == -1){
      return;
    }
    target_setup_db(& target, & record);
    if(record.information != -1){

      fread(target.mat, sizeof(long), target.n_bits * target.n_bytes, db->mat);
      fread(target.typ, sizeof(long), target.n_bits,                  db->typ);

      state_allocate(& state, query, & target);
      state_setup(& state, query, & target);
      //show(state.mat, query->len, target.n_bits);
      search_by_ullmann(& state, query, & target);
    }else{
      fread(target.typ, sizeof(long), target.n_bytes, db->typ);
      printf("atom_number : %d\n", target.typ[0]);
    }
  }
  target_free_db(& target);
  state_free(& state);
}
Exemplo n.º 14
0
/*
 * A spatial file manager. Treat directories as independent resources with
 * fixed positions. Useful for navigating your filesystem with a predictable
 * GUI.
 */
int
main(int argc, char *argv[])
{
	struct geometry	*geometry;
	GtkWidget	*window;
	WnckWindow	*w;
        struct state	*d;
	char		*dir, ch;

	if ((d = state_new(argv[0])) == NULL)
		err(1, "could not build the callback data");

	gtk_init(&argc, &argv);

	while ((ch = getopt(argc, argv, "")) != -1)
		switch (ch) {
		default:
			usage();
			/* NOTREACHED */
		}
	argc -= optind;
	argv += optind;

	dir = getdir(argc, argv);

	if (((w = window_by_title(dir)) != NULL) && window_activate(w) != -1)
		goto done;

	if (state_add_dir(d, dir) < 0)
		err(1, "state_add_dir");

	if ((geometry = malloc(sizeof(struct geometry))) == NULL)
		err(1, "malloc");
	getgeometry(dir, geometry);
	window = prepare_window(dir, geometry, d);
	free(geometry);

	gtk_widget_show(window);
	gtk_main();

done:
	state_free(d);

	return 0;
}
Exemplo n.º 15
0
/*
 * A desktop file manager. This opens files and directories the same way that
 * argonaut(1) does.
 */
int
main(int argc, char *argv[])
{
	GtkBuilder	*builder;
	GtkWidget	*root, *icons;
        struct state	*d;
	char		*dir;

	if ((dir = get_dir()) == NULL)
		err(1, "get_dir");

	if ((d = state_new(BINDIR"/argonaut")) == NULL)
		err(1, "could not build the callback data");

	if (state_add_dir(d, dir) < 0)
		err(1, "state_add_dir");

	gtk_init(&argc, &argv);

	builder = gtk_builder_new_from_file(INTERFACE_PATH);
	icons = GTK_WIDGET(gtk_builder_get_object(builder, "desktop-icons"));
	d->icon_view = GTK_ICON_VIEW(icons);

	root = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_widget_set_name(root, "argonaut-desktop");

	set_window_geometry(GTK_WINDOW(root), GTK_WIDGET(icons));
	desktopize(root);
	skip_pager(root);
	populate_model(dir, d->icon_view);
	set_up_icon_view(icons, d);

	gtk_container_add(GTK_CONTAINER(root), icons);

	gtk_widget_show(icons);
	gtk_widget_show(root);

	gtk_main();

	state_free(d);
	free(dir);
	return 0;
}
Exemplo n.º 16
0
void run_command_event(
	struct state *state, struct event *event, struct command_spec *command)
{
	char *script_path = NULL;
	DEBUGP("%d: command: `%s`\n", event->line_number,
	       command->command_line);

	/* Wait for the right time before firing off this event. */
	wait_for_event(state);

	char *error = NULL;
	if (safe_system(command->command_line, &error))
		goto error_out;
	return;

error_out:
	script_path = strdup(state->config->script_path);
	state_free(state);
	die("%s:%d: error executing `%s` command: %s\n",
	    script_path, event->line_number,
	    command->command_line, error);
	free(script_path);
	free(error);
}
Exemplo n.º 17
0
void run_script(struct config *config, struct script *script)
{
	char *error = NULL;
	struct state *state = NULL;
	struct netdev *netdev = NULL;
	struct event *event = NULL;

	DEBUGP("run_script: running script\n");

	set_scheduling_priority();
	lock_memory();

	/* This interpreter loop runs for local mode or wire client mode. */
	assert(!config->is_wire_server);

	/* How we use the network is of course a little different in
	 * each of the two cases....
	 */
	if (config->is_wire_client)
		netdev = wire_client_netdev_new(config);
	else
		netdev = local_netdev_new(config);

	state = state_new(config, script, netdev);

	if (config->is_wire_client)
	{
		state->wire_client = wire_client_new();
		wire_client_init(state->wire_client, config, script, state);
	}

	if (script->init_command != NULL)
	{
		if (safe_system(script->init_command->command_line,
		                &error))
		{
			die("%s: error executing init command: %s\n",
			    config->script_path, error);
		}
	}

	signal(SIGPIPE, SIG_IGN);	/* ignore EPIPE */

	state->live_start_time_usecs = schedule_start_time_usecs();
	DEBUGP("live_start_time_usecs is %lld\n",
	       state->live_start_time_usecs);

	if (state->wire_client != NULL)
		wire_client_send_client_starting(state->wire_client);

	while (1)
	{
		if (get_next_event(state, &error))
			die("%s", error);
		event = state->event;
		if (event == NULL)
			break;

		if (state->wire_client != NULL)
			wire_client_next_event(state->wire_client, event);

		/* In wire mode, we adjust relative times after
		 * getting notification that previous packet events
		 * have completed, if any.
		 */
		adjust_relative_event_times(state, event);

		switch (event->type)
		{
		case PACKET_EVENT:
			/* For wire clients, the server handles packets. */
			if (!config->is_wire_client)
			{
				run_local_packet_event(state, event,
				                       event->event.packet);
			}
			break;
		case SYSCALL_EVENT:
			run_system_call_event(state, event,
			                      event->event.syscall);
			break;
		case COMMAND_EVENT:
			run_command_event(state, event,
			                  event->event.command);
			break;
		case CODE_EVENT:
			run_code_event(state, event,
			               event->event.code->text);
			break;
		case INVALID_EVENT:
		case NUM_EVENT_TYPES:
			assert(!"bogus type");
			break;
			/* We omit default case so compiler catches missing values. */
		}
	}

	/* Wait for any outstanding packet events we requested on the server. */
	if (state->wire_client != NULL)
		wire_client_next_event(state->wire_client, NULL);

	if (code_execute(state->code, &error))
	{
		die("%s: error executing code: %s\n",
		    state->config->script_path, error);
		free(error);
	}

	state_free(state);

	DEBUGP("run_script: done running\n");
}
Exemplo n.º 18
0
void astar(t_env *env)
{
	t_state_tree state_tree;
	t_state_list *opened = NULL;
	t_state *best_state;
	t_state_list *expend;
	t_state_list *tmp;
	t_state *tmp_state;
	int in_closed;
	int complexity_time = 0;
	int complexity_size = 0;
	int success = 0;
	int size_tmp;
	int opened_size = 0;
	int closed_size = 0;
	int tmpg;
	int is_closed = 0;

	memset(&state_tree, 0, sizeof(state_tree));
	if (!(state_tree.childs = malloc(sizeof(*state_tree.childs) * env->size * env->size)))
	{
		ft_putendl_fd("nuzzle: malloc failed", 2);
		exit(EXIT_FAILURE);
	}
	memset(state_tree.childs, 0, sizeof(*state_tree.childs) * env->size * env->size);
	state_list_push(&opened, env->start);
	state_tree_push(env, &state_tree, env->start, 1);
	if ((size_tmp = opened_size + closed_size) > complexity_size)
	{
		complexity_size = size_tmp;
	}
	while (opened)
	{
		best_state = opened->state;
		complexity_time++;
		if (best_state->h == 0)
		{
			success = 1;
			break;
		}
		tmp = opened;
		opened = opened->next;
		free(tmp);
		opened_size--;
		closed_size++;
		state_tree_set(env, &state_tree, best_state, 0);
		expend = state_expend(env, best_state);
		if ((size_tmp = opened_size + closed_size + state_list_size(expend)) > complexity_size)
		{
			complexity_size = size_tmp;
		}
		while (expend)
		{
			tmp_state = state_tree_get(env, &state_tree, expend->state, &is_closed);
			in_closed = tmp_state != NULL && is_closed;
			if (in_closed)
			{
				tmp = expend;
				expend = expend->next;
				state_free(env, tmp->state);
				free(tmp);
				continue;
			}
			tmpg = best_state->g + 1;
			if (!tmp_state)
			{
				expend->state->pred = best_state;
				expend->state->g = tmpg;
				expend->state->f = 0;
				if (!env->greedy)
					expend->state->f += expend->state->g;
				if (!env->uniform)
					expend->state->f += expend->state->h;
				state_list_push(&opened, expend->state);
				state_tree_push(env, &state_tree, expend->state, 1);
				opened_size++;
				tmp = expend;
				expend = expend->next;
				free(tmp);
				continue;
			}
			else if (tmpg >= tmp_state->g)
			{
				tmp = expend;
				expend = expend->next;
				state_free(env,tmp->state);
				free(tmp);
				continue;
			}
			tmp_state->pred = best_state;
			tmp_state->g = tmpg;
			tmp_state->f = 0;
			if (!env->greedy)
				tmp_state->f += tmp_state->g;
			if (!env->uniform)
				tmp_state->f += tmp_state->h;
			tmp = expend;
			expend = expend->next;
			state_free(env, tmp->state);
			free(tmp);
		}
	}
	if (success)
	{
		t_state *kek = best_state;
		int i = 0;
		while (kek)
		{
			++i;
			kek = kek->pred;
		}
		setvbuf(stdout, NULL, _IOFBF, BUFSIZ);
		printf("solution: \n");
		print_solution(env, best_state);
		printf("time complexity: %d\nsize complexity: %d\nnumber of moves: %d\n", complexity_time, complexity_size, i);
		fflush(stdout);
		setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
	}
	else
	{
		ft_putendl("This puzzle is not solvable");
	}
	state_tree_free(env, &state_tree);
	state_list_free(opened);
}
void history_free(history_t* past)
{
    state_free(dict_lookup(past->states, "x"));
    state_free(dict_lookup(past->states, "y"));
    state_free(dict_lookup(past->states, "scalex"));
    state_free(dict_lookup(past->states, "scaley"));
    state_free(dict_lookup(past->states, "cxform.r0"));
    state_free(dict_lookup(past->states, "cxform.g0"));
    state_free(dict_lookup(past->states, "cxform.b0"));
    state_free(dict_lookup(past->states, "cxform.a0"));
    state_free(dict_lookup(past->states, "cxform.r1"));
    state_free(dict_lookup(past->states, "cxform.g1"));
    state_free(dict_lookup(past->states, "cxform.b1"));
    state_free(dict_lookup(past->states, "cxform.a1"));
    state_free(dict_lookup(past->states, "rotate"));
    state_free(dict_lookup(past->states, "shear"));
    state_free(dict_lookup(past->states, "pivot.x"));
    state_free(dict_lookup(past->states, "pivot.y"));
    state_free(dict_lookup(past->states, "pin.x"));
    state_free(dict_lookup(past->states, "pin.y"));
    state_free(dict_lookup(past->states, "blendmode"));
    state_free(dict_lookup(past->states, "flags"));
    filterState_free(dict_lookup(past->states, "filter"));
    dict_destroy(past->states);
    free(past);
}
Exemplo n.º 20
0
/*
 * eq: equlibirium factor
 * ti: temperature initial
 * te: temperature end
 * cf: cooling factor (0 < cf < 1)
 */
uint32_t simulated_annealing(sat_t *sat, double te, double steps) {
	state_t *state = state_init(sat->vars_cnt, STATE_RANDOMIZE);
	state_t *state_next = state_init(sat->vars_cnt, STATE_ALL_0);
	uint32_t ret = 0;
	uint32_t real_cost = 0;
	uint32_t eq; /* equlibrium */
	double cf; /* cooling factor */
	double ti; /* temperature initial */

	ti = sat->vars_cnt * sat->weight_max * 10;
	cf = pow(te / ti, 1 / (steps - 1));
//	cf = 1 - ((ti - te) / steps);

	static bool print_once = false; //true;

	uint32_t it = 0;

//	printf("ti=%lf te=%lf cf=%lf, eq=%d\n", ti, te, cf, eq);

//	for (double t = ti; te < t; t *= cf) {
//		for (int i = 0; i < eq; i++) {
//			state_gen_next(state, state_next);
//			double d = ((double) cost(sat, state))
//					- ((double) cost(sat, state_next));
//
//			if (d < 0 || randd() < pow(M_E, -d / t)) {
//				state_swap(&state, &state_next);
//				continue;
//			}
//
//			//printf("it= %4u best= %4u bits= ", it++, cost(sat, state));
//			//			state_print(state);
//		}
//	}
	//http://www.cs.ubc.ca/~hoos/SATLIB/benchm.html
	eq = (uint32_t) (sat->vars_cnt / (double) 2.0);
	uint32_t *p = calloc(sat->vars_cnt, sizeof(uint32_t));
	for (double t = ti; te < t; t *= cf) {
		permutation(p, sat->vars_cnt);
		it++;
//		printf("t=%lf\n", t);
		for (uint32_t i = 0; i < eq; i++) {

			double c = cost(sat, state);

			uint32_t ind = p[i];
			state->ch[ind] = (state->ch[ind] + 1) % 2;

			double d = (c - (double) cost(sat, state));

			if (d < 0 || randd() < pow(M_E, -d / t)) {
				continue;
			}

			state->ch[ind] = (state->ch[ind] + 1) % 2;
		}

		real_cost = cost_main(sat, state);

		if (g_print_progress) {
			printf("%u %u %lf\n", it, real_cost, cost(sat, state));
		}

		ret = max(ret, real_cost);
	}

	if (print_once) {
		fprintf(stderr, "ti=%lf cf=%lf it=%u eq=%u\n", ti, cf, it, eq);
		assert(0 < cf && cf < 1);
		print_once = false;
		state_print(state);
	}

	free(p);
	state_free(state);
	state_free(state_next);

	return (ret);
}
Exemplo n.º 21
0
void mcmc(tree *tr, analdef *adef)
{
  int i=0;

  tr->startLH = tr->likelihood;
  printBothOpen("start minimalistic search with LH %f\n", tr->likelihood);
  printBothOpen("tr LH %f, startLH %f\n", tr->likelihood, tr->startLH);
  
  int insert_id;
  int j;

  int maxradius = 30;
  int accepted_spr = 0, accepted_nni = 0, accepted_bl = 0, accepted_model = 0, accepted_gamma = 0, inserts = 0;
  int rejected_spr = 0, rejected_nni = 0, rejected_bl = 0, rejected_model = 0, rejected_gamma = 0;
  int num_moves = 10000;
  boolean proposalAccepted;
  boolean proposalSuccess;
  prop which_proposal;
  double testr;
  double acceptance;

  srand (440);
  double totalTime = 0.0, proposalTime = 0.0, blTime = 0.0, printTime = 0.0;
  double t_start = gettime();
  double t;


  //allocate states
  double bl_prior_exp_lambda = 0.1;
  double bl_sliding_window_w = 0.005;
  double gm_sliding_window_w = 0.75;
  double rt_sliding_window_w = 0.5;
  state *curstate = state_init(tr, adef, maxradius, bl_sliding_window_w, rt_sliding_window_w, gm_sliding_window_w, bl_prior_exp_lambda);
  printStateFileHeader(curstate);
  set_start_bl(curstate);
  printf("start bl_prior: %f\n",curstate->bl_prior);
  set_start_prior(curstate);
  curstate->hastings = 1;//needs to be set by the proposal when necessary

  /* Set the starting LH with a full traversal */
  evaluateGeneric(tr, tr->start, TRUE);	 
  tr->startLH = tr->likelihood;
  printBothOpen("Starting with tr LH %f, startLH %f\n", j, tr->likelihood, tr->startLH);

  /* Set reasonable model parameters */
  evaluateGeneric(curstate->tr, curstate->tr->start, FALSE); // just for validation 
  printBothOpen("tr LH before modOpt %f\n",curstate->tr->likelihood);
  printSubsRates(curstate->tr, curstate->model, curstate->numSubsRates);

  /* optimize the model with Brents method for reasonable starting points */
  modOpt(curstate->tr, curstate->adef, 5.0); /* not by proposal, just using std raxml machinery... */
  evaluateGeneric(curstate->tr, curstate->tr->start, FALSE); // just for validation 
  printBothOpen("tr LH after modOpt %f\n",curstate->tr->likelihood);
  printSubsRates(curstate->tr, curstate->model, curstate->numSubsRates);
  recordSubsRates(curstate->tr, curstate->model, curstate->numSubsRates, curstate->curSubsRates);

  int first = 1;
  /* beginning of the MCMC chain */
  for(j=0; j<num_moves; j++)
  {
    //printBothOpen("iter %d, tr LH %f, startLH %f\n",j, tr->likelihood, tr->startLH);
    //printRecomTree(tr, TRUE, "startiter");
    proposalAccepted = FALSE;
    t = gettime(); 

    /*
      evaluateGeneric(tr, tr->start); // just for validation 
      printBothOpen("before proposal, iter %d tr LH %f, startLH %f\n", j, tr->likelihood, tr->startLH);
    */

    which_proposal = proposal(curstate);
    if (first == 1)
    {
      first = 0;
      curstate->curprior = curstate->newprior;
    }
   //printBothOpen("proposal done, iter %d tr LH %f, startLH %f\n", j, tr->likelihood, tr->startLH);
    assert(which_proposal == SPR || which_proposal == stNNI ||
           which_proposal == UPDATE_ALL_BL || 
           which_proposal == UPDATE_MODEL || which_proposal == UPDATE_GAMMA);
    proposalTime += gettime() - t;
    /* decide upon acceptance */
    testr = (double)rand()/(double)RAND_MAX;
    //should look something like 
    acceptance = fmin(1,(curstate->hastings) * 
		      (exp(curstate->newprior-curstate->curprior)) * (exp(curstate->tr->likelihood-curstate->tr->startLH)));
    
    /*
      //printRecomTree(tr, FALSE, "after proposal");
      printBothOpen("after proposal, iter %d tr LH %f, startLH %f\n", j, tr->likelihood, tr->startLH);
    */
    if(testr < acceptance)
    {
      proposalAccepted = TRUE;

      switch(which_proposal)
	{
	case SPR:      
	  //printRecomTree(tr, TRUE, "after accepted");
	  // printBothOpen("SPR new topology , iter %d tr LH %f, startLH %f\n", j, tr->likelihood, tr->startLH);
	   accepted_spr++;
	  break;
	case stNNI:	  
	  printBothOpen("NNI new topology , iter %d tr LH %f, startLH %f\n", j, tr->likelihood, tr->startLH);
	  accepted_nni++;
	  break;
	case UPDATE_ALL_BL:	  
	  //      printBothOpen("BL new , iter %d tr LH %f, startLH %f\n", j, tr->likelihood, tr->startLH);
	  accepted_bl++;
	  break;
	case UPDATE_MODEL:      
	  //	printBothOpen("Model new, iter %d tr LH %f, startLH %f\n", j, tr->likelihood, tr->startLH);
	  accepted_model++;
	  break;
	case UPDATE_GAMMA:      
	  //	printBothOpen("Gamma new, iter %d tr LH %f, startLH %f\n", j, tr->likelihood, tr->startLH);
	  accepted_gamma++;
	  break;
	default:
	  assert(0);
	}

      curstate->tr->startLH = curstate->tr->likelihood;  //new LH
      curstate->curprior = curstate->newprior;          
    }
    else
    {
      //printBothOpen("rejected , iter %d tr LH %f, startLH %f, %i \n", j, tr->likelihood, tr->startLH, which_proposal);
      resetState(which_proposal,curstate);
      
      switch(which_proposal)
	{
	case SPR:
	  rejected_spr++;
	  break;
	case stNNI:
	  rejected_nni++;
	  break;
	case UPDATE_ALL_BL:
	  rejected_bl++;
	  break;
	case UPDATE_MODEL:
	  rejected_model++;
	  break;
	case UPDATE_GAMMA:
	  rejected_gamma++;
	  break;
	default:
	  assert(0);
	}
      
      evaluateGeneric(tr, tr->start, FALSE); 
      
      // just for validation 

      if(fabs(curstate->tr->startLH - tr->likelihood) > 1.0E-10)
      {
        printBothOpen("WARNING: LH diff %.10f\n", curstate->tr->startLH - tr->likelihood);
      }
      //printRecomTree(tr, TRUE, "after reset");
      //printBothOpen("after reset, iter %d tr LH %f, startLH %f\n", j, tr->likelihood, tr->startLH);
      assert(fabs(curstate->tr->startLH - tr->likelihood) < 1.0E-10);
    }       
    inserts++;
    
    /* need to print status */
    if (j % 50 == 0)
    {
      t = gettime(); 
      printBothOpen("sampled at iter %d, tr LH %f, startLH %f, prior %f, incr %f\n",j, tr->likelihood, tr->startLH, curstate->curprior, tr->likelihood - tr->startLH);
      boolean printBranchLengths = TRUE;
      /*printSimpleTree(tr, printBranchLengths, adef);*/
      //TODO: print some parameters to a file 
      printStateFile(j,curstate);
      printTime += gettime() - t;
    }
  }

  t = gettime(); 
  treeEvaluate(tr, 1);
  blTime += gettime() - t;
  printBothOpen("accepted SPR %d, accepted stNNI %d, accepted BL %d, accepted model %d, accepted gamma %d, num moves tried %d, SPRs with max radius %d\n", 
		accepted_spr, accepted_nni, accepted_bl, accepted_model, accepted_gamma, num_moves, maxradius);
  printBothOpen("rejected SPR %d, rejected stNNI %d, rejected BL %d, rejected model %d, rejected gamma %d\n",
		rejected_spr, rejected_nni, rejected_bl, rejected_model, rejected_gamma);
  printBothOpen("ratio SPR %f, ratio stNNI %f,  ratio BL %f, ratio model %f, ratio gamma %f\n",
		accepted_spr/(double)(rejected_spr+accepted_spr), accepted_nni/(double)(rejected_nni+accepted_nni), accepted_bl/(double)(rejected_bl+accepted_bl), 
		accepted_model/(double)(rejected_model+accepted_model), accepted_gamma/(double)(rejected_gamma+accepted_gamma));
  printBothOpen("total  %f, BL %f, printing %f, proposal %f\n", gettime()- t_start, blTime, printTime, proposalTime);
  assert(inserts == num_moves);
  state_free(curstate);
}
Exemplo n.º 22
0
/* Handle a wire connection from a client. */
static void *wire_server_thread(void *arg)
{
	struct wire_server *wire_server = (struct wire_server *)arg;
	struct netdev *netdev = NULL;
	char *error = NULL;

	DEBUGP("wire_server_thread\n");

	set_default_config(&wire_server->config);

	if (wire_server_receive_args(wire_server))
		goto error_done;

	if (wire_server_receive_script_path(wire_server))
		goto error_done;

	if (wire_server_receive_script(wire_server))
		goto error_done;

	if (wire_server_receive_hw_address(wire_server))
		goto error_done;

	if (parse_script_and_set_config(wire_server->argc,
						wire_server->argv,
						&wire_server->config,
						&wire_server->script,
						wire_server->script_path,
						wire_server->script_buffer))
		goto error_done;

	set_scheduling_priority();
	lock_memory();

	netdev =
	  wire_server_netdev_new(&wire_server->config,
				 wire_server->wire_server_device,
				 &wire_server->client_ether_addr,
				 &wire_server->server_ether_addr);

	wire_server->state = state_new(&wire_server->config,
					       &wire_server->script,
					       netdev);

	if (wire_server_send_server_ready(wire_server))
		goto error_done;

	if (wire_server_receive_client_starting(wire_server))
		goto error_done;

	if (wire_server_run_script(wire_server, &error))
		goto error_done;

	DEBUGP("wire_server_thread: finished test successfully\n");

error_done:
	if (error != NULL)
		fprintf(stderr, "%s\n", error);

	if (wire_server->state != NULL)
		state_free(wire_server->state, 0);

	DEBUGP("wire_server_thread: connection is done\n");
	wire_server_free(wire_server);
	return NULL;
}
void state_free(state_t* state)
{
    if (state->next)
	state_free(state->next);
    free(state);
}