예제 #1
0
int main() {
  c = new Crypto(CRYPTO_TYPE_PRIVATE, CRYPTO_ELGAMAL, PNG_CHACHA, false, FIELD_NBITS);
  gpuc = new GPUCrypto(CRYPTO_TYPE_PRIVATE, CRYPTO_ELGAMAL, PNG_CHACHA, false, FIELD_NBITS);
  cpu2_c = new CPUCrypto(CRYPTO_TYPE_PRIVATE, CRYPTO_ELGAMAL, PNG_CHACHA, false, FIELD_NBITS);

  // Always enable gpu
  if(!gpuc->is_gpu_enabled()) gpuc->enable_gpu(true);

  rand_init(plain, ARRY_SIZE, EGGROUP_NBITS);
  rand_init(pi, ARRY_SIZE, FIELD_NBITS);

  //for (int i = 0; i < ARRY_SIZE; i++)
    //mpz_set_ui(pi[i], i);//(i+1));

  mpz_set_ui(plain[0], 1);

  init(encoded, ARRY_SIZE, EGGROUP_NBITS);
  init(cipher, 2 * ARRY_SIZE, EGGROUP_NBITS);
  init(cipher_gpu, 2 * ARRY_SIZE, EGGROUP_NBITS);
  init(plain_cpu, ARRY_SIZE, EGGROUP_NBITS);
  init(plain_gpu, ARRY_SIZE, EGGROUP_NBITS);

  // Encode plaintext as g^{plain}
  encode_plain(c, encoded, plain, ARRY_SIZE);

  test_elgamal_enc(ARRY_SIZE);
  test_dot_product_enc(ARRY_SIZE);

#if TEST_LEVEL >= STRESS_TEST
  {
    int numTests = 0;
    int min = 1;
    int max = 2;
    for (int i = 0; i < ARRY_SIZE; i += min + (rand() % (max - min)))
    {
      cout << "[n = " << i << "]" << endl;
      test_dot_product_enc(i, false);
      numTests++;

      if (numTests % 5 == 0)
        max <<= 1;

      if (max > 128 && numTests % 5 == 0)
        min <<= 1;
    }
  }
#endif
}
예제 #2
0
int core_init(void) {
	if (core_ctx == NULL) {
		core_ctx = &(first_ctx);
	}

#if defined(CHECK) || defined(TRACE)
	core_ctx->trace = 0;
#endif

#ifdef CHECK
	core_ctx->reason[ERR_NO_MEMORY] = MSG_NO_MEMORY;
	core_ctx->reason[ERR_NO_PRECI] = MSG_NO_PRECI;
	core_ctx->reason[ERR_NO_FILE] = MSG_NO_FILE;
	core_ctx->reason[ERR_NO_READ] = MSG_NO_READ;
	core_ctx->reason[ERR_NO_VALID] = MSG_NO_VALID;
	core_ctx->reason[ERR_NO_BUFFER] = MSG_NO_BUFFER;
	core_ctx->reason[ERR_NO_FIELD] = MSG_NO_FIELD;
	core_ctx->reason[ERR_NO_CURVE] = MSG_NO_CURVE;
	core_ctx->reason[ERR_NO_CONFIG] = MSG_NO_CONFIG;
	core_ctx->last = NULL;
#endif /* CHECK */

#if ALLOC == STATIC
	core_ctx->next = 0;
#endif

#ifdef OVERH
	core_ctx->over = 0;
#endif

	core_ctx->code = STS_OK;

	TRY {
		arch_init();
		rand_init();
#ifdef WITH_FP
		fp_prime_init();
#endif
#ifdef WITH_FB
		fb_poly_init();
#endif
#ifdef WITH_FT
		ft_poly_init();
#endif
#ifdef WITH_EP
		ep_curve_init();
#endif
#ifdef WITH_EB
		eb_curve_init();
#endif
#ifdef WITH_PP
		pp_map_init();
#endif
	}
	CATCH_ANY {
		return STS_ERR;
	}

	return STS_OK;
}
예제 #3
0
파일: rand.c 프로젝트: 0x00evil/nmap
rand_t *
rand_open(void)
{
	rand_t *r;
	u_char seed[256];
#ifdef _WIN32
	HCRYPTPROV hcrypt = 0;

	CryptAcquireContext(&hcrypt, NULL, NULL, PROV_RSA_FULL,
	    CRYPT_VERIFYCONTEXT);
	CryptGenRandom(hcrypt, sizeof(seed), seed);
	CryptReleaseContext(hcrypt, 0);
#else
	struct timeval *tv = (struct timeval *)seed;
	int fd;

	if ((fd = open("/dev/arandom", O_RDONLY)) != -1 ||
	    (fd = open("/dev/urandom", O_RDONLY)) != -1) {
		read(fd, seed + sizeof(*tv), sizeof(seed) - sizeof(*tv));
		close(fd);
	}
	gettimeofday(tv, NULL);
#endif
	if ((r = malloc(sizeof(*r))) != NULL) {
		rand_init(r);
		rand_addrandom(r, seed, 128);
		rand_addrandom(r, seed + 128, 128);
		r->tmp = NULL;
		r->tmplen = 0;
	}
	return (r);
}
예제 #4
0
파일: main.c 프로젝트: germ/Whacko
int main(void) {
  Pile *players[PLAYERS],
       *deck,
       *discard;
  int i, j, k;
  Player* 

  /* Initilize game state memory */
  k = rand_init();
  assert(k == 0);

  for (i = 0; i < PLAYERS; i++) 
    players[i] = create_deck(10, 0, 1);

  discard = create_deck(deck_sizes[PLAYERS], 0, 1);
  deck    = create_deck(deck_sizes[PLAYERS], 0, 0);

  /* Set game to initial state */
  for (i = 0; i < PLAYERS; i++) 
    for (j = 0; j < 10; j++) 
      players[i]->deck[j] = draw_card(deck);

  /* Free up allocated memory */
  (void)free_deck(&deck);
  (void)free_deck(&discard);
  for (i = 0; i < PLAYERS; i++)
    if (players[i] != NULL) 
      (void)free_deck(&players[i]);
  
  return 0;
}
예제 #5
0
파일: q.c 프로젝트: vabc3/EOJ
int main()
{
	rand_init();
	int i=0;
	for(i=0;i<20;i++){
		printf("%d\n",rand_n(5));
	}
}
예제 #6
0
파일: rand.c 프로젝트: 0x00evil/nmap
int
rand_set(rand_t *r, const void *buf, size_t len)
{
	rand_init(r);
	rand_addrandom(r, (u_char *)buf, len);
	rand_addrandom(r, (u_char *)buf, len);
	return (0);
}
예제 #7
0
    Server::Server(int port) : _port(port),_gameThread(&Server::runGame,this), _listenThread(&Server::listen,this)
    {
        rand_init();
        _currentClient = nullptr;

        onLogOut = [this](Client* client){
            _clients.emplace_back(client);
        };
    }
