Ejemplo n.º 1
0
int
main ()
{
    random_t* random1Ptr;
    random_t* random2Ptr;
    random_t* random3Ptr;
    long i;

    puts("Starting...");

    random1Ptr = random_alloc();
    random2Ptr = random_alloc();
    random3Ptr = random_alloc();

    random_seed(random2Ptr, (RANDOM_DEFAULT_SEED + 1));
    random_seed(random3Ptr, (RANDOM_DEFAULT_SEED + 1));

    for (i = 0; i < NUM_ITERATIONS; i++) {
        unsigned long rand1 = random_generate(random1Ptr);
        unsigned long rand2 = random_generate(random2Ptr);
        unsigned long rand3 = random_generate(random3Ptr);
        printf("i = %2li, rand1 = %12lu, rand2 = %12lu, rand2 = %12lu\n",
                i, rand1, rand2, rand3);
        assert(rand1 != rand2);
        assert(rand2 == rand3);
    }

    random_free(random1Ptr);
    random_free(random2Ptr);

    puts("Done.");

    return 0;
}
Ejemplo n.º 2
0
static void
Randomizer_dealloc(Randomizer* self)
{            
    random_free(self->randomizer);
    
    Py_TYPE(self)->tp_free((PyObject*)self);
}
Ejemplo n.º 3
0
static void _scheduler_free(Scheduler* scheduler) {
    MAGIC_ASSERT(scheduler);

    guint nWorkers = g_queue_get_length(scheduler->threadItems);

    while(!g_queue_is_empty(scheduler->threadItems)) {
        SchedulerThreadItem* item = g_queue_pop_head(scheduler->threadItems);
        countdownlatch_free(item->notifyDoneRunning);
        g_free(item);
    }

    g_queue_free(scheduler->threadItems);

    scheduler->policy->free(scheduler->policy);
    random_free(scheduler->random);

    countdownlatch_free(scheduler->executeEventsBarrier);
    countdownlatch_free(scheduler->collectInfoBarrier);
    countdownlatch_free(scheduler->prepareRoundBarrier);
    countdownlatch_free(scheduler->startBarrier);
    countdownlatch_free(scheduler->finishBarrier);

    if(scheduler->threadToWaitTimerMap) {
        g_hash_table_destroy(scheduler->threadToWaitTimerMap);
    }

    g_mutex_clear(&(scheduler->globalLock));

    message("%i worker threads finished", nWorkers);

    MAGIC_CLEAR(scheduler);
    g_free(scheduler);
}
Ejemplo n.º 4
0
/* =============================================================================
 * initializeManager
 * =============================================================================
 */
static manager_t*
initializeManager ()
{
    manager_t* managerPtr;
    long i;
    long numRelation;
    random_t* randomPtr;
    long* ids;
    bool_t (*manager_add[])(manager_t*, long, long, long) = {
        &manager_addCar_seq,
        &manager_addFlight_seq,
        &manager_addRoom_seq,
        &addCustomer
    };
    long t;
    long numTable = sizeof(manager_add) / sizeof(manager_add[0]);

    printf("Initializing manager... ");
    fflush(stdout);

    randomPtr = random_alloc();

    managerPtr = manager_alloc();

    numRelation = (long)global_params[PARAM_RELATIONS];
    ids = (long*)malloc(numRelation * sizeof(long));
    for (i = 0; i < numRelation; i++) {
        ids[i] = i + 1;
    }

    for (t = 0; t < numTable; t++) {

        /* Shuffle ids */
        for (i = 0; i < numRelation; i++) {
            long x = random_generate(randomPtr) % numRelation;
            long y = random_generate(randomPtr) % numRelation;
            long tmp = ids[x];
            ids[x] = ids[y];
            ids[y] = tmp;
        }

        /* Populate table */
        for (i = 0; i < numRelation; i++) {
            bool_t status;
            long id = ids[i];
            long num = ((random_generate(randomPtr) % 5) + 1) * 100;
            long price = ((random_generate(randomPtr) % 5) * 10) + 50;
            status = manager_add[t](managerPtr, id, num, price);
        }

    } /* for t */

    puts("done.");
    fflush(stdout);

    random_free(randomPtr);
    free(ids);

    return managerPtr;
}
Ejemplo n.º 5
0
static void
tester (long geneLength, long segmentLength, long minNumSegment, bool_t doPrint)
{
    gene_t* genePtr;
    segments_t* segmentsPtr;
    random_t* randomPtr;
    bitmap_t* startBitmapPtr;
    long i;
    long j;

    genePtr = gene_alloc(geneLength);
    segmentsPtr = segments_alloc(segmentLength, minNumSegment);
    randomPtr = random_alloc();
    startBitmapPtr = bitmap_alloc(geneLength);

    random_seed(randomPtr, 0);
    gene_create(genePtr, randomPtr);
    random_seed(randomPtr, 0);
    segments_create(segmentsPtr, genePtr, randomPtr);

    assert(segmentsPtr->minNum == minNumSegment);
    assert(vector_getSize(segmentsPtr->contentsPtr) >= minNumSegment);

    if (doPrint) {
        printf("Gene = %s\n", genePtr->contents);
    }

    /* Check that each segment occurs in gene */
    for (i = 0; i < vector_getSize(segmentsPtr->contentsPtr); i++) {
        char *charPtr = strstr(genePtr->contents,
                               (char*)vector_at(segmentsPtr->contentsPtr, i));
        assert(charPtr != NULL);
        j = charPtr - genePtr->contents;
        bitmap_set(startBitmapPtr, j);
        if (doPrint) {
            printf("Segment %li (@%li) = %s\n",
                   i, j, (char*)vector_at(segmentsPtr->contentsPtr, i));
        }
    }

    /* Check that there is complete overlap */
    assert(bitmap_isSet(startBitmapPtr, 0));
    for (i = 0, j = 0; i < geneLength; i++ ) {
        if (bitmap_isSet(startBitmapPtr, i)) {
           assert((i-j-1) < segmentLength);
           j = i;
        }
    }

    gene_free(genePtr);
    segments_free(segmentsPtr);
    random_free(randomPtr);
    bitmap_free(startBitmapPtr);
}
Ejemplo n.º 6
0
END_TEST

