Ejemplo n.º 1
0
void setEncoderFLY(LTencoderFLY *encoder, DegDistr code,
                   unsigned int w, unsigned int s,
                   double lt_delta, double lt_c, double raptor_eps) {

    struct hashtable *h = encoder->DistributionsTable;

    encoder->code	= code;			// set the code type (LT or Raptor)

    struct value *v = NULL;
    v = searchEntryInLThashTable(h, w, s, lt_delta, lt_c, raptor_eps);

    if (NULL == v) {
        if ((v = insertEntryInLThashTable(h, w, s, lt_delta, lt_c, raptor_eps)) != NULL) {
            // Create the degree distribution
            createDegreeDistribution(encoder, (v->cumulative), w, s, lt_delta, lt_c, raptor_eps);
            // Set the randm for this configuration
            v->confSeed = encoder->refRandomSeed + hashtable_count(h)-1;
            initRandom(&v->randomGenerator, v->confSeed);
        }
    }

    // Update the current cumulative and the current w.
    encoder->currConfig = v;

    return;
}
Ejemplo n.º 2
0
Globals::Globals(string fileName)
    :
    nodeCounter(0),
    linkCounter(0),
    speciesCounter(0)
{
    cout << "Populating sigmoid table...";
    for (int a=0; a<6001; a++)
    {
        signedSigmoidTable[a] = ((1 / (1+exp(-((a-3000)/1000.0)))) - 0.5)*2.0;
        unsignedSigmoidTable[a] = 1 / (1+exp(-((a-3000)/1000.0)));
    }
    cout << "done!\n";

    cout << "Loading Parameter data from " << fileName << endl;

    if (fileName==string(""))
    {
        return;
    }

    ifstream infile;
    infile.open(fileName.c_str());

    if (infile.is_open()==false)
    {
        throw CREATE_LOCATEDEXCEPTION_INFO(string("COULD NOT OPEN GLOBALS .dat FILE: ")+fileName);
    }

    string line="test";
    istringstream instream;
    while (getline(infile,line))
    {
#if DEBUG_NEAT_GLOBALS
        cout << "LINE: " << line << endl;
#endif
#ifdef linux
        if (int(line[line.size()-1])==13) //DOS line breaks
            line.erase(line.begin()+(int(line.size())-1));
#endif
        if (line[0]==';') //comment
        {
            continue;
        }
        if (line.size()==0)
        {
            continue;
        }
        istringstream input(line);
        string parameterName;
        double value=0.0;
        input >> parameterName >> value;
        parameters.insert(parameterName,value);
    }

    cacheParameters();

    initRandom();
}
Ejemplo n.º 3
0
// Given 15, will return a rand nr between 0-14
int getRandomNumber(int range)
{
	static bool randNotInitialised = false;
	if (randNotInitialised)
	{
		initRandom();
	}
	return rand()%range; 
}
Ejemplo n.º 4
0
int main() {
	initRandom();

	Genome g;
	Individual i(&g);


    return 0;
}
Ejemplo n.º 5
0
void init(){	
	TRISA=0b00111111; //RA6 & RA7 as outputs
	TRISB=0b11111111;
	PCON = 0b00001000; //4 MHz internal oscillator

	T1CON = 0b00110000; //Setup Timer 1 with prescale 8

	initRandom();
}
Ejemplo n.º 6
0
Globals::Globals()
    :
    nodeCounter(0),
    linkCounter(0),
    speciesCounter(0)
{
    cout << "Populating sigmoid table...";
    for (int a=0; a<6001; a++)
    {
        signedSigmoidTable[a] = ((1 / (1+exp(-((a-3000)/1000.0)))) - 0.5)*2.0;
        unsignedSigmoidTable[a] = 1 / (1+exp(-((a-3000)/1000.0)));
    }
    cout << "done!\n";

    cout << "Loading Parameter data from defaults" << endl;

    parameters.insert("PopulationSize",120.0);
    parameters.insert("MaxGenerations",600.0);
    parameters.insert("DisjointCoefficient",2.0);
    parameters.insert("ExcessCoefficient", 2.0);
    parameters.insert("WeightDifferenceCoefficient", 1.0);
    parameters.insert("FitnessCoefficient", 0.0);
    parameters.insert("CompatibilityThreshold", 6.0);
    parameters.insert("CompatibilityModifier", 0.3);
    parameters.insert("SpeciesSizeTarget", 8.0);
    parameters.insert("DropoffAge", 15.0);
    parameters.insert("vAgeSignificance",	1.0);
    parameters.insert("SurvivalThreshold", 0.2);
    parameters.insert("MutateAddNodeProbability", 0.03);
    parameters.insert("MutateAddLinkProbability", 0.3);
    parameters.insert("MutateDemolishLinkProbability", 0.00);
    parameters.insert("MutateLinkWeightsProbability", 0.8);
    parameters.insert("MutateOnlyProbability", 0.25);
    parameters.insert("MutateLinkProbability", 0.1);
    parameters.insert("AllowAddNodeToRecurrentConnection", 0.0);
    parameters.insert("SmallestSpeciesSizeWithElitism", 5.0);
    parameters.insert("MutateSpeciesChampionProbability", 0.0);
    parameters.insert("MutationPower", 2.5);
    parameters.insert("AdultLinkAge", 18.0);
    parameters.insert("AllowRecurrentConnections", 0.0);
    parameters.insert("AllowSelfRecurrentConnections", 0.0);
    parameters.insert("ForceCopyGenerationChampion", 1.0);
    parameters.insert("LinkGeneMinimumWeightForPhentoype", 0.0);
    parameters.insert("GenerationDumpModulo", 10.0);
    parameters.insert("RandomSeed", -1.0);
    parameters.insert("ExtraActivationFunctions", 9.0);
    parameters.insert("AddBiasToHiddenNodes", 0.0);
    parameters.insert("SignedActivation", 1.0);
    parameters.insert("ExtraActivationUpdates", 9.0);
    parameters.insert("OnlyGaussianHiddenNodes", 0.0);
    parameters.insert("ExperimentType", 15.0);

    cacheParameters();

    initRandom();
}
Ejemplo n.º 7
0
Arc::Program::Program( void )
	: _systems()
{
    INFO(toString(), "Initializing");

	_pInstance = this;

    initRandom();

    INFO(toString(), "Complete");
}
 void Fuzzy::initEverything () {
   switch (init_type_) {
     case kSoftCInitRandom:
       initRandom ();
       break;
     case kSoftCInitKmeansPP:
       initKmeansPP ();
       break;
     default:
       break;
   }
 }