예제 #8
0
파일: eina_value_02.c 프로젝트: Limsik/e17
int main(int argc, char **argv)
{
   Eina_Value *v1, *v2;

   eina_init();
   value_init();
   srand(time(NULL));

   v1 = eina_value_struct_new(V1_DESC);
   v2 = eina_value_struct_new(V2_DESC);

   rand_init(v1);
   my_struct_use(v1);

   rand_init(v2);
   my_struct_use(v2);

   eina_value_free(v1);
   eina_value_free(v2);
   eina_shutdown();
}
void rndtfile(char *nameout, unsigned long int size)
{
unsigned long int i=0;

najout(nameout);

rand_init();
for (i=0; i<size; i++)
fputc(((rand() % 95)+' '), naji_output);

najoutclose();
}
예제 #10
0
Game::Game() : _window(sf::VideoMode(800, 600),"SFML Tetris"), _board() {
    _window.setFramerateLimit(60);
    // std::cout << "ka" << "\n";
    rand_init();
    // std::cout << "ki" << "\n";
    _board.setPosition(10,10);
    // std::cout << "ku" << "\n";
    _stats.setPosition(300,10);
    // std::cout << "ke" << "\n";
    newPiece();
    // std::cout << "ko" << "\n";
}
예제 #11
0
int main(int argc, char**argv) {
    layout_t *layout = parser_parseNetlist(argv[1]); 
    struct timeval start, end;
    if (!layout) {
        return -1;
    }
    int threads = 1; 
    if (argc > 2) {
        #ifdef PRODUCTION
        printf("Threads %d\n",atoi(argv[2])); 
        #else 
        printf("THDS: %d",atoi(argv[2])); 
        #endif
        threads = atoi(argv[2]);
    }
    gettimeofday(&start,NULL);
    int sum = 0;
    #ifdef ANNEALER
    int sum1 = 0;    
    rand_init(); 
    annealer_createInitialPlacement(layout);
    sum1 = netlist_layoutWirelength(layout);
    annealer_anneal(layout,sum1,threads);
    sum = netlist_layoutWirelength(layout);
    printf("Wirelength: %d %d\n",sum,sum1);
    #else 
    omp_set_dynamic(0); 
    omp_set_num_threads(threads);
    solver_quadraticWirelength(layout);
    #endif 
    
    gettimeofday(&end,NULL); 
    long int sec = ((end.tv_sec * 1000000 + end.tv_usec)-(start.tv_sec*1000000+start.tv_usec)); 
    sum = netlist_layoutWirelength(layout);
    

    #ifdef PRODUCTION 
    netlist_printNetlist(layout); 
    netlist_printNetlist(layout); 
    netlist_printQoR(layout);
    //netlist_printForMatlab(layout);
    printf("Wirelength: %d\n Seconds: %lu\n",sum,sec/1000000);
    printf("done\n");
    #else
    printf(" WL: %d TIME: %lu.%lu\n",sum,sec/1000000,(sec/10000)%100);
    #endif
    netlist_free(layout);
    return 0;
}
예제 #12
0
int main() {

	SORT_TYPE *dst, *tmp;
	double *time_arr;

	size_t i, t = 2;
	setlocale(LC_NUMERIC, "");

	size_t len = pow(10, 8);
	size_t max = 10 * len;

	dst = (SORT_TYPE *)malloc((size_t) sizeof(SORT_TYPE) * len);
	tmp = (SORT_TYPE *)malloc((size_t) sizeof(SORT_TYPE) * len);

	rand_init(dst, max, len);

	memcpy(tmp, dst, len * sizeof(SORT_TYPE));
	double merge_sort_time = test(int64_merge_sort, tmp, len, 0);


	double min = merge_sort_time;
	size_t min_idx = 0;
	double merge_t = 0;


	//printf("insertion sort: %20d %20d %20f \n", len, t, insertion_sort_time);
	printf("merge sort    : %20d %20d %20f \n", len, t, merge_sort_time);


	for (i = 10; i < 30; i += 1) {
		memcpy(tmp, dst, len * sizeof(SORT_TYPE));
		merge_t = test(int64_merge_sort, tmp, len, i);
		if (merge_t < min) {
			min = merge_t;
			min_idx = i;
			//printf("merge sort t  : %20d %20d %20f \n", len, i, merge_t);
			
		}
		
	}

	printf("best time: %f, index=%d\n", min, min_idx);
	//print(time_arr, time_arr_len);
	free(dst);
	free(tmp);
	getch();
	return 0;
}
예제 #13
0
    void Configuration::initialize()
    {
        initTextures();
        initFonts();
        initSounds();
        initMusics();

        initPlayerInputs();
        initGuiInputs();

        rand_init();

        musics.get(Musics::Theme).setLoop(true);
        musics.get(Musics::Theme).play();

    }