START_TEST(random_bytes_returns_random_bytes) {
  random_t random;
  random_create(random);

  uint8_t a[16] = {};
  uint8_t b[16] = {};

  random_bytes(random, a, 16);
  random_bytes(random, b, 16);

  fail_unless(memcmp(a, b, 16) != 0);

  random_free(random);
}
Ejemplo n.º 7
0
int
main ()
{
    gene_t* gene1Ptr;
    gene_t* gene2Ptr;
    gene_t* gene3Ptr;
    random_t* randomPtr;

    bool_t status = memory_init(1, 4, 2);
    assert(status);

    puts("Starting...");

    gene1Ptr = gene_alloc(10);
    gene2Ptr = gene_alloc(10);
    gene3Ptr = gene_alloc(9);
    randomPtr = random_alloc();

    random_seed(randomPtr, 0);
    gene_create(gene1Ptr, randomPtr);
    random_seed(randomPtr, 1);
    gene_create(gene2Ptr, randomPtr);
    random_seed(randomPtr, 0);
    gene_create(gene3Ptr, randomPtr);

    assert(gene1Ptr->length == strlen(gene1Ptr->contents));
    assert(gene2Ptr->length == strlen(gene2Ptr->contents));
    assert(gene3Ptr->length == strlen(gene3Ptr->contents));

    assert(gene1Ptr->length == gene2Ptr->length);
    assert(strcmp(gene1Ptr->contents, gene2Ptr->contents) != 0);

    assert(gene1Ptr->length == (gene3Ptr->length + 1));
    assert(strcmp(gene1Ptr->contents, gene3Ptr->contents) != 0);
    assert(strncmp(gene1Ptr->contents,
                   gene3Ptr->contents,
                   gene3Ptr->length) == 0);

    gene_free(gene1Ptr);
    gene_free(gene2Ptr);
    gene_free(gene3Ptr);
    random_free(randomPtr);

    puts("All tests passed.");

    return 0;
}
Ejemplo n.º 8
0
void master_free(Master* master) {
    MAGIC_ASSERT(master);

    /* engine is now killed */
    master->killed = TRUE;

    GDateTime* dt_now = g_date_time_new_now_local();
    gchar* dt_format = g_date_time_format(dt_now, "%F %H:%M:%S");
    message("Shadow v%s shut down cleanly at %s", SHADOW_VERSION, dt_format);
    g_date_time_unref(dt_now);
    g_free(dt_format);

    random_free(master->random);

    MAGIC_CLEAR(master);
    g_free(master);
}
Ejemplo n.º 9
0
/* =============================================================================
 * stream_free
 * =============================================================================
 */
void
stream_free (stream_t* streamPtr)
{
    vector_t* allocVectorPtr = streamPtr->allocVectorPtr;
    long a;
    long numAlloc = vector_getSize(allocVectorPtr);

    for (a = 0; a < numAlloc; a++) {
        char* str = (char*)vector_at(allocVectorPtr, a);
        free(str);
    }

    MAP_FREE(streamPtr->attackMapPtr);
    queue_free(streamPtr->packetQueuePtr);
    vector_free(streamPtr->allocVectorPtr);
    random_free(streamPtr->randomPtr);
    free(streamPtr);
}
Ejemplo n.º 10
0
// the test program with defined testing paramaters
int main(int argc, char** argv){
	clock_t start, stop;
	double cpu_time;
	start = clock();
	time_t t;
	FILE* f = fopen("log","w");
	int paramaters[6] = {ntrials, pctget, pctlarge, small_limit, large_limit, -1};
	setup(paramaters, argc, argv);
	if(paramaters[5] < 0) srand((unsigned)time(&t));
	else srand((unsigned)paramaters[5]);
	int i;
	
	for(i=0; i<paramaters[0]; i++){
		int function_choice = makechoice(paramaters[1]);
		int size_choice = makechoice(paramaters[2]);
		int small = paramaters[3];
		int large = paramaters[4];
		if(function_choice){
			int size = gen_size(size_choice, small, large);
			getmem(size);
		}else{
			random_free();
		}
	}
	print_heap(f);
	uintptr_t *total_size = (uintptr_t *)malloc(sizeof(uintptr_t));
	uintptr_t *total_free = (uintptr_t *)malloc(sizeof(uintptr_t));
	uintptr_t *n_free_blocks = (uintptr_t *)malloc(sizeof(uintptr_t));
	// get and print the mem stats to file 
	get_mem_stats(total_size, total_free, n_free_blocks);
	stop = clock();
    cpu_time = ((double) (stop - start)) / CLOCKS_PER_SEC;
    fprintf(f,"cpu_time: %f  seconds\n",cpu_time);
    fprintf(f,"total_size: %lu bytes\n",*total_size);
//    printf("n_free_blocks: %lu blocks\n",*n_free_blocks);
    fprintf(f,"n_free_blocks: %lu blocks\n",*n_free_blocks);
    fprintf(f,"total_free size :%lu bytes\n",*total_free);
	fclose(f);
	free(total_size);
	free(total_free);
	free(n_free_blocks);
	return 0;
}
Ejemplo n.º 11
0
void engine_free(Engine* engine) {
	MAGIC_ASSERT(engine);

	/* engine is now killed */
	engine->killed = TRUE;

	/* this launches delete on all the plugins and should be called before
	 * the engine is marked "killed" and workers are destroyed.
	 */
	internetwork_free(engine->internet);

	/* we will never execute inside the plugin again */
	engine->forceShadowContext = TRUE;

	if(engine->workerPool) {
		engine_teardownWorkerThreads(engine);
	}

	if(engine->masterEventQueue) {
		asyncpriorityqueue_free(engine->masterEventQueue);
	}

	registry_free(engine->registry);
	g_cond_free(engine->workersIdle);
	g_mutex_free(engine->engineIdle);

	GDateTime* dt_now = g_date_time_new_now_local();
	gchar* dt_format = g_date_time_format(dt_now, "%F %H:%M:%S:%N");
	message("clean engine shutdown at %s", dt_format);
	g_date_time_unref(dt_now);
	g_free(dt_format);

	for(int i = 0; i < engine->numCryptoThreadLocks; i++) {
		g_static_mutex_free(&(engine->cryptoThreadLocks[i]));
	}

	random_free(engine->random);
	g_mutex_free(engine->lock);

	MAGIC_CLEAR(engine);
	shadow_engine = NULL;
	g_free(engine);
}
Ejemplo n.º 12
0
void master_free(Master* master) {
    MAGIC_ASSERT(master);

    if(master->topology) {
        topology_free(master->topology);
    }
    if(master->dns) {
        dns_free(master->dns);
    }
    if(master->config) {
        configuration_free(master->config);
    }
    if(master->random) {
        random_free(master->random);
    }

    MAGIC_CLEAR(master);
    g_free(master);

    message("simulation master destroyed");
}
Ejemplo n.º 13
0
/* =============================================================================
 * initializeWork
 * =============================================================================
 */