Ejemplo n.º 9
0
/*
  Initializes some of the global mechanisms (timing), and makes
  necessary sanity checks (e.g., data types sizes).
 */
void initializeLSHGlobal(){
  checkDataTypes();

  // Initialize global variables
  timingOn = TRUE;

  // Initialize timings.
  tuneTimeFunctions();

  // Initialize the random number generator.
  initRandom();
}
Ejemplo n.º 10
0
void initBucketFLY(BucketFLY *bucket, unsigned long seed, int symblen,
                   unsigned int w, unsigned int s, double lt_delta,
                   double lt_c, double epsShok, DegDistr code) {

    bucket->seed = seed;
    bucket->symbLen = symblen;
    bucket->w = w;
    bucket->s = s;
    bucket->lt_delta = lt_delta;
    bucket->lt_c = lt_c;
    bucket->epsShok = epsShok;
    bucket->code = code;

    initRandom(&bucket->buckRan, seed);

    unsigned int i;
    if (bucket->symbols != NULL) {
        for (i=0; i<bucket->genSymbs; i++) {
            if (bucket->symbols[i].header != NULL)
                free(bucket->symbols[i].header);
        }
        free(bucket->symbols);
        bucket->symbols = NULL;
    }

    bucket->genSymbs = 0;

    if (bucket->cumulative != NULL) {
        free(bucket->cumulative);
        bucket->cumulative = NULL;
    }
    bucket->cumulative = (double *) chk_calloc(w, sizeof(double));

    switch (code) {
    case Luby:
        RSDcumulative(bucket->cumulative, w, s, lt_delta, lt_c);
        break;
    case Shokrollahi:
        SHOKcumulative(bucket->cumulative, w, s, epsShok);
        break;
    default:
        print_error("ERROR: currently only LT and Raptor codes are implemented.\n");
        exit(EXIT_FAILURE);
        break;
    }

#ifdef DEBUGdecoderPrintBucketRandomSeed
    printf("Bucket[%d] - Seed: %lu\n", bucket->nameBucket, bucket->seed);
#endif

    return;
}
Ejemplo n.º 11
0
GTEST_TEST(DownhillSimplex, bench2)
{
  std::array<Rangef, 2> ranges;
  ranges[0] = Rangef(-50.f, 50);
  ranges[1] = Rangef(-50.f, 50);

  auto errorFunction = []
                       (const Vector2f& vals)
  {
    LIP currentState(250.f);
    LIP targetState(250.f);
    float timeToStep = 0.3f;
    float timeAfterStep = 0.3f;
    float footTrans = -50.f;
    float posWeight = 1;
    float velWeight = 50;

    const float currentZmp = vals(0);
    const float nextZmp = vals(1);

    LIP forwardedState = currentState.predict(timeToStep, currentZmp);
    forwardedState.position += footTrans;
    forwardedState.update(timeAfterStep, nextZmp);

    return posWeight * sqr(targetState.position - forwardedState.position) +
           velWeight * sqr(targetState.velocity - forwardedState.velocity);
  };
  auto optimizer = Optimizer::makeDownhillSimplexOptimizer(errorFunction, ranges);

  Eigen::BenchTimer optTimer;

  for(int i = 0; i < TRIES; ++i)
  {
    optimizer.initRandom(Vector2f(-1.f, 0.f));
    auto copy = optimizer.simplex;
    // waste some cycles to get the return type automatically
    auto res = optimizer.optimize(0.0001f, 1);
    optTimer.start();
    for(int j = 0; j < RUNS; ++j)
    {
      optimizer.simplex = copy;
      res = optimizer.optimize(0.0001f, 100);
    }
    optTimer.stop();
  }

  PRINTF("overall - best: %.3fs, avg: %.3fs, worst: %.3fs \n", optTimer.best(), optTimer.total() / TRIES, optTimer.worst());
  PRINTF("per run - best: %.6fs, avg: %.6fs, worst: %.6fs \n", optTimer.best() / RUNS, optTimer.total() / (TRIES * RUNS), optTimer.worst() / RUNS);
}
Ejemplo n.º 12
0
Globals::Globals(TiXmlElement *root)
    :
    nodeCounter(-1),
    linkCounter(-1),
    speciesCounter(-1)
{
    cout << "Populating sigmoid table...";
    for (int a=0; a<6001; a++)
    {
        signedSigmoidTable[a] = ((1 / (1+exp(-((a-3000)/1000.0)))) - 0.5)*2.0;
        unsignedSigmoidTable[a] = 1 / (1+exp(-((a-3000)/1000.0)));
    }
    cout << "done!\n";

    TiXmlAttribute *firstAttribute = root->FirstAttribute();

    while (firstAttribute)
    {
        if (iequals(firstAttribute->Name(),"NodeCounter"))
        {
            nodeCounter = firstAttribute->IntValue();
        }
        else if (iequals(firstAttribute->Name(),"LinkCounter"))
        {
            linkCounter = firstAttribute->IntValue();
        }
        else if (iequals(firstAttribute->Name(),"SpeciesCounter"))
        {
            speciesCounter = firstAttribute->IntValue();
        }
        else
        {
            addParameter( firstAttribute->Name() , firstAttribute->DoubleValue());
        }

        firstAttribute = firstAttribute->Next();
    }

    if (nodeCounter==-1 || linkCounter==-1 || speciesCounter==-1)
    {
        throw CREATE_LOCATEDEXCEPTION_INFO("MALFORMED XML!");
    }

    cacheParameters();

    initRandom();
}
Ejemplo n.º 13
0
/////////////////////////////////////////////////////////
// Constructor
//
/////////////////////////////////////////////////////////
pix_noise :: pix_noise(t_floatarg xsize, t_floatarg ysize) :
    m_banged(false), m_automatic(false),
    m_mode(GL_RGBA_GEM),
    m_rand_p(0), m_rand_k(24)
{
    if (xsize < 1) xsize = 256;
    if (ysize < 1) ysize = 256;
    int randInit = 307*1319;
    initRandom(randInit);

    //	m_pixBlock.image = m_imageStruct;
    m_pixBlock.image.xsize = (int)xsize;
    m_pixBlock.image.ysize = (int)ysize;
    m_pixBlock.image.setCsizeByFormat(GL_RGBA_GEM);
    m_pixBlock.image.allocate();

    generateNoise();
}
Ejemplo n.º 14
0
Engine::Engine()
{
    engine = this;
#ifdef ENABLE_CRASH_LOGGER
#ifdef __WIN32__
    ExcHndlInit();
#endif//__WIN32__
#endif//ENABLE_CRASH_LOGGER
    initRandom();
    windowManager = nullptr;
    CollisionManager::initialize();
    InputHandler::initialize();
    gameSpeed = 1.0;
    running = true;
    elapsedTime = 0.0;
    
    soundManager = new SoundManager();
}
Ejemplo n.º 15
0
static void TestMonkey(void)
{
    int32_t scale;
    UErrorCode status = U_ZERO_ERROR;

    for (scale = 0; scale < UDTS_MAX_SCALE; scale += 1) {
        int64_t fromMin = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_FROM_MIN_VALUE, &status);
        int64_t fromMax = utmscale_getTimeScaleValue((UDateTimeScale)scale, UTSV_FROM_MAX_VALUE, &status);
        int32_t i;

        initRandom(fromMin, fromMax);

        for (i = 0; i < LOOP_COUNT; i += 1) {
            int64_t value = randomInRange();

            roundTripTest(value, (UDateTimeScale)scale);
        }
    }
}
Ejemplo n.º 16
0
int main(int argc, char *argv[])
{
int min, max, count = 1;
int i;

if (argc != 3 && argc != 4)
    usage();
min = getInt(argv[1]);
max = getInt(argv[2]);
if (min >= max)
    usage();
if (argc == 4)
    count = getInt(argv[3]);

initRandom();
for (i=0; i<count; ++i)
    printf("%d ", rangedRandom(min, max));
printf("\n"); 
return 0;
}
Ejemplo n.º 17
0
void reseedEncoderFLY(LTencoderFLY *encoder, unsigned long newSeed) {

    // Reinit the totGenSymbols and the refRandomSeed
    encoder->totGenSymbols = 0;
    unsigned long oldSeed = encoder->refRandomSeed;
    encoder->refRandomSeed = newSeed;
    unsigned long oldConfSeed;
    struct hashtable *h = encoder->DistributionsTable;

#ifdef DEBUGencoderPrintBucketRandomSeed
    printf("Encoder[reseed()] - Seed: %lu\n", encoder->refRandomSeed);
#endif

    struct hashtable_itr *itr;
    struct key *k;
    struct value *v;

    // Update all the configurations, if any
    itr = hashtable_iterator(h);
    if (hashtable_count(h) > 0) {
        do {
            k = hashtable_iterator_key(itr);
            v = hashtable_iterator_value(itr);

            // Update the confSeed
            oldConfSeed = v->confSeed;
            v->confSeed = newSeed + (oldConfSeed-oldSeed);

            // Reinit the random generator
            initRandom(&v->randomGenerator, v->confSeed);

            // Erase the number of generated symbols
            v->genSymbols = 0;
        } while (hashtable_iterator_advance(itr));
    }
    free(itr);
    itr = NULL;
    return;
}
Ejemplo n.º 18
0
Archivo: 09.c Proyecto: yabeenico/psp
/*main関数。*/
int main(void){
	int N;

	/*乱数のシードを設定。*/
	srand((unsigned int)time(NULL));
#if 1
	/*Nを増やして計測時間を調べる。*/
	for(N = 10000; N <= 1000000; N *= 10){
		measure(N);
	}
#else
	/*デバッグ*/
	N = 30;
	int *array = (int*)malloc(sizeof(int) * N);
	initRandom(array, N);

	HS(array, N);

	graph(array, N);

#endif
	return 0;
}
Ejemplo n.º 19
0
int main(void) {
    // Create ConfigData objects and load configuration files
    ConfigData mainConfig;
    mainConfig.readFromFile("./config/cfg.txt");
    ConfigData textStrings;
    textStrings.readFromFile("./config/localization/" + mainConfig.getString("language") + ".txt");

    // Create the screen object
    Screen s;
    s.init(mainConfig);

    // Create the god object
    God g;

    // Create the land object
    Land l;
    l.newGame(s.getWidth()/4 - 20, s.getHeight()/4 - 20);
    s.adaptToLand(l, true);

    // Create the interface object
    Interface i;
    i.init(s, textStrings);

    // Other stuff
    bool exit = 0;
    initRandom();

    while(!exit) {
        l.switchAtuAndAtuNotif();
        s.draw(l, g, i);
        l.loop();
        s.handleEvents(l, g, i, exit);
        i.loop();
    }

    return 0;
}
Ejemplo n.º 20
0
Archivo: 09.c Proyecto: yabeenico/psp
/*それぞれのソート方法のカウント数を表示。*/
void measure(int N){
	int *array;
	int j;
	int i;
	double times[2][11];
	void (*sorts[])(int*, int) = {QS, HS};
	double sum;

	/*計測セクション。*/

	/*arrayにメモリを確保。*/
	array = (int*)malloc(sizeof(int) * N);

	/*計測時間を調べる。*/
	for(j = 0; j < 10; j++){
		/*arrayをランダムに初期化。*/
		initRandom(array, N);

		/*2つのソート方法で計測時間を調べる。*/
		for(i = 0; i < 2; i++){
			/*計測時間を取得。*/
			times[i][j] =  getTime(sorts[i], array, N);
		}
	}



	/*表示セクション。*/

	/*Nを表示。*/
	printf("N = %d\n", N);

	/*ソート名を表示。*/
	printf("--QS--");
	printf("-");
	printf("--HS--");
	printf("\n");

	/*計測結果を表示。*/
	for(j = 0; j < 10; j++){
		for(i = 0; i < 2; i++){
			printf("%6.4f ", times[i][j]);
		}

		printf("\n");
	}

	/*平均を表示。*/
	for(i = 0; i < 2; i++){
		/*sumを初期化。*/
		sum = 0;

		/*計測結果の合計を計算。*/
		for(j = 0; j < 10; j++){
			sum += times[i][j];
		}

		/*計測時間の平均値を表示。*/
		printf("%6.4f ", sum / 10);
	}

	/*平均であることを示す。*/
	printf("<---avg\n\n");
}
Ejemplo n.º 21
0
Archivo: stego.c Proyecto: sebros/stego
int main(int argc, char **argv) {

	ConfigInfo configinfo;

	IplImage *img;
	char *img_path;
	int img_channels;

	PixelMap *pixelmap;
	int pixelmap_iterations;
	unsigned long int area_size;

	unsigned int treshold;
	unsigned int useable_pixels;

	FILE *file;

	unsigned int seed;


	//first set struct to 0
	memset(&configinfo, 0, sizeof(ConfigInfo));

	configinfo.treshold = DEFAULT_TRESHOLD;

	getCmdLineParamsToConfig(argc, argv, &configinfo);

	configinfo.lsb_usage = LSB_USAGE_1; //TODO: fix to userinput



	if(configinfo.cover_file != NULL)
	{
		img_path = configinfo.cover_file;
	}

	if(configinfo.stego_file != NULL)
	{
		img_path = configinfo.stego_file;
	}


	img = cvLoadImage(img_path, CV_LOAD_IMAGE_COLOR); //TODO: load image with original channel depth
	if(!img) {
		printf("Error: Failed to Load Image %s\n", img_path);
		exit(1);
	}

	area_size = img->width * img->height;


	if( 0 == (pixelmap_iterations = getLaplacePixelMap(img, &pixelmap, configinfo.lsb_usage)) )
	{
		printf("Error: can't extract laplace-information\n");
		cvReleaseImage( &img );
		exit(1);
	}

	quickSortPixelMap(pixelmap, area_size);

	//calculate treshold, factor 100 is a good value here
	treshold = (unsigned int) pixelmap[ area_size/(100-configinfo.treshold) ].value;


	//count number of pixels to use
	for(useable_pixels=0; ;useable_pixels++)
	{
		if( pixelmap[useable_pixels].value < treshold ) break;
	}


	if(img->nChannels == 1)
	{
		img_channels = 1;
	}
	if(img->nChannels >= 3){
		img_channels = 3;
	}


	if( configinfo.only_calc == TRUE)
	{
		printf("usable data size to embedd is %u Bytes\n", (unsigned int)( ((useable_pixels * img_channels) - MESSAGE_LENGTH_BITS) / BYTE ));	//32 bits for message length

		cvReleaseImage( &img );
		free( pixelmap );
		exit(0);
	}


	seed = generateSeed(configinfo.password);
	initRandom(seed);

	//write data to cover
	if(configinfo.cover_file != NULL)
	{

		if( NULL == (file = fopen(configinfo.message_file, "r")) )
		{
			printf("Failed to open message file: %s\n", configinfo.message_file);

			cvReleaseImage( &img );
			free( pixelmap );
			exit(0);
		}

		writeDataToImage(img, pixelmap, file, configinfo, useable_pixels); //TODO: catch return value

		cvSaveImage(configinfo.output_file, img, NULL);

	}
	//extract data from stego file
	else if(configinfo.stego_file != NULL)
	{
		if( NULL == (file = fopen(configinfo.message_file, "w")) )
		{
			printf("Failed to open message file: %s\n", configinfo.message_file);

			cvReleaseImage( &img );
			free( pixelmap );
			exit(0);
		}

		readDataFromImage(img, pixelmap, file, configinfo, useable_pixels); //TODO: catch return value
	}
	else
	{
		//this should not be reached
		DEBUG( ("Something went totally wrong! line: %d\n", __LINE__) );
	}


	cvReleaseImage( &img );
	free( pixelmap );
	fclose(file);

	return 0;

}
Ejemplo n.º 22
0
Archivo: zombie.c Proyecto: xhkz/zombie
int main(int argc, char **argv)
{

    int threadsLimit = 0;

    int c;
    while ((c = getopt (argc, argv, "n:t")) != -1)
    {
        switch (c)
        {
        case 'n':
            threadsLimit = atoi(optarg);
            break;
        case 't':
            benchmark = true;
            break;
        default:
            ;
        }
    }
    
    if (threadsLimit) {
        omp_set_dynamic(0);
        omp_set_num_threads(threadsLimit);
    }
    
    clock_t start;
    start = clock();

    bool *locks = (bool *)malloc((SIZEX + 2) * sizeof(bool));
    for (int i = 0; i < SIZEX + 2; i++)
        locks[i] = false;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    initRandom(0, rank);
    Entity **matrix_a = createMatrix(SIZEX + 2, SIZEY + 2);
    Entity **matrix_b = createMatrix(SIZEX + 2, SIZEY + 2);
    initMatrix(matrix_a, SIZEX, SIZEY);

    MPI_Type_contiguous(sizeof(Entity), MPI_BYTE, &cell_t);
    MPI_Type_commit(&cell_t);
    MPI_Type_vector(SIZEX + 2, 1, 1, cell_t, &row_t);
    MPI_Type_commit(&row_t);
    MPI_Type_contiguous(sizeof(Counter), MPI_BYTE, &counter_t);
    MPI_Type_commit(&counter_t);

    Entity * northBuffer = (Entity *) malloc((SIZEX + 2) * sizeof(Entity));
    Entity * southBuffer = (Entity *) malloc((SIZEX + 2) * sizeof(Entity));

    if (!benchmark) {
        // update local counter and sync
        updateCounter(matrix_a);
        syncCounter();
        printHeader(rank);
        printCSV(0, rank);
    }

    for (int n = 0; n < STEPS; n++)
    {
        // set adjacent borders
        if (rank == NORTH)
        {
            MPI_Recv(northBuffer, 1, row_t, SOUTH, TAG, MPI_COMM_WORLD, &status);
            setBorder(northBuffer, matrix_a, SIZEY+1);

            setBuffer(matrix_a, northBuffer, SIZEY);
            MPI_Send(northBuffer, 1, row_t, SOUTH, TAG, MPI_COMM_WORLD);
        }

        if (rank == SOUTH)
        {
            setBuffer(matrix_a, southBuffer, 1);
            MPI_Send(southBuffer, 1, row_t, NORTH, TAG, MPI_COMM_WORLD);

            MPI_Recv(southBuffer, 1, row_t, NORTH, TAG, MPI_COMM_WORLD, &status);
            setBorder(southBuffer, matrix_a, 0);
        }

        #pragma omp parallel for default(none) shared(matrix_a, matrix_b, n, locks) schedule(static, SIZEX/omp_get_max_threads())
        for (int i = 1; i <= SIZEX; i++)
        {
            lock(i, locks);
            #pragma omp parallel for
            for (int j = 1; j <= SIZEY; j++)
                process(matrix_a, matrix_b, i, j);

            unlock(i, locks);
        }

        // merge adjacent border
        if (rank == NORTH)
        {
            MPI_Recv(northBuffer, 1, row_t, SOUTH, TAG, MPI_COMM_WORLD, &status);
            mergeGhost(northBuffer, matrix_b, SIZEY);

            setGhost(matrix_b, northBuffer, SIZEY+1);
            MPI_Send(northBuffer, 1, row_t, SOUTH, TAG, MPI_COMM_WORLD);
        }

        if (rank == SOUTH)
        {
            setGhost(matrix_b, southBuffer, 0);
            MPI_Send(southBuffer, 1, row_t, NORTH, TAG, MPI_COMM_WORLD);

            MPI_Recv(southBuffer, 1, row_t, NORTH, TAG, MPI_COMM_WORLD, &status);
            mergeGhost(southBuffer, matrix_b, 1);
        }

        // clear original adjacent border in matrix_a
        for (int i = 0; i < SIZEX + 2; i++)
            clearEntity(&matrix_a[i][rank == NORTH ? SIZEY + 1 : 0]);

        //some times it can not move back, then stay in the border
        transferInBorder(matrix_a, matrix_b);
        moveBackInBorder(matrix_b);

        // swap matrixes
        Entity **matrix_t = matrix_a;
        matrix_a = matrix_b;
        matrix_b = matrix_t;

        if (!benchmark)
        {
            updateCounter(matrix_a);
            syncCounter();
            printCSV(n+1, rank);
        }
    }
    
    if (benchmark)
        printf("Thread: %d, Time: %f sec\n", omp_get_max_threads(), (double)(clock() - start) / CLOCKS_PER_SEC);

    destroyMatrix(matrix_a);
    destroyMatrix(matrix_b);
    
    free(northBuffer);
    free(southBuffer);

    MPI_Finalize();

    return 0;
}
Ejemplo n.º 23
0
/*
=====================
	initSystem
=====================
*/
BOOL initSystem() {

	//get game directory path (Ex: D:\Games\Netrix)
	//
	GetCurrentDirectory( MAX_PATH, k_system.szStartDir );

	N_InitTrace();

	//init Win32 system
	//
	initWin32();

	//System
	//
	k_system.pLeftGame	= NULL;
	k_system.pRightGame	= NULL;
	k_system.gameType	= GNO;
	k_system.pause		= FALSE;
	k_system.flags		= 0;
	k_system.dwAccumTime	= 0;
	k_system.dwTime		= 0;
	
	//Maps
	//
	k_system.cMaps	= 0;
	k_system.pMaps	= NULL;
	k_system.idMap	= -1;
	
	//Bots
	//
	k_system.cBots	= 0;
	k_system.pBots	= NULL;
	k_system.idBotLeft	= -1;
	k_system.idBotRight	= -1;
	
	//Paths
	//
	k_system.pPaths	= NULL;
	k_system.cPaths	= 0;
	
	//HWND
	//
	k_system.hwnd		= NULL;
	k_system.hwndLeft	= NULL;
	k_system.hwndRight	= NULL;
	
	k_system.cPlayers	= 0;

	initRandom();

	cfInitTable();

	//resources
	//
	loadResources();
	
	//init bot system
	//
	botInit();

	//Skins
	//
	loadSkin( &k_system.hSkinRgnLeft, &k_system.hSkinBitmapLeft,
		&k_system.cxSkinLeft, &k_system.cySkinLeft, IDR_SKIN_LEFT );

	loadSkin( &k_system.hSkinRgnRight, &k_system.hSkinBitmapRight,
		&k_system.cxSkinRight, &k_system.cySkinRight, IDR_SKIN_RIGHT );

	createWindow();
	
	//GUI
	//
	populateGUI();

	if( !initGraphics( NEUTRAL ) )
		return FALSE;

	if( !initGraphics( LEFTGAME ) )
		return FALSE;

	updateWindow( CGF_DRAWLEFT );
	
	//winmm
	timeBeginPeriod( 1 );
	
	return TRUE;
}
Ejemplo n.º 24
0
float Utils::randomValue(){
	initRandom();

	float result = (rand() % 1000000) / (float)1000000;
	return result;
}
Ejemplo n.º 25
0
int Utils::randomRange(int min, int max) {
	initRandom();

	return (rand() + min) % max;
}
Ejemplo n.º 26
0
int Utils::randomRange(int max) {
	initRandom();

	return rand() % max;
}
Ejemplo n.º 27
0
 \brief

 \fn initRandom
 \return int