예제 #14
0
int dgreed_main(int argc, const char** argv) {
	params_init(argc, argv);
	rand_init(time(NULL));
	layouts_init();
	layouts_set("dvorak");

	bool fullscreen = true;
	if(params_find("-windowed") != ~0)
		fullscreen = false;

	video_init_ex(SCREEN_WIDTH, SCREEN_HEIGHT, 
		SCREEN_WIDTH, SCREEN_HEIGHT, "KeyMingler", fullscreen);
	font = font_load(FONT_FILE);	
	float text_width = font_width(font, LOADING_TEXT);
	float text_height = font_height(font);
	Vector2 pos = vec2((SCREEN_WIDTH - text_width) / 2.0f,
		(SCREEN_HEIGHT - text_height) / 2.0f);
	font_draw(font, LOADING_TEXT, 0, &pos, COLOR_WHITE);	
	video_present();
	system_update();

	game_init();
	sounds_init();
	music = sound_load_stream(MUSIC_FILE);
	sound_play(music);

	while(system_update()) {
		game_update();
		game_render();
		video_present();
		sound_update();

		if(key_up(KEY_QUIT))
			break;
	}
	
	font_free(font);
	sound_free(music);
	sounds_close();
	game_close();
	video_close();
	layouts_close();

	return 0;
}
예제 #15
0
파일: ptst.c 프로젝트: linuxbox2/mcas-bsd
ptst_t *critical_enter(gc_global_t *gc_global)
{
    ptst_t *ptst, *next, *new_next;
#ifdef NEED_ID
    unsigned int id, oid;
#endif

    ptst = (ptst_t *)pthread_getspecific(gc_global->ptst_key);
    if ( ptst == NULL )
    {
        for ( ptst = _ptst_first(gc_global); ptst != NULL; ptst = ptst_next(ptst) )
        {
            if ( (ptst->count == 0) && (CASIO(&ptst->count, 0, 1) == 0) )
            {
                break;
            }
        }

        if ( ptst == NULL )
        {
            ptst = ALIGNED_ALLOC(sizeof(*ptst));
            if ( ptst == NULL ) exit(1);
            memset(ptst, 0, sizeof(*ptst));
            ptst->gc = gc_init(gc_global);
            rand_init(ptst);
            ptst->count = 1;
#ifdef NEED_ID
            id = gc_global->next_id;
            while ( (oid = CASIO(&gc_global->next_id, id, id+1)) != id ) id = oid;
            ptst->id = id;
#endif
            new_next = gc_global->ptst_list;
            do {
                ptst->next = next = new_next;
                WMB_NEAR_CAS();
            }
            while ( (new_next = CASPO(&gc_global->ptst_list, next, ptst)) != next );
        }

        pthread_setspecific(gc_global->ptst_key, ptst);
    }

    gc_enter(ptst);
    return(ptst);
}
void rndffill(char *named)
{
long size=0;
long i=0;

najed(named);

        size = najedsize();

        rand_init();

        fseek(naji_edit, 0, SEEK_SET);

        for (i=0; i<size; i++)
        fputc(rand() % 255, naji_edit);

najedclose();
}
예제 #17
0
파일: fd_deriv.c 프로젝트: cselab/pi4u
int main(int argc, char *argv[])
{
	/* read theta, xl, xu, uh, iord, reps */
	data_init();

	torc_register_task(rand_init_task);
	aux_init();
	c_pndl_init();

	torc_init(argc, argv, MODE_MW);

        fprint_matrix_1d(stdout, "theta", data.theta, data.Nth);

	rand_init();

	do_mytest();

	torc_finalize();

	return 0;
}
예제 #18
0
파일: md.c 프로젝트: SahanGH/psi4public
static void velocitize(struct md *md)
{
	rand_init();

	double temperature = cfg_get_double(md->state->cfg, "temperature");
	double ke = temperature * BOLTZMANN * md->n_freedom / (2.0 * 6.0 * md->n_bodies);

	for (size_t i = 0; i < md->n_bodies; i++) {
		struct body *body = md->bodies + i;

		double vel = sqrt(2.0 * ke / body->mass);

		body->vel.x = vel * rand_normal();
		body->vel.y = vel * rand_normal();
		body->vel.z = vel * rand_normal();

		body->angmom.x = sqrt(2.0 * ke * body->inertia.x) * rand_normal();
		body->angmom.y = sqrt(2.0 * ke * body->inertia.y) * rand_normal();
		body->angmom.z = sqrt(2.0 * ke * body->inertia.z) * rand_normal();
	}
}
예제 #19
0
void run_isaac_test (rand_ctx ctx) {
    ub4 i;
    ub4 j;
    ub4 k;

    static char text[] = "This is <i>not</i> the right mytext.";

    std::memcpy((char *) ctx.rand_rsl, (char *) text, sizeof(text));

    rand_init(&ctx, TRUE);

    for (i = 0, k = 0; i < 10; ++i) {
        for (j = 0; j < RANDSIZ; ++j) {
            std::cout << std::hex << std::setfill('0') << std::setw(8);
            std::cout << get_random_value(&ctx) << " ";

            if (++k == 8) {
                k = 0;
                std::cout << std::endl;
            }
        }
    }
}
예제 #20
0
bool dgreed_init(int argc, const char** argv) {
#ifndef _WIN32
    params_init(argc, argv);
#else
    params_init(1, NULL);
#endif

    rand_init(432);

    const char* sprsheet = ASSETS_PRE "sprsheet_768p.mml";
    const char* particles = "particles.mml";
    uint width = 1024;
    uint height = 768;
    uint v_width = 1024;
    uint v_height = 768;

    uint n_width, n_height;
    video_get_native_resolution(&n_width, &n_height);

    LOG_INFO("Native resolution %u %u", n_width, n_height);

    // Select screen size
    scr_size = SCR_IPAD;
    if(params_find("-iphone5") != ~0 || (n_width == 1136 && n_height == 640)) {
        LOG_INFO("iphone5");
        sprsheet = ASSETS_PRE "sprsheet_640p.mml";
        particles = "particles_small.mml";
        scr_size = SCR_IPHONE;
        v_width = 568;
        v_height = 320;
        width = v_width * 2;
        height = v_height * 2;
        retina = true;
    }
    else if(params_find("-retinaipad") != ~0 || (n_width == 2048 && n_height == 1536)) {
        LOG_INFO("retina ipad");
        sprsheet = ASSETS_PRE "sprsheet_1536p.mml";
        width = 2048;
        height = 1536;
        retina = true;
    }
    else if(params_find("-iphone") != ~0 || (n_width < 960 || n_height < 640)) {
        LOG_INFO("iphone");
        sprsheet = ASSETS_PRE "sprsheet_320p.mml";
        particles = "particles_small.mml";
        scr_size = SCR_IPHONE;
        v_width = width = 480;
        v_height = height = 320;
    }
    else if(params_find("-retina") != ~0 || (n_width < 1024 || n_height < 768)) {
        LOG_INFO("retina iphone");
        sprsheet = ASSETS_PRE "sprsheet_640p.mml";
        particles = "particles_small.mml";
        scr_size = SCR_IPHONE;
        v_width = 480;
        v_height = 320;
        width = v_width * 2;
        height = v_height * 2;
        retina = true;
    }

    video_init_ex(width, height, v_width, v_height, "nulis", false);
    sound_init();

    keyval_init("nulis2_progress.db");
    keyval_set_bool("unlocked", true);

    particles_init_ex(ASSETS_PRE, particles, 4);
    mfx_init(ASSETS_PRE "effects.mml");

    malka_init();
    malka_params(argc, argv);
    malka_register(bind_open_nulis2);

    sprsheet_init(sprsheet);

    malka_states_init(SCRIPTS_PRE "main.lua");
    malka_states_start();

    return true;
}
예제 #21
0
파일: rtv1.c 프로젝트: ebaudet/Raytracer
void	rtv1(void)
{
	rand_init();
	init_scene();
	eb_mlx();
}
예제 #22
0
main()
{
   // Declaraciones 
   FILE *dptr;    
   int i,j,k,m,n;
   double x[TOP]={0.0},y[TOP]={0.0},xlin[TOP]={0.0},mapa[TOP]={0.0};
   double a,b,p1,p2,paso,pinh;

   rand_init();  
 
   if((dptr=fopen("mapa.dat","w"))==NULL)
      printf("\nEl archivo de salida no puede ser abierto\n");

   a=0.1;
   b=1.0;
   p1 = 0.25;
   p2 = 0.999999;
   pinh=0.00625;

   if(a>=0.0) 
      //x[0]=drand48();
      x[0]=0.265;
   else if(a<0.0) 
      x[0]=b+1.0+drand48();
  
   y[0]=0;

   // Iteraciones
   for(n=1;n<34;n++)
   {
      if(fmod((double)n,2.0)!=0.0) 
      {
         x[n]=x[n-1];
         y[n]=enzima49(x[n-1],a,b,p1,p2);
         //y[n]=enzima47(x[n-1],a,b,p1,p2);
         //y[n]=enzima48(x[n-1],a,b,p1);
         //y[n]=enzima47bis(x[n-1],a,b,p1,p2,pinh);
      }
      else
      {
         x[n]=y[n-1];
         y[n]=y[n-1];
      }
   }

   // linea x=y
   paso=-1.0;
   for(i=0;i<TOP;i++)
   {
      paso+=(b+4.0)/TOP;
      xlin[i]=paso;
   } 
  
   // mapa 
   for(n=0;n<TOP;n++)
      mapa[n]=enzima49(xlin[n],a,b,p1,p2);
      //mapa[n]=enzima47(xlin[n],a,b,p1,p2);
      //mapa[n]=enzima47bis(xlin[n],a,b,p1,p2,pinh);
      //mapa[]=enzima48(xlin[n],a,b,p1);
   
   for(i=0;i<TOP;i++)
      fprintf(dptr,"\n%f\t%f\t%f\t%f",xlin[i],x[i],y[i],mapa[i]);

   fclose(dptr);

}
예제 #23
0
Bool zpl_read_with_args(char** argv, int argc, Bool with_management, void* user_data)
{
   const char* options = "D:mP:sv:";

   unsigned long seed = 13021967UL;
   char**        param_table;
   int           param_count = 0;
   int           c;
   int           i;
   Prog*         prog = NULL;
   Set*          set;
   void*         lp  = NULL;
   Bool          ret = FALSE;
   char*         inppipe = NULL;
   Bool          use_startval = FALSE;
   
   stkchk_init();

   yydebug       = 0;
   yy_flex_debug = 0;
   param_table   = malloc(sizeof(*param_table));

   zpl_print_banner(stdout, FALSE);

   /* getopt might be called more than once
    */
   optind = 1;
   
   while((c = getopt(argc, argv, options)) != -1)
   {
      switch(c)
      {
      case 'D' :
         param_table =
            realloc(param_table, ((unsigned int)param_count + 1) * sizeof(*param_table));
         param_table[param_count] = strdup(optarg);

         if (verbose >= VERB_DEBUG)
            printf("Parameter %d [%s]\n", param_count, param_table[param_count]);

         param_count++;
         break;
      case 'm' :
         use_startval = TRUE;
         break;
      case 'P' :
         inppipe = strdup(optarg);
         break;
      case 's' :
         seed = (unsigned long)atol(optarg);
         break;
      case 'v' :
         verbose = atoi(optarg);
         break;
      case '?':
         fprintf(stderr, "Unknown option '%c'\n", c);
         return FALSE;
      default :
         abort();
      }
   }
   if ((argc - optind) < 1)
   {
      fprintf(stderr, "Filename missing\n");
      free(param_table);

      return FALSE;
   }

   blk_init();
   str_init();
   rand_init(seed);
   numb_init(with_management);
   elem_init();
   set_init();
   mio_init();
   interns_init();
   local_init();
   
   if (0 == setjmp( zpl_read_env))
   {
      is_longjmp_ok = TRUE;
      
      /* Make symbol to hold entries of internal variables
       */
      set = set_pseudo_new();
      (void)symbol_new(SYMBOL_NAME_INTERNAL, SYM_VAR, set, 100, NULL);
      set_free(set);
   
      /* Now store the param defines
       */
      for(i = 0; i < param_count; i++)
         zpl_add_parameter(param_table[i]);

      prog = prog_new();

      for(i = optind; i < argc; i++)
         prog_load(prog, inppipe, argv[i]);

      if (prog_is_empty(prog))
         fprintf(stderr, "*** Error 168: No program statements to execute\n");
      else
      {
         if (verbose >= VERB_DEBUG)
            prog_print(stderr, prog);
   
         lp = xlp_alloc(argv[optind], use_startval, user_data);

         prog_execute(prog, lp);

         ret = TRUE;
      }
   }
   is_longjmp_ok = FALSE;

   if (lp != NULL)
      xlp_free(lp);

   /* Now clean up. 
    */
   if (inppipe != NULL)
      free(inppipe);
   
   for(i = 0; i < param_count; i++)
      free(param_table[i]);
   free(param_table);

   if (prog != NULL)
      prog_free(prog);

   local_exit();
   interns_exit();
   mio_exit();
   symbol_exit();
   define_exit();
   set_exit();
   elem_exit();
   numb_exit();
   str_exit();
   blk_exit();

   return ret;
}
예제 #24
0
Bool zpl_read(const char* filename, Bool with_management, void* user_data)
{
   Prog*       prog = NULL;
   Set*        set;
   void*       lp  = NULL;
   Bool        ret = FALSE;

   stkchk_init();
   
   yydebug       = 0;
   yy_flex_debug = 0;

   zpl_print_banner(stdout, FALSE);

   blk_init();
   str_init();
   rand_init(13021967UL);
   numb_init(with_management);
   elem_init();
   set_init();
   mio_init();
   interns_init();
   local_init();
   
   if (0 == setjmp(zpl_read_env))
   {
      is_longjmp_ok = TRUE;
      
      set = set_pseudo_new();
      (void)symbol_new(SYMBOL_NAME_INTERNAL, SYM_VAR, set, 100, NULL);
      set_free(set);
   
      prog = prog_new();

      prog_load(prog, NULL, filename);

      if (prog_is_empty(prog))
         fprintf(stderr, "*** Error 168: No program statements to execute\n");
      else
      {
         if (verbose >= VERB_DEBUG)
            prog_print(stderr, prog);
   
         lp = xlp_alloc(filename, FALSE, user_data);

         prog_execute(prog, lp);

         ret = TRUE;
      }
   }
   is_longjmp_ok = FALSE;

   if (lp != NULL)
      xlp_free(lp);

   if (prog != NULL)
      prog_free(prog);

   local_exit();
   interns_exit();
   mio_exit();
   symbol_exit();
   define_exit();
   set_exit();
   elem_exit();
   numb_exit();
   str_exit();
   blk_exit();
   
   return ret;
}
예제 #25
0
파일: tint.c 프로젝트: yaozongyou/tetris
int main(int argc, char* argv[]) {
    bool finished;
    int ch;
    engine_t engine;
    /* Initialize */
    rand_init();							/* must be called before engine_init () */
    engine_init(&engine, score_function);	/* must be called before using engine.curshape */
    finished = shownext = FALSE;
    memset(shapecount, 0, NUMSHAPES * sizeof(int));
    shapecount[engine.curshape]++;
    parse_options(argc,argv);				/* must be called after initializing variables */
    if (level < MINLEVEL) {
        choose_level();
    }
    io_init();
    drawbackground();
    in_timeout(DELAY);
    /* Main loop */
    do {
        /* draw shape */
        showstatus(&engine);
        drawboard(engine.board);
        out_refresh();
        /* Check if user pressed a key */
        if ((ch = in_getch ()) != ERR) {
            switch (ch) {
            case 'j':
            case KEY_LEFT:
                engine_move(&engine,ACTION_LEFT);
                break;
            case 'k':
            case '\n':
                engine_move(&engine,ACTION_ROTATE);
                break;
            case 'l':
            case KEY_RIGHT:
                engine_move(&engine,ACTION_RIGHT);
                break;
            case ' ':
            case KEY_DOWN:
                engine_move(&engine,ACTION_DROP);
                break;
                /* show next piece */
            case 's':
                shownext = TRUE;
                break;
                /* toggle dotted lines */
            case 'd':
                dottedlines = !dottedlines;
                break;
                /* next level */
            case 'a':
            case KEY_UP:
                if (level < MAXLEVEL) {
                    level++;
                    in_timeout(DELAY);
                }
                else out_beep();
                break;
                /* quit */
            case 'q':
                finished = TRUE;
                break;
                /* pause */
            case 'p':
                out_setcolor(COLOR_WHITE,COLOR_BLACK);
                out_gotoxy((out_width() - 34) / 2,out_height() - 2);
                out_printf("Paused - Press any key to continue");
                while ((ch = in_getch ()) == ERR) ;	/* Wait for a key to be pressed */
                in_flush();							/* Clear keyboard buffer */
                out_gotoxy((out_width() - 34) / 2, out_height() - 2);
                out_printf("                                  ");
                break;
                /* unknown keypress */
            default:
                out_beep();
            }
            in_flush();
        } else {
            switch (engine_evaluate(&engine)) {
            /* game over (board full) */
            case -1:
                if ((level < MAXLEVEL) && ((engine.status.droppedlines / 10) > level)) level++;
                finished = TRUE;
                break;
                /* shape at bottom, next one released */
            case 0:
                if ((level < MAXLEVEL) && ((engine.status.droppedlines / 10) > level)) {
                    level++;
                    in_timeout(DELAY);
                }
                shapecount[engine.curshape]++;
                break;
                /* shape moved down one line */
            case 1:
                break;
            }
        }
    } while (!finished);
    /* Restore console settings and exit */
    io_close();
    /* Don't bother the player if he want's to quit */
    if (ch != 'q') {
        showplayerstats(&engine);
        savescores(GETSCORE(engine.score));
    }
    exit(EXIT_SUCCESS);
}
예제 #26
0
파일: main.c 프로젝트: kandycs/kitten-perf
/**
 * This is the architecture-independent kernel entry point. Before it is
 * called, architecture-specific code has done the bare minimum initialization
 * necessary. This function initializes the kernel and its various subsystems.
 * It calls back to architecture-specific code at several well defined points,
 * which all architectures must implement (e.g., setup_arch()).
 *
 * \callgraph
 */