static long
initializeWork (heap_t* workHeapPtr, mesh_t* meshPtr)
{
    random_t* randomPtr = random_alloc();
    random_seed(randomPtr, 0);
    mesh_shuffleBad(meshPtr, randomPtr);
    random_free(randomPtr);
    long numBad = 0;

    while (1) {
        element_t* elementPtr = mesh_getBad(meshPtr);
        if (!elementPtr) {
            break;
        }
        numBad++;
        bool status = heap_insert(workHeapPtr, (void*)elementPtr);
        assert(status);
        element_setIsReferenced(elementPtr, true);
    }

    return numBad;
}
Ejemplo n.º 14
0
static void
test (long numVar, long numRecord)
{
    random_t* randomPtr = random_alloc();
    data_t* dataPtr = data_alloc(numVar, numRecord, randomPtr);
    assert(dataPtr);
    data_generate(dataPtr, 0, 10, 10);
    if (global_doPrint) {
        printData(dataPtr);
    }

    data_t* copyDataPtr = data_alloc(numVar, numRecord, randomPtr);
    assert(copyDataPtr);
    data_copy(copyDataPtr, dataPtr);

    adtree_t* adtreePtr = adtree_alloc();
    assert(adtreePtr);

    TIMER_T start;
    TIMER_READ(start);

    adtree_make(adtreePtr, copyDataPtr);

    TIMER_T stop;
    TIMER_READ(stop);

    printf("%lf\n", TIMER_DIFF_SECONDS(start, stop));

    if (global_doPrint) {
        printAdtree(adtreePtr);
    }

    testCounts(adtreePtr, dataPtr);

    adtree_free(adtreePtr);
    random_free(randomPtr);
    data_free(dataPtr);
}
Ejemplo n.º 15
0
void din_close()
{/* The function closes everything that needs to be closed */
  int i,j;
  free(init_name);
  free(data_name);
  free(conf_name);
  free(input_name);
  free(out_name);
  for(j=0;j<MAX_N_HIST_ENT;j++){
    for(i=0;i<MAX_N_ARG;i++)
      free(buf_hist[j][i]);
    free(buf_hist[j]);
  }
  free(buf_hist);
  for(i=0;i<MAX_N_ARG;i++)
    free(cmd[i]);
  free(cmd);
  /* The following is deprecated */
  for(i=0;i<BUFFER;i++)
    free(xs[i]);
  free(xs);
  free(ts);
  /* *************************** */
  //free(ampl);
  //free(max_x);
  //free(min_x);
  free(x_cross);
  free(x);
  free(y);
  free(xin);
  free(xin_par);
  free(yin);
  free(f);
  free(ksi);
  free(pr);
  free(a);
  for(i=0;i<DIM;i++)
    free(var_name[i]);
  free(var_name);
  for(i=0;i<AUXNUM;i++)
    free(aux_name[i]);
  free(aux_name);
  gnuplot_close(plot_handle);
  if(!perDet)
    free(perDet);
  if(!perStoch)
    free(perStoch);
  /* Free Random */
  random_free();
  /*Free Lyapunov*/
  lyap_free();
  /* Free periods histogram */
  thist_free();
  /* Deleting unnecessary files after finishing the program */
  printf("Deleting unnecessary files...\n");
  if((fopen("slopeAmpl.dat","r")) != NULL){
    if(remove("slopeAmpl.dat") != 0)
      printf("Error deleting file slopeAmpl.dat\n");
  }
  if((fopen("slopeAmpl1.dat","r")) != NULL){
    if(remove("slopeAmpl1.dat") != 0)
      printf("Error deleting file slopeAmpl.dat\n");
  }
  if((fopen("hist.dat","r")) != NULL){
    if(remove("hist.dat") != 0)
      printf("Error deleting file hist.dat\n");
  }
  if((fopen("acorr.dat","r")) != NULL){
    if(remove("acorr.dat") != 0)
      printf("Error deleting file acorr.dat\n");
  }
  if((fopen("tmap.dat","r")) != NULL){
    if(remove("tmap.dat") != 0)
      printf("Error deleting file tmap.dat\n");
  }
  if((fopen("rand.throw","r")) != NULL){
    if(remove("rand.throw") != 0)
      printf("Error deleting file rand.throw\n");
  }
  printf("Done.\n");
}
Ejemplo n.º 16
0
/* =============================================================================
 * main
 * =============================================================================
 */
int main (int argc, char** argv)
{
    int result = 0;
    TIMER_T start;
    TIMER_T stop;

    /* Initialization */
    parseArgs(argc, (char** const)argv);

    printf("Creating gene and segments... ");
    fflush(stdout);

    long geneLength = global_params[PARAM_GENE];
    long segmentLength = global_params[PARAM_SEGMENT];
    long minNumSegment = global_params[PARAM_NUMBER];
    long numThread = global_params[PARAM_THREAD];

    thread_startup(numThread);

    random_t* randomPtr = random_alloc();
    assert(randomPtr != NULL);
    random_seed(randomPtr, 0);

    gene_t* genePtr = gene_alloc(geneLength);
    assert( genePtr != NULL);
    gene_create(genePtr, randomPtr);
    char* gene = genePtr->contents;

    segments_t* segmentsPtr = segments_alloc(segmentLength, minNumSegment);
    assert(segmentsPtr != NULL);
    segments_create(segmentsPtr, genePtr, randomPtr);
    sequencer_t* sequencerPtr = sequencer_alloc(geneLength, segmentLength, segmentsPtr);
    assert(sequencerPtr != NULL);

    puts("done.");
    printf("Gene length     = %li\n", genePtr->length);
    printf("Segment length  = %li\n", segmentsPtr->length);
    printf("Number segments = %li\n", vector_getSize(segmentsPtr->contentsPtr));
    fflush(stdout);

    /* Benchmark */
    printf("Sequencing gene... ");
    fflush(stdout);
    TIMER_READ(start);
#ifdef OTM
#pragma omp parallel
    {
        sequencer_run(sequencerPtr);
    }
#else
    thread_start(sequencer_run, (void*)sequencerPtr);
#endif
    TIMER_READ(stop);
    puts("done.");
    printf("Time = %lf\n", TIMER_DIFF_SECONDS(start, stop));
    fflush(stdout);

    /* Check result */
    {
        char* sequence = sequencerPtr->sequence;
        result = strcmp(gene, sequence);
        printf("Sequence matches gene: %s\n", (result ? "no" : "yes"));
        if (result) {
            printf("gene     = %s\n", gene);
            printf("sequence = %s\n", sequence);
        }
        fflush(stdout);
        assert(strlen(sequence) >= strlen(gene));
    }

    /* Clean up */
    printf("Deallocating memory... ");
    fflush(stdout);
    sequencer_free(sequencerPtr);
    segments_free(segmentsPtr);
    gene_free(genePtr);
    random_free(randomPtr);
    puts("done.");
    fflush(stdout);

    thread_shutdown();

    return result;
}
Ejemplo n.º 17
0
Archivo: genome.c Proyecto: takayuki/al
/* =============================================================================
 * main
 * =============================================================================
 */
MAIN (argc,argv)
{
    TIMER_T start;
    TIMER_T stop;

    GOTO_REAL();

    /* Initialization */
    parseArgs(argc, (char** const)argv);
    SIM_GET_NUM_CPU(global_params[PARAM_THREAD]);

    printf("Creating gene and segments... ");
    fflush(stdout);

    long geneLength = global_params[PARAM_GENE];
    long segmentLength = global_params[PARAM_SEGMENT];
    long minNumSegment = global_params[PARAM_NUMBER];
    long numThread = global_params[PARAM_THREAD];

    TM_STARTUP(numThread);
    P_MEMORY_STARTUP(numThread);

    random_t* randomPtr = random_alloc();
    assert(randomPtr != NULL);
    random_seed(randomPtr, 0);

    gene_t* genePtr = gene_alloc(geneLength);
    assert( genePtr != NULL);
    gene_create(genePtr, randomPtr);
    char* gene = genePtr->contents;

    segments_t* segmentsPtr = segments_alloc(segmentLength, minNumSegment);
    assert(segmentsPtr != NULL);
    segments_create(segmentsPtr, genePtr, randomPtr);
    sequencer_t* sequencerPtr = sequencer_alloc(geneLength, segmentLength, segmentsPtr);
    assert(sequencerPtr != NULL);

    puts("done.");
    printf("Gene length     = %li\n", genePtr->length);
    printf("Segment length  = %li\n", segmentsPtr->length);
    printf("Number segments = %li\n", vector_getSize(segmentsPtr->contentsPtr));
    fflush(stdout);

    /* Benchmark */
    printf("Sequencing gene... ");
    fflush(stdout);
    TIMER_READ(start);
    GOTO_SIM();
    thread_startup(numThread, sequencer_run, (void*)sequencerPtr);
    thread_start();
    GOTO_REAL();
    TIMER_READ(stop);
    puts("done.");
    printf("Time = %lf\n", TIMER_DIFF_SECONDS(start, stop));
    fflush(stdout);

    /* Check result */
    {
        char* sequence = sequencerPtr->sequence;
        int result = strcmp(gene, sequence);
        printf("Sequence matches gene: %s\n", (result ? "no" : "yes"));
        if (result) {
            printf("gene     = %s\n", gene);
            printf("sequence = %s\n", sequence);
        }
        fflush(stdout);
        assert(strlen(sequence) >= strlen(gene));
    }

    /* Clean up */
    printf("Deallocating memory... ");
    fflush(stdout);
    sequencer_free(sequencerPtr);
    segments_free(segmentsPtr);
    gene_free(genePtr);
    random_free(randomPtr);
    puts("done.");
    fflush(stdout);

    al_dump(&sequencerLock);

    TM_SHUTDOWN();
    P_MEMORY_SHUTDOWN();

    GOTO_SIM();

    thread_shutdown();

    MAIN_RETURN(0);
}
Ejemplo n.º 18
0
/* =============================================================================
 * main
 * =============================================================================
 */
