Пример #1
0
void board::generation()
{
	srand(time(0));

	if (playerone.tosses<5)
	{
		playerone.x=rand()%10;
		playerone.y=rand()%10;

		if (pitch[playerone.y][playerone.x]=='P')
		{
			generation();
		}
		else
		{
			system("cls");
			scoring();
			pitch[playerone.y][playerone.x]='P';
			playerone.tosses++;
			showboard();
			cout<<"Score for that throw "<<playerone.throwscore<<endl;
			cout<<"Number of tosses "<<playerone.tosses<<"/5"<<endl;
			wait();
			system("pause");
			generation();
		}
	}
	else
	{
		system("cls");
	}

}
Пример #2
0
void Worker::internal()
{

	try {
		reporter->startTiming();

		primary();

		if(generate) {
			update();
			generation();
		}
		reporter->setReturnCode(EXIT_SUCCESS);

#if USE_CGAL
	} catch(CGAL::Failure_exception e) {
		reporter->reportException(QString::fromStdString(e.what()));
#endif
	} catch(...) {
		reporter->reportException(tr("Unknown error."));
	}

	update();

	finish();
}
Пример #3
0
/*
    Construct a random dungeon
*/
void buildMap() {
    int ii;
    int jj;

    mapTopX = 0;
    mapTopY = 0;
    initMap();

    generations = 1;
    fillprob = 35;
    params = params_set = (generation_params*)malloc( sizeof(generation_params) * generations);

    params->r1_cutoff = 24;
    params->r2_cutoff = 5;
    params->reps = 1;
    params++;

    params->r1_cutoff = 20;
    params->r2_cutoff = 3;
    params->reps = 1;
    params++;

 	for(ii=0; ii<generations; ii++) {
 		params = &params_set[ii];
 		for(jj=0; jj<params->reps; jj++)
 			generation();
 	}

    free(params);
    free(params_set);
}
Пример #4
0
void Generation::readGenerations(const string &file,
        vector<GenerationPtr> &generations) {
    XMLPlatformUtils::Initialize();
    XercesDOMParser parser;

    GenerationErrorHandler handler;
    parser.setErrorHandler(&handler);
    parser.setEntityResolver(&handler);

    parser.parse(file.c_str());

    DOMDocument *doc = parser.getDocument();
    DOMElement *root = doc->getDocumentElement();

    XMLCh tempStr[12];
    XMLString::transcode("generation", tempStr, 11);
    DOMNodeList *list = root->getElementsByTagName(tempStr);

    int length = list->getLength();
    for (int i = 0; i < length; ++i) {
        DOMElement *item = (DOMElement *)list->item(i);
        GenerationPtr generation(new Generation());
        generation->m_impl->m_owner = generation.get();
        generation->m_impl->getGeneration(item);
        generation->m_impl->m_idx = i;
        generations.push_back(generation);
    }
}
Пример #5
0
void main_constz() {
  string gen_name, det_name, root_name;
  string gen_prefix = "events_z";
  string det_prefix = "measures_z";
  string root_prefix = "reconstruction_z";
  string str_buff;
  string str_dat = ".dat";
  string str_root = ".root";
  stringstream ss;
  double z_val;
  
  for (int i = 0; i <= 30; i++) {
    z_val = double(i);
    cout << "Starting analysis with z = " << z_val << "..." << endl;
    ss << z_val;
    ss >> str_buff;
    gen_name = gen_prefix + str_buff;
    det_name = det_prefix + str_buff;
    root_name = root_prefix + str_buff;
    
    ss.clear();

    cout << '\t' << "Generation..." << '\n' << endl;
    generation(gen_name.c_str(), "CONST Z");
    cout << '\t' << "Detector response..." << '\n' << endl;
    detector(gen_name.c_str(), det_name.c_str());
    cout << '\t' << "Reconstruction..." << '\n' << endl;
    reconstruction(gen_name.c_str(), det_name.c_str(), root_name.c_str());

    cout << '\n' << "-------------------------" << '\n' << endl;
  }


}
void ParScanClosure::do_oop_work(oop* p,
				 bool gc_barrier, bool only_two_gens,
				 bool root_scan,
				 bool jvmpi_slow_alloc) {
  oop obj = *p;
  assert((!Universe::heap()->is_in_reserved(p) ||
	  generation()->is_in_reserved(p))
	 && (generation()->level() == 0 || gc_barrier),
	 "The gen must be right, and we must be doing the barrier "
	 "in older generations.");
  if (obj != NULL) {
    if ((HeapWord*)obj < _boundary) {
      assert(!_g->to()->contains(obj), "Scanning field twice?");
      // OK, we need to ensure that it is copied.
      // We read the klass and mark in this order, so that we can reliably 
      // get the size of the object: if the mark we read is not a
      // forwarding pointer, then the klass is valid: the klass is only
      // overwritten with an overflow next pointer after the object is
      // forwarded.
      klassOop objK = obj->klass();
      markOop m = obj->mark();
      if (m->is_marked()) { // Contains forwarding pointer.
	*p = ParNewGeneration::real_forwardee(obj);
      } else {
        size_t obj_sz = obj->size_given_klass(objK->klass_part()); 
        *p = _g->copy_to_survivor_space(_par_scan_state, obj, obj_sz, m, 
					jvmpi_slow_alloc);
	if (root_scan) {
	  // This may have pushed an object.  If we have a root
	  // category with a lot of roots, can't let the queue get too
	  // full:
	  (void)_par_scan_state->trim_queues(10 * ParallelGCThreads);
	}
      }
      if (gc_barrier && only_two_gens) {
	// Now call parent closure
	par_do_barrier(p);
      }
    }
    if (gc_barrier && !only_two_gens) {
      // Now call parent closure
      par_do_barrier(p);
    }
  }
}
void ParScanClosure::par_do_barrier(oop* p) {
  assert(generation()->is_in_reserved(p), "expected ref in generation");
  oop obj = *p;
  assert(obj != NULL, "expected non-null object");
  // If p points to a younger generation, mark the card.
  if ((HeapWord*)obj < gen_boundary()) {
    rs()->write_ref_field_gc_par(p, obj);
  }
}
int main()
{
	input();
	s_alph();
	generation();
	calculation();
	output();
	return 0;
}
template <class T> inline void ParScanClosure::par_do_barrier(T* p) {
  assert(generation()->is_in_reserved(p), "expected ref in generation");
  assert(!oopDesc::is_null(*p), "expected non-null object");
  oop obj = oopDesc::load_decode_heap_oop_not_null(p);
  // If p points to a younger generation, mark the card.
  if ((HeapWord*)obj < gen_boundary()) {
    rs()->write_ref_field_gc_par(p, obj);
  }
}
void OopsInGenClosure::do_barrier(oop* p) {
  assert(generation()->is_in_reserved(p), "expected ref in generation");
  oop obj = *p;
  assert(obj != NULL, "expected non-null object");
  // If p points to a younger generation, mark the card.
  if ((HeapWord*)obj < _gen_boundary) {
    _rs->inline_write_ref_field_gc(p, obj);
  }
}
Пример #11
0
template <class T> inline void OopsInGenClosure::do_barrier(T* p) {
  assert(generation()->is_in_reserved(p), "expected ref in generation");
  T heap_oop = oopDesc::load_heap_oop(p);
  assert(!oopDesc::is_null(heap_oop), "expected non-null oop");
  oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
  // If p points to a younger generation, mark the card.
  if ((HeapWord*)obj < _gen_boundary) {
    _rs->inline_write_ref_field_gc(p, obj);
  }
}
Пример #12
0
int main(void){
    t_case grille[N][N];
    t_score Liste[1000];
    int tailleListe;
    generation(grille);
    printf("\n\n\t  RUZZLE SOLVER\n");
    afficher_matrice(grille);
    points = trouverListe(grille);
    tri(Liste, &tailleListe);
    printf("Voici la liste des mots trouve dans la grille et leur nombre de points :\n");
    afficher_liste(tailleListe, Liste);
void test(void){ 
	CU_ASSERT_EQUAL(points, 21); 
}
Пример #13
0
void main()
{
    initialize();
    cout<<zuiyougeti->geti<<" "<<zuiyougeti->shiyingdu<<endl;/////////////
    for(gen=1;gen<maxgen;gen++)
    { generation();
    }
    jingyingbaoliu();
    cout<<setiosflags(ios::fixed)<<setprecision(6)<<zuiyougeti->geti<<" "<<setiosflags(ios::fixed)<<setprecision(6)<<(zuiyougeti->shiyingdu)<<endl;////////////////
    delete [] newpop;
    delete [] nowpop;
    delete [] zuiyougeti;
    system("pause");
}
Пример #14
0
int main()
{
    int k = 0;
    int m = 0;
    int n = 0;
    printf("Enter # of Homozygous dominant: ");
    fscanf(stdin, "%d", &k);
    printf("Enter # of Heterozygous: ");
    fscanf(stdin, "%d", &m);
    printf("Enter # of Homozygous recessive: ");
    fscanf(stdin, "%d", &n);

    float probability = generation(k,m,n);
    printf("Probabily of displaying dominant phenotype: %f", probability);
}
Пример #15
0
cell* huffdecoditication::generation(QString Tree)
{
    cell* Left;
    cell* Right;
    QString TreeLeft=TreeHuffmanDecodificationLeft(Tree);
    QString TreeRight=TreeHuffmanDecodificationRight(Tree);
    if(TreeLeft.size()>1)
    {
        Left = generation(TreeLeft);
    }
    else
    {
        Left=new cell(TreeLeft.at(0).toLatin1(),0);
    }
    if(TreeRight.size()>1)
    {
        Right = generation(TreeRight);
    }
    else
    {
        Right = new cell(TreeRight.at(0).toLatin1(),0);
    }
    return new cell(0,Left,Right);
}
Пример #16
0
void
run (void) {
  while (1) {
    message("Turn : %6d ; <Press any key to interrupt>", turn);
    display();
		
    if(key_pressed())
      break;
		
    generation();
		
    turn++;
    sleep(1);
  }
}
Пример #17
0
static void display_variable(GtkTreeModel *Variables, GtkTreeIter *Iter, Std$Object$t *Value, Std$Object_t **Address) {
	//printf("Address = 0x%x, Value = 0x%x\n", Address, Value);
	const char *String;
	if (Value->Type == Agg$Table$T) {
		size_t OldGeneration, CurrentGeneration = Agg$Table$generation(Value);
		gtk_tree_model_get(Variables, Iter, 5, &OldGeneration, -1);
		//printf("OldGeneration = %d, CurrentGeneration = %d\n", OldGeneration, CurrentGeneration);
		if (OldGeneration != CurrentGeneration) {
			gtk_tree_store_set(Variables, Iter, 1, "{...}", 3, Value, 5, CurrentGeneration, -1);
			GtkTreeIter Child;
			while (gtk_tree_model_iter_children(Variables, &Child, Iter)) gtk_tree_store_remove(Variables, &Child);
			if (Agg$Table$size(Value) < 100) {
				Agg$Table$trav *Trav = Agg$Table$trav_new();
				for (Std$Object$t *Node = Agg$Table$trav_first(Trav, Value); Node; Node = Agg$Table$trav_next(Trav)) {
					gtk_tree_store_append(Variables, &Child, Iter);
					gtk_tree_store_set(Variables, &Child, 0, to_string(Agg$Table$node_key(Node)) ?: "<key>", 5, -1, -1);
					Std$Object$t **NodeAddress = Agg$Table$node_value_ref(Node);
					display_variable(Variables, &Child, *NodeAddress, NodeAddress);
				};
			};
Пример #18
0
 int main(int argc, char **argv)
 {
 	int ii, jj;
 
 	if(argc < 7) {
 		printf("Usage: %s xsize ysize fill (r1 r2 count)+\n", argv[0]);
 		return 1;
 	}
 	size_x     = atoi(argv[1]);
 	size_y     = atoi(argv[2]);
 	fillprob   = atoi(argv[3]);
 
 	generations = (argc-4)/3;
	printf("gen: %d, %d\n",argc,generations);
 
 	params = params_set = (generation_params*)malloc( sizeof(generation_params) * generations );
 
 	for(ii=4; ii+2<argc; ii+=3)
 	{
 		params->r1_cutoff  = atoi(argv[ii]);
 		params->r2_cutoff  = atoi(argv[ii+1]);
 		params->reps = atoi(argv[ii+2]);
 		params++;
 	}
 
 	srand(time(NULL));
 
 	initmap();
 
 	for(ii=0; ii<generations; ii++)
 	{
 		params = &params_set[ii];
 		for(jj=0; jj<params->reps; jj++)
 			generation();
 	}
 	printfunc();
 	printmap();
 	return 0;
 }
Пример #19
0
main()
{
	int gencount, xforms;

	maprows = 64;
	mapcols = 64;

    srand48(time(NULL));

	genmap();

	gencount = 1;

	while((xforms = generation()) > (maprows*mapcols/30)
	&& gencount < 11)
		fprintf(stderr,
			"Generation %4d -- %5d Transforms\n", gencount++, xforms);

	fprintf(stderr,
		"Generation %4d -- %5d Transforms\n", gencount++, xforms);

	savemap();
}
Пример #20
0
void affiche(void)
{
    int		xw,	yw,	ww,	hw,	pxy[4],	x,	y;
    int		wcell,	hcell,	attributs[10];
    int		dummy;
    C_OBJ		*obj;

    vqt_attributes(VDIhandle,	 attributs);
    wcell=attributs[8];
    hcell=attributs[9];

    /* Coordonn‚es zone de travail fenˆtre : */
    wind_get (buf[3],	 WF_WORKXYWH,	 &xw,	 &yw,	 &ww,	 &hw);

    vst_alignment (VDIhandle,	 0,	 5,	 &dummy,	 &dummy); /* Texte en haut … gauche */

    x=xw-(prog.w_col-tab*generation(curr_aff))*wcell;
    y=yw;

    ecrit(curr_aff,	x,	&y,	wcell,	 hcell,	yw+hw);

    if(curr_aff->pere)		/* ce bloc traite le cas o— les parents de curr_aff ne sont pas affiche	*/
    {
        obj=curr_aff->pere;
        while (y<yw+hw && obj->suivant)
        {
            x-=tab*wcell;
            ecrit(obj->suivant,	x,	&y,	wcell,	 hcell,	yw+hw);

            if (obj->pere)
                obj=obj->pere;
            else
                y=yw+hw+1;	/*	cree un condition fausse pour sortir de la boucle	*/
        }
    }
}
Пример #21
0
TTEntry* TranspositionTable::probe(const Key key, bool& found
#if defined(USE_GLOBAL_OPTIONS)
	, size_t thread_id
#endif
	
	) const
{
	ASSERT_LV3(clusterCount != 0);

#if defined(USE_GLOBAL_OPTIONS)
	if (!GlobalOptions.use_hash_probe)
	{
		// 置換表にhitさせないモードであるなら、見つからなかったことにして
		// つねに確保しているメモリの先頭要素を返せば良い。(ここに書き込まれたところで問題ない)
		return found = false, first_entry(0);
	}
#endif

	// 最初のTT_ENTRYのアドレス(このアドレスからTT_ENTRYがClusterSize分だけ連なっている)
	// keyの下位bitをいくつか使って、このアドレスを求めるので、自ずと下位bitはいくらかは一致していることになる。
	TTEntry* tte;
	u8 gen8;

#if !defined(USE_GLOBAL_OPTIONS)

	tte = first_entry(key);
	gen8 = generation();

#else

	if (GlobalOptions.use_per_thread_tt)
	{
		// スレッドごとに置換表の異なるエリアを渡す必要がある。
		// 置換表にはclusterCount個のクラスターがあるのでこれをスレッドの個数で均等に割って、
		// そのthread_id番目のblockを使わせてあげる、的な考え。
		//
		// ただしkeyのbit0は手番bitであり、これはそのままindexのbit0に反映されている必要がある。
		//
		// また、blockは2の倍数になるように下丸めしておく。
		// ・上丸めするとblock*max_thread > clusterCountになりかねない)
		// ・2の倍数にしておかないと、(key % block)にkeyのbit0を反映させたときにこの値がblockと同じ値になる。
		//   (各スレッドが使えるのは、( 0~(block-1) ) + (thread_id * block)のTTEntryなので、これはまずい。

		size_t block = (clusterCount / max_thread) & ~1;
		size_t index = (((size_t)key % block) & ~1 ) | ((size_t)key & 1);
		tte = &table[index + thread_id * block].entry[0];

	}	else {
		tte = first_entry(key);
	}
	gen8 = generation(thread_id);

#endif

	// 上位16bitが合致するTT_ENTRYを探す
	const uint16_t key16 = key >> 48;

	// クラスターのなかから、keyが合致するTT_ENTRYを探す
	for (int i = 0; i < ClusterSize; ++i)
	{
		// returnする条件
		// 1. 空のエントリーを見つけた(そこまではkeyが合致していないので、found==falseにして新規TT_ENTRYのアドレスとして返す)
		// 2. keyが合致しているentryを見つけた。(found==trueにしてそのTT_ENTRYのアドレスを返す)

		// Stockfishのコードだと、1.が成立したタイミングでもgenerationのrefreshをしているが、
		// save()のときにgenerationを書き出すため、このケースにおいてrefreshは必要ない。

		// 1.
		if (!tte[i].key16)
			return found = false, &tte[i];

		// 2.
		if (tte[i].key16 == key16)
		{
#if defined(USE_GLOBAL_OPTIONS)
			// 置換表とTTEntryの世代が異なるなら、信用できないと仮定するフラグ。
			if (GlobalOptions.use_strict_generational_tt)
				if (tte[i].generation() != gen8)
					return found = false, &tte[i];
#endif

			tte[i].set_generation(gen8); // Refresh
			return found = true, &tte[i];
		}
	}

	// 空きエントリーも、探していたkeyが格納されているentryが見当たらなかった。
	// クラスター内のどれか一つを潰す必要がある。

	TTEntry* replace = tte;
	for (int i = 1; i < ClusterSize; ++i)

		// ・深い探索の結果であるものほど価値があるので残しておきたい。depth8 × 重み1.0
		// ・generationがいまの探索generationに近いものほど価値があるので残しておきたい。geration(4ずつ増える)×重み 2.0
		// 以上に基いてスコアリングする。
		// 以上の合計が一番小さいTTEntryを使う。

		if (replace->depth8 - ((259 + gen8 - replace->genBound8) & 0xFC) * 2
		  >   tte[i].depth8 - ((259 + gen8 -   tte[i].genBound8) & 0xFC) * 2)
			replace = &tte[i];

	// generationは256になるとオーバーフローして0になるのでそれをうまく処理できなければならない。
	// a,bが8bitであるとき ( 256 + a - b ) & 0xff のようにすれば、オーバーフローを考慮した引き算が出来る。
	// このテクニックを用いる。
	// いま、
	//   a := generationは下位2bitは用いていないので0。
	//   b := genBound8は下位2bitにはBoundが入っているのでこれはゴミと考える。
	// ( 256 + a - b + c) & 0xfc として c = 3としても結果に影響は及ぼさない、かつ、このゴミを無視した計算が出来る。

	return found = false, replace;
}
Пример #22
0
/* The main function */
int main(int argc, char const *argv[])
{
	DBusError dbe;
	struct state_st state;

        /* Parse the command line. */
	if (argv[1] && argv[1][0] == 'd')
	{       /* Debug dump */
		assert(loadstate(&state));
		dumpop(&state);
		return 0;
	} else if (argv[1] && argv[1][0] == 'r')
	{       /* Repair the GA state. */
		unsigned i;

		assert(loadstate(&state));
		for (i = 0; i < G_N_ELEMENTS(state.pop); i++)
		{       /* Ensure that genes are bounded. */
			struct genome_st *g = &state.pop[i];
			if (g->window > TIMEOUT)
				g->window = TIMEOUT;
			else if (g->window < 3)
				g->window = 3;
			if (g->threshold <= 0)
				g->threshold = 0.1;
			else if (g->threshold >= 1)
				g->threshold = 0.9;
		}
		savestate(&state);
		return 0;
	}

        /* Redirect stdio. */
	assert((stderr = fopen(FNAME".err", "a")) != NULL);
	assert((stdout = fopen(FNAME".log", "a")) != NULL);

        /* Initialize infrastructure for the test. */
	Loop = g_main_loop_new(0, 0);

	DBus = dbus_bus_get(DBUS_BUS_SESSION, NULL);
	dbus_connection_setup_with_g_main(DBus, g_main_context_default());
	dbus_error_init(&dbe);
	dbus_bus_add_match(DBus, "type='method_call',interface='com.nokia.HildonDesktop.AppMgr',member='LaunchApplication'", &dbe);
	assert(!dbus_error_is_set(&dbe));

	Dpy = XOpenDisplay(NULL);
	assert(Dpy != NULL);

	if (!loadstate(&state))
		initpop(&state);

        /* Test */
	eval(&state.pop[state.idx++]);
	if (state.idx >= G_N_ELEMENTS(state.pop))
		generation(&state);

        /* Done and reboot. */
	savestate(&state);
	if (argv[1])
		system("echo reboot | sudo gainroot");

	return 0;
} /* main */
Пример #23
0
 template <class T> inline void do_oop_work(T* p) {
   assert(generation()->is_in_reserved((void*)p), "Must be in!");
   _boc.do_oop(p);
 }
Пример #24
0
int main(int argc,char *argv[])
{
   	//Inicia MPI
   	inicializa_mpi(argc,argv);
   	
  	// Obtiene rutas de trabajo y crea archivos generales
  	if(inicializa_archivos(argc, argv, rank) == -1) exit(-1); 
  	   
   	#ifdef _PRINT_MIGRACION_
   		printf("#Bienvenido a MAPAPOC (MÁquina PAralela para Problemas de Optimización Combinatoria) en Rank %d... [OK]\n", rank);
    #endif
      
   	if(rank != 0) {
            //Inicializa semilla aleatoria
            inicializa_semilla();

            //Espera que nodo0 entregue dato runmax (cantidad de archivos a procesar)
            for(;;){
                MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                if(flag1 == true){
                    if (status.MPI_TAG == MSJ_RUNMAX){
                        MPI_Recv(&runmax, 1, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                        flag1 = 0;
                        #ifdef _PRINT_MIGRACION_
                            printf("Rank = %d Recibió desde Rank = 0 Mensaje RUNMAX = %d (cantidad máxima de instancias a resolver)...\n", rank, runmax);
                        #endif
                        break;
                    }//End else if
                }//End if
            }//End for

            for(run=1; run<=runmax; run++) {
                #ifdef _PRINT_MIGRACION_
                        printf("Rank = %d Antes de generar semilla aleatoria...\n", rank);
                #endif
                //Nueva semilla aleatoria
                for(rank_seed = 1; rank_seed <= rank; rank_seed++) {
                    int s = 0;
/*
                    s = atoi(argv[7]);
*/
                    if(s==0) {
                        do {
                            randomseed = nueva_semilla();
                        } while (randomseed == 0);
                    } else {
                        randomseed = (float)((s%10000)/10000.0);
                    }
                }//End for
                #ifdef _PRINT_MIGRACION_
                    printf("Rank = %d Después de generar semilla aleatoria...\n", rank);
                #endif

                //Espera que nodo0 entregue información relevante para nodox
                for(;;) {
                    MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                    if(flag1 == true){
                        if (status.MPI_TAG == MSJ_LINEA_IN){
                            MPI_Recv(linea_in, 100, MPI_CHAR, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            //Asigna variables globales desde linea_in recibida desde Rank 0
                            //sscanf(linea_in,"%d %s %d %s %d %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env_rec, &tasa_migracion, answer_mod_mig, &randomseed);
                            sscanf(linea_in,"%d %s %d %s %d %f %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env, &pind_rec, &tasa_migracion, answer_mod_mig, &randomseed);                 		
                            randomseed = randomseed + (rank * 0.001);
                            //printf("#Rank = %d estableción semilla : %f\n", rank, randomseed);
                            #ifdef _PRINT_MIGRACION_
                                printf("Rank = %d Recibió desde Rank = 0 Mensaje LINEA_IN (PARAMETROS GLOBALES)...\n", rank);
                            #endif
                        } else if (status.MPI_TAG == MSJ_CANT_CHAR_A_REC) {
                            //cantidad_char_a_recibir es la variable que indica cuantos enteros recibirá nodox desde Rank 0
                            MPI_Recv(&cantidad_char_a_recibir, 1, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            #ifdef _PRINT_MIGRACION_
                            printf("Rank = %d Recibió desde Rank = 0 Mensaje MSJ_CANT_CHAR_A_REC...\n", rank);
                            #endif
                            break;
                        } else if (status.MPI_TAG == MSJ_ERROR_ARCHIVO_INSTANCIA) {
                            MPI_Recv(0, 0, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            cantidad_char_a_recibir = -1; //setea a -1 para indicar que hubo error al leer archivo instancia
                            #ifdef _PRINT_MIGRACION_
                            printf("Rank = %d Recibió desde Rank = 0 Mensaje MSJ_ERROR_ARCHIVO_INSTANCIA...\n", rank);
                            #endif
                            break;
                        }//End else if
                    }//End if
                }//End for

                //Setea variable printstrings
                if(strncmp(answer,"n",1) == 0) printstrings = 0;
                else printstrings = 1;

                //Setea variables dependiendo de la cantidad de workers 
                popsize = popsize / workers;
                if(popsize%2) popsize++;
                //n_ind_a_enviar = (int) popsize * pind_env_rec;  //% de la subpoblación se envía
                //n_ind_a_recibir = (int) popsize * pind_env_rec; //% de la subpoblación se recibe
                n_ind_a_enviar = (int) popsize * pind_env;  //% de la subpoblación se envía
                n_ind_a_recibir = (int) popsize * pind_rec; //% de la subpoblación se recibe
                //tasa_migracion = maxgen / workers; //tasa de migración depende de la cantidad de generaciones
                #ifdef _PRINT_MIGRACION_
                    printf("Rank = %d tiene popsize %d, n_ind_a_enviar %d, n_ind_a_recibir %d, tasa_migracion %d...\n", rank, popsize, n_ind_a_enviar, n_ind_a_recibir, tasa_migracion);
                #endif

                // nro. que identifica que migración está ocurriendo
                n_migracion = 0;

                //Inicializa contador de segundos de comunicación 
                time_comm = 0.0;

                //Setea variable modelo_migracion
                if(strncmp(answer_mod_mig,"A",1) == 0) modelo_migracion = 0; // Migración Asíncrona
                else modelo_migracion = 1; //Migración Síncrona

                #ifdef _PRINT_MIGRACION_
                    printf("Rank %d debería recibir %d caracteres representando la instancia a resolver...\n", rank, cantidad_char_a_recibir);
                #endif

                if(cantidad_char_a_recibir > 0) {
                    //Lee enteros con información del archivo instancia  
                    if(lee_char_y_genera_achivo_instancia_tmp(tipo_problema, cantidad_char_a_recibir)) {
                        #ifdef _PRINT_MIGRACION_
                                printf("Espere, MAPAPOC en Rank %d está procesando archivo %s...\n", rank, nomarch);
                        #endif

                        //Actualiza Resultados Estadísticos Evolutivos para cada problema particular
                        fprintf(evofp, "\n\nCorrida : %d, PROBLEMA : %s\n", run, nomarch);
                        fprintf(evofp, "Migracion Generacion Minimo Maximo Media DesvEstandar TiempoTranscurrido GenMejor\n");
                        // Inicia la cuenta de Segundos
                        time_start = MPI_Wtime();

                        // Rutina de inicialización de variables globales
                        initialize();

                        // Ubica espacio malloc para las estructuras de datos globales
                        initmalloc();

                        // Define tipos de Individuos a Enviar y Recibir
                        Build_type_pop(envpop, &message_type_send, n_ind_a_enviar);
                        Build_type_pop(recpop, &message_type_receive, n_ind_a_recibir);

                        // Initializa la población de individuos y determina datos estadísticos
                        // y mejor individuo de la población
                        initpop(tipo_problema);
                        statistics(oldpop);

                        //Avisa a nodo0 que esté listo para comenzar evolución...
                        time_send = MPI_Wtime();
                        MPI_Isend(0, 0, MPI_INT, nodo0, MSJ_LISTO_PARA_COMENZAR, MPI_COMM_WORLD, &request);
                        for(;;){
                            MPI_Test(&request, &flag2, &status);
                            if(flag2 == true){
                            time_send = MPI_Wtime() - time_send;
                            time_comm += time_send;
                            #ifdef _PRINT_MIGRACION_
                                    printf("Envió desde Rank = %d a Rank = 0 Mensaje Listo para comenzar...\n", rank);
                            #endif
                            break;
                            }//End If
                        }//End for

                            //Espera que nodo0 dé la partida para comenzar evolución...
                        for(;;){
                            MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                            if(flag1 == true) {
                                if (status.MPI_TAG == MSJ_COMIENCE){
                                    MPI_Recv(0, 0, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                                    flag1 = 0;
                                    #ifdef _PRINT_MIGRACION_
                                            printf("Rank = %d Recibió desde Rank = 0 Mensaje de COMINECE, comienza evolución...\n", rank);
                                    #endif
                                    break;
                                }//End if
                            }//End if
                        }//End for

                        //Setea contador de generaciones para Migrar en Modelo de Migración Asíncrona
                        if (modelo_migracion == 0) cuenta_gen_para_migracion=1;

                        for(gen=0; gen<maxgen; gen++) {
                            if(printstrings == 1) fprintf(outfp,"\nGENERATION %d->%d\n",gen,maxgen);
                            // Crea una nueva generación
                            generation(tipo_problema);
/*
                            printf("generacion: %d de %d => %f\n",gen, maxgen, bestfit.fitness);
*/

                            // Efectúa estadísticas sobre nueva población y obtiene mejor individuo
                            statistics(newpop);

                            if (modelo_migracion == 0) 
                            //Establece comunicación Asincrona con Coordinador
                            comunicacion_asincrona_con_coordinador();         
                            else
                            //Establece comunicación sincrona con Coordinador
                            comunicacion_sincrona_con_coordinador();    
/*
                            printf("rank %i gen %i best fitness: %f\n", rank, gen, bestfit.fitness);
*/
/*
                            if(bestfit.fitness < 107.0) {
                                printf("rank %i gen %i best fitness: %f done!\n", rank, gen, bestfit.fitness);
                                gen = maxgen;
                            }
*/
/*
                            printf("%i.%i=>%f\n", rank, gen, bestfit.fitness);
*/
                            // Avanza de Generación
                            temppop = oldpop;
                            oldpop = newpop;
                            newpop = temppop;
                        }//End for

                            // Libera memoria temporal
                        freeall();

                            //Libera memoria tipos creados por MPI
                        MPI_Type_free(&message_type_send);
                        MPI_Type_free(&message_type_receive);

                    } else
                        printf("!!! ADVERTENCIA ¡¡¡ Rank %d no procesó archivo de instancia ya que hubo problemas al leer enteros, generar o leer tmp...\n", rank);
                } else 
                    printf("!!! ADVERTENCIA ¡¡¡ Rank %d no procesó archivo de instancia ya que Rank 0 tuvo problemas al leerlo...\n", rank);

                // Libera variables del problema  
                app_free(tipo_problema);

                //Mensaje de término de procesamiento de archivo actual se envía a Rank = 0
                MPI_Isend(&time_comm, 1, MPI_DOUBLE, nodo0, MSJ_TERMINO, MPI_COMM_WORLD, &request);
                for(;;){
                    MPI_Test(&request, &flag2, &status);
                    if(flag2 == true){
                        #ifdef _PRINT_MIGRACION_
                            printf("Envió desde Rank = %d a Rank = 0 Mensaje de Término, archivo %s...\n", rank, nomarch);
                        #endif
                        break;
                    }//End If
                }//End for

                    //Espera que nodo0 dé el OK para poder finalizar el procesamiento del archivo actual
                for(;;){
                    MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                    if(flag1 == true){
                        if(status.MPI_TAG == MSJ_TERMINO_CONFIRMADO){
                            MPI_Recv(0, 0, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            #ifdef _PRINT_MIGRACION_
                                printf("Rank = %d Recibió desde Rank = 0 Mensaje de TERMINO_CONFIRMADO, pasa siguiente archivo o termina...\n", rank);
                            #endif
                            break;
                        }//End if
                    }//End if
                }//End for
                #ifdef _PRINT_MIGRACION_
                        printf("#Corrida %d, Archivo %s procesado por Rank %d...   [OK]\n", run, nomarch, rank);
                #endif
            }//End for

            if(runmax == 0){
                //Que runmax = 0 significa que la consistencia del archivo arrojó un error 
                //=> rank debe mandar mensaje al Coordinador que va ha terminar el proceso...
                //Mensaje de término de procesamiento de archivo actual se envía a Rank = 0
                MPI_Isend(&time_comm, 1, MPI_DOUBLE, nodo0, MSJ_TERMINO, MPI_COMM_WORLD, &request);
                for(;;){
                    MPI_Test(&request, &flag2, &status);
                    if(flag2 == true){
                        #ifdef _PRINT_MIGRACION_
                                printf("Envió desde Rank = %d a Rank = 0 Mensaje de Término, archivo %s...\n", rank, nomarch);
                        #endif
                        break;
                    }//End If
                }//End for
                printf("Proceso en Rank %d detenido ya que Rank 0 informa error en archivo de entrada...   [OK]\n", rank);
            }//End if
        } else {
      	//Rank = 0 => Coordinador
/*
   		printf("#Bienvenido a Máquina Paralela para Problemas de Optimización Combinatoria, espere por favor...\n");
*/
      	
      	// Revisa consistencia del archivo de entrada in.txt
      	runmax = consistenciaarchivo(workers);
      	
      	//Envía runmax a cada Rank
      	envia_a_cada_rank(MSJ_RUNMAX);
   
      	for(run=1;run<=runmax;run++) {
         	//Lee archivo en infp con parametros (todos ya chequeados)
         	//OJO => Cada AG tendrá popsize/workers individuos => Población Total = popsize          	
			//fscanf(infp,"%d %s %d %s %d %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env_rec, &tasa_migracion, answer_mod_mig, &randomseed);
            fscanf(infp,"%d %s %d %s %d %f %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env, &pind_rec, &tasa_migracion, answer_mod_mig, &randomseed);
            int i=0;
            randomseed = (float)((atoi(argv[7])%100)/100.0);
            
/*
            printf("argv[7]: %i\n", atoi(argv[7]));
            printf("randomseed: %f\n", randomseed);
*/
            for(i=0; i<argc; i++) {
//                printf("argv[%i]: %s\n", i, argv[i]);
                if(strcmp(argv[i], "-pr")==0) tipo_problema = atoi(argv[++i]);
                if(strcmp(argv[i], "-po")==0) popsize = atoi(argv[++i]);
                if(strcmp(argv[i], "-g")==0) maxgen = atoi(argv[++i]);
                if(strcmp(argv[i], "-m")==0) pmutation = atof(argv[++i]);
                if(strcmp(argv[i], "-c")==0) pcross = atof(argv[++i]);
                if(strcmp(argv[i], "-pe")==0) pind_env = atof(argv[++i]);
                if(strcmp(argv[i], "-pa")==0) pind_rec = atof(argv[++i]);
                if(strcmp(argv[i], "-tm")==0) tasa_migracion = atoi(argv[++i]);
                if(strcmp(argv[i], "-am")==0) sprintf(answer_mod_mig, "%s", argv[++i]);
                if(strcmp(argv[i], "-f")==0) sprintf(nomarch, "%s", argv[++i]);
                if(strcmp(argv[i], "-a")==0) sprintf(answer, "%s", argv[++i]);
            }
//            exit(0);
         	
			//Inicializa contador de segundos de comunicación 
         	time_comm = 0.0;
         
         	//Llena con información linea_in para ser enviada a cada Rank
         	//sprintf(linea_in,"%d %s %d %s %d %f %f %f %d %s %f\n", tipo_problema, nomarch, popsize, answer, maxgen, pcross, pmutation, pind_env_rec, tasa_migracion, answer_mod_mig, randomseed);
			sprintf(linea_in,"%d %s %d %s %d %f %f %f %f %d %s %f", tipo_problema, nomarch, popsize, answer, maxgen, pcross, pmutation, pind_env, pind_rec, tasa_migracion, answer_mod_mig, randomseed);
/*
                        printf("%d %s %d %s %d %f %f %f %f %d %s %f\n", tipo_problema, nomarch, popsize, answer, maxgen, pcross, pmutation, pind_env, pind_rec, tasa_migracion, answer_mod_mig, randomseed);
*/

       		#ifdef _PRINT_MIGRACION_
       			printf("Espere, MAPAPOC en Rank %d está enviando archivo %s a todos los rank...\n", rank, nomarch);
       		#endif

        	//Envía linea_in a cada Rank
      		envia_a_cada_rank(MSJ_LINEA_IN);
      	
         	//Setea variable printstrings
         	if(strncmp(answer,"n",1) == 0) printstrings = 0;
         	else printstrings = 1;
      
         	//Setea variables dependiendo de la cantidad de workers 
         	popsize = popsize / workers;
/*
                printf("popsize: %i\n", popsize);
*/
         	if(popsize%2) popsize++;
         	//n_ind_a_enviar = (int) popsize * pind_env_rec;  //% de la subpoblación se envía
         	//n_ind_a_recibir = (int) popsize * pind_env_rec; //% de la subpoblación se recibe
                n_ind_a_enviar = (int) popsize * pind_env;  //% de la subpoblación se envía
         	n_ind_a_recibir = (int) popsize * pind_rec; //% de la subpoblación se recibe
         	//tasa_migracion = maxgen / workers; //tasa de migración debende de la cantidad de generaciones
               
         	//Setea variable modelo_migracion
         	if(strncmp(answer_mod_mig,"A",1) == 0) modelo_migracion = 0; //Migración Asíncrona
         	else modelo_migracion = 1; //Migración Síncrona
         
         	if(app_leearchivo(tipo_problema, nomarch, rank)) {     
            	if(almacena_archivo_instancia(nomarch)) {
	            	//Determina cantidad_char_a_recibir por cada rank que coordinador enviará. Todos estos char determinan los datos del problema a resolver
	            	cantidad_char_a_recibir = cantidad_char_que_determinan_instancia_del_problema;
	            	
	            	//Envía a cada Rank cantidad de char a recibir del problema
	            	envia_a_cada_rank(MSJ_CANT_CHAR_A_REC); 
	            
	            	//Envía a cada Rank un grupo de char que determinan la estructura de una instancia del problema
	            	envia_a_cada_rank(MSJ_CHAR_ARCHIVO_INSTANCIA);
	            	
	        		// Rutina de inicialización de variables globales
	           		// nro. individuos a enviar desde coord. a nodo AG
	           		coord_ind_a_env  = n_ind_a_recibir;  
	           		// nro. individuos a recibir desde cada nodo AG a coord
	           		coord_ind_a_rec = n_ind_a_enviar; 
	           		// nro. individuos total recibidos => Población Global del Coordinador
	           		coord_ind_global = workers * n_ind_a_enviar; 
	           		// nro. que identifica qué migración está ocurriendo
	           		n_migracion = 1;  
	           		#ifdef _PRINT_MIGRACION_
	           			printf("Espere, MAPAPOC en Rank %d está procesando archivo %s...\n", rank, nomarch);
	              		printf("Rank = %d tiene popsize %d, coord_ind_a_env %d, coord_ind_a_rec %d, coord_ind_global % d, tasa_migracion %d...\n", rank, popsize, coord_ind_a_env, coord_ind_a_rec, coord_ind_global, tasa_migracion);
	           		#endif
	     
				   	//Actualiza Resultados Estadísticos Evolutivos para cada problema particular
				   	fprintf(evofp, "\n\nCorrida : %d, PROBLEMA : %s\n", run, nomarch);
				   	fprintf(evofp, "Migracion Generacion Minimo Maximo Media DesvEstandar TiempoTranscurrido\n");
				   	// Inicia la cuenta de Segundos
				   	time_start = MPI_Wtime();
	           
	           		//Rutina de inicialización de variables globales
	           		initialize();
	           
	           		//Dimensiona poblaciones de individuos que recibe y envía...
	           		initmallocMaster(coord_ind_a_rec, coord_ind_a_env, coord_ind_global);
	     
	           		//Define tipos de Individuos a Enviar y Recibir
	           		Build_type_pop(envpop, &message_type_send, coord_ind_a_env);
	           		Build_type_pop(recpop, &message_type_receive, coord_ind_a_rec);
	  
	           		if (modelo_migracion == 0) 
	              		//Establece comunicación Asincrona con cada rank (AG)
		              		comunicacion_asincrona_con_cada_rank();         
	           		else
	              		//Establece comunicación sincrona con cada rank (AG)
	              		comunicacion_sincrona_con_cada_rank();         
	              
                                // Calcula cantidad de segundos que demoró en cada Algoritmo Genético
                                time_end = MPI_Wtime() - time_start;
                                time_consumation.elapsed_time = time_end;
                                time_consumation.comm_time = time_comm;
                                time_consumation.cpu_time = time_end - time_comm;

                                //Graba datos en archivo de resultados del algoritmo
                                genera_resultados_algoritmo(run, tipo_problema, nomarch, &time_consumation);

                                //Graba datos en archivo de resultados del problema
                                app_genera_resultados_problema(run, tipo_problema, nomarch);

                                //IMPRIME SALIDA PARA PROGRAMA PARAMILS
/*
                                printf("RunsExecuted = 1\n");
                                printf("CPUTime_Mean = %f\n", time_consumation.elapsed_time);
                                printf("BestSolution_Mean = %f\n", bestfit.fitness);
*/
/*
                                printf("Result for ParamILS: SAT, %f, %i, %f, %s\n", -1.0, -1, bestfit.fitness, argv[7]);
*/
                                printf("Resultado: SAT, %s, %f, %f, %f, %f\n", nomarch, time_consumation.elapsed_time, time_consumation.cpu_time, bestfit.fitness, randomseed);

                                //Genera la Salida hacia archivo de Resultados LAYOUT
                                app_objfuncfinal(tipo_problema, &(bestfit));
				  	
	           		//Libera memoria del Coordinador
	           		freeallMaster(coord_ind_a_rec, coord_ind_a_env, coord_ind_global);
	           
	           		//Libera memoria tipos creados por MPI
	           		MPI_Type_free(&message_type_send);
	           		MPI_Type_free(&message_type_receive);
	         	}//End if
	         	else {
	            	printf("!!! ERROR ¡¡¡ Rank 0, en datos del archivo de piezas <%s> => Archivo no procesado...\n", nomarch);
	            	//Envía a cada Rank que ARCHIVO_INSTANCIA está con algún error
	            	envia_a_cada_rank(MSJ_ERROR_ARCHIVO_INSTANCIA); 
	         	}//End else
         	}//End if
         	else {
            	printf("!!! ERROR ¡¡¡ Rank 0, en datos del archivo de piezas <%s> => Archivo no procesado...\n", nomarch);
            	//Envía a cada Rank que ARCHIVO_INSTANCIA está con algún error
            	envia_a_cada_rank(MSJ_ERROR_ARCHIVO_INSTANCIA); 
         	}//End else
	      	// Libera variables del problema  
	      	app_free(tipo_problema);

                #ifdef _PRINT_MIGRACION_
         		printf("#Corrida %d, Archivo %s procesado por Coordinador...   [OK]\n", run, nomarch);
         	#else
//         		printf("#Corrida %d, Archivo %s procesado...   [OK]\n", run, nomarch);
         	#endif
      	}//End for
      	if(runmax == 0){
         	//Que runmax = 0 significa que la consistencia del archivo arrojó un error 
         	printf("Archivo %s NO procesado por Rank %d debido a error...   [OK]\n", nomarch, rank);
      	}//End if
   	}//End else    

	//Cierra archivos
	cierra_archivos();
	
   	//Rutina para MPI
   	MPI_Finalize();
 
   	#ifdef _PRINT_MIGRACION_
   		printf("Terminó rank = %d...\n", rank);
    #endif
   
	exit(0);
}//End main
Пример #25
0
/* Creates a map for a level in the world list */
LEVELMAP* create_map(char *level_name, int level_id, int width, int height, boolean has_shops, int level_type) {
    LEVELMAP *new_element;
    generation_params *params;
    generation_params *params_set;
    int xi, yi, ii, jj;
    int generations = 1;

    if ( (new_element = (LEVELMAP *)malloc(sizeof(LEVELMAP))) == NULL) return NULL;
    memset(new_element, 0, sizeof(LEVELMAP));

    new_element->level_name = (char *)malloc(sizeof(char)*strlen(level_name)+1);
    memset(new_element->level_name, 0, strlen(level_name) + 1);
    if (level_name != NULL)
        strcpy(new_element->level_name,level_name);

    new_element->level_id = level_id;
    if (width < MAP_DISPLAY_WIDTH * 3) width = MAP_DISPLAY_WIDTH * 3;
    if (height < MAP_DISPLAY_HEIGHT * 3) height = MAP_DISPLAY_HEIGHT * 3;

    new_element->width = width;
    new_element->height = height;
    new_element->has_shops = has_shops;
    new_element->level_type = level_type;
    new_element->portal_up_loc.x = new_element->portal_up_loc.y = new_element->portal_down_loc.x = new_element->portal_down_loc.y = new_element->shop_loc.x = new_element->shop_loc.y = 0;
    new_element->next = NULL;

    /*
        Now we build up the level
    */
	new_element->grid  = (int**)malloc(sizeof(int*) * height);

	/* Allocate for the scratch area */
	grid2 = (int**)malloc(sizeof(int*) * height);

	for(yi=0; yi < height; yi++) {
		new_element->grid[yi] = (int*)malloc(sizeof(int) * width);
		grid2[yi] = (int*)malloc(sizeof(int) * width);
	}

	for(yi=1; yi < height-1; yi++)
        for(xi=1; xi < width-1; xi++)
            new_element->grid[yi][xi] = mapPick(35);

	for(yi=0; yi < height; yi++)
        for(xi=0; xi < width; xi++)
            grid2[yi][xi] = OUTERWALL;

	for(yi=0; yi < height; yi++)
		new_element->grid[yi][0] = new_element->grid[yi][new_element->width-1] = OUTERWALL;
	for(xi=0; xi < width; xi++)
		new_element->grid[0][xi] = new_element->grid[new_element->height-1][xi] = OUTERWALL;

    params = params_set = (generation_params*)malloc( sizeof(generation_params) * generations);

    params->r1_cutoff = 30;
    params->r2_cutoff = 5;
    params->reps = 5;
/*
    params++;
    params->r1_cutoff = 20;
    params->r2_cutoff = 3;
    params->reps = 1;
    params++;
*/
 	for(ii=0; ii < generations; ii++) {
 		params = &params_set[ii];
 		for(jj=0; jj < params->reps; jj++)
 			generation(new_element,params);
 	}

    free(params);
    free(params_set);

    for (ii = 0; ii < new_element->height; ii++) {
        free(grid2[ii]);
    }

    /* We're done with the secondary grid, deallocate it */
    free(grid2);

    /* If a shop needs to be placed place it */
    if (new_element->has_shops) {
            placeShop(new_element);
    }

    placePortal(new_element);

    /* return the newly created element in memory */
    return new_element;
}
Пример #26
0
void main()
{
	void generation(int array_x[], int array_y[], int n); 
	void Normalize(double *point1);
	void fcm_method(int x_second[], int y_third[], double *point2,double *point3);

	srand((int)time(0));
	
	// Generate information database
	int data_x[TOTAL_NUM], data_y[TOTAL_NUM];
	generation(data_x, data_y, TOTAL_NUM);

	//Get the initial membership matrix
	double u[3][50], *p1;
	p1 = u[0];
	Normalize(p1);

	// FCM algorithm
	int class_fcm[TOTAL_NUM] = {0};
	double center_point[2][3];
	double *p2, *p3;
	p2 = u[0];
	p3 = center_point[0];
	fcm_method(data_x, data_y, p2, p3);

	// proof
	for(int i = 0; i < 3;i++)
	{
		for(int j = 0;j < 50;j++)
		{
			printf(" %f ",u[i][j]);
		}
		printf("\n");
	}
	for(int i = 0; i < 2;i++)
	{
		for(int j = 0;j < 3;j++)
		{
			printf(" %f ",center_point[i][j]);
		}
		printf("\n");
	}


	// Out put database and center_point as a text file!
	FILE *fp;
	if( (fp = fopen("data.txt","w")) == NULL )
	{
		printf("cannot open file\n");
		exit(0);
	}
	fprintf(fp,"Measurement\n");
	fprintf(fp,"x,y\n");
	for(int i = 0;i < 50; i++)
	{
		fprintf(fp,"%d,%d\n",data_x[i],data_y[i]);	
	}
	fprintf(fp,"Center\n");
	fprintf(fp,"x,y\n");
	for(int i = 0; i < 3 ; i++)
	{
		fprintf(fp,"%f,%f\n",center_point[0][i],center_point[1][i]);
	}
	fclose(fp);
	
	FILE *fp_1;
	if( (fp_1 = fopen("degree.txt","w")) == NULL )
	{
		printf("cannot open file\n");
		exit(0);
	}
	for(int i = 0;i < 3; i++)
	{
		for(int j = 0;j < 50; j++)
		{
			fprintf(fp_1," %f ",u[i][j]);
		}
		fprintf(fp_1,"\n");
	}
	fclose(fp_1);

	getchar();
}
Пример #27
0
void MockMediaSample::dump(PrintStream& out) const
{
    out.print("{PTS(", presentationTime(), "), DTS(", decodeTime(), "), duration(", duration(), "), flags(", (int)flags(), "), generation(", generation(), ")}");
}
inline void ParScanClosure::do_oop_work(T* p,
                                        bool gc_barrier,
                                        bool root_scan) {
  assert((!GenCollectedHeap::heap()->is_in_reserved(p) ||
          generation()->is_in_reserved(p))
         && (GenCollectedHeap::heap()->is_young_gen(generation()) || gc_barrier),
         "The gen must be right, and we must be doing the barrier "
         "in older generations.");
  T heap_oop = oopDesc::load_heap_oop(p);
  if (!oopDesc::is_null(heap_oop)) {
    oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
    if ((HeapWord*)obj < _boundary) {
#ifndef PRODUCT
      if (_g->to()->is_in_reserved(obj)) {
        tty->print_cr("Scanning field (" PTR_FORMAT ") twice?", p2i(p));
        GenCollectedHeap* gch = GenCollectedHeap::heap();
        Space* sp = gch->space_containing(p);
        oop obj = oop(sp->block_start(p));
        assert((HeapWord*)obj < (HeapWord*)p, "Error");
        tty->print_cr("Object: " PTR_FORMAT, p2i((void *)obj));
        tty->print_cr("-------");
        obj->print();
        tty->print_cr("-----");
        tty->print_cr("Heap:");
        tty->print_cr("-----");
        gch->print();
        ShouldNotReachHere();
      }
#endif
      // OK, we need to ensure that it is copied.
      // We read the klass and mark in this order, so that we can reliably
      // get the size of the object: if the mark we read is not a
      // forwarding pointer, then the klass is valid: the klass is only
      // overwritten with an overflow next pointer after the object is
      // forwarded.
      Klass* objK = obj->klass();
      markOop m = obj->mark();
      oop new_obj;
      if (m->is_marked()) { // Contains forwarding pointer.
        new_obj = ParNewGeneration::real_forwardee(obj);
        oopDesc::encode_store_heap_oop_not_null(p, new_obj);
#ifndef PRODUCT
        if (TraceScavenge) {
          gclog_or_tty->print_cr("{%s %s ( " PTR_FORMAT " ) " PTR_FORMAT " -> " PTR_FORMAT " (%d)}",
             "forwarded ",
             new_obj->klass()->internal_name(), p2i(p), p2i((void *)obj), p2i((void *)new_obj), new_obj->size());
        }
#endif

      } else {
        size_t obj_sz = obj->size_given_klass(objK);
        new_obj = _g->copy_to_survivor_space(_par_scan_state, obj, obj_sz, m);
        oopDesc::encode_store_heap_oop_not_null(p, new_obj);
        if (root_scan) {
          // This may have pushed an object.  If we have a root
          // category with a lot of roots, can't let the queue get too
          // full:
          (void)_par_scan_state->trim_queues(10 * ParallelGCThreads);
        }
      }
      if (is_scanning_a_klass()) {
        do_klass_barrier();
      } else if (gc_barrier) {
        // Now call parent closure
        par_do_barrier(p);
      }
    }
  }
}
Пример #29
0
int main (int argc, char *argv[]){
	int continuer = 10;
#ifdef GUI_ENABLE
	int afficher;
#endif
	char nom_file[1000];
	Matrice mat = NULL;
	FILE *input = NULL;
	FILE *output = stdout;
	FILE *nullstream = stdout;
	nullstream = fopen ("nullstream", "w");
	if (nullstream == NULL){
		printf("probleme a l'ouverture du fichier\n");
		exit(1);
	}

	if(argc >= 2){
		output = fopen (argv[1], "w");
		if (output == NULL){
			printf("probleme a l'ouverture du fichier\n");
			exit(1);
		}
	}

	while (continuer){
		printf("TSP : selectionner l'action a executer :\n");
		printf("\t1 : generer une liste de ville\n");
		printf("\t2 : appliquer l'algorithme prim à un fichier de ville\n");
#ifdef GUI_ENABLE
		printf("\t3 : afficher une liste de ville (aucune action possible -> efficace pour de grand nombre de villes)\n");
#endif
		printf("\t0 : quitter le programme\n");
		scanf("%d", &continuer);

		switch(continuer){
		case 1 :
			continuer = generation(nom_file, &mat);
			break;
		case 2 :
			printf("entrer le nom du fichier :\n");
			scanf("%s", nom_file);
			input = fopen (nom_file, "r");
			if (input == NULL)
			{
				printf("probleme a l'ouverture du fichier\n");
				exit(1);
			}
			mat = matrice_of_coordonnees(input);
			fclose(input);
			TSP (mat,output);
			fprintf(output,"\n");
			continuer = 13;
			break;
#ifdef GUI_ENABLE
		case 3 :
			printf("entrer le nom du fichier :\n");
			scanf("%s", nom_file);
			affichage_gui(nom_file);
			break;
#endif
		case 0 :
			break;
		default :
			continuer = 10;
			break;
		}

#ifdef GUI_ENABLE
		/*propose l'affichage graphique, et initialise la matrice en fonction des choix fait par l'utilisateur*/
		afficher = 0;
		switch(continuer){
		case 13:
		case 12:
		case 11:
			do{
				printf("voulez vous afficher graphiquement le resultat ? (oui = 1, non = 0) ");
				scanf("%d", &afficher);
			}while (afficher != 0 && afficher != 1);
			break;
		}
		if (afficher){
			printf("\ncommande :\nla pression des touches suivantes permet d'afficher ou masquer : \n"
					"c(ycle) : le chemin calculé par l'algorithme\n"
					"t(ree) : l'arbre couvrant minimum\n"
					"s(ommet) : les sommets representant les villes\n"
					"Appuyez sur esc pour fermer l'interface graphique\n");
			switch(continuer){
			case 12://un fichier liste de ville (nom_file) vient d'etre cree.
				input = fopen(nom_file, "r");
				if (input == NULL)
				{
					printf("probleme a l'ouverture du fichier\n");
					exit(1);
				}
				mat = matrice_of_coordonnees(input);
				fclose(input);
				//break omis volontairement
			case 11:// la matrice est initialisee, il suffit d'afficher le cycle
				TSP (mat, nullstream);
				fprintf(nullstream,"\n");
				//break omis volontairement
			case 13:
				gui(mat);
				break;
			}
		}
#endif
		if (mat){
			liberer_mat(mat);
			mat = NULL;
		}
	}
	fclose(nullstream);
	if (argc >= 2)fclose(output);
	return 0;
}
Пример #30
0
void Entity::run()
{
    if (age() == 1 && generation() > 50 && generation() % 50 == 0) {
        mNeuralNetwork.optimize();
    }

    setHeatLevel(mMap->cell(mX, mY).mHeatLevel / 255.0);


    int index = 0;
    for (int y = -1; y <= 1; ++y) {
        for (int x = -1; x <= 1; ++x) {
            const Cell &cell = mMap->safeCell(mX + x, mY + y);
            mNeuralNetwork.setInputValue(M_FOOD_LEVEL_PROPERTY_START + index, cell.mFoodLevelM / 255.0);
            mNeuralNetwork.setInputValue(V_FOOD_LEVEL_PROPERTY_START + index, cell.mFoodLevelV / 255.0);
            mNeuralNetwork.setInputValue(ENTITY_HEALTH_PROPERTY_START + index, cell.mEntity ? cell.mEntity->getHealth() : 0);
            mNeuralNetwork.setInputValue(WATER_LEVEL_PROPERTY_START + index, cell.mWaterLevel / 255.0);
            ++index;
        }
    }

    mNeuralNetwork.run();


    const std::vector<NNType> &output = mNeuralNetwork.outputValues();
    NNType moveLeft = output[0];
    NNType moveRight = output[1];
    NNType moveUp = output[2];
    NNType moveDown = output[3];

    NNType attackLeft = output[4];
    NNType attackRight = output[5];
    NNType attackUp = output[6];
    NNType attackDown = output[7];

    NNType eatV = output[8];
    NNType eatM = output[9];
    NNType drink = output[10];
    NNType split = output[11];

    setValueStore1(output[12]);
    setValueStore2(output[13]);
    setValueStore3(output[14]);
    setValueStore4(output[15]);

    setActionMoveLeft(moveLeft);
    setActionMoveRight(moveRight);
    setActionMoveUp(moveUp);
    setActionMoveDown(moveDown);
    setActionAttackLeft(attackLeft);
    setActionAttackRight(attackRight);
    setActionAttackUp(attackUp);
    setActionAttackDown(attackDown);
    setActionEatV(eatV);
    setActionEatM(eatM);
    setActionDrink(drink);
    setActionSplit(split);

    NNType bestVal = 0;
    Action::Type actionType = Action::None;
#define MAX_ACTION(var, actionEnum) if (var > bestVal) { bestVal = var; actionType = actionEnum; }

    MAX_ACTION(moveLeft, Action::MoveLeft);
    MAX_ACTION(moveRight, Action::MoveRight);
    MAX_ACTION(moveUp, Action::MoveUp);
    MAX_ACTION(moveDown, Action::MoveDown);

    MAX_ACTION(attackLeft, Action::AttackLeft);
    MAX_ACTION(attackRight, Action::AttackRight);
    MAX_ACTION(attackUp, Action::AttackUp);
    MAX_ACTION(attackDown, Action::AttackDown);

    MAX_ACTION(eatV, Action::EatV);
    MAX_ACTION(eatM, Action::EatM);
    MAX_ACTION(drink, Action::Drink);
    MAX_ACTION(split, Action::Split);

    ++mAge;

    mLastAction.mType = actionType;
}