map<Position, char> MapGenerator::Generate(MapMeta meta)
	{
		map<Position, char> level;
		Position::width = meta.width;
		Position::height = meta.height;
		Position playerPos;
		for (int x = 0; x < meta.width; x++)
		{
			for (int y = 0; y < meta.height; y++)
			{
				if (x == 0 || y == 0 || x == meta.width - 1 || y == meta.height - 1)
					level[{x, y}] = '8';
				else
					level[{x, y}] = '.';
			}
		}
		for (auto code : meta.codes)
		{
			int c = code.minCount;
			if (code.maxCount > code.minCount)
				c += rand() % (1 + code.maxCount - code.minCount);
			while (c > 0)
			{
				Position p;
				p.x = RANDINT(1, meta.width - 2);
				p.y = RANDINT(1, meta.height - 2);
				if (level[p] != '.') continue;
				level[p] = code.code;
				if (code.code == '@') playerPos = p;
				c--;
			}
		}

		return level;
	}
Esempio n. 2
0
static std::string randomKey( unsigned int maxlen)
{
	enum {AlphabetSize=71};
	static const char alphabet[AlphabetSize+1] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,?()/%&#";
	std::string rt;
	unsigned int limit = maxlen-1;
	while (RANDINT(1,maxlen) < limit && RANDINT(0,100) >= 5)
	{
		limit -= 1;
		rt.push_back( alphabet[ RANDINT(0,AlphabetSize)]);
	}
	return rt;
}
static TreeNode* createRandomTree( const GlobalContext* ctx, const strus::utils::Document& doc, std::size_t& docitr, unsigned int depth=0)
{
	TreeNode* rt = 0;
	if (RANDINT( 1,5-depth) == 1)
	{
		if (docitr >= doc.itemar.size()) return 0;
		rt = new TreeNode( termId( strus::utils::Token, doc.itemar[ docitr].termid));
	}
	else
	{
		unsigned int argc = ctx->randomArgc();
		unsigned int range = argc + ctx->randomRange();
		unsigned int cardinality = 0; //... it seems currently too difficult to handle other than the default cardinality in this test
		TreeNode::JoinOperation op = ctx->randomOp();
		std::vector<TreeNode*> args;
		unsigned int rangesum = 0;
		unsigned int ai;
		for (ai=0; docitr < doc.itemar.size() && ai<argc; ++ai,++docitr)
		{
			TreeNode* arg = createRandomTree( ctx, doc, docitr, depth+1);
			if (arg == 0)
			{
				TreeNode::deleteTreeAr( args);
				return 0;
			}
			args.push_back( arg);
			rangesum += arg->range();
		}
		if (argc == 1
			&& (op == strus::PatternMatcherInstanceInterface::OpSequenceStruct
				|| op == strus::PatternMatcherInstanceInterface::OpWithinStruct)
			&& args[0]->term() == termId( strus::utils::SentenceDelim, 0))
		{
			// ... add another node for a sequence of size 1, if we have a sequence of length 1 with a delimiter element only (prevent anomaly)
			TreeNode* arg = createRandomTree( ctx, doc, docitr, depth+1);
			if (arg == 0)
			{
				TreeNode::deleteTreeAr( args);
				return 0;
			}
			args.push_back( arg);
			rangesum += arg->range();
		}
		range += rangesum;
		if (ai < argc)
		{
			TreeNode::deleteTreeAr( args);
			return 0;
		}
		switch (op)
		{
			case strus::PatternMatcherInstanceInterface::OpSequence:
			case strus::PatternMatcherInstanceInterface::OpSequenceImm:
			{
				break;
			}
			case strus::PatternMatcherInstanceInterface::OpSequenceStruct:
			{
				TreeNode* delim = new TreeNode( termId( strus::utils::SentenceDelim, 0));
				args.insert( args.begin(), delim);
				++argc;
				break;
			}
			case strus::PatternMatcherInstanceInterface::OpWithin:
			{
				for (int ii=0; ii<3; ii++)
				{
					unsigned int r1 = RANDINT(0,argc);
					unsigned int r2 = RANDINT(0,argc);
					if (r1 != r2) std::swap( args[r1], args[r2]);
				}
				break;
			}
			case strus::PatternMatcherInstanceInterface::OpWithinStruct:
			{
				for (int ii=0; ii<3; ii++)
				{
					unsigned int r1 = RANDINT(0,argc);
					unsigned int r2 = RANDINT(0,argc);
					if (r1 != r2) std::swap( args[r1], args[r2]);
				}
				TreeNode* delim = new TreeNode( termId( strus::utils::SentenceDelim, 0));
				args.insert( args.begin(), delim);
				++argc;
				break;
			}
			case strus::PatternMatcherInstanceInterface::OpAny:
				cardinality = 0;
				break;
			case strus::PatternMatcherInstanceInterface::OpAnd:
				throw std::runtime_error( "operator 'And' not implemented yet");
		}
		rt = new TreeNode( op, args, range, cardinality);
	}
	if (RANDINT(1,10) == 1)
	{
		rt->attachVariable( RANDINT(1,10));
	}
	return rt;
}
	unsigned int randomArgc() const
	{
		unsigned int rt = m_argcdist.random();
		if (rt == 1 && RANDINT(1,5)>=2) ++rt;
		return rt;
	}