MAIN(argc, argv)
{
    GOTO_REAL();

    /*
     * Initialization
     */

    parseArgs(argc, (char** const)argv);
    long numThread     = global_params[PARAM_THREAD];
    long numVar        = global_params[PARAM_VAR];
    long numRecord     = global_params[PARAM_RECORD];
    long randomSeed    = global_params[PARAM_SEED];
    long maxNumParent  = global_params[PARAM_NUMBER];
    long percentParent = global_params[PARAM_PERCENT];
    global_insertPenalty = global_params[PARAM_INSERT];
    global_maxNumEdgeLearned = global_params[PARAM_EDGE];
    SIM_GET_NUM_CPU(numThread);
    TM_STARTUP(numThread);
    P_MEMORY_STARTUP(numThread);
    thread_startup(numThread);

    printf("Random seed                = %li\n", randomSeed);
    printf("Number of vars             = %li\n", numVar);
    printf("Number of records          = %li\n", numRecord);
    printf("Max num parents            = %li\n", maxNumParent);
    printf("%% chance of parent         = %li\n", percentParent);
    printf("Insert penalty             = %li\n", global_insertPenalty);
    printf("Max num edge learned / var = %li\n", global_maxNumEdgeLearned);
    printf("Operation quality factor   = %f\n", global_operationQualityFactor);
    fflush(stdout);

    /*
     * Generate data
     */

    printf("Generating data... ");
    fflush(stdout);

    random_t* randomPtr = random_alloc();
    assert(randomPtr);
    random_seed(randomPtr, randomSeed);

    data_t* dataPtr = data_alloc(numVar, numRecord, randomPtr);
    assert(dataPtr);
    net_t* netPtr = data_generate(dataPtr, -1, maxNumParent, percentParent);
    puts("done.");
    fflush(stdout);

    /*
     * Generate adtree
     */

    adtree_t* adtreePtr = adtree_alloc();
    assert(adtreePtr);

    printf("Generating adtree... ");
    fflush(stdout);

    TIMER_T adtreeStartTime;
    TIMER_READ(adtreeStartTime);

    adtree_make(adtreePtr, dataPtr);

    TIMER_T adtreeStopTime;
    TIMER_READ(adtreeStopTime);

    puts("done.");
    fflush(stdout);
    printf("Adtree time = %f\n",
           TIMER_DIFF_SECONDS(adtreeStartTime, adtreeStopTime));
    fflush(stdout);

    /*
     * Score original network
     */

    float actualScore = score(netPtr, adtreePtr);
    net_free(netPtr);

    /*
     * Learn structure of Bayesian network
     */

    learner_t* learnerPtr = learner_alloc(dataPtr, adtreePtr, numThread);
    assert(learnerPtr);
    data_free(dataPtr); /* save memory */

    printf("Learning structure...");
    fflush(stdout);

    TIMER_T learnStartTime;
    TIMER_READ(learnStartTime);
    GOTO_SIM();

    learner_run(learnerPtr);

    GOTO_REAL();
    TIMER_T learnStopTime;
    TIMER_READ(learnStopTime);

    puts("done.");
    fflush(stdout);
    printf("Time = %f\n",
           TIMER_DIFF_SECONDS(learnStartTime, learnStopTime));
    fflush(stdout);

    /*
     * Check solution
     */

    bool_t status = net_isCycle(learnerPtr->netPtr);
    assert(!status);

#ifndef SIMULATOR
    float learnScore = learner_score(learnerPtr);
    printf("Learn score  = %f\n", learnScore);
#endif
    printf("Actual score = %f\n", actualScore);

    /*
     * Clean up
     */

    fflush(stdout);
    random_free(randomPtr);
#ifndef SIMULATOR
    adtree_free(adtreePtr);
#  if 0    
    learner_free(learnerPtr);
#  endif    
#endif

    TM_SHUTDOWN();
    P_MEMORY_SHUTDOWN();

    GOTO_SIM();

    thread_shutdown();

    MAIN_RETURN(0);
}
Ejemplo n.º 19
0
void subkey_create(subkey_t key, master_key_t master_key) {
  random_t random;
  random_create(random);
  subkey_create_with_random(key, master_key, random);
  random_free(random);
}
Ejemplo n.º 20
0
/* =============================================================================
 * genScalData_seq
 * =============================================================================
 */