*/
static int initRandom ()
{
    srand   (time (NULL));
#ifndef WIN32
    srand48 (time (NULL));
#endif
    return 0;
}

// initialise random number generator
static int someNumber = initRandom (); /*!< TODO */

/*

Expression-evaluator
--------------------

Author: Nick Gammon
-------------------


Example usage:

    Parser p ("2 + 2 * (3 * 5) + nick");

    p.symbols_ ["nick"] = 42;
Ejemplo n.º 28
0
void pix_noise :: seed(int seedval)
{
    initRandom(seedval);
    bang();
}
void paraNode()
/* paraNode - a net server. */
{
char *line;
char *command;
struct sockaddr_in sai;

/* We have to know who we are... */
hostName = getMachine();
initRandom();
getTicksToHundreths();

/* log init */
if (optionExists("log"))
    logOpenFile("paraNode", optionVal("log", NULL));
else    
    logOpenSyslog("paraNode", optionVal("logFacility", NULL));
logSetMinPriority(optionVal("logMinPriority", "info"));
logInfo("starting paraNode on %s", hostName);

/* Make job lists. */
jobsRunning = newDlList();
jobsFinished = newDlList();

/* Set up socket and self to listen to it. */
ZeroVar(&sai);
sai.sin_family = AF_INET;
sai.sin_port = htons(paraNodePort);
sai.sin_addr.s_addr = INADDR_ANY;
mainRudp = rudpMustOpenBound(&sai);
mainRudp->maxRetries = 12;

/* Event loop. */
findNow();
for (;;)
    {
    /* Get next incoming message and optionally check to make
     * sure that it's from a host we trust, and check signature
     * on first bit of incoming data. */
    if (pmReceive(&pmIn, mainRudp))
	{
	findNow();
	if (hubName == NULL || ntohl(pmIn.ipAddress.sin_addr.s_addr) == hubIp 
		|| ntohl(pmIn.ipAddress.sin_addr.s_addr) == localIp)
	    {
	    /* Host and signature look ok,  read a string and
	     * parse out first word as command. */
	    line = pmIn.data;
	    logDebug("message from %s: \"%s\"",
                     paraFormatIp(ntohl(pmIn.ipAddress.sin_addr.s_addr)),
                     line);
	    command = nextWord(&line);
	    if (command != NULL)
		{
		if (sameString("quit", command))
		    break;
		else if (sameString("run", command))
		    doRun(line, &pmIn.ipAddress);
		else if (sameString("jobDone", command))
		    jobDone(line);
		else if (sameString("status", command))
		    doStatus();
		else if (sameString("kill", command))
		    doKill(line);
		else if (sameString("check", command))
		    doCheck(line, &pmIn.ipAddress);
		else if (sameString("resurrect", command))
		    doResurrect(line, &pmIn.ipAddress);
		else if (sameString("listJobs", command))
		    listJobs();
		else if (sameString("fetch", command))
		    doFetch(line);
                else
                    logWarn("invalid command: \"%s\"", command);
		}
	    logDebug("done command");
	    }
	else
	    {
	    logWarn("command from unauthorized host %s",
                    paraFormatIp(ntohl(pmIn.ipAddress.sin_addr.s_addr)));
	    }
	}
    }
rudpClose(&mainRudp);
}
Ejemplo n.º 30
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qreal ax = -5, bx = 5;
    TVect b;
    TVect testVector = {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9};
    char *itemMenu[] =
    {
        "A - Загрузить тестовый вектор",
        "B - Загрузить вектор с помощью генератора случайных чисел",
        "C - Сортировать вектор с помощью метода выбора",
        "D - Сортировать вектор с помощью метода пузырька",
        "E - Сортировать вектор с помощью метода вставки",
        "F - Сохранить вектор в файле",
        "G - Считать вектор из файла",
        "X - Выйти из программы"
    };
    char *hotKeys = "ABCDEFG";
    char selectedBranch;
    initRandom();
    while (true)
    {
        selectedBranch = menu(itemMenu, hotKeys);
        switch (selectedBranch) {
        case 'A':
            cout << "Загрузка тестового вектора" << endl;
            loadTestVector(b, testVector);
            printArray(b);
            break;
        case 'B':
            cout << "Загрузка вектора с помощью генератора случайных чисел" << endl;
            fillArrayRand(b, ax, bx);
            printArray(b);
            break;
        case 'C':
            cout << "Сортировать вектор с помощью метода выбора" << endl;
            cout << "Вектор до сортировки" << endl;
            printArray(b);
            selectionSort(b);
            cout << "Вектор после сортировки" << endl;
            printArray(b);
            break;
        case 'D':
            cout << "Сортировать вектор с помощью метода пузырька" << endl;
            cout << "Вектор до сортировки" << endl;
            printArray(b);
            bubbleSort(b);
            cout << "Вектор после сортировки" << endl;
            printArray(b);

            break;
        case 'E':
            cout << "Сортировать вектор с помощью метода вставки" << endl;
            cout << "Вектор до сортировки" << endl;
            printArray(b);
            insertionSort(b, N);
            cout << "Вектор после сортировки" << endl;
            printArray(b);
            break;
        case 'F':
            cout << "Сохранить вектор в файле" << endl;
            cout << "Введите имя файла:";
        {
            string fileName = "";
            cin >> fileName;
            char *cstr = new char[fileName.length() + 1];
            strcpy(cstr, fileName.c_str());
            if (writeVectFile(cstr, b))
            {
                cout << "Вектор сохранён в файле"<< "\n";
            }
            else
            {
                cout << "При сохранении произошла ошибка\n";
            }
            delete [] cstr;
        }
            break;
        case 'G':
            cout << "Считать вектор из файла" << endl;
            cout << "Введите имя файла:";
        {
            string fileName = "";
            cin >> fileName;
            if (readVectFile(fileName,b))
            {
                cout << "Вектор прочитан из файла"<< "\n";
            }
            else
            {
                cout << "При считывании произошла ошибка\n";
            }
        }

            break;
        default:
            break;
        }
    }
    initRandom();
    fillArrayRand(b, ax, bx);
    printArray(b);
    //selectionSort(b);
    bubbleSort(b);
    cout<<"After selection sorting"<<endl;
    printArray(b);
    cout<<"Insertion sorting"<<endl;
    fillArrayRand(b, ax, bx);
    cout<<"Before:"<<endl;
    printArray(b);
    cout<<"After:"<<endl;
    insertionSort(b, N);
    printArray(b);
    writeVectFile("/home/ametovii/Temp/vect.txt", b);
    return 0;
}