Esempio n. 5
0
int main(int argc, char** argv){

  // declare metal properties
  float m, a, n, c, density;
  
  // check for second and third arguments, and initialize metal properties accordingly
  if (argc < 2) {
    std::cout << "Program must be invoked with argument \'gold\' or \'silver\'\n\n";
    return -1; // terminate with error
  }
  else if (strcmp(argv[1],"gold") == 0) {
    m = gold_m;
    a = gold_a;
    n = gold_n;
    c = gold_c;
    density = gold_density;
    setpoint_temperature[0] = gold_temperature;
  }
  else if (strcmp(argv[1],"silver") == 0) {
    m = silver_m;
    a = silver_a;
    n = silver_n;
    c = silver_c;
    density = silver_density;
    setpoint_temperature[0] = silver_temperature;
  }
  else {
    std::cout << "Argument must be \'gold\' or \'silver\'\n\n";
    return -1;
  }

  // declaring variables
  int timestart = time (NULL), timend, steps = 500;		                             // Number of time steps to take
  float timeEvolved, deltaT = 0.001;     // Size of time step
  float b = pow(abs(N/density) , (1.0/3.0));
  float rc = b/2;
  
  // open files for write
  FILE * fileData;
  fileData = fopen("Results.txt", "w");
  if (fileData == NULL) {
    std::cout << "Unable to open Results.txt" << std::endl;
    exit(1); // terminate with error
  }    
  FILE * fileBestConfig;
  fileBestConfig = fopen("BestConfig.txt", "w");
  if (fileBestConfig == NULL) {
    std::cout << "Unable to open BestConfig.txt" << std::endl;
    exit(1); // terminate with error
  } 
  FILE * fileResults;
  fileResults = fopen("Data.txt", "w");
  if (fileResults == NULL) {
    std::cout << "Unable to open Data.txt" << std::endl;
    exit(1); // terminate with error
  }
    
  // Initialize positions, forces, energies, and temperatures
  setup_temperatures();
  GetInitPositionsAndInitVelocities();         // Start cold to prevent huge forces (should pass SetpointTemperature)
  CalcForces(b, rc, a, c, m, n);
  update_energy_and_temperature();
  
  // print results

  fprintf (fileResults, "NOTE: POTENTIAL ENERGY IS GIVEN BY THE SUTTON-CHEN POTENTIAL.  KINETIC ENERGY IS GIVEN BY THE PARTICLES' VELOCITIES.\n");
  fprintf (fileResults, "Box length = %f\n", b);
  fprintf (fileResults, "Starting Temperature = %f\n", current_temperature[0]);
  fprintf (fileData, "NOTE: POTENTIAL ENERGY IS GIVEN BY THE SUTTON-CHEN POTENTIAL.  KINETIC ENERGY IS GIVEN BY THE PARTICLES' VELOCITIES.\n");
  fprintf (fileData, "Time \t\tTotal Energy \tPotentialE(V) \tKineticE \tCurrent Temp \n");	// Print headers
  fprintf (fileData, "%f \t%f \t%f \t%f \t%f\n", 0.0, total_energy[0], potential_energy[0], kinetic_energy[0], current_temperature[0]);	// Print starting values


  
  for (int i = 0; i < steps; i++){

    // keep the 0th config for MD, use the 1st to last configs as replicas
    if (RAN3() < 0.5) {
      int p = RANDINT(1, num_replicas);
      int q = p;
      if (p == 1)
	q++;
      else if (p == num_replicas-1 || RAN3() < 0.5)
	q--;
      else
	q++;

      float dBeta = (1.0/setpoint_temperature[q]) - (1.0/setpoint_temperature[p]);
      float dEnergy = total_energy[q] - total_energy[p];
      
      if (RAN3() < min(1.0, exp(dBeta*dEnergy))) {
	float temp;

	// swap configurations (positions, velocities, and forces)
	for (int y=0; y<N; y++) {
	  for (int z=0; z<3; z++) {
	    temp = position[p][y][z];
	    position[p][y][z] = position[q][y][z];
	    position[q][y][z] = temp;

	    temp = velocity[p][y][z];
	    velocity[p][y][z] = velocity[q][y][z];
	    velocity[q][y][z] = temp;

	    temp = force[p][y][z];
	    force[p][y][z] = force[q][y][z];
	    force[q][y][z] = temp;
	  }
	}
      }
    }
    
    // Update position, force, velocity, energy, and temperatures
    VelocityVerlet(deltaT, b, rc, a, c, m, n);    
    update_energy_and_temperature();

    // Increase and control temperature, but wait until particles have spread equilibrated first
    if (i > 0.3*steps)
      BussiThermostat(deltaT);               

    // save best configuration
    save_best_config();
    
    timeEvolved = (i+1) * deltaT;      
    fprintf (fileData, "%f \t%f \t%f \t%f \t%f\n", timeEvolved, total_energy[0], potential_energy[0], kinetic_energy[0], current_temperature[0]);  
    
  }

  int BEST = get_best_global_config();
  
  current_temperature[0] = (2 * kinetic_energy[0])/(3 * N - 3);
  fprintf (fileResults, "Final Temperature = %f\n", current_temperature[0]);
  fprintf (fileResults, "Potential Energy = %f\n", potential_energy[0]);
  fprintf (fileResults, "Kinetic Energy = %f\n", kinetic_energy[0]);
  fprintf (fileResults, "Binding Energy (V/N) = %f\n", potential_energy[0] / N);
  fprintf (fileResults, "Binding Energy ((V+K)/N) = %f\n", total_energy[0] / N);
  fprintf (fileResults, "Diffusitivity = %f\n\n", CalculateDiffusitivity(timeEvolved, b));

  fprintf (fileResults, "Global Minimum Search Results (found by Replica Exchange MD):\n");
  fprintf (fileResults, "Global Potential Energy Minimnum (V at best config) = %f\n", best_v[BEST]);
  fprintf (fileResults, "Kinetic Energy at Global Minimnum = %f\n", best_k[BEST]);
  fprintf (fileResults, "Total Energy at Global Minimnum = %f\n", best_v[BEST]+best_k[BEST]);
  fprintf (fileResults, "Binding Energy at Global Minimnum (V/N) = %f\n\n", best_v[BEST] / N);
  fprintf (fileResults, "Binding Energy at Global Minimnum ((V+K)/N) = %f\n\n", (best_v[BEST]+best_k[BEST]) / N);
    
  timend = time (NULL);
  fprintf (fileResults, "%i seconds to execute.", timend-timestart);
    
  fprintf (fileBestConfig, "Best Configuration:\n\n");
  fprintf (fileBestConfig, "x\t\ty\t\tz\n");
  for (int i = 0; i < N; i++) {
    fprintf (fileBestConfig, "%f \t%f \t%f\n", best_configuration[BEST][i][0], best_configuration[BEST][i][1], best_configuration[BEST][i][2]);
  }
    
  fclose (fileBestConfig);
  fclose (fileData);
  fclose (fileResults);
  
  return 0;
}
Esempio n. 6
0
int mutate(int * mutated_shape,  shape_t *  dna_test)
{
    *mutated_shape = RANDINT(NUM_SHAPES);
    double roulette = RANDDOUBLE(2.8);
    double drastic = RANDDOUBLE(2);

    // mutate color
    if(roulette<1)
    {
        if(dna_test[*mutated_shape].a < 0.01 // completely transparent shapes are stupid
                || roulette<0.25)
        {
            if(drastic < 1)
            {
                dna_test[*mutated_shape].a += RANDDOUBLE(0.1);
                dna_test[*mutated_shape].a = CLAMP(dna_test[*mutated_shape].a, 0.0, 1.0);
            }
            else
                dna_test[*mutated_shape].a = RANDDOUBLE(1.0);
        }
        else if(roulette<0.50)
        {
            if(drastic < 1)
            {
                dna_test[*mutated_shape].r += RANDDOUBLE(0.1);
                dna_test[*mutated_shape].r = CLAMP(dna_test[*mutated_shape].r, 0.0, 1.0);
            }
            else
                dna_test[*mutated_shape].r = RANDDOUBLE(1.0);
        }
        else if(roulette<0.75)
        {
            if(drastic < 1)
            {
                dna_test[*mutated_shape].g += RANDDOUBLE(0.1);
                dna_test[*mutated_shape].g = CLAMP(dna_test[*mutated_shape].g, 0.0, 1.0);
            }
            else
                dna_test[*mutated_shape].g = RANDDOUBLE(1.0);
        }
        else
        {
            if(drastic < 1)
            {
                dna_test[*mutated_shape].b += RANDDOUBLE(0.1);
                dna_test[*mutated_shape].b = CLAMP(dna_test[*mutated_shape].b, 0.0, 1.0);
            }
            else
                dna_test[*mutated_shape].b = RANDDOUBLE(1.0);
        }
    }
    
    // mutate shape
    else if(roulette < 2.0)
    {
        int point_i = RANDINT(NUM_POINTS);
        if(roulette<1.5)
        {
            if(drastic < 1)
            {
                dna_test[*mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0);
                dna_test[*mutated_shape].points[point_i].x = CLAMP(dna_test[*mutated_shape].points[point_i].x, 0, WIDTH-1);
            }
            else
                dna_test[*mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH);
        }
        else
        {
            if(drastic < 1)
            {
                dna_test[*mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0);
                dna_test[*mutated_shape].points[point_i].y = CLAMP(dna_test[*mutated_shape].points[point_i].y, 0, HEIGHT-1);
            }
            else
                dna_test[*mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT);
        }
    }

    // mutate stacking
    else
    {
        int destination = RANDINT(NUM_SHAPES);
        shape_t s = dna_test[*mutated_shape];
        dna_test[*mutated_shape] = dna_test[destination];
        dna_test[destination] = s;
        return destination;
    }
    return -1;

}
Esempio n. 7
0
Mutation getMutation(const ShapeCollection &collection)
{
    Mutation mutation{};

    double roulette = (collection.polygonCount > 1 ? RANDDOUBLE(2.2) : RANDDOUBLE(2.0));

    mutation.type = (roulette >= 2.0f ? Mutation::kOrderSwapped :
                     (roulette < 1.0f ? Mutation::kColorChanged :
                      Mutation::kPointChanged));

    mutation.shapeIdx = RANDINT(collection.polygonCount);

    switch(mutation.type) {

    case Mutation::kOrderSwapped:
    {
        mutation.data.shapeIdxB = RANDINT(collection.polygonCount);
        while (mutation.shapeIdx == mutation.data.shapeIdxB) {
            mutation.data.shapeIdxB = RANDINT(collection.polygonCount);
        }
        if (mutation.shapeIdx > mutation.data.shapeIdxB) {
            std::swap(mutation.shapeIdx, mutation.data.shapeIdxB);
        }
    }
    break;

    case Mutation::kColorChanged:
    {
        mutation.data.color = collection.shapes[mutation.shapeIdx].rgba;

        bool drastic = RANDBOOL();

        int part = roulette  * 4;
        mutation.data.color[part] = (drastic ?
                                     CLAMPINT(RANDUINT8(), part == 3 ? 0 : 1, 255) :
                                     CLAMPINT(mutation.data.color[part] +
                                              (RANDBOOL() ? + 1 : -1)
                                              * RANDINT(25), part == 3 ? 0 : 1, 255));
    }
    break;

    case Mutation::kPointChanged:
    {
        mutation.data.pt.idx = RANDINT(collection.vertexCount);
        mutation.data.pt.val = collection.shapes[mutation.shapeIdx].polygon[mutation.data.pt.idx];

        bool drastic = RANDBOOL(); ;

        bool changeX = roulette < 1.5;
        std::array<float, 2> &ptRef = mutation.data.pt.val;

        if (changeX) {
            double x = ptRef[0];
            if (drastic) {
                ptRef[0] = RANDINT(collection.width + 1);
                while (x == ptRef[0]) {
                    ptRef[0] = RANDINT(collection.width + 1);
                }
            } else {
                ptRef[0] = CLAMPINT(ptRef[0] + (RANDBOOL() ? +1 : -1) *
                                    static_cast<int>(RANDDOUBLE(collection.width / 10.0)), 0, collection.width);
            }
        } else {
            double y = ptRef[1];
            if (drastic) {
                ptRef[1] = RANDINT(collection.height + 1);
                while (y == ptRef[1]) {
                    ptRef[1] = RANDINT(collection.height + 1);
                }
            } else {
                ptRef[1] = CLAMPINT(ptRef[1] + (RANDBOOL() ? +1 : -1) *
                                    static_cast<int>(RANDDOUBLE(collection.height / 10.0)), 0,
                                    collection.height);
            }
        }
    }
    break;

    default:
        ;
    }

    return mutation;
}
Esempio n. 8
0
int main( int argc, const char** argv)
{
	try
	{
		if (argc < 3)
		{
			throw std::runtime_error( "missing arguments <nof inserts> <nof queries>");
		}
		unsigned int nofInserts;
		unsigned int nofQueries;
		try
		{
			nofInserts = strus::utils::toint( argv[1]);
			nofQueries = strus::utils::toint( argv[2]);
		}
		catch (const std::exception& e)
		{
			throw std::runtime_error( std::string("bad values for arguments <nof inserts> <nof queries> (2 non negative integers expected): ") + e.what());
		}
		initRand();
		typedef strus::StringMap<strus::Index> TestMap;
		TestMap testmap;
		conotrie::CompactNodeTrie origmap;
		std::vector<std::string> keyar;

		std::size_t ii = 0;
		for (; ii<nofInserts; ++ii)
		{
			std::string key;
			do
			{
				key = randomKey( 32);
			}
			while (testmap.find(key) != testmap.end());

			testmap[ key] = ii+1;
			keyar.push_back( key);
		}
		testmap.clear();

		std::clock_t start;
		double duration;
		start = std::clock();

		for (ii=0; ii<nofInserts; ++ii)
		{
			testmap[ keyar[ ii]] = ii+1;
		}
		duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
		std::cerr << "inserted " << nofInserts << " keys in STL map in " << doubleToString(duration) << " seconds" << std::endl;

		start = std::clock();
		for (ii=0; ii<nofInserts; ++ii)
		{
			origmap.set( keyar[ ii].c_str(), ii+1);
		}
		duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
		std::cerr << "inserted " << nofInserts << " keys in variable size node tree in " << doubleToString(duration) << " seconds" << std::endl;

		start = std::clock();
		for (ii=0; ii<nofQueries; ++ii)
		{
			unsigned int keyidx = RANDINT(0,nofInserts);
			TestMap::const_iterator
				mi = testmap.find( keyar[ keyidx]);
			if (mi == testmap.end() || mi->second != (strus::Index)keyidx+1)
			{
				throw std::logic_error("TESTMAP LOOKUP FAILED");
			}
		}
		duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
		std::cerr << "queried boost unordered map with " << nofQueries << " random selected keys in " << doubleToString(duration) << " seconds" << std::endl;

		start = std::clock();
		for (ii=0; ii<nofQueries; ++ii)
		{
			unsigned int keyidx = RANDINT(0,nofInserts);
			conotrie::CompactNodeTrie::NodeData val;
			if (!origmap.get( keyar[ keyidx].c_str(), val)
			||  val != keyidx+1)
			{
				throw std::runtime_error( "VARIABLE SIZE NODE LOOKUP FAILED");
			}
		}
		duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
		std::cerr << "queried variable size node tree " << nofQueries << " random selected keys in " << doubleToString(duration) << " seconds" << std::endl;

		TestMap::const_iterator
			ti = testmap.begin(), te = testmap.end();

		for (; ti != te; ++ti)
		{
			conotrie::CompactNodeTrie::NodeData val;
			if (!origmap.get( ti->first, val))
			{
				throw std::runtime_error( std::string( "inserted key '") + ti->first + "' disapeared in variable size node tree");
			}
		}

		conotrie::CompactNodeTrie::const_iterator
			oi = origmap.begin(), oe = origmap.end();
		std::size_t oidx = 0;
		for (; oi != oe; ++oi,++oidx)
		{
			TestMap::const_iterator ti = testmap.find( oi.key());
			if (ti == testmap.end())
			{
				throw std::runtime_error( std::string( "non existing key '") + oi.key() + "' found in variable size node tree");
			}
			else if (ti->second != (strus::Index)oi.data())
			{
				std::ostringstream dt;
				dt << ti->second << " != " << oi.data();
				throw std::runtime_error( std::string( "inserted key '") + oi.key() + "' has not the expected value (" + dt.str() + ")");
			}
		}
		if (oidx != nofInserts)
		{
			std::ostringstream dt;
			dt << oidx << " != " << nofInserts;
			throw std::runtime_error( std::string( "number of inserts in variable size node tree does not match (") + dt.str() + ")");
		}
		std::cerr << "checked inserted content in maps. OK" << std::endl;
		return 0;
	}
	catch (const std::exception& err)
	{
		std::cerr << "EXCEPTION " << err.what() << std::endl;
	}
	return -1;
}