void
genScalData_seq (graphSDG* SDGdataPtr)
{
    /*
     * STEP 0: Create the permutations required to randomize the vertices
     */

    random_t* stream = random_alloc();
    assert(stream);
    random_seed(stream, 0);

    ULONGINT_T* permV; /* the vars associated with the graph tuple */
    permV = (ULONGINT_T*)malloc(TOT_VERTICES * sizeof(ULONGINT_T));
    assert(permV);

    long i;

    /* Initialize the array */
    for (i = 0; i < TOT_VERTICES; i++) {
        permV[i] = i;
    }

    for (i = 0; i < TOT_VERTICES; i++) {
        long t1 = random_generate(stream);
        long t = i + t1 % (TOT_VERTICES - i);
        if (t != i) {
            ULONGINT_T t2 = permV[t];
            permV[t] = permV[i];
            permV[i] = t2;
        }
    }

    /*
     * STEP 1: Create Cliques
     */

    long* cliqueSizes;

    long estTotCliques = ceil(1.5 * TOT_VERTICES / ((1+MAX_CLIQUE_SIZE)/2));

    /*
     * Allocate mem for Clique array
     * Estimate number of clique required and pad by 50%
     */
    cliqueSizes = (long*)malloc(estTotCliques * sizeof(long));
    assert(cliqueSizes);


    /* Generate random clique sizes. */
    for (i = 0; i < estTotCliques; i++) {
        cliqueSizes[i] = 1 + (random_generate(stream) % MAX_CLIQUE_SIZE);
    }

    long totCliques = 0;

    /*
     * Allocate memory for cliqueList
     */

    ULONGINT_T* lastVsInCliques;
    ULONGINT_T* firstVsInCliques;

    lastVsInCliques = (ULONGINT_T*)malloc(estTotCliques * sizeof(ULONGINT_T));
    assert(lastVsInCliques);
    firstVsInCliques = (ULONGINT_T*)malloc(estTotCliques * sizeof(ULONGINT_T));
    assert(firstVsInCliques);

    /*
     * Sum up vertices in each clique to determine the lastVsInCliques array
     */

    lastVsInCliques[0] = cliqueSizes[0] - 1;
    for (i = 1; i < estTotCliques; i++) {
        lastVsInCliques[i] = cliqueSizes[i] + lastVsInCliques[i-1];
        if (lastVsInCliques[i] >= TOT_VERTICES-1) {
            break;
        }
    }
    totCliques = i + 1;

    /*
     * Fix the size of the last clique
     */
    cliqueSizes[totCliques-1] =
        TOT_VERTICES - lastVsInCliques[totCliques-2] - 1;
    lastVsInCliques[totCliques-1] = TOT_VERTICES - 1;

    firstVsInCliques[0] = 0;


    /*
     * Compute start Vertices in cliques.
     */
    for (i = 1; i < totCliques; i++) {
        firstVsInCliques[i] = lastVsInCliques[i-1] + 1;
    }

#ifdef WRITE_RESULT_FILES
    /* Write the generated cliques to file for comparison with Kernel 4 */
    FILE* outfp = fopen("cliques.txt", "w");
    fprintf(outfp, "No. of cliques - %lu\n", totCliques);
    for (i = 0; i < totCliques; i++) {
        fprintf(outfp, "Clq %lu - ", i);
        long j;
        for (j = firstVsInCliques[i]; j <= lastVsInCliques[i]; j++) {
            fprintf(outfp, "%lu ", permV[j]);
        }
        fprintf(outfp, "\n");
    }
    fclose(outfp);
#endif

    /*
     * STEP 2: Create the edges within the cliques
     */

    /*
     * Estimate number of edges - using an empirical measure
     */
    long estTotEdges;
    if (SCALE >= 12) {
        estTotEdges = ceil(((MAX_CLIQUE_SIZE-1) * TOT_VERTICES));
    } else {
        estTotEdges = ceil(1.2 * (((MAX_CLIQUE_SIZE-1)*TOT_VERTICES)
                                  * ((1 + MAX_PARAL_EDGES)/2) + TOT_VERTICES*2));
    }

    /*
     * Initialize edge counter
     */
    long i_edgePtr = 0;
    float p = PROB_UNIDIRECTIONAL;

    /*
     * Partial edgeLists
     */

    ULONGINT_T* startV;
    ULONGINT_T* endV;
    long numByte = (estTotEdges) * sizeof(ULONGINT_T);
    startV = (ULONGINT_T*)malloc(numByte);
    endV = (ULONGINT_T*)malloc(numByte);
    assert(startV);
    assert(endV);

    /*
     * Tmp array to keep track of the no. of parallel edges in each direction
     */
    ULONGINT_T** tmpEdgeCounter =
        (ULONGINT_T**)malloc(MAX_CLIQUE_SIZE * sizeof(ULONGINT_T *));
    assert(tmpEdgeCounter);
    for (i = 0; i < MAX_CLIQUE_SIZE; i++) {
        tmpEdgeCounter[i] =
            (ULONGINT_T*)malloc(MAX_CLIQUE_SIZE * sizeof(ULONGINT_T));
        assert(tmpEdgeCounter[i]);
    }

    /*
     * Create edges
     */
     long i_clique;

     for (i_clique = 0; i_clique < totCliques; i_clique++) {

        /*
         * Get current clique parameters
         */

        long i_cliqueSize = cliqueSizes[i_clique];
        long i_firstVsInClique = firstVsInCliques[i_clique];

        /*
         * First create at least one edge between two vetices in a clique
         */

        for (i = 0; i < i_cliqueSize; i++) {

            long j;
            for (j = 0; j < i; j++) {

                float r = (float)(random_generate(stream) % 1000) / (float)1000;
                if (r >= p) {

                    startV[i_edgePtr] = i + i_firstVsInClique;
                    endV[i_edgePtr] = j + i_firstVsInClique;
                    i_edgePtr++;
                    tmpEdgeCounter[i][j] = 1;

                    startV[i_edgePtr] = j + i_firstVsInClique;
                    endV[i_edgePtr] = i + i_firstVsInClique;
                    i_edgePtr++;
                    tmpEdgeCounter[j][i] = 1;

                } else  if (r >= 0.5) {

                    startV[i_edgePtr] = i + i_firstVsInClique;
                    endV[i_edgePtr] = j + i_firstVsInClique;
                    i_edgePtr++;
                    tmpEdgeCounter[i][j] = 1;
                    tmpEdgeCounter[j][i] = 0;

                } else {

                    startV[i_edgePtr] = j + i_firstVsInClique;
                    endV[i_edgePtr] = i + i_firstVsInClique;
                    i_edgePtr++;
                    tmpEdgeCounter[j][i] = 1;
                    tmpEdgeCounter[i][j] = 0;

                }

            } /* for j */
        } /* for i */

        if (i_cliqueSize != 1) {
            long randNumEdges = (long)(random_generate(stream)
                                       % (2*i_cliqueSize*MAX_PARAL_EDGES));
            long i_paralEdge;
            for (i_paralEdge = 0; i_paralEdge < randNumEdges; i_paralEdge++) {
                i = (random_generate(stream) % i_cliqueSize);
                long j = (random_generate(stream) % i_cliqueSize);
                if ((i != j) && (tmpEdgeCounter[i][j] < MAX_PARAL_EDGES)) {
                    float r = (float)(random_generate(stream) % 1000) / (float)1000;
                    if (r >= p) {
                        /* Copy to edge structure. */
                        startV[i_edgePtr] = i + i_firstVsInClique;
                        endV[i_edgePtr] = j + i_firstVsInClique;
                        i_edgePtr++;
                        tmpEdgeCounter[i][j]++;
                    }
                }
            }
        }

    } /* for i_clique */

    for (i = 0; i < MAX_CLIQUE_SIZE; i++) {
        free(tmpEdgeCounter[i]);
    }

    free(tmpEdgeCounter);


    /*
     * Merge partial edge lists
     */

    ULONGINT_T i_edgeStartCounter = 0;
    ULONGINT_T i_edgeEndCounter = i_edgePtr;
    long edgeNum = i_edgePtr;

    /*
     * Initialize edge list arrays
     */

    ULONGINT_T* startVertex;
    ULONGINT_T* endVertex;

    if (SCALE < 10) {
        long numByte = 2 * edgeNum * sizeof(ULONGINT_T);
        startVertex = (ULONGINT_T*)malloc(numByte);
        endVertex = (ULONGINT_T*)malloc(numByte);
    } else {
        long numByte = (edgeNum + MAX_PARAL_EDGES * TOT_VERTICES)
                       * sizeof(ULONGINT_T);
        startVertex = (ULONGINT_T*)malloc(numByte);
        endVertex = (ULONGINT_T*)malloc(numByte);
    }
    assert(startVertex);
    assert(endVertex);

    for (i = i_edgeStartCounter; i < i_edgeEndCounter; i++) {
        startVertex[i] = startV[i-i_edgeStartCounter];
        endVertex[i] = endV[i-i_edgeStartCounter];
    }

    ULONGINT_T numEdgesPlacedInCliques = edgeNum;

    /*
     * STEP 3: Connect the cliques
     */

    i_edgePtr = 0;
    p = PROB_INTERCL_EDGES;

    /*
     * Generating inter-clique edges as given in the specs
     */

    for (i = 0; i < TOT_VERTICES; i++) {

        ULONGINT_T tempVertex1 = i;
        long h = totCliques;
        long l = 0;
        long t = -1;
        while (h - l > 1) {
            long m = (h + l) / 2;
            if (tempVertex1 >= firstVsInCliques[m]) {
                l = m;
            } else {
                if ((tempVertex1 < firstVsInCliques[m]) && (m > 0)) {
                    if (tempVertex1 >= firstVsInCliques[m-1]) {
                        t = m - 1;
                        break;
                    } else {
                        h = m;
                    }
                }
            }
        }

        if (t == -1) {
            long m;
            for (m = (l + 1); m < h; m++) {
                if (tempVertex1<firstVsInCliques[m]) {
                    break;
                }
            }
            t = m-1;
        }

        long t1 = firstVsInCliques[t];

        ULONGINT_T d;
        for (d = 1, p = PROB_INTERCL_EDGES; d < TOT_VERTICES; d *= 2, p /= 2) {

            float r = (float)(random_generate(stream) % 1000) / (float)1000;

            if (r <= p) {

                ULONGINT_T tempVertex2 = (i+d) % TOT_VERTICES;

                h = totCliques;
                l = 0;
                t = -1;
                while (h - l > 1) {
                    long m = (h + l) / 2;
                    if (tempVertex2 >= firstVsInCliques[m]) {
                        l = m;
                    } else {
                        if ((tempVertex2 < firstVsInCliques[m]) && (m > 0)) {
                            if (firstVsInCliques[m-1] <= tempVertex2) {
                                t = m - 1;
                                break;
                            } else {
                                h = m;
                            }
                        }
                    }
                }

                if (t == -1) {
                    long m;
                    for (m = (l + 1); m < h; m++) {
                        if (tempVertex2 < firstVsInCliques[m]) {
                            break;
                        }
                    }
                    t = m - 1;
                }

                long t2 = firstVsInCliques[t];

                if (t1 != t2) {
                    long randNumEdges =
                        random_generate(stream) % MAX_PARAL_EDGES + 1;
                    long j;
                    for (j = 0; j < randNumEdges; j++) {
                        startV[i_edgePtr] = tempVertex1;
                        endV[i_edgePtr] = tempVertex2;
                        i_edgePtr++;
                    }
                }

            } /* r <= p */

            float r0 = (float)(random_generate(stream) % 1000) / (float)1000;

            if ((r0 <= p) && (i-d>=0)) {

                ULONGINT_T tempVertex2 = (i-d) % TOT_VERTICES;

                h = totCliques;
                l = 0;
                t = -1;
                while (h - l > 1) {
                    long m = (h + l) / 2;
                    if (tempVertex2 >= firstVsInCliques[m]) {
                        l = m;
                    } else {
                        if ((tempVertex2 < firstVsInCliques[m]) && (m > 0)) {
                            if (firstVsInCliques[m-1] <= tempVertex2) {
                                t = m - 1;
                                break;
                            } else {
                                h = m;
                            }
                        }
                    }
                }

                if (t == -1) {
                    long m;
                    for (m = (l + 1); m < h; m++) {
                        if (tempVertex2 < firstVsInCliques[m]) {
                            break;
                        }
                    }
                    t = m - 1;
                }

                long t2 = firstVsInCliques[t];

                if (t1 != t2) {
                    long randNumEdges =
                        random_generate(stream) % MAX_PARAL_EDGES + 1;
                    long j;
                    for (j = 0; j < randNumEdges; j++) {
                        startV[i_edgePtr] = tempVertex1;
                        endV[i_edgePtr] = tempVertex2;
                        i_edgePtr++;
                    }
                }

            } /* r0 <= p && (i-d) > 0 */

        } /* for d, p */

    } /* for i */


    i_edgeEndCounter = i_edgePtr;
    i_edgeStartCounter = 0;

    edgeNum = i_edgePtr;
    ULONGINT_T numEdgesPlacedOutside = edgeNum;

    for (i = i_edgeStartCounter; i < i_edgeEndCounter; i++) {
        startVertex[i+numEdgesPlacedInCliques] = startV[i-i_edgeStartCounter];
        endVertex[i+numEdgesPlacedInCliques] = endV[i-i_edgeStartCounter];
    }

    ULONGINT_T  numEdgesPlaced = numEdgesPlacedInCliques + numEdgesPlacedOutside;

    SDGdataPtr->numEdgesPlaced = numEdgesPlaced;

    printf("Finished generating edges\n");
    printf("No. of intra-clique edges - %lu\n", numEdgesPlacedInCliques);
    printf("No. of inter-clique edges - %lu\n", numEdgesPlacedOutside);
    printf("Total no. of edges        - %lu\n", numEdgesPlaced);

    free(cliqueSizes);
    free(firstVsInCliques);
    free(lastVsInCliques);

    free(startV);
    free(endV);

    /*
     * STEP 4: Generate edge weights
     */

    SDGdataPtr->intWeight =
        (LONGINT_T*)malloc(numEdgesPlaced * sizeof(LONGINT_T));
    assert(SDGdataPtr->intWeight);

    p = PERC_INT_WEIGHTS;
    ULONGINT_T numStrWtEdges  = 0;

    for (i = 0; i < numEdgesPlaced; i++) {
        float r = (float)(random_generate(stream) % 1000) / (float)1000;
        if (r <= p) {
            SDGdataPtr->intWeight[i] =
                1 + (random_generate(stream) % (MAX_INT_WEIGHT-1));
        } else {
            SDGdataPtr->intWeight[i] = -1;
            numStrWtEdges++;
        }
    }

    long t = 0;
    for (i = 0; i < numEdgesPlaced; i++) {
        if (SDGdataPtr->intWeight[i] < 0) {
            SDGdataPtr->intWeight[i] = -t;
            t++;
        }
    }

    SDGdataPtr->strWeight =
        (char*)malloc(numStrWtEdges * MAX_STRLEN * sizeof(char));
    assert(SDGdataPtr->strWeight);

    for (i = 0; i < numEdgesPlaced; i++) {
        if (SDGdataPtr->intWeight[i] <= 0) {
            long j;
            for (j = 0; j < MAX_STRLEN; j++) {
                SDGdataPtr->strWeight[(-SDGdataPtr->intWeight[i])*MAX_STRLEN+j] =
                    (char) (1 + random_generate(stream) % 127);
            }
        }
    }

    /*
     * Choose SOUGHT STRING randomly if not assigned
     */

    if (strlen(SOUGHT_STRING) != MAX_STRLEN) {
        SOUGHT_STRING = (char*)malloc(MAX_STRLEN * sizeof(char));
        assert(SOUGHT_STRING);
    }

    t = random_generate(stream) % numStrWtEdges;
    long j;
    for (j = 0; j < MAX_STRLEN; j++) {
        SOUGHT_STRING[j] =
            (char) ((long) SDGdataPtr->strWeight[t*MAX_STRLEN+j]);
    }

    /*
     * STEP 5: Permute Vertices
     */

    for (i = 0; i < numEdgesPlaced; i++) {
        startVertex[i] = permV[(startVertex[i])];
        endVertex[i] = permV[(endVertex[i])];
    }

    /*
     * STEP 6: Sort Vertices
     */

    /*
     * Radix sort with StartVertex as primary key
     */

    numByte = numEdgesPlaced * sizeof(ULONGINT_T);
    SDGdataPtr->startVertex = (ULONGINT_T*)malloc(numByte);
    assert(SDGdataPtr->startVertex);
    SDGdataPtr->endVertex = (ULONGINT_T*)malloc(numByte);
    assert(SDGdataPtr->endVertex);

    all_radixsort_node_aux_s3_seq(numEdgesPlaced,
                                  startVertex,
                                  SDGdataPtr->startVertex,
                                  endVertex,
                                  SDGdataPtr->endVertex);

    free(startVertex);
    free(endVertex);

    if (SCALE < 12) {

        /*
         * Sort with endVertex as secondary key
         */

        long i0 = 0;
        long i1 = 0;
        i = 0;

        while (i < numEdgesPlaced) {

            for (i = i0; i < numEdgesPlaced; i++) {
                if (SDGdataPtr->startVertex[i] !=
                    SDGdataPtr->startVertex[i1])
                {
                    i1 = i;
                    break;
                }
            }

            long j;
            for (j = i0; j < i1; j++) {
                long k;
                for (k = j+1; k < i1; k++) {
                    if (SDGdataPtr->endVertex[k] <
                        SDGdataPtr->endVertex[j])
                    {
                        long t = SDGdataPtr->endVertex[j];
                        SDGdataPtr->endVertex[j] = SDGdataPtr->endVertex[k];
                        SDGdataPtr->endVertex[k] = t;
                    }
                }
            }

            if (SDGdataPtr->startVertex[i0] != TOT_VERTICES-1) {
                i0 = i1;
            } else {
                long j;
                for (j=i0; j<numEdgesPlaced; j++) {
                    long k;
                    for (k=j+1; k<numEdgesPlaced; k++) {
                        if (SDGdataPtr->endVertex[k] <
                            SDGdataPtr->endVertex[j])
                        {
                            long t = SDGdataPtr->endVertex[j];
                            SDGdataPtr->endVertex[j] = SDGdataPtr->endVertex[k];
                            SDGdataPtr->endVertex[k] = t;
                        }
                    }
                }
            }

        } /* while i < numEdgesPlaced */

    } else {

        ULONGINT_T* tempIndex =
            (ULONGINT_T*)malloc((TOT_VERTICES + 1) * sizeof(ULONGINT_T));

        /*
         * Update degree of each vertex
         */

        tempIndex[0] = 0;
        tempIndex[TOT_VERTICES] = numEdgesPlaced;
        long i0 = 0;

        for (i=0; i < TOT_VERTICES; i++) {
            tempIndex[i+1] = tempIndex[i];
            long j;
            for (j = i0; j < numEdgesPlaced; j++) {
                if (SDGdataPtr->startVertex[j] !=
                    SDGdataPtr->startVertex[i0])
                {
                    if (SDGdataPtr->startVertex[i0] == i) {
                        tempIndex[i+1] = j;
                        i0 = j;
                        break;
                    }
                }
            }
        }

        /*
         * Insertion sort for now, replace with something better later on
         */
        for (i = 0; i < TOT_VERTICES; i++) {
            long j;
            for (j = tempIndex[i]; j < tempIndex[i+1]; j++) {
                long k;
                for (k = (j + 1); k < tempIndex[i+1]; k++) {
                    if (SDGdataPtr->endVertex[k] <
                        SDGdataPtr->endVertex[j])
                    {
                        long t = SDGdataPtr->endVertex[j];
                        SDGdataPtr->endVertex[j] = SDGdataPtr->endVertex[k];
                        SDGdataPtr->endVertex[k] = t;
                    }
                }
            }
        }

       free(tempIndex);

    } /* SCALE >= 12 */

    random_free(stream);
    free(permV);
}
Ejemplo n.º 21
0
/* Checks that the guessed balls in the state match up with the real balls
 * for all possible lasers (i.e. not just the ones that the player might
 * have already guessed). This is required because any layout with >4 balls
 * might have multiple valid solutions. Returns non-zero for a 'correct'
 * (i.e. consistent) layout. */