void
start_kernel()
{
	unsigned int cpu;
	unsigned int timeout;
	int status;

	/*
 	 * Parse the kernel boot command line.
 	 * This is where boot-time configurable variables get set,
 	 * e.g., the ones with param() and DRIVER_PARAM() specifiers.
 	 */
	parse_params(lwk_command_line);

	/*
 	 * Initialize the console subsystem.
 	 * printk()'s will be visible after this.
 	 */
	console_init();

	/*
	 * Hello, Dave.
	 */
	printk("%s", lwk_banner);
	printk(KERN_DEBUG "%s\n", lwk_command_line);
	sort_exception_table();
	/*
	 * Do architecture specific initialization.
	 * This detects memory, CPUs, architecture dependent irqs, etc.
	 */
	setup_arch();

	/*
	 * Setup the architecture independent interrupt handling.
	 */
	irq_init();

	/*
	 * Initialize the kernel memory subsystem. Up until now, the simple
	 * boot-time memory allocator (bootmem) has been used for all dynamic
	 * memory allocation. Here, the bootmem allocator is destroyed and all
	 * of the free pages it was managing are added to the kernel memory
	 * pool (kmem) or the user memory pool (umem).
	 *
	 * After this point, any use of the bootmem allocator will cause a
	 * kernel panic. The normal kernel memory subsystem API should be used
	 * instead (e.g., kmem_alloc() and kmem_free()).
	 */
	mem_subsys_init();

	/*
 	 * Initialize the address space management subsystem.
 	 */
	aspace_subsys_init();


	sched_init_runqueue(0); /* This CPUs scheduler state + idle task */
	sched_add_task(current);  /* now safe to call schedule() */

	/*
 	 * Initialize the task scheduling subsystem.
 	 */
	core_timer_init(0);

	/* Start the kernel filesystems */
	kfs_init();

	/*
	 * Initialize the random number generator.
	 */
	rand_init();

	workq_init();

	/*
	 * Boot all of the other CPUs in the system, one at a time.
	 */
	printk(KERN_INFO "Number of CPUs detected: %d\n", num_cpus());
	for_each_cpu_mask(cpu, cpu_present_map) {
		/* The bootstrap CPU (that's us) is already booted. */
		if (cpu == 0) {
			cpu_set(cpu, cpu_online_map);
			continue;
		}

		printk(KERN_DEBUG "Booting CPU %u.\n", cpu);
		arch_boot_cpu(cpu);

		/* Wait for ACK that CPU has booted (5 seconds max). */
		for (timeout = 0; timeout < 50000; timeout++) {
			if (cpu_isset(cpu, cpu_online_map))
				break;
			udelay(100);
		}

		if (!cpu_isset(cpu, cpu_online_map))
			panic("Failed to boot CPU %d.\n", cpu);
	}

	/*
	 * Initialize the PCI subsystem.
	 */
	init_pci();

	/*
	 * Enable external interrupts.
	 */
	local_irq_enable();

#ifdef CONFIG_NETWORK
	/*
	 * Bring up any network devices.
	 */
	netdev_init();
#endif

#ifdef CONFIG_CRAY_GEMINI
	driver_init_list("net", "gemini");
#endif

#ifdef CONFIG_BLOCK_DEVICE
	/**
	 * Initialize the block devices
	 */
	blkdev_init();
#endif


	mcheck_init_late();

	/*
	 * And any modules that need to be started.
	 */
	driver_init_by_name( "module", "*" );

#ifdef CONFIG_KGDB
	/* 
	 * Stop eary (before "late" devices) in KGDB if requested
	 */
        kgdb_initial_breakpoint();
#endif

	/*
	 * Bring up any late init devices.
	 */
	driver_init_by_name( "late", "*" );

	/*
	 * Bring up the Linux compatibility layer, if enabled.
	 */
	linux_init();

#ifdef CONFIG_DEBUG_HW_NOISE
	/* Measure noise/interference in the underlying hardware/VMM */
	extern void measure_noise(int, uint64_t);
	measure_noise(0, 0);
#endif

	/*
	 * Start up user-space...
	 */
	printk(KERN_INFO "Loading initial user-level task (init_task)...\n");
	if ((status = create_init_task()) != 0)
		panic("Failed to create init_task (status=%d).", status);
	current->state = TASK_EXITED;
	schedule();  /* This should not return */
	BUG();
}
예제 #27
0
/* main: application entry point.
 * @argc: the number of commandline arguments.
 * @argv: the commandline argument string array.
 */
