static void init_rand_gen() { int fd = open("/dev/urandom", O_RDONLY); if (fd != -1) { uint32_t seed; read(fd, &seed, sizeof(uint32_t)); g_mt_rand.seed(seed); close(fd); } else { g_mt_rand.seed(time(NULL)); } }
int main() { gen.seed(static_cast<unsigned int>(std::time(0))); const int beam_size = 3; const int vocab_size = 10; const int start_symbol = 0; const int end_symbol = 1; const int max_decoding_length = 30; const int min_decoding_length = 10; const int source_length = 10; const precision penalty = 3; decoder<precision> d(beam_size,vocab_size,start_symbol,end_symbol, max_decoding_length,min_decoding_length,penalty,""); Eigen::Matrix<precision,Eigen::Dynamic, Eigen::Dynamic> outputDist; Eigen::Matrix<precision, 1, Eigen::Dynamic> normalization; outputDist.resize(vocab_size,beam_size); normalization.resize(1,beam_size); init_output_dist(outputDist,normalization); d.init_decoder(); for(int i=0; i<20; i++) { init_output_dist(outputDist,normalization); d.expand_hypothesis(outputDist); d.print_current_hypotheses(); } d.finish_current_hypotheses(outputDist); d.print_current_hypotheses(); }
void UnsyncedRNG::Seed(unsigned seed) { #ifdef USE_BOOST_RNG rng.seed(seed); #else randSeed = seed; #endif }
int main(int argc, char** argv) { ptime begin = microsec_clock::local_time(); random::mt19937 rng; random::uniform_real_distribution<> uni(-1, 1); int seed = lexical_cast<int>(argv[1]); double Wi = lexical_cast<double>(argv[2]); double Wf = lexical_cast<double>(argv[3]); double mu = lexical_cast<double>(argv[4]); double Ui = UWi(Wi); double D = lexical_cast<double>(argv[5]); double taui = lexical_cast<double>(argv[6]); double tauf = lexical_cast<double>(argv[7]); int ntaus = lexical_cast<int>(argv[8]); // double tf = 2*tau; // int nsteps = lexical_cast<int>(argv[9]); double dt = lexical_cast<double>(argv[9]); // int dnsav = lexical_cast<int>(argv[8]); // int nsteps = (int) ceil(2 * tau / dt); // double h = 2 * tau / nsteps; int numthreads = lexical_cast<int>(argv[10]); int resi = lexical_cast<int>(argv[11]); // int resi = 0; // if (argc > 9) { // resi = lexical_cast<int>(argv[9]); // } int subresi = -1; int seed2 = 0; if (argc > 12) { // subresi = lexical_cast<int>(argv[12]); seed2 = lexical_cast<int>(argv[12]); } #ifdef AMAZON // path resdir("/home/ubuntu/Results/Canonical Transformation Dynamical Gutzwiller"); path resdir("/home/ubuntu/Dropbox/Amazon EC2/Simulation Results/Canonical Transformation Dynamical Gutzwiller 2"); #else path resdir("/Users/Abuenameh/Documents/Simulation Results/Canonical Transformation Dynamical Gutzwiller 2"); // path resdir("/Users/Abuenameh/Documents/Simulation Results/Dynamical Gutzwiller Hartmann Comparison"); #endif if (!exists(resdir)) { cerr << "Results directory " << resdir << " does not exist!" << endl; exit(1); } ostringstream oss; if (subresi == -1) { oss << "res." << resi << ".txt"; } else { oss << "res." << resi << "." << subresi << ".txt"; } path resfile = resdir / oss.str(); //#ifndef AMAZON while (exists(resfile)) { resi++; oss.str(""); if (subresi == -1) { oss << "res." << resi << ".txt"; } else { oss << "res." << resi << "." << subresi << ".txt"; } resfile = resdir / oss.str(); } //#endif // if (seed == -1) { // resi = -1; if (seed < 0) { resi = seed; oss.str(""); oss << "res." << resi << ".txt"; resfile = resdir / oss.str(); } vector<double> xi(L, 1); rng.seed(seed); if (seed > -1) { for (int j = 0; j < L; j++) { xi[j] = (1 + D * uni(rng)); } } // double Ui = UWi(Wi); double mui = mu * Ui; filesystem::ofstream os(resfile); printMath(os, "seed", resi, seed); printMath(os, "Delta", resi, D); // printMath(os, "Wres", resi, Wi); printMath(os, "mures", resi, mui); printMath(os, "Ures", resi, Ui); printMath(os, "xires", resi, xi); os << flush; printMath(os, "dtres", resi, dt); // printMath(os, "tauires", resi, taui); // printMath(os, "taufres", resi, tauf); // printMath(os, "ntausres", resi, ntaus); os << flush; // printMath(os, "Wires", resi, Wi); // printMath(os, "Wfres", resi, Wf); os << flush; cout << "Res: " << resi << endl; queue<input> inputs; if (ntaus == 1) { input in; in.tau = taui; inputs.push(in); } else { for (int i = 0; i < ntaus; i++) { input in; double tau = taui + i * (tauf - taui) / (ntaus - 1); in.tau = tau; inputs.push(in); } } vector<results> res; vector<double> f0(2 * L*dim, 1); rng.seed(seed2); for (int i = 0; i < 2 * L * dim; i++) { f0[i] = uni(rng); } DynamicsProblem::setup(Wi, mui, xi); // DynamicsProblem::setup(Wi, Wf, mui, xi, f0, dt); // return 0; progress_display progress(inputs.size()); barrier bar(numthreads); thread_group threads; for (int i = 0; i < numthreads; i++) { threads.create_thread(bind(&threadfunc, Wi, Wf, mui, xi, tauf, boost::ref(inputs), boost::ref(res), boost::ref(progress), boost::ref(bar), i)); } threads.join_all(); vector<double> taures; vector<double> Eires; vector<double> Efres; vector<double> Qres; vector<double> pres; vector<double> U0res; vector<vector<double>> J0res; vector<vector<complex<double>>> b0res; vector<vector<complex<double>>> bfres; vector<vector < vector<complex<double>>>> f0res; vector<vector < vector<complex<double>>>> ffres; // vector<vector<vector<double>>> bsres; vector<string> runtimeres; for (results ires : res) { taures.push_back(ires.tau); Eires.push_back(ires.Ei); Efres.push_back(ires.Ef); Qres.push_back(ires.Q); pres.push_back(ires.p); U0res.push_back(ires.U0); J0res.push_back(ires.J0); b0res.push_back(ires.b0); bfres.push_back(ires.bf); f0res.push_back(ires.f0); ffres.push_back(ires.ff); // bsres.push_back(ires.bs); runtimeres.push_back(ires.runtime); } printMath(os, "taures", resi, subresi, taures); printMath(os, "Eires", resi, subresi, Eires); printMath(os, "Efres", resi, subresi, Efres); printMath(os, "Qres", resi, subresi, Qres); printMath(os, "pres", resi, subresi, pres); printMath(os, "U0res", resi, subresi, U0res); printMath(os, "J0res", resi, subresi, J0res); printMath(os, "b0res", resi, subresi, b0res); printMath(os, "bfres", resi, subresi, bfres); // printMath(os, "f0res", resi, subresi, f0res); // printMath(os, "ffres", resi, subresi, ffres); // printMath(os, "bsres", resi, bsres); printMath(os, "runtime", resi, subresi, runtimeres); ptime end = microsec_clock::local_time(); time_period period(begin, end); cout << endl << period.length() << endl << endl; if (subresi == -1) { os << "totalruntime[" << resi << "]=\"" << period.length() << "\";" << endl; } else { os << "subtotalruntime[" << resi << "," << subresi << "]=\"" << period.length() << "\";" << endl; } return 0; // cout << setprecision(10); // // double Wi = 2e11; // double Wf = 1e11; // double tau = 1e-6; // double mu = 0.5; // vector<double> xi(L, 1); // // int ndim = 2 * L*dim; // // vector<double> f0(ndim, 1); // // vector<double> Eiv, Efv, Qv, pv; // vector<vector<double>> bv; // // DynamicsProblem prob; // // for (int i = 0; i < 10; i++) { // prob.setParameters(Wi, Wf, tau + i * 0.1e-6, xi, mu); // prob.setInitial(f0); // prob.solve(); // prob.evolve(); // // Eiv.push_back(prob.getEi()); // Efv.push_back(prob.getEf()); // Qv.push_back(prob.getQ()); // pv.push_back(prob.getRho()); // bv.push_back(prob.getBs()); // } // // cout << math(bv) << endl; // cout << math(Eiv) << endl; // cout << math(Efv) << endl; // cout << math(Qv) << endl; // cout << math(pv) << endl; // cout << prob.getGSRuntime() << endl; // cout << prob.getRuntime() << endl; return 0; return 0; }
int Helper::getRandomNumber(const int _min, const int _max) { randomGenerator.seed(std::time(0)); boost::random::uniform_int_distribution<> dist(_min, _max); return dist(randomGenerator); }
// Initialize the seed of the random number generator void random_initialize(unsigned int seed) { random_gen.seed(seed); }
int main() { string x, y, opcode; string cmd; boost::random::uniform_int_distribution<> dist32bit(0, 2147483647); boost::random::uniform_int_distribution<> dist3bit(0, 4); vector<pair<string,string> > db; for(int i = 0; i < 5000; i++) { gen.seed(static_cast<unsigned int>(time(0) + getpid()) + i); int r0 = dist32bit(gen); int r1 = dist32bit(gen); int r2 = dist3bit(gen); //cout << r0 << " " << r1 << " " << r2 << endl; bitset<32> t0(r0); bitset<32> t1(r1); bitset<3> t2(r2); x = t0.to_string(); y = t1.to_string(); opcode = t2.to_string(); //cout << x << " " << y << " " << opcode << endl; cmd = "vvp a.out +x=" + x + " +y=" + y + " +opcode=" + opcode; // Program to run or "wrap" string out = exec(cmd); //cout << out; int index; string delay; const char* process = out.c_str(); for(int i = strlen(process) - 1; i >= 0; i--) { if(process[i] == ' ') { index = i; break; } } for(int i = index + 1; i < strlen(process); i++) { delay = delay + process[i]; } add(delay, opcode, db); cout << i << endl; } int j; ofstream f("5krandominputs.txt"); // Output file for(vector<pair<string,string> >::const_iterator i = db.begin(); i != db.end(); ++i) { string first = (*i).first; string second = (*i).second; trim(first); trim(second); string w = first + " " + second + '\n'; f << w; int j; cout << "writing..." << j++ << endl; } }
namespace sfs { boost::random::mt19937 randfast; boost::random::mt19937_64 randfast64; boost::random::random_device randomizer; void seedrand() { randfast.seed(time(0)); randfast64.seed(time(0)); } double random(double min, double max, bool slow) { boost::random::uniform_real_distribution<double> d(min, max); if(slow) { return d(randomizer); } return d(randfast64); } float random(float min, float max, bool slow) { boost::random::uniform_real_distribution<float> d(min, max); if(slow) { return d(randomizer); } return d(randfast); } template<typename T> T random(T min, T max, bool slow) { boost::random::uniform_int_distribution<T> d(min, max); if(slow) { return d(randomizer); } if(sizeof(T) >= 8) { // If we want 64-bit, use 64-bit generator. return d(randfast64); } return d(randfast); } rgba random(rgba min, rgba max, bool slow) { rgba result; result.r = random(min.r, max.r, slow); result.g = random(min.g, max.g, slow); result.b = random(min.b, max.b, slow); result.a = random(min.a, max.a, slow); return result; } vec3 random(vec3 min, vec3 max, bool slow) { vec3 result; result.x = random(min.x, max.x, slow); result.y = random(min.y, max.y, slow); result.z = random(min.z, max.z, slow); return result; } }
void seed(int seed) { gen.seed(seed); }
RandomInt(int min, int max, int seed) : dist(min, max) { gen.seed(seed); }
namespace robogen { void init(unsigned int seed, std::string outputDirectory, std::string confFileName, bool overwrite, bool saveAll); void printUsage(char *argv[]) { std::cout << std::endl << "USAGE: " << std::endl << " " << std::string(argv[0]) << " <SEED, INTEGER> <OUTPUT_DIRECTORY, STRING> " << "<CONFIGURATION_FILE, STRING> [<OPTIONS>]" << std::endl << std::endl << "WHERE: " << std::endl << " <SEED> is a number to seed " << "the pseudorandom number generator." << std::endl << std::endl << " <OUTPUT_DIRECTORY> is the directory to write output " << "files to." << std::endl << std::endl << " <CONFIGURATION_FILE> is the evolution" << " configuration file to use." << std::endl << std::endl << "OPTIONS: " << std::endl << " --help" << std::endl << " Print all configuration options and exit." << std::endl << std::endl << " --overwrite" << std::endl << " Overwrite existing output file directory if it " << "exists." << std::endl << " (Default is to keep creating new output " << "directories with incrementing suffixes)." << std::endl << std::endl << " --save-all" << std::endl << " Save all individuals instead of just the generation" << "best." << std::endl << std::endl; } void printHelp() { boost::shared_ptr<EvolverConfiguration> conf = boost::shared_ptr< EvolverConfiguration>(new EvolverConfiguration()); conf->init("help"); std::cout << std::endl; boost::shared_ptr<RobogenConfig> robotConf = ConfigurationReader::parseConfigurationFile("help"); } boost::shared_ptr<Population> population; IndividualContainer children; boost::shared_ptr<NeatContainer> neatContainer; boost::shared_ptr<RobogenConfig> robotConf; boost::shared_ptr<EvolverConfiguration> conf; boost::shared_ptr<EvolverLog> log; bool neat; boost::shared_ptr<Selector> selector; boost::shared_ptr<Mutator> mutator; unsigned int generation; boost::random::mt19937 rng; std::vector<Socket*> sockets; void parseArgsThenInit(int argc, char* argv[]) { startRobogen(); // --------------------------------------- // verify usage and load configuration // --------------------------------------- if (argc > 1 && std::string(argv[1]) == "--help") { printUsage(argv); printHelp(); exitRobogen(EXIT_SUCCESS); } if ((argc < 4)) { printUsage(argv); std::cout << "RUN: " << std::endl << std::endl << " " << std::string(argv[0]) << " --help to see all configuration options." << std::endl << std::endl; exitRobogen(EXIT_FAILURE); } unsigned int seed = atoi(argv[1]); std::string outputDirectory = std::string(argv[2]); std::string confFileName = std::string(argv[3]); bool overwrite = false; bool saveAll = false; int currentArg = 4; for (; currentArg < argc; currentArg++) { if (std::string("--help").compare(argv[currentArg]) == 0) { printUsage(argv); printHelp(); exitRobogen(EXIT_SUCCESS); } else if (std::string("--overwrite").compare(argv[currentArg]) == 0) { overwrite = true; } else if (std::string("--save-all").compare(argv[currentArg]) == 0) { saveAll = true; } else { std::cerr << std::endl << "Invalid option: " << argv[currentArg] << std::endl << std::endl; printUsage(argv); exitRobogen(EXIT_FAILURE); } } init(seed, outputDirectory, confFileName, overwrite, saveAll); } void init(unsigned int seed, std::string outputDirectory, std::string confFileName, bool overwrite, bool saveAll) { // Seed random number generator rng.seed(seed); conf.reset(new EvolverConfiguration()); if (!conf->init(confFileName)) { std::cerr << "Problems parsing the evolution configuration file. Quit." << std::endl; exitRobogen(EXIT_FAILURE); } robotConf = ConfigurationReader::parseConfigurationFile( conf->simulatorConfFile); if (robotConf == NULL) { std::cerr << "Problems parsing the robot configuration file. Quit." << std::endl; exitRobogen(EXIT_FAILURE); } // --------------------------------------- // Set up evolution // --------------------------------------- if (conf->selection == conf->DETERMINISTIC_TOURNAMENT) { selector.reset(new DeterministicTournament(conf->tournamentSize, rng)); } else { std::cerr << "Selection type id " << conf->selection << " unknown." << std::endl; exitRobogen(EXIT_FAILURE); } mutator.reset(new Mutator(conf, rng)); log.reset(new EvolverLog()); try { if (!log->init(conf, robotConf, outputDirectory, overwrite, saveAll)) { std::cerr << "Error creating evolver log. Aborting." << std::endl; exitRobogen(EXIT_FAILURE); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; exitRobogen(EXIT_FAILURE); } catch (...) { std::cerr << "non standard exception " << std::endl; exitRobogen(EXIT_FAILURE); } // --------------------------------------- // parse robot from file & initialize population // --------------------------------------- boost::shared_ptr<RobotRepresentation> referenceBot( new RobotRepresentation()); bool growBodies = false; if (conf->evolutionMode == EvolverConfiguration::BRAIN_EVOLVER && conf->referenceRobotFile.compare("") == 0) { std::cerr << "Trying to evolve brain, but no robot file provided." << std::endl; exitRobogen(EXIT_FAILURE); } else if (conf->referenceRobotFile.compare("") != 0) { if (!referenceBot->init(conf->referenceRobotFile)) { std::cerr << "Failed interpreting robot from text file" << std::endl; exitRobogen(EXIT_FAILURE); } } else { //doing body evolution and don't have a reference robot if (referenceBot->init()) { growBodies = true; } else { std::cerr << "Failed creating base robot for body evolution" << std::endl; exitRobogen(EXIT_FAILURE); } } neat = (conf->evolutionaryAlgorithm == EvolverConfiguration::HYPER_NEAT); population.reset(new Population()); if (!population->init(referenceBot, conf->mu, mutator, growBodies, (!(conf->useBrainSeed || neat)) ) ) { std::cerr << "Error when initializing population!" << std::endl; exitRobogen(EXIT_FAILURE); } if (neat) { neatContainer.reset(new NeatContainer(conf, population, seed, rng)); } // --------------------------------------- // open sockets for communication with simulator processes // --------------------------------------- #ifndef EMSCRIPTEN sockets.resize(conf->sockets.size()); for (unsigned int i = 0; i < conf->sockets.size(); i++) { sockets[i] = new TcpSocket; #ifndef FAKEROBOTREPRESENTATION_H // do not bother with sockets when using // benchmark if (!sockets[i]->open(conf->sockets[i].first, conf->sockets[i].second)) { std::cerr << "Could not open connection to simulator" << std::endl; exitRobogen(EXIT_FAILURE); } #endif } #endif // --------------------------------------- // run evolution TODO stopping criterion // --------------------------------------- if(neat) { if(!neatContainer->fillPopulationWeights(population)) { std::cerr << "Filling weights from NEAT failed." << std::endl; exitRobogen(EXIT_FAILURE); } } generation = 1; population->evaluate(robotConf, sockets); } void mainEvolutionLoop(); void postEvaluateNEAT() { population->sort(true); mainEvolutionLoop(); } void postEvaluateStd() { // comma or plus? if (conf->replacement == conf->PLUS_REPLACEMENT) { children += *population.get(); } // replace population.reset(new Population()); if (!population->init(children, conf->mu)) { std::cout << "Error when initializing population!" << std::endl; exitRobogen(EXIT_FAILURE); } mainEvolutionLoop(); } void triggerPostEvaluate() { if (generation == 1) { mainEvolutionLoop(); } else { if (neat) { postEvaluateNEAT(); } else { postEvaluateStd(); } } } void mainEvolutionLoop() { #ifdef EMSCRIPTEN std::stringstream ss; double best, average, stddev; population->getStat(best, average, stddev); ss << "{best : " << best << ", average : " << average << ", stddev : " << stddev << ", generation : " << generation << "}"; sendJSEvent("stats", ss.str()); #endif std::cout << "mainEvolutionLoop" << std::endl; if (!log->logGeneration(generation, *population.get())) { exitRobogen(EXIT_FAILURE); } generation++; if (generation <= conf->numGenerations) { std::cout << "Generation " << generation << std::endl; children.clear(); // create children if (neat) { //neatPopulation->Epoch(); if(!neatContainer->produceNextGeneration(population)) { std::cerr << "Producing next generation from NEAT failed." << std::endl; exitRobogen(EXIT_FAILURE); } population->evaluate(robotConf, sockets); } else { selector->initPopulation(population); unsigned int numOffspring = 0; while (numOffspring < conf->lambda) { std::pair<boost::shared_ptr<RobotRepresentation>, boost::shared_ptr<RobotRepresentation> > selection; if (!selector->select(selection.first)) { std::cerr << "Selector::select() failed." << std::endl; exitRobogen(EXIT_FAILURE); } unsigned int tries = 0; do { if (tries > 10000) { std::cerr << "Selecting second parent failed after " "10000 tries, giving up."; exitRobogen(EXIT_FAILURE); } if (!selector->select(selection.second)) { std::cerr << "Selector::select() failed." << std::endl; exitRobogen(EXIT_FAILURE); } tries++; } while (selection.first == selection.second); std::vector<boost::shared_ptr<RobotRepresentation> > offspring = mutator->createOffspring(selection.first, selection.second); // no crossover, or can fit both new individuals if ( (numOffspring + offspring.size()) <= conf->lambda ) { children.insert(children.end(), offspring.begin(), offspring.end() ); numOffspring += offspring.size(); } else { // crossover, but can only fit one children.push_back(offspring[0]); numOffspring++; } } children.evaluate(robotConf, sockets); } #ifndef EMSCRIPTEN triggerPostEvaluate(); #endif } else { #ifdef EMSCRIPTEN sendJSEvent("evolutionTerminated", "{}"); #endif } } #ifdef EMSCRIPTEN void EMSCRIPTEN_KEEPALIVE evaluationResultAvailable(int ptr, double fitness) { RobotRepresentation* robot = (RobotRepresentation*) ptr; robot->asyncEvaluateResult(fitness); } void EMSCRIPTEN_KEEPALIVE evaluationIsDone() { triggerPostEvaluate(); } #endif }
void init(unsigned int seed, std::string outputDirectory, std::string confFileName, bool overwrite, bool saveAll) { // Seed random number generator rng.seed(seed); conf.reset(new EvolverConfiguration()); if (!conf->init(confFileName)) { std::cerr << "Problems parsing the evolution configuration file. Quit." << std::endl; exitRobogen(EXIT_FAILURE); } robotConf = ConfigurationReader::parseConfigurationFile( conf->simulatorConfFile); if (robotConf == NULL) { std::cerr << "Problems parsing the robot configuration file. Quit." << std::endl; exitRobogen(EXIT_FAILURE); } // --------------------------------------- // Set up evolution // --------------------------------------- if (conf->selection == conf->DETERMINISTIC_TOURNAMENT) { selector.reset(new DeterministicTournament(conf->tournamentSize, rng)); } else { std::cerr << "Selection type id " << conf->selection << " unknown." << std::endl; exitRobogen(EXIT_FAILURE); } mutator.reset(new Mutator(conf, rng)); log.reset(new EvolverLog()); try { if (!log->init(conf, robotConf, outputDirectory, overwrite, saveAll)) { std::cerr << "Error creating evolver log. Aborting." << std::endl; exitRobogen(EXIT_FAILURE); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; exitRobogen(EXIT_FAILURE); } catch (...) { std::cerr << "non standard exception " << std::endl; exitRobogen(EXIT_FAILURE); } // --------------------------------------- // parse robot from file & initialize population // --------------------------------------- boost::shared_ptr<RobotRepresentation> referenceBot( new RobotRepresentation()); bool growBodies = false; if (conf->evolutionMode == EvolverConfiguration::BRAIN_EVOLVER && conf->referenceRobotFile.compare("") == 0) { std::cerr << "Trying to evolve brain, but no robot file provided." << std::endl; exitRobogen(EXIT_FAILURE); } else if (conf->referenceRobotFile.compare("") != 0) { if (!referenceBot->init(conf->referenceRobotFile)) { std::cerr << "Failed interpreting robot from text file" << std::endl; exitRobogen(EXIT_FAILURE); } } else { //doing body evolution and don't have a reference robot if (referenceBot->init()) { growBodies = true; } else { std::cerr << "Failed creating base robot for body evolution" << std::endl; exitRobogen(EXIT_FAILURE); } } neat = (conf->evolutionaryAlgorithm == EvolverConfiguration::HYPER_NEAT); population.reset(new Population()); if (!population->init(referenceBot, conf->mu, mutator, growBodies, (!(conf->useBrainSeed || neat)) ) ) { std::cerr << "Error when initializing population!" << std::endl; exitRobogen(EXIT_FAILURE); } if (neat) { neatContainer.reset(new NeatContainer(conf, population, seed, rng)); } // --------------------------------------- // open sockets for communication with simulator processes // --------------------------------------- #ifndef EMSCRIPTEN sockets.resize(conf->sockets.size()); for (unsigned int i = 0; i < conf->sockets.size(); i++) { sockets[i] = new TcpSocket; #ifndef FAKEROBOTREPRESENTATION_H // do not bother with sockets when using // benchmark if (!sockets[i]->open(conf->sockets[i].first, conf->sockets[i].second)) { std::cerr << "Could not open connection to simulator" << std::endl; exitRobogen(EXIT_FAILURE); } #endif } #endif // --------------------------------------- // run evolution TODO stopping criterion // --------------------------------------- if(neat) { if(!neatContainer->fillPopulationWeights(population)) { std::cerr << "Filling weights from NEAT failed." << std::endl; exitRobogen(EXIT_FAILURE); } } generation = 1; population->evaluate(robotConf, sockets); }
/** * Set the random seed used by the random functions (Random() and RandInt()). * The seed is casted to a 32-bit integer before being given to the random * number generator, but a size_t is taken as a parameter for API consistency. * * @param seed Seed for the random number generator. */ inline void RandomSeed(const size_t seed) { randGen.seed((uint32_t) seed); srand((unsigned int) seed); }
namespace math /** Miscellaneous math routines. */ { // Annoying Boost versioning issues. #include <boost/version.hpp> #if BOOST_VERSION >= 104700 // Global random object. extern boost::random::mt19937 randGen; // Global uniform distribution. extern boost::random::uniform_01<> randUniformDist; // Global normal distribution. extern boost::random::normal_distribution<> randNormalDist; #else // Global random object. extern boost::mt19937 randGen; #if BOOST_VERSION >= 103900 // Global uniform distribution. extern boost::uniform_01<> randUniformDist; #else // Pre-1.39 Boost.Random did not give default template parameter values. extern boost::uniform_01<boost::mt19937, double> randUniformDist; #endif // Global normal distribution. extern boost::normal_distribution<> randNormalDist; #endif /** * Set the random seed used by the random functions (Random() and RandInt()). * The seed is casted to a 32-bit integer before being given to the random * number generator, but a size_t is taken as a parameter for API consistency. * * @param seed Seed for the random number generator. */ inline void RandomSeed(const size_t seed) { randGen.seed((uint32_t) seed); srand((unsigned int) seed); } /** * Generates a uniform random number between 0 and 1. */ inline double Random() { #if BOOST_VERSION >= 103900 return randUniformDist(randGen); #else // Before Boost 1.39, we did not give the random object when we wanted a // random number; that gets given at construction time. return randUniformDist(); #endif } /** * Generates a uniform random number in the specified range. */ inline double Random(const double lo, const double hi) { #if BOOST_VERSION >= 103900 return lo + (hi - lo) * randUniformDist(randGen); #else // Before Boost 1.39, we did not give the random object when we wanted a // random number; that gets given at construction time. return lo + (hi - lo) * randUniformDist(); #endif } /** * Generates a uniform random integer. */ inline int RandInt(const int hiExclusive) { #if BOOST_VERSION >= 103900 return (int) std::floor((double) hiExclusive * randUniformDist(randGen)); #else // Before Boost 1.39, we did not give the random object when we wanted a // random number; that gets given at construction time. return (int) std::floor((double) hiExclusive * randUniformDist()); #endif } /** * Generates a uniform random integer. */ inline int RandInt(const int lo, const int hiExclusive) { #if BOOST_VERSION >= 103900 return lo + (int) std::floor((double) (hiExclusive - lo) * randUniformDist(randGen)); #else // Before Boost 1.39, we did not give the random object when we wanted a // random number; that gets given at construction time. return lo + (int) std::floor((double) (hiExclusive - lo) * randUniformDist()); #endif } /** * Generates a normally distributed random number with mean 0 and variance 1. */ inline double RandNormal() { return randNormalDist(randGen); } /** * Generates a normally distributed random number with specified mean and * variance. * * @param mean Mean of distribution. * @param variance Variance of distribution. */ inline double RandNormal(const double mean, const double variance) { return variance * randNormalDist(randGen) + mean; } }; // namespace math
worker_input* initialize(double Wi, double Wf, double mu, vector<double>& xi, managed_shared_memory& segment) { SX f = SX::sym("f", 2 * L * dim); SX dU = SX::sym("dU", L); SX J = SX::sym("J", L); SX U0 = SX::sym("U0"); U0 = UW(Wi); for (int i = 0; i < L; i++) { J[i] = JWij(Wi * xi[i], Wi * xi[mod(i + 1)]); dU[i] = UW(Wi * xi[i]) - U0; } SX E = energy(f, J, U0, dU, mu).real(); SX g = SX::sym("g", L); for (int i = 0; i < L; i++) { g[i] = 0; for (int n = 0; n < dim; n++) { g[i] += f[2 * (i * dim + n)] * f[2 * (i * dim + n)] + f[2 * (i * dim + n) + 1] * f[2 * (i * dim + n) + 1]; } } SXFunction nlp("nlp", nlpIn("x", f), nlpOut("f", E, "g", g)); NlpSolver solver("solver", "ipopt", nlp, make_dict("hessian_approximation", "limited-memory", "linear_solver", "ma86", "print_level", 0, "print_time", false, "obj_scaling_factor", 1)); boost::random::mt19937 rng; boost::random::uniform_real_distribution<> uni(-1, 1); vector<double> xrand(2 * L*dim, 1); rng.seed(); for (int i = 0; i < 2 * L * dim; i++) { xrand[i] = uni(rng); } map<string, DMatrix> arg; arg["lbx"] = -1; arg["ubx"] = 1; arg["x0"] = xrand; arg["lbg"] = 1; arg["ubg"] = 1; map<string, DMatrix> res = solver(arg); vector<double> x0 = res["x"].nonzeros(); // vector<double> x0 = xrand; // cout << "x0 = " << ::math(x0) << endl; // cout << "E0 = " << ::math(res["f"].toScalar()) << endl; vector<complex<double>> x0i(dim); for (int i = 0; i < L; i++) { for (int n = 0; n <= nmax; n++) { x0i[n] = complex<double>(x0[2 * (i * dim + n)], x0[2 * (i * dim + n) + 1]); } double nrm = sqrt(abs(dot(x0i, x0i))); for (int n = 0; n <= nmax; n++) { x0[2 * (i * dim + n)] /= nrm; x0[2 * (i * dim + n) + 1] /= nrm; } } // cout << "nlp: " << ::math(nlp(vector<DMatrix>{x0, vector<double>()})[0].toScalar()) << endl; void_allocator void_alloc(segment.get_segment_manager()); worker_input* input = segment.construct<worker_input>("input")(void_alloc); input->U0 = UW(Wi); for (int i = 0; i < L; i++) { input->J0.push_back(JWij(Wi * xi[i], Wi * xi[mod(i + 1)])); } for (int i = 0; i < 2 * L * dim; i++) { input->x0.push_back(x0[i]); } for (int i = 0; i < L; i++) { complex_vector f0i(dim, void_alloc); for (int n = 0; n <= nmax; n++) { f0i[n] = complex<double>(x0[2 * (i * dim + n)], x0[2 * (i * dim + n) + 1]); } input->f0.push_back(f0i); } input->Wi = Wi; input->Wf = Wf; input->mu = mu; for (int i = 0; i < L; i++) { input->xi.push_back(xi[i]); } return input; }
int main(int argc, char** argv) { build_odes(); return 0; // build_odes(); // return 0; ptime begin = microsec_clock::local_time(); random::mt19937 rng; random::uniform_real_distribution<> uni(-1, 1); int seed = lexical_cast<int>(argv[1]); if (seed != -1) { double Wi = lexical_cast<double>(argv[2]); double Wf = lexical_cast<double>(argv[3]); double mu = lexical_cast<double>(argv[4]); double Ui = UWi(Wi); double D = lexical_cast<double>(argv[5]); double taui = lexical_cast<double>(argv[6]); double tauf = lexical_cast<double>(argv[7]); int ntaus = lexical_cast<int>(argv[8]); int numthreads = lexical_cast<int>(argv[9]); int resi = lexical_cast<int>(argv[10]); // int integrator = lexical_cast<int>(argv[11]); std::string intg = argv[11]; double dt = lexical_cast<double>(argv[12]); #ifdef AMAZON // path resdir("/home/ubuntu/Results/Canonical Transformation Dynamical Gutzwiller"); path resdir("/home/ubuntu/Dropbox/Amazon EC2/Simulation Results/CTDG"); #else path resdir("/Users/Abuenameh/Documents/Simulation Results/Canonical Transformation Dynamical Gutzwiller 2"); // path resdir("/Users/Abuenameh/Documents/Simulation Results/Dynamical Gutzwiller Hartmann Comparison"); #endif if (!exists(resdir)) { cerr << "Results directory " << resdir << " does not exist!" << endl; exit(1); } ostringstream oss; oss << "res." << resi << ".txt"; path resfile = resdir / oss.str(); //#ifndef AMAZON while (exists(resfile)) { resi++; oss.str(""); oss << "res." << resi << ".txt"; resfile = resdir / oss.str(); } //#endif if (seed < 0) { resi = seed; oss.str(""); oss << "res." << resi << ".txt"; resfile = resdir / oss.str(); } vector<double> xi(L, 1); rng.seed(seed); if (seed > -1) { for (int j = 0; j < L; j++) { xi[j] = (1 + D * uni(rng)); } } // double Ui = UWi(Wi); double mui = mu * Ui; filesystem::ofstream os(resfile); printMath(os, "int", resi, intg); printMath(os, "seed", resi, seed); printMath(os, "Delta", resi, D); printMath(os, "dt", resi, dt); printMath(os, "mures", resi, mui); printMath(os, "Ures", resi, Ui); printMath(os, "xires", resi, xi); os << flush; printMath(os, "Wires", resi, Wi); printMath(os, "Wfres", resi, Wf); os << flush; cout << "Res: " << resi << endl; struct shm_remove { shm_remove() { shared_memory_object::remove("SharedMemory"); } ~shm_remove() { shared_memory_object::remove("SharedMemory"); } } remover; int size = 1000 * (sizeof (worker_input) + numthreads * (sizeof (worker_tau) + sizeof (worker_output))); //2 * (((2 * L * dim + L + 1) + numthreads * (4 * L * dim + 5 * L + 6)) * sizeof (double) +numthreads * 2 * sizeof (ptime)/*sizeof(time_period)*/); managed_shared_memory segment(create_only, "SharedMemory", size); worker_input* w_input = initialize(Wi, Wf, mui, xi, segment); // return 0; void_allocator void_alloc(segment.get_segment_manager()); char_string integrator(intg.begin(), intg.end(), void_alloc); w_input->integrator = integrator; w_input->dt = dt; queue<input> inputs; if (ntaus == 1) { input in; in.tau = taui; inputs.push(in); } else { for (int i = 0; i < ntaus; i++) { input in; double tau = taui + i * (tauf - taui) / (ntaus - 1); in.tau = tau; inputs.push(in); } } vector<results> res; progress_display progress(inputs.size()); thread_group threads; for (int i = 0; i < numthreads; i++) { threads.create_thread(bind(&threadfunc, argv[0], tauf, boost::ref(inputs), boost::ref(res), boost::ref(progress), i, boost::ref(segment))); } threads.join_all(); vector<double> taures; vector<double> Eires; vector<double> Efres; vector<double> Qres; vector<double> pres; vector<vector<double>> Esres; vector<vector<complex<double>>> b0res; vector<vector<complex<double>>> bfres; // vector<complex_vector_vector> f0res; vector<vector < vector<complex<double>>>> ffres; vector<std::string> runtimeres; for (results& ires : res) { taures.push_back(ires.tau); Eires.push_back(ires.Ei); Efres.push_back(ires.Ef); Qres.push_back(ires.Q); pres.push_back(ires.p); // Esres.push_back(ires.Es); b0res.push_back(ires.b0); bfres.push_back(ires.bf); runtimeres.push_back(replace_all_copy(ires.runtime, "\"", "\\\"")); // vector<double> Es(ires.Es.begin(), ires.Es.end()); // Esres.push_back(Es); // vector<complex<double>> b0(ires.b0.begin(), ires.b0.end()); // vector<complex<double>> bf(ires.bf.begin(), ires.bf.end()); // b0res.push_back(b0); // bfres.push_back(bf); // f0res.push_back(ires.f0); ffres.push_back(ires.ff); // std::string runtime(ires.runtime.begin(), ires.runtime.end()); // runtimeres.push_back(replace_all_copy(runtime, "\"", "\\\"")); } printMath(os, "taures", resi, taures); printMath(os, "Eires", resi, Eires); printMath(os, "Efres", resi, Efres); printMath(os, "Qres", resi, Qres); printMath(os, "pres", resi, pres); printMath(os, "U0res", resi, w_input->U0); printMath(os, "J0res", resi, w_input->J0); printMath(os, "Esres", resi, Esres); printMath(os, "b0res", resi, b0res); printMath(os, "bfres", resi, bfres); printMath(os, "f0res", resi, w_input->f0); // printMath(os, "f0res", resi, f0res); printMath(os, "ffres", resi, ffres); printMath(os, "runtime", resi, runtimeres); ptime end = microsec_clock::local_time(); time_period period(begin, end); cout << endl << period.length() << endl << endl; os << "totalruntime[" << resi << "]=\"" << period.length() << "\";" << endl; segment.destroy<worker_input>("input"); } else { managed_shared_memory segment(open_only, "SharedMemory"); worker_input* input = segment.find<worker_input>("input").first; worker_tau* tau = segment.find<worker_tau>(argv[2]).first; worker_output* output = segment.find<worker_output>(argv[3]).first; worker(input, tau, output, segment); } return 0; }
void reset(int min, int max, int seed) { dist = boost::random::uniform_int_distribution<>(min, max); gen.seed(seed); }
void seedrand() { randfast.seed(time(0)); randfast64.seed(time(0)); }
int main(int argc, char **argv) { time_t tim; time(&tim); RAND.seed(tim); TCODConsole::initRoot(SCREEN_W,SCREEN_H,"libtcod",false); int messagesWinHeight = 8; int messagesWinWidth = SCREEN_W; int statusWinHeight = SCREEN_H - messagesWinHeight; int statusWinWidth = 21; DUNGEON_WIN_H = statusWinHeight; DUNGEON_WIN_W = SCREEN_W - statusWinWidth; Level level(DUNGEON_WIN_W,DUNGEON_WIN_H,statusWinWidth,statusWinHeight ,messagesWinWidth,messagesWinHeight); level.generate(); level.m_player->customize(); level.update(); while ( !TCODConsole::isWindowClosed() ) { TCODConsole::root->clear(); level.render(); TCODConsole::flush(); if(level.m_player->m_running){ level.m_player->run(); level.update(); } else{ TCOD_key_t key = TCODConsole::waitForKeypress(true); if(key.pressed){ if(!level.m_playerAlive){ return 0; } else{ switch(key.c) { case 'S' : return 0; case 'q' : level.m_player->doQuaff();break; case 'h' : level.m_player->walk(-1,0); break; case 'j' : level.m_player->walk(0,1); break; case 'k' : level.m_player->walk(0,-1); break; case 'l' : level.m_player->walk(1,0); break; case 'y' : level.m_player->walk(-1,-1); break; case 'u' : level.m_player->walk(1,-1); break; case 'b' : level.m_player->walk(-1,1); break; case 'n' : level.m_player->walk(1,1); break; case 'H' : level.m_player->startRun(-1,0); break; case 'J' : level.m_player->startRun(0,1); break; case 'K' : level.m_player->startRun(0,-1); break; case 'L' : level.m_player->startRun(1,0); break; case 'Y' : level.m_player->startRun(-1,-1); break; case 'U' : level.m_player->startRun(1,-1); break; case 'B' : level.m_player->startRun(-1,1); break; case 'N' : level.m_player->startRun(1,1); break; case 'i': level.m_player->showInventory(); break; case '.': level.m_player->act(); break; case 'g': level.m_player->doPickUp(); break; case 'f': level.m_player->doFire(); break; case 'o': level.m_player->doOpen(); break; case 'Q': level.m_player->doQuiver(); break; case 'w': level.m_player->doWield(); break; case 'd': level.m_player->doDrop(); break; case '1': level.m_player->invokeAbility(0); break; case '2': level.m_player->invokeAbility(1); break; case '3': level.m_player->invokeAbility(2); break; case '>': level.m_player->goDown(); break; case '<': level.m_player->goUp(); break; /*case 'D': DEBUG = !DEBUG; if(DEBUG) level.m_messages->showMessage("DEBUG MODE ON",MESSAGE_WARNING); else level.m_messages->showMessage("DEBUG MODE OFF",MESSAGE_WARNING); break; case '-' : level.m_player->m_hp--; break; case '+' : level.m_player->m_hp++; break; case 'z' : level.m_player->gainExp(300); break; case 'r': level.generate(); break; */ default: break; } if(level.m_playerWon){ return 0; } if(level.m_player->m_time > 0.0f){ level.update(); } } } } } }