static int check_guesses(game_state *state, int cagey)
{
    game_state *solution, *guesses;
    int i, x, y, n, unused, tmp;
    int ret = 0;

    if (cagey) {
	/*
	 * First, check that each laser the player has already
	 * fired is consistent with the layout. If not, show them
	 * one error they've made and reveal no further
	 * information.
	 *
	 * Failing that, check to see whether the player would have
	 * been able to fire any laser which distinguished the real
	 * solution from their guess. If so, show them one such
	 * laser and reveal no further information.
	 */
	guesses = dup_game(state);
	/* clear out BALL_CORRECT on guess, make BALL_GUESS BALL_CORRECT. */
	for (x = 1; x <= state->w; x++) {
	    for (y = 1; y <= state->h; y++) {
		GRID(guesses, x, y) &= ~BALL_CORRECT;
		if (GRID(guesses, x, y) & BALL_GUESS)
		    GRID(guesses, x, y) |= BALL_CORRECT;
	    }
	}
	n = 0;
	for (i = 0; i < guesses->nlasers; i++) {
	    if (guesses->exits[i] != LASER_EMPTY &&
		guesses->exits[i] != laser_exit(guesses, i))
		n++;
	}
	if (n) {
	    /*
	     * At least one of the player's existing lasers
	     * contradicts their ball placement. Pick a random one,
	     * highlight it, and return.
	     *
	     * A temporary random state is created from the current
	     * grid, so that repeating the same marking will give
	     * the same answer instead of a different one.
	     */
	    random_state *rs = random_new((char *)guesses->grid,
					  (state->w+2)*(state->h+2) *
					  sizeof(unsigned int));
	    n = random_upto(rs, n);
	    random_free(rs);
	    for (i = 0; i < guesses->nlasers; i++) {
		if (guesses->exits[i] != LASER_EMPTY &&
		    guesses->exits[i] != laser_exit(guesses, i) &&
		    n-- == 0) {
		    state->exits[i] |= LASER_WRONG;
		    tmp = laser_exit(state, i);
		    if (RANGECHECK(state, tmp))
			state->exits[tmp] |= LASER_WRONG;
		    state->justwrong = TRUE;
		    free_game(guesses);
		    return 0;
		}
	    }
	}
	n = 0;
	for (i = 0; i < guesses->nlasers; i++) {
	    if (guesses->exits[i] == LASER_EMPTY &&
		laser_exit(state, i) != laser_exit(guesses, i))
		n++;
	}
	if (n) {
	    /*
	     * At least one of the player's unfired lasers would
	     * demonstrate their ball placement to be wrong. Pick a
	     * random one, highlight it, and return.
	     *
	     * A temporary random state is created from the current
	     * grid, so that repeating the same marking will give
	     * the same answer instead of a different one.
	     */
	    random_state *rs = random_new((char *)guesses->grid,
					  (state->w+2)*(state->h+2) *
					  sizeof(unsigned int));
	    n = random_upto(rs, n);
	    random_free(rs);
	    for (i = 0; i < guesses->nlasers; i++) {
		if (guesses->exits[i] == LASER_EMPTY &&
		    laser_exit(state, i) != laser_exit(guesses, i) &&
		    n-- == 0) {
		    fire_laser(state, i);
		    state->exits[i] |= LASER_OMITTED;
		    tmp = laser_exit(state, i);
		    if (RANGECHECK(state, tmp))
			state->exits[tmp] |= LASER_OMITTED;
		    state->justwrong = TRUE;
		    free_game(guesses);
		    return 0;
		}
	    }
	}
	free_game(guesses);
    }

    /* duplicate the state (to solution) */
    solution = dup_game(state);

    /* clear out the lasers of solution */
    for (i = 0; i < solution->nlasers; i++) {
        tmp = range2grid(solution, i, &x, &y, &unused);
        assert(tmp);
        GRID(solution, x, y) = 0;
        solution->exits[i] = LASER_EMPTY;
    }

    /* duplicate solution to guess. */
    guesses = dup_game(solution);

    /* clear out BALL_CORRECT on guess, make BALL_GUESS BALL_CORRECT. */
    for (x = 1; x <= state->w; x++) {
        for (y = 1; y <= state->h; y++) {
            GRID(guesses, x, y) &= ~BALL_CORRECT;
            if (GRID(guesses, x, y) & BALL_GUESS)
                GRID(guesses, x, y) |= BALL_CORRECT;
        }
    }

    /* for each laser (on both game_states), fire it if it hasn't been fired.
     * If one has been fired (or received a hit) and another hasn't, we know
     * the ball layouts didn't match and can short-circuit return. */
    for (i = 0; i < solution->nlasers; i++) {
        if (solution->exits[i] == LASER_EMPTY)
            fire_laser(solution, i);
        if (guesses->exits[i] == LASER_EMPTY)
            fire_laser(guesses, i);
    }

    /* check each game_state's laser against the other; if any differ, return 0 */
    ret = 1;
    for (i = 0; i < solution->nlasers; i++) {
        tmp = range2grid(solution, i, &x, &y, &unused);
        assert(tmp);

        if (solution->exits[i] != guesses->exits[i]) {
            /* If the original state didn't have this shot fired,
             * and it would be wrong between the guess and the solution,
             * add it. */
            if (state->exits[i] == LASER_EMPTY) {
                state->exits[i] = solution->exits[i];
                if (state->exits[i] == LASER_REFLECT ||
                    state->exits[i] == LASER_HIT)
                    GRID(state, x, y) = state->exits[i];
                else {
                    /* add a new shot, incrementing state's laser count. */
                    int ex, ey, newno = state->laserno++;
                    tmp = range2grid(state, state->exits[i], &ex, &ey, &unused);
                    assert(tmp);
                    GRID(state, x, y) = newno;
                    GRID(state, ex, ey) = newno;
                }
		state->exits[i] |= LASER_OMITTED;
            } else {
		state->exits[i] |= LASER_WRONG;
	    }
            ret = 0;
        }
    }
    if (ret == 0 ||
	state->nguesses < state->minballs ||
	state->nguesses > state->maxballs) goto done;

    /* fix up original state so the 'correct' balls end up matching the guesses,
     * as we've just proved that they were equivalent. */
    for (x = 1; x <= state->w; x++) {
        for (y = 1; y <= state->h; y++) {
            if (GRID(state, x, y) & BALL_GUESS)
                GRID(state, x, y) |= BALL_CORRECT;
            else
                GRID(state, x, y) &= ~BALL_CORRECT;
        }
    }

done:
    /* fill in nright and nwrong. */
    state->nright = state->nwrong = state->nmissed = 0;
    for (x = 1; x <= state->w; x++) {
        for (y = 1; y <= state->h; y++) {
            int bs = GRID(state, x, y) & (BALL_GUESS | BALL_CORRECT);
            if (bs == (BALL_GUESS | BALL_CORRECT))
                state->nright++;
            else if (bs == BALL_GUESS)
                state->nwrong++;
            else if (bs == BALL_CORRECT)
                state->nmissed++;
        }
    }
    free_game(solution);
    free_game(guesses);
    state->reveal = 1;
    return ret;
}
Ejemplo n.º 22
0
/* =============================================================================
 * main
 * =============================================================================
 */