int main (int argc, char **argv) {
  /* declare required variables. */
  struct vector *x, *y, *z, *u;
  struct matrix *V, *R, *C;
  double theta;
  char *smean, *svar, *label;
  unsigned long n;
  int i;

  /* initialize the random number generator. */
  rand_init (time (NULL));

  /* parse the command-line arguments. */
  if (!opts_init (argc, argv)) {
    /* output an error message and exit. */
    ferror ("failed to parse arguments");
    fprintf (stdout, HELP);
    return 1;
  }

  /* see if we should display the help message. */
  if (opts_geti (OPTS_S_HELP)) {
    /* print the help message and quit. */
    fprintf (stdout, HELP);
    return 0;
  }

  /* get the number of points to produce. */
  n = opts_geti (OPTS_S_COUNT);

  /* ensure the point count is valid. */
  if (!n) {
    /* output an error message and exit. */
    ferror ("invalid point count (%lu)", n);
    fprintf (stdout, HELP);
    return 1;
  }

  /* get the points label. */
  label = opts_gets (OPTS_S_LABEL);

  /* ensure the points label is valid. */
  if (!label) {
    /* output an error message and exit. */
    ferror ("invalid label '%s'", label);
    fprintf (stdout, HELP);
    return 1;
  }

  /* allocate the math structures. */
  x = vector_new (2);
  y = vector_new (2);
  z = vector_new (2);
  u = vector_new (2);
  V = matrix_new (2, 2);
  R = matrix_new (2, 2);
  C = matrix_new (2, 2);

  /* ensure we allocated the math structures. */
  if (!x || !y || !z || !u || !V || !R || !C) {
    /* output an error message and exit. */
    ferror ("failed to allocate math structures");
    return 1;
  }

  /* get the mean string. */
  smean = opts_gets (OPTS_S_MEAN);

  /* did we get a mean string? */
  if (smean) {
    /* try to parse the string. */
    if (sscanf (smean, "(%lf,%lf)", &u->d[0], &u->d[1]) != 2) {
      /* output an error message and exit. */
      ferror ("failed to parse mean string '%s'", smean);
      fprintf (stdout, HELP);
      return 1;
    }
  }
  else {
    /* initialize to the origin. */
    u->d[0] = u->d[1] = 0.0;
  }

  /* get the variance string. */
  svar = opts_gets (OPTS_S_VAR);

  /* did we get a variance string? */
  if (svar) {
    /* try to parse the string. */
    if (sscanf (svar, "(%lf,%lf)", &V->d[0][0], &V->d[1][1]) != 2) {
      /* output an error message and exit. */
      ferror ("failed to parse variance string '%s'", svar);
      fprintf (stdout, HELP);
      return 1;
    }
  }
  else {
    /* initialize to unit variances. */
    V->d[0][0] = V->d[1][1] = 1.0;
  }

  /* get the rotation value. */
  theta = opts_getf (OPTS_S_ROT) / 180.0 * M_PI;

  /* build the rotation matrix. */
  R->d[0][0] = cos (theta);
  R->d[0][1] = -sin (theta);
  R->d[1][0] = sin (theta);
  R->d[1][1] = cos (theta);

  /* calculate the covariance matrix. */
  if (!matrix_matrix_mul (1.0, R, V, C)) {
    /* output an error message and exit. */
    ferror ("failed to calculate covariance matrix");
    return 1;
  }

  /* see if we should produce a header. */
  if (opts_geti (OPTS_S_HEADER)) {
    /* yep. print one. */
    fprintf (stdout,
      "Obs ID (Primary)\tObs ID (Obs. Sec. ID:1)\tM1.t[2]\tM1.t[1]\n");
  }

  /* loop a set number of times. */
  for (i = 0; i < n; i++) {
    /* calculate the two values. */
    x->d[0] = randnormal ();
    x->d[1] = randnormal ();

    /* scale the values. */
    if (!matrix_vector_mul (1.0, C, x, y)) {
      /* output an error message and exit. */
      ferror ("failed to scale random variate %d", i + 1);
      return 1;
    }

    /* translate the values. */
    if (!vector_sum (1.0, y, 1.0, u, z)) {
      /* output an error message and exit. */
      ferror ("failed to translate random variate %d", i + 1);
      return 1;
    }

    /* print the values. */
    fprintf (stdout, "%d\t%s\t%lf\t%lf\n", i + 1, label, z->d[0], z->d[1]);
  }

  /* free the math structures. */
  vector_free (x);
  vector_free (y);
  vector_free (z);
  vector_free (u);
  matrix_free (V);
  matrix_free (R);
  matrix_free (C);

  /* return success. */
  return 0;
}
예제 #28
0
int main()
{
	// Declaraciones 
	FILE *dptr;    
	int i,j,k,m,n,z,P,flag1,flag2,pos,KM,KI,I0,Ic,conc;
	int estado[N][2]={0},sg[SS]={0},sort[N];
	double fase[N][2]={0.0},v[VECES]={0.0},vprom[SS-1]={0.0},mm[SS-1]={0.0};
	double a,b,p1d,p2,pinh=0.0,pinh1=0.0,pinh2=0.0,sum,phic,smax,vtop=0;
        double fase_ins,fase_ini,fase_outs,fase_outi,kmapp,pmolar,trec,vmax,s;

	if((dptr=fopen("mminc.dat","w"))==NULL)
	   printf("\nEl archivo de salida no puede ser abierto\n");

        rand_init();

        a=0.1;
        p2=0.999999;

        // PESOS MOLARES: en Daltons
        pmolar = 60000.;

	// Fraccion del tiempo de procesamiento
        trec = 0.01;		

	// Calcula velocidad para una sola enzima
        vmax=VMAX*1.e-3*pmolar/60.0;		
   
        // Calcula los parametros "b" y "phic"
        b=a/(vmax*DT)-3.0*a;
        printf("\nEl numero de iteraciones para la r. dir. es %f, el No. de ciclos/iteracion es %lf",(b/a)+3,(double)TOPE/((b/a)+3)); 
        phic=1.0+b;

        // Afinidad por el sustrato
        KM=(int)Km*NA*VSIM/1.e6;	

	// Afinidad por el inhibidor
        KI=(int)Ki*NA*VSIM/1.e6;

	// Concentracion de inhibidor
        I0=I*NA*VSIM/1.e6;	

        // Parametros de la enzima
        smax=(double)KM/vmax;

        printf("\nsmax = %f, b = %f",smax,b);

        // Inicializa vector de recorrido de las enzimas
        for(j=0;j<N;j++)
           sort[j]=j;

	// Ciclo de las enzimas 
	for(conc=1;conc<SS;conc++)
	{
           sg[conc-1]=conc;  			// Guarda valores de concentracion de sustrato
           s=(double)conc*NA*VSIM/1.e6;	

           p1d=DT*s/smax;		// Define probabilidad reaccion directa

           for(k=0;k<VECES;k++)
              v[k]=0.0; 

           for(n=0;n<VECES;n++)
           {
	      // Inicializacion: 
              // Las enzimas arrancan en la region caotica 	
              rand_init(); 
	      for(i=0;i<N;i++)
              {
	         fase[i][0]=drand48();
	         fase[i][1]=drand48();
              }

              // Las enzimas estan en reposo
	      for(i=0;i<N;i++)
              {
	         estado[i][0]=0;
	         estado[i][1]=1;
              } 

              P=0;  
              Ic=I0;
              for(z=0;z<TOPE;z++)
              {
                 // Baraja vector de recorrido de las enzimas
                 if(z==0)
                 {
                    for(k=0;k<10;k++)
                    {   
                       for(j=0;j<N;j++)
                       {
                          pos=drnd(N); 
                          i=sort[pos];
                          sort[pos]=sort[j];
                          sort[j]=i;
                       }
                    }        
                 }
                 else if(z%20==0)
                 {
                    for(j=0;j<N;j++)
                    {
                       pos=drnd(N); 
                       i=sort[pos];
                       sort[pos]=sort[j];
                       sort[j]=i;
                   }
                 }

	         // Actualizacion de las fases de las enzimas
	         for(k=0;k<N;k++)  
	         {	
                    pos=sort[k];
 
                    // Actualiza fase para sustrato
                    if((estado[pos][0]==0)||(estado[pos][0]==1)||(estado[pos][0]==-1))	// No hay inhibidor adherido
                    { 
                       flag1=0;
                       flag2=0;
                       fase_ins=fase[pos][0];
                       while(flag1==0)			// Toma en cuenta puntos fijos
                       {  
                          while(flag2==0)
                          { 
                             if(fase_ins==0.5)
                                fase_ins=drand48();
                             else if(fase_ins!=0.5)
                                flag2=1;
                          }  
                          fase_outs=enzima47(fase_ins,a,b,p1d,p2);
                          if(fase_outs!=fase_ins)
                             flag1=1;
                          else
                             fase_ins=drand48();
                       }    
                       fase[pos][0]=fase_outs; 
                    } 

                    // Actualiza fase para inhibidor
                    if((I0!=0)&(Ic>=0))			// Hay inhibidor...
                    {  
                       pinh1=(double)Ic*vmax/(10*KI);	// Probabilidad de entrada del inhibidor
                       pinh2=(double)Ic*vmax/230;  	// Probabilidad de salida del inhibidor

                       if(estado[pos][1]==1)		// El inhibidor entra
                          pinh=pinh1;
                       if(estado[pos][1]==-1)		// El inhibidor sale
                          pinh=pinh2;

                       flag1=0;
                       flag2=0;
                       fase_ini=fase[pos][1];
                       while(flag1==0)			// Toma en cuenta puntos fijos
                       {  
                          while(flag2==0)
                          { 
                             if(fase_ini==0.5)
                                fase_ini=drand48();
                             else if(fase_ini!=0.5)
                                flag2=1;
                          }  
  	                  fase_outi=enzima47(fase_ini,a,b,pinh,p2);
                          if(fase_outi!=fase_ini)
                             flag1=1;
                          else
                             fase_ini=drand48();
                       }
                       fase[pos][1]=fase_outi; 
                    }

                    // Actualiza concentraciones

                    // Formacion de complejo ES: el sustrato entra primero y pasa a region laminar
                    if((estado[pos][0]==0)&(estado[pos][1]==1)&(fase_outs>1)&(fase_ins<=1))	
                       estado[pos][0]=1;

                    // Formacion de complejo ESI inactivo a partir de complejo ES
                    if((estado[pos][0]==1)&(estado[pos][1]==1)&(fase_outi>1)&(fase_ini<=1)&(Ic>0)) 
                    {
                       estado[pos][0]=11;		// Detiene avance de la enzima
                       estado[pos][1]=-1;		// Inhibidor entra
                       fase[pos][1]=drand48();
                       fase_outi=0.0;
                       fase_ini=0.0;
                       Ic--;  
                    }

                    // Formacion de complejo ES a partir de complejo ESI
                    if((estado[pos][0]==11)&(estado[pos][1]==-1)&(fase_outi>1)&(fase_ini<=1))
                    {
                       estado[pos][0]=1;		// Reanuda avance de la enzima
                       estado[pos][1]=1;		// Inhibidor salio
                       fase[pos][1]=drand48();
                       fase_outi=0.0;
                       fase_ini=0.0;
                       Ic++; 
                    }

                    // Complejo ES libera producto
                    if((estado[pos][0]==1)&(estado[pos][1]==1)&(fase_outs>phic))  
                    {
                       estado[pos][0]=-1;		// Enzima queda en recuperacion
                       P++;
                    }

                    // Enzima completa ciclo y queda en reposo
                    if((estado[pos][0]==-1)&(fabs(fase_outs-fase_ins)>=phic)) 
                       estado[pos][0]=0;

                    // Formacion de complejo EI: el inhibidor entro primero
                    if((estado[pos][0]==0)&(estado[pos][1]==1)&(fase_outi>1)&(fase_ini<=1)&(Ic>0))	
                    {
                       estado[pos][0]=10; 		// Detiene avance de la enzima
                       estado[pos][1]=-1;		// Inhibidor sale
                       fase[pos][1]=drand48();
                       fase_outi=0.0;
                       fase_ini=0.0;
                       Ic--;
                    }

                    // Complejo EI libera inhibidor
                    if((estado[pos][0]==10)&(estado[pos][1]==-1)&(fase_outi>1)&(fase_ini<=1))
                    {
                       estado[pos][0]=0;
                       estado[pos][1]=1;
                       fase[pos][1]=drand48();  
                       fase_outi=0.0;
                       fase_ini=0.0;
                       Ic++;
                    }   

                    // Formacion de complejo EI a partir de complejo EIS
                    //if((estado[pos][0]==11)&(estado[pos][1]==-1)&(fase_outs>1)&(fase_ins<=1))	
                    //   estado[pos][0]=11; 

                 }
              }  
              v[n]=(double)P*1.e6*60./(NA*VSIM*DT*TOPE);
           }  
           sum=0.0;
           for(k=0;k<VECES;k++)
              sum+=v[k];

           vprom[conc-1]=sum/(double)VECES; 

           printf("\nEl valor de la concentracion es %d",conc);
           
	}

        for(k=0;k<SS-1;k++)
           mm[k]=VMAX*(N*pmolar*1.e3/(NA*VSIM))*sg[k]/(Km+sg[k]); 

        for(k=0;k<SS-1;k++)
	   fprintf(dptr,"%d \t %f \t %f \n",sg[k],vprom[k],mm[k]);

        for(k=0;k<SS-1;k++)
        {
           if(vprom[k]>vtop)
              vtop=vprom[k];  
        }

        printf("\nVmax es %lf, Vmax/2 es %lf",vtop,vtop/2);

	fclose(dptr);
	return(0);
}
예제 #29
0
파일: cluster.c 프로젝트: rforge/muste
void muste_cluster(char *argv)
        {
        int i,k;
        double a;
        char ch;

//      if (argc==1) return;
        s_init(argv);

        if (g<2)
            {
            sur_print("\nUsage: CLUSTER <SURVO_data>,<output_line>");
            WAIT; return;
            }
        tulosrivi=0;
        if (g>2)
            {
            tulosrivi=edline2(word[2],1,1);
            if (tulosrivi==0) return;
            }

        strcpy(aineisto,word[1]);
        i=data_open(aineisto,&d); if (i<0) return;
        i=sp_init(r1+r-1); if (i<0) return;
        i=mask(&d); if (i<0) return;
        scales(&d);
        i=conditions(&d); if (i<0) return;

        gvar=activated(&d,'G');
        if (gvar<0)
            {
            sur_print("\nNo grouping variable (activated by 'G') given!");
            WAIT; return;
            }

        ivar=-1; ivar=activated(&d,'I');

        i=spfind("TRIALS");
        if (i>=0) maxiter=atoi(spb[i]);

        i=rand_init(); if (i<0) return;   /* 30.4.1994 */

        i=spfind("TEMPFILE");
        if (i>=0) strcpy(tempfile,spb[i]);
        else { strcpy(tempfile,etmpd); strcat(tempfile,"SURVO.CLU"); }

        i=spfind("PRIND");
        if (i>=0 && atoi(spb[i])>0) prind=1;

        data_load(&d,1L,gvar,&a);
        i=data_save(&d,1L,gvar,a);
        if (i<0) return;

        gvar2=(int *)muste_malloc(d.m_act*sizeof(int));
        if (gvar2==NULL) { not_enough_memory(); return; }

        k=0; n_saved=0; m=0;
        for (i=0; i<d.m_act; ++i)
            {
            ch=d.vartype[d.v[i]][1];
            if (ch=='G')
                {
                ++k;
                gvar2[n_saved]=d.v[i];    /* gvar=gvar2[0] */
                ++n_saved; continue;
                }
            if (ch=='I') { ++k; continue; }
            d.v[m++]=d.v[i];
            }
/*
printf("\nivar=%d gvar=%d m=%d\n",ivar,gvar,m); getch();
for (i=0; i<m; ++i) Rprintf(" %d",d.v[i]); getch();
printf("\n"); for (i=0; i<n_saved; ++i) Rprintf(" %d",gvar2[i]); getch();
*/

        i=spfind("GROUPS");
        if (i<0) ng=2; else ng=atoi(spb[i]);
        if (ng<2) ng=2;
        ng2=ng+2;
        mn=m; if (mn<ng) mn=ng;

        first_line=r+1; if (r+n_saved>r3) first_line=1;
        n_show=n_saved; if (n_show>r3) n_show=r3;

        i=varaa_tilat(); if (i<0) return;

        i=lue_havainnot(); if (i<0) return;
        hav_muistissa=havainnot_muistiin();
        ortogonalisoi();
        if (ivar_init) alustava_luokittelu();
        LOCATE(first_line,1);
        SCROLL_UP(first_line,r3+1,r3);
        sur_print("\nCluster analysis: Iteration 1:");
        while (sur_kbhit()) sur_getch();
        it=0;
        while (1)
            {
            while (1)
                {
                if (it) init_gr();
                i=init_tilat();
                if (i>=0) break;
                if (maxiter==1) return;
                }
            iteroi();
            ++it;
            if (maxiter>1) vertaa_muihin();
            if (it==maxiter) break;
            LOCATE(first_line,1);
            sprintf(sbuf,"\nIteration %d (Cluster analysis)",it);
            sur_print(sbuf);
            for (i=0; i<n_show; ++i)
               {
               if (freq[i]==0) break;
               sprintf(sbuf,"\n%d %g %d        ",i+1,lambda2[i],freq[i]); sur_print(sbuf);
               }
            if (sur_kbhit())
                {
                i=sur_getch(); if (i=='.') break;
                }
            }
        tulosta();

        data_close(&d);
        sur_delete(tempfile);
        s_end(argv);
        }
예제 #30
0
int main(int argc, char **argv) {
  // counter
  uint64_t i;
  // arg placeholder for getopt
  int c;
  // timing variables
  clock_t t1, t2;

  // simulation input
  krapivsky_input_t *input;
  // model data structure
  krapivsky_model_t *km;
  
  // model parameters
  double p = 0.2;
  double lambda = 3.5;
  double mu = 1.8;
  
  // number of nodes to simulate
  uint64_t target_n_nodes = 1000;
  
  // number of simulations to run
  uint64_t n_runs = 1;

  // base output dir
  char base_dir_name[BUFSIZE] = ".";
  
  // edge output filename
  char edge_file_name[BUFSIZE] = "edges.csv";
  char edge_file_fullname[BUFSIZE];
  // write out the network's edges?
  int write_edges = 0;

  // degree output filename
  char degree_file_name[BUFSIZE] = "degree.csv";
  char degree_file_fullname[BUFSIZE];
  char run_degree_file_fullname[BUFSIZE];
  // write out the network's edges?
  int write_degree = 0;
  
  // output filename for each run, constructed automatically
  char run_file_fullname[BUFSIZE];
  // output filename for timing data
  char time_file_name[BUFSIZE] = "times.csv";
  char time_file_fullname[BUFSIZE];
  FILE *time_file;

  // random seed filename
  char random_seed_file_name[BUFSIZE] = "randomseed.csv";
  
  // write out timing information?
  int write_time = 0;
  // array of execution times
  double *times;
  
  // the type of data structure to use for node indexing
  char type[BUFSIZE] = "heap";
  
  // parse command line args
  while((c = getopt(argc, argv, "d:s:e:t:p:m:l:n:o:r:u:")) != -1){
    switch(c) {
    case 'd':
      write_degree = 1;
      strcpy(degree_file_name, optarg);
      break;
    case 's':
      strcpy(random_seed_file_name, optarg);
      break;
    case 'e':
      strcpy(edge_file_name, optarg);
      write_edges = 1;
      break;
    case 't':
      strcpy(type, optarg);
      break;
    case 'p':
      sscanf(optarg, "%lf", &p);
      break;
    case 'm':
      sscanf(optarg, "%lf", &mu);
      break;
    case 'l':
      sscanf(optarg, "%lf", &lambda);
      break;
    case 'n':
      sscanf(optarg, "%llu", &target_n_nodes);
      break;
    case 'o':
      strcpy(base_dir_name,optarg);
      break;
    case 'r':
      sscanf(optarg, "%llu", &n_runs);
      break;
    case 'u':
      write_time = 1;
      strcpy(time_file_name,optarg);
      break;
    }
  }

  // prepend basedir to filenames
  sprintf(edge_file_fullname, "%s/%s", base_dir_name, edge_file_name);
  sprintf(time_file_fullname, "%s/%s", base_dir_name, time_file_name);
  sprintf(degree_file_fullname, "%s/%s", base_dir_name, degree_file_name);

  // initialize pseudorandom number generator
  rand_init(base_dir_name, random_seed_file_name);

  // open the time file if we'll be using it
  if(write_time) {
    times = (double*) malloc(n_runs * sizeof(*times));
    time_file = fopen(time_file_fullname,"w");
  }

  // construct the simulation input
  input = krapivsky_make_input(p, lambda, mu, target_n_nodes);
  
  // run the simulations
  for(i=0;i<n_runs;i++) {
    t1 = clock();
    if(strcmp(type,"lnu") == 0) {
      km = krapivsky_bstreap_simulate_lnu(input);
    } else if(strcmp(type,"lnn") == 0) {
      km = krapivsky_bstreap_simulate_lnn(input);
    } else if(strcmp(type,"lsu") == 0) {
      km = krapivsky_bstreap_simulate_lsu(input);
    } else if(strcmp(type,"lsn") == 0) {
      km = krapivsky_bstreap_simulate_lsn(input);
    } else if(strcmp(type,"heap") == 0) {
      km = krapivsky_heap_simulate(input);
    } else if(strcmp(type,"lnupareto") == 0) {
      km = krapivsky_bstreap_simulate_pareto_lnu(input);
    } else if(strcmp(type,"lnnpareto") == 0) {
      km = krapivsky_bstreap_simulate_pareto_lnn(input);
    } else if(strcmp(type,"lsupareto") == 0) {
      km = krapivsky_bstreap_simulate_pareto_lsu(input);
    } else if(strcmp(type,"lsnpareto") == 0) {
      km = krapivsky_bstreap_simulate_pareto_lsn(input);
    } else if(strcmp(type,"heappareto") == 0) {
      km = krapivsky_heap_simulate_pareto(input);
    } else if(strcmp(type,"heapnormal") == 0) {
      km = krapivsky_heap_simulate_normal(input);
    } else if(strcmp(type,"heapquadratic") == 0) {
      km = krapivsky_heap_simulate_quadratic(input);
    } else if(strcmp(type,"heapalpha100") == 0) {
      km = krapivsky_heap_simulate_alpha_100(input);
    } else if(strcmp(type,"heapalpha101") == 0) {
      km = krapivsky_heap_simulate_alpha_101(input);
    } else if(strcmp(type,"heapalpha102") == 0) {
      km = krapivsky_heap_simulate_alpha_102(input);
    } else if(strcmp(type,"heapalpha103") == 0) {
      km = krapivsky_heap_simulate_alpha_103(input);
    } else if(strcmp(type,"heapalpha104") == 0) {
      km = krapivsky_heap_simulate_alpha_104(input);
    } else if(strcmp(type,"heapalpha105") == 0) {
      km = krapivsky_heap_simulate_alpha_105(input);
    } else if(strcmp(type,"heapalpha106") == 0) {
      km = krapivsky_heap_simulate_alpha_106(input);
    } else if(strcmp(type,"heapalpha107") == 0) {
      km = krapivsky_heap_simulate_alpha_107(input);
    } else if(strcmp(type,"heapalpha108") == 0) {
      km = krapivsky_heap_simulate_alpha_108(input);
    } else if(strcmp(type,"heapalpha109") == 0) {
      km = krapivsky_heap_simulate_alpha_109(input);
    } else if(strcmp(type,"heapalpha110") == 0) {
      km = krapivsky_heap_simulate_alpha_110(input);
    } else if(strcmp(type,"heapalpha115") == 0) {
      km = krapivsky_heap_simulate_alpha_115(input);
    } else if(strcmp(type,"heapalpha120") == 0) {
      km = krapivsky_heap_simulate_alpha_120(input);
    } else if(strcmp(type,"heapalpha130") == 0) {
      km = krapivsky_heap_simulate_alpha_130(input);
    } else if(strcmp(type,"heapalpha140") == 0) {
      km = krapivsky_heap_simulate_alpha_140(input);
    } else if(strcmp(type,"heapalpha150") == 0) {
      km = krapivsky_heap_simulate_alpha_150(input);
    } else if(strcmp(type,"heapalpha160") == 0) {
      km = krapivsky_heap_simulate_alpha_160(input);
    } else if(strcmp(type,"heapalpha170") == 0) {
      km = krapivsky_heap_simulate_alpha_170(input);
    } else if(strcmp(type,"heapalpha180") == 0) {
      km = krapivsky_heap_simulate_alpha_180(input);
    } else if(strcmp(type,"heapalpha190") == 0) {
      km = krapivsky_heap_simulate_alpha_190(input);
    } else if(strcmp(type,"heapalpha200") == 0) {
      km = krapivsky_heap_simulate_alpha_200(input);
    } else {
      printf("Unknown type: %s\n",type);
      return 1;
    }
    t2 = clock();
    if(write_edges) {
      sprintf(run_file_fullname,
              "%s_%llu",
              edge_file_fullname,
              i);
      krapivsky_write_edges(km,run_file_fullname);
    }
    if(write_time) {
      times[i] = ((double) (t2 - t1))/CLOCKS_PER_SEC;  //time in seconds
      fprintf(time_file, "%lf\n", times[i]);  
    }
    if(write_degree) {
      sprintf(run_degree_file_fullname,
              "%s_%llu",
              degree_file_fullname,
              i);
      krapivsky_write_degrees(km,run_degree_file_fullname);
    }
    krapivsky_free(km);
  }
  free(input);

  // output and clean up timing data
  if(write_time) {
    printf("Simulated %llu networks with %llu nodes each.\nEach network took %lf +/- %lf seconds to simulate.\n",
           n_runs,
           target_n_nodes,
           mean(times,n_runs),
           stdev(times,n_runs));
    free(times);
    fclose(time_file);
  }
  return 0;
}