MAIN (argc,argv)
{
    TIMER_T start;
    TIMER_T stop;

    /* Initialization */
    parseArgs(argc, (char** const)argv);
    SIM_GET_NUM_CPU(global_params[PARAM_THREAD]);

    printf("Creating gene and segments... ");
    fflush(stdout);

    long geneLength = global_params[PARAM_GENE];
    long segmentLength = global_params[PARAM_SEGMENT];
    long minNumSegment = global_params[PARAM_NUMBER];
    long numThread = global_params[PARAM_THREAD];


    random_t* randomPtr;
    gene_t* genePtr;
    char* gene;
    segments_t* segmentsPtr;
    sequencer_t* sequencerPtr;

    TM_STARTUP(numThread);
    P_MEMORY_STARTUP(numThread);
    TM_THREAD_ENTER();

    //    TM_BEGIN();
    randomPtr= random_alloc();
    assert(randomPtr != NULL);
    random_seed(randomPtr, 0);

    genePtr = gene_alloc(geneLength);
    assert( genePtr != NULL);
    gene_create(genePtr, randomPtr);
    gene = genePtr->contents;

    segmentsPtr = segments_alloc(segmentLength, minNumSegment);
    assert(segmentsPtr != NULL);
    segments_create(segmentsPtr, genePtr, randomPtr);
    sequencerPtr = sequencer_alloc(geneLength, segmentLength, segmentsPtr);
    assert(sequencerPtr != NULL);
    //TM_END();
    thread_startup(numThread);
    puts("done.");
    printf("Gene length     = %li\n", genePtr->length);
    printf("Segment length  = %li\n", segmentsPtr->length);
    printf("Number segments = %li\n", vector_getSize(segmentsPtr->contentsPtr));
    fflush(stdout);

    /* Benchmark */
    printf("Sequencing gene... ");
    fflush(stdout);
    // NB: Since ASF/PTLSim "REAL" is native execution, and since we are using
    //     wallclock time, we want to be sure we read time inside the
    //     simulator, or else we report native cycles spent on the benchmark
    //     instead of simulator cycles.
    GOTO_SIM();
    TIMER_READ(start);
#ifdef OTM
#pragma omp parallel
    {
        sequencer_run(sequencerPtr);
    }
#else
    thread_start(sequencer_run, (void*)sequencerPtr);
#endif
    TIMER_READ(stop);
    // NB: As above, timer reads must be done inside of the simulated region
    //     for PTLSim/ASF
    GOTO_REAL();
    puts("done.");
    printf("Time = %lf\n", TIMER_DIFF_SECONDS(start, stop));
    fflush(stdout);

    /* Check result */
    {
      char* sequence;
      int result;
      //TM_BEGIN();
      sequence= sequencerPtr->sequence;
      result = strcmp(gene, sequence);
      //TM_END();
        printf("Sequence matches gene: %s\n", (result ? "no" : "yes"));
        if (result) {
            printf("gene     = %s\n", gene);
            printf("sequence = %s\n", sequence);
        }
        fflush(stdout);
        assert(strlen(sequence) >= strlen(gene));
    }

    /* Clean up */
    printf("Deallocating memory... ");
    fflush(stdout);
    sequencer_free(sequencerPtr);
    segments_free(segmentsPtr);
    gene_free(genePtr);
    random_free(randomPtr);
    puts("done.");
    fflush(stdout);

    TM_SHUTDOWN();
    P_MEMORY_SHUTDOWN();

    thread_shutdown();

    MAIN_RETURN(0);
}