NeuroAndSimEvaluationBaseApplication::NeuroAndSimEvaluationBaseApplication() : EvaluationBaseApplication() { Physics::install(); new ControllerFitnessFunctionParser(dynamic_cast<ControllerProvider*>(Physics::getPhysicsManager())); CommandLineArgument *mPlayArgument = new CommandLineArgument("playKeyFrames", "play", "<agent> <file>", "Loads keyframe file <file> and starts to playback the keyframes on agent <agent>", 2, 0, true); QStringList files = mPlayArgument->getEntries(); for(int i = 0; i < files.size(); ++i) { QStringList args = files.at(i).split(" "); if(args.size() == 2) { QString keyFrameTarget(args.at(0)); QString keyFrameFileName(args.at(1)); KeyFramePlayer *player = new KeyFramePlayer(keyFrameTarget); player->setKeyFrameFile(keyFrameFileName); } else { cerr << "Warning: Size was " << args.size() << endl; } } }
/** * Standard constructor. */ PhysicsManager::PhysicsManager() : mPhysicalSimulationAlgorithm(0), mCollisionManager(0), mSynchronizeObjectsWithPhysicalModel(true), mNextStepEvent(0), mCompletedNextStepEvent(0), mResetEvent(0), mResetFinalizedEvent(0), mResetSettingsEvent(0), mResetSettingsTerminatedEvent(0), mInitialResetDone(false), mCurrentSimulationTime(0), mCurrentRealTime(0), mCurrentStep(0), mResetDuration(0), mStepExecutionDuration(0), mPhysicalStepDuration(0), mSynchronizationDuration(0), mPostStepDuration(0), mCollisionHandlingDuration(0), mDisablePhysics(0), mResetMutex(QMutex::Recursive) { EventManager *em = Core::getInstance()->getEventManager(); //make sure these events are created right at the beginning (required for morphology evolution) em->getEvent(NerdConstants::EVENT_EXECUTION_RESET_SETTINGS, true); em->getEvent(NerdConstants::EVENT_EXECUTION_RESET_SETTINGS_COMPLETED, true); mPhysicsEnvironmentChangedEvent = em->createEvent( SimulationConstants::EVENT_PHYSICS_ENVIRONMENT_CHANGED); CommandLineArgument *switchXZArg = new CommandLineArgument("switchYZAxis", "switchYZAxis", "", "The y-axis now means height, so that the position of a robot in the plane is (x,z).", 0, 0, true, false); bool switchXZ = switchXZArg->getNumberOfEntries() > 0 ? false : true; mSwitchYZAxes = new BoolValue(switchXZ); mSwitchYZAxes->setDescription("Changes the XYZ space to a XZY space, so that X and Y are in the plain."); Core::getInstance()->getValueManager()->addValue(SimulationConstants::VALUE_SWITCH_YZ_AXES, mSwitchYZAxes); mDisablePhysics = new BoolValue(false); mDisablePhysics->setDescription("If true, then the physical simulation is skipped and no update or resets of the physics takes place."); Core::getInstance()->getValueManager()->addValue(SimulationConstants::VALUE_DISABLE_PHYSICS, mDisablePhysics); }
bool NeuroAndSimEvaluationStandardGuiApplication::setupGui() { //Register command line argument descriptions to the PlugInManager to support //switching the GUI on and off CommandLineArgument *guiArgument = new CommandLineArgument( "enableGui", "gui", "", "Starts the application with graphical user interface.", 0, 0, true); CommandLineArgument *noGuiArgument = new CommandLineArgument( "disableGui", "nogui", "", "Starts the application without graphical user interface.", 0, 0, true); if(noGuiArgument->getParameterValue()->get() != "") { mEnableGui = false; } if(guiArgument->getParameterValue()->get() != "") { mEnableGui = true; } if(mEnableGui) { mGuiMainWindow = new GuiMainWindow(mEnableControl, mEnableDebugging); connect(this, SIGNAL(showGui()), mGuiMainWindow, SLOT(showWindow())); } return true; }
bool NerdClusterNeuroEvoApplication::setupGui() { bool enableGui = true; CommandLineArgument *guiArgument = new CommandLineArgument( "enableGui", "gui", "", "Starts the application with graphical user interface.", 0, 0, true); CommandLineArgument *noGuiArgument = new CommandLineArgument( "disableGui", "nogui", "", "Starts the application without graphical user interface.", 0, 0, true); if(noGuiArgument->getParameterValue()->get() != "") { enableGui = false; } if(guiArgument->getParameterValue()->get() != "") { enableGui = true; } if(enableGui) { mMainGui = new SimpleEvolutionMainWindow(true); OnlineFitnessPlotter *plotterButton = new OnlineFitnessPlotter(); mMainGui->getMenu("Evolution")->addAction(plotterButton->getAction()); new EvolutionPropertyPanelCollection(mMainGui->getMenu("Evolution"), "Evolution Parameters", true); connect(this, SIGNAL(showGui()), mMainGui, SLOT(show())); } return true; }
const string SuperComponent::checkForCommandLinePassedConfigurationFileOrDefaultConfigurationFile(const int &argc, char **argv) { string configurationFile = "configuration"; CommandLineParser cmdParser; cmdParser.addCommandLineArgument("configuration"); cmdParser.parse(argc, argv); CommandLineArgument cmdArgumentCONFIGURATION = cmdParser.getCommandLineArgument("configuration"); // Check the centrally maintained managed level. if (cmdArgumentCONFIGURATION.isSet()) { configurationFile = cmdArgumentCONFIGURATION.getValue<string>(); core::strings::StringToolbox::trim(configurationFile); } return configurationFile; }
int main(int argc, char** argv) { /* Step 0 */ if (!cmd_arguments.ParseCommandLineArgument(argc, argv)) return -1; /* Step 1 */ std::cout << "Load pcd file ...\n"; pcl::io::loadPCDFile(cmd_arguments.raw_pcd_, *cloud); std::cout << "Before resample, #points = " << cloud->points.size() << std::endl; std::cout << "Resample ...\n"; pcl::PointCloud<pcl::PointXYZ>::Ptr sample(new pcl::PointCloud<pcl::PointXYZ>); // create the filtering object pcl::VoxelGrid<pcl::PointXYZ> grid; grid.setInputCloud(cloud); //grid.setLeafSize(size_x, size_y, size_z); grid.setLeafSize(cmd_arguments.resample_resolution_[0],cmd_arguments.resample_resolution_[1], cmd_arguments.resample_resolution_[2]); grid.filter(*sample); /* Step 2 */ std::cout << "After resample, #points = " << sample->points.size() << std::endl; std::cout << "Saving ...\n"; pcl::io::savePCDFile(cmd_arguments.raw_pcd_, *sample); return 0; }
bool NerdNeuroEvoApplication::setupGui() { CommandLineArgument *guiArgument = new CommandLineArgument( "enableGui", "gui", "", "Starts the application with graphical user interface.", 0, 0, true); CommandLineArgument *noGuiArgument = new CommandLineArgument( "disableGui", "nogui", "", "Starts the application without graphical user interface.", 0, 0, true); if(noGuiArgument->getParameterValue()->get() != "") { mEnableGui = false; } if(guiArgument->getParameterValue()->get() != "") { mEnableGui = true; } if(mEnableGui) { mGuiMainWindow = new GuiMainWindow(true, true); connect(this, SIGNAL(showGui()), mGuiMainWindow, SLOT(showWindow())); OnlineFitnessPlotter *plotterButton = new OnlineFitnessPlotter(); mGuiMainWindow->getMenu("Evolution")->addAction(plotterButton->getAction()); EvolutionProgressBar *progressBar = new EvolutionProgressBar(); mGuiMainWindow->addWidget(progressBar); MultiplePopulationOverviewWindowWidget *overview = new MultiplePopulationOverviewWindowWidget(); overview->getAction()->setShortcut(tr("Ctrl+Shift+p")); mGuiMainWindow->getMenu("Evolution")->addAction(overview->getAction()); EvolutionPropertyPanelCollection(mGuiMainWindow->getMenu("Evolution"), "Evolution Parameters"); BoolValueSwitcherAction *runEvolutionButton = new BoolValueSwitcherAction("&Run Evolution", EvolutionConstants::VALUE_EVO_RUN_EVOLUTION); runEvolutionButton->setShortcut(tr("Ctrl+e")); mGuiMainWindow->getMenu("Evolution")->addAction(runEvolutionButton); NetworkEditorCollection(mGuiMainWindow->getMenu("Tools"), "Network Editor"); } return true; }
NerdBaseApplication::NerdBaseApplication(int argc, char *argv[], bool enableGui) : BaseApplication(), mSeedCommunication(0), mEnableGui(enableGui), mServerPort(45454) { for(int i = 0; i < argc; ++i) { QString flag(argv[i]); flag = flag.trimmed(); if((flag.compare("-port") == 0 || flag.compare("-p") == 0) && (i < (argc - 1))) { QString portValue(argv[i + 1]); ++i; bool ok = false; int port = portValue.toInt(&ok); if(ok) { mServerPort = port; } else { qDebug("Could not parse the port!"); } } } CommandLineArgument *guiArgument = new CommandLineArgument( "enableGui", "gui", "", "Starts the application with graphical user interface.", 0, 0, true); CommandLineArgument *noGuiArgument = new CommandLineArgument( "disableGui", "nogui", "", "Starts the application without graphical user interface.", 0, 0, true); if(noGuiArgument->getParameterValue()->get() != "") { mEnableGui = false; } if(guiArgument->getParameterValue()->get() != "") { mEnableGui = true; } }
bool NerdMultiCoreEvaluationApplication::setupApplication() { bool ok = true; CommandLineArgument *evalNameArg = new CommandLineArgument("name", "name", "<evalName>", "The name of this evaluation process.", 1, 0, true, true); if(evalNameArg->getEntries().size() > 0) { QStringList params = evalNameArg->getEntryParameters(0); mEvaluationName = params.at(0); } mRunner = new MultiCoreEvaluationRunner(); Core::log("EvaluationName: " + mEvaluationName, true); return ok; }
OSP_BaseApplication::OSP_BaseApplication() : BaseApplication(), mSeedCommunication(0), mServerPort(45454) { CommandLineArgument *portArgument = new CommandLineArgument("port", "p", "<port>", "Sets the port of the OSP server. ", 1, 0, true); QStringList params = portArgument->getParameters(); if(params.size() > 0) { bool ok = false; int port = params.at(0).toInt(&ok); if(ok) { mServerPort = port; } else { Core::log("OSP_BaseApplication: Could not parse the port!"); } } }
/** * Constructs a new NeuralNetworkEditorApplication. */ NetworkDynamicsPlotterApplication::NetworkDynamicsPlotterApplication() : BaseApplication(), mExecutionLoop(0), mEnableSimulator(false) { mName = "NeuralNetworkApplication"; //Add statis mode value to allow the plotters to prevent network modifications in the editor //while the plots are calculated. BoolValue *stasisModeValue = new BoolValue(true); Core::getInstance()->getValueManager()->addValue( EvolutionConstants::VALUE_EVO_STASIS_MODE, stasisModeValue); //Check if the physical simulator is enabled. CommandLineArgument *simArg = new CommandLineArgument("useSimulator", "sim", "", "Enables the physical simulator.", 0, 0, true, true); if(simArg->getNumberOfEntries() > 0) { mEnableSimulator = true; } Physics::install(); }
bool CollisionManager::bind() { CommandLineArgument *printCollisionRulePrototypesArg = new CommandLineArgument( "collisionRulePrototypes", "colp", "", "Displays a list with all available collision rule prototypes", 0, 0, false, false); CommandLineArgument *printCollisionRulesArg = new CommandLineArgument( "collisionRules", "col", "", "Displays a list with all available collision rules that have been registered up to the binding phase.", 0, 0, false, false); if(printCollisionRulePrototypesArg->getNumberOfEntries() > 0) { printCollisionRulePrototypes(); } if(printCollisionRulesArg->getNumberOfEntries() > 0) { printCollisionRules(); } return true; }
/** * Constructs a new UniversalNeuroScriptLoader. */ UniversalNeuroScriptLoader::UniversalNeuroScriptLoader() { CommandLineArgument *scriptLoaderArgument = new CommandLineArgument( "installScript", "is", "<ScriptName> [<ScriptFileName> <TriggerEvent> <ResetEvent> <AgentInterface>]", QString("Installs a new script with name <ScriptName>, that loads file <ScriptFileName> ") + "during the bind phase. The script is reset by <ResetEvent> and executed each " + "time <TriggerEvent> is triggered.\nThe <AgentInterface> " + "specifies the agents whose neural network can be changed.", 1, 4, true); QList<QString> scriptNames; int numberOfScriptsToInstall = scriptLoaderArgument->getNumberOfEntries(); for(int i = 0; i < numberOfScriptsToInstall; ++i) { QList<QString> entryParams = scriptLoaderArgument->getEntryParameters(i); QString name = entryParams.at(0); QString fileName = ""; if(entryParams.size() > 1) { fileName = entryParams.at(1); } QString triggerEvent = ""; if(entryParams.size() > 2) { triggerEvent = entryParams.at(2); } QString resetEvent = ""; if(entryParams.size() > 3) { resetEvent = entryParams.at(3); } QString agentName = ""; if(entryParams.size() > 4) { agentName = entryParams.at(4); } if(name != "" && !scriptNames.contains(name)) { new UniversalNeuroScriptingContext(name, fileName, triggerEvent, resetEvent, agentName); scriptNames.append(name); Core::log("UniversalScriptLoader: Installed UniversalScriptingContext [" + name + "]"); } } }
/** * Initializes the FitnessManager. */ bool FitnessManager::init() { bool initOk = true; //print names of FitnessFunctionPrototypes if required CommandLineArgument *printFitnessFunctionsArgument = new CommandLineArgument("fitnessPrototypes", "fitnessPrototypes", "", "Prints the names of all available FitnessFunction prototypes.", 0, 0, false, false); printFitnessFunctionsArgument->setProperty("debug"); if(printFitnessFunctionsArgument->getNumberOfEntries() > 0) { cerr << "FitnessFunction Prototypes: " << endl << "-----------------------------" << endl; QList<FitnessFunction*> prototypes = mFitnessFunctionPrototypes.values(); for(QListIterator<FitnessFunction*> i(prototypes); i.hasNext();) { FitnessFunction *ff = i.next(); cerr << " > " << ff->getName().toStdString().c_str() << endl; } } return initOk; }
int run_image_mode(const Configuration &cfg, const CommandLineArgument<std::string> &image_argument, const CommandLineArgument<std::string> &landmarks_argument) { FaceTracker * tracker = LoadFaceTracker(cfg.model_pathname.c_str()); FaceTrackerParams *tracker_params = LoadFaceTrackerParams(cfg.params_pathname.c_str()); cv::Mat image; cv::Mat_<uint8_t> gray_image = load_grayscale_image(image_argument->c_str(), &image); int result = tracker->NewFrame(gray_image, tracker_params); std::vector<cv::Point_<double> > shape; std::vector<cv::Point3_<double> > shape3; Pose pose; if (result >= cfg.tracking_threshold) { shape = tracker->getShape(); shape3 = tracker->get3DShape(); pose = tracker->getPose(); } if (!have_argument_p(landmarks_argument)) { display_data(cfg, image, shape, pose); } else if (shape.size() > 0) { if (cfg.save_3d_points) save_points3(landmarks_argument->c_str(), shape3); else save_points(landmarks_argument->c_str(), shape); } delete tracker; delete tracker_params; return 0; }
MultiCoreEvaluationRunner::MultiCoreEvaluationRunner() : mDoShutDown(false), mShutDownEvent(0), mMessageValue(0), mMinIndex(-1), mMaxIndex(-1) { connect(this, SIGNAL(quitMainApplication()), QCoreApplication::instance(), SLOT(quit())); mMessageValue = new StringValue(""); mMessageValue->setNotifyAllSetAttempts(true); Core::getInstance()->getValueManager()->addValue( "/Evaluation/Messages", mMessageValue); mNumberOfProcesses = new IntValue(4); Core::getInstance()->getValueManager()->addValue( "/Evaluation/NumberOfProcesses", mNumberOfProcesses); CommandLineArgument *jobFileNameArg = new CommandLineArgument("scriptFile", "scriptFile", "<absoluteFileName>", "The name of the main evaluation script", 1, 0, true, true); if(jobFileNameArg->getEntries().size() > 0) { QStringList jobScriptName = jobFileNameArg->getEntryParameters(0); if(jobScriptName.size() > 0) { mJobFile = jobScriptName.at(0); } } CommandLineArgument *indicesArg = new CommandLineArgument("index", "index", "<minIndex> [<maxIndex]", "The working directory indices to evaluate.\n" "If maxIndex is ommited, then only a single evaluation takes place.", 1, 1, true, true); if(indicesArg->getEntries().size() > 0) { QStringList indicesList = indicesArg->getEntryParameters(0); if(indicesList.size() > 0) { bool ok = true; int index = indicesList.at(0).toInt(&ok); if(ok && index >= 0) { mMinIndex = index; } } if(indicesList.size() > 1) { bool ok = true; int index = indicesList.at(1).toInt(&ok); if(ok && index >= 0 && index >= mMinIndex) { mMaxIndex = index; } } else { mMaxIndex = mMinIndex; } } Core::getInstance()->addSystemObject(this); }
int main (int argc, char** argv) { /* Step 0 */ if (!cmd_arguments.ParseCommandLineArgument(argc, argv)) return -1; /* Step 1 */ cout << "\n=========== Load raw building point cloud ... ==================\n"; pcl::io::loadPCDFile(cmd_arguments.raw_pcd_, *build_cloud_raw); /* Step 2 */ cout << "\n=========== Extract the building plane ... ==================\n"; ExtractBuildPlane(); /* Step 3 */ cout << "\n=========== Showing the building plane ... ==================\n"; ShowCloud(); }
bool NerdNeuroSimApplication::setupApplication() { //install simulation recorder new NetworkSimulationRecorder(); // StandardConstraintCollection(); // StandardNeuralNetworkFunctions(); NeuroAndSimEvaluationStandardGuiApplication::setupApplication(); //Install network characterization new NeuralNetworkAttributes(); //Choose Physics Engine (or external Yars simulator) CommandLineArgument *physicsArg = new CommandLineArgument("physics", "p", "<physicsLibrary>", "Uses <physicsLibrary> as physics engine. " "Currently there are [ode, yars].", 1,0, true); if(physicsArg->getNumberOfEntries() != 0 && !physicsArg->getEntryParameters(0).empty() && physicsArg->getEntryParameters(0).at(0).trimmed() == "yars") { YarsCommunication(); } else if(physicsArg->getNumberOfEntries() != 0 && !physicsArg->getEntryParameters(0).empty() && physicsArg->getEntryParameters(0).at(0).trimmed() == "s2d") { Simple2D_Physics(); } else { //install ODE PhysicsLayer ODE_Physics(); } new StepsPerSecondCounter(); EvolutionSimulationPrototypes(); //install file parser new SimpleObjectFileParser(); //install neural network control parser. new NetworkAgentControlParser(); new ActivationFrequencyCalculator("A"); //add motor model rotation new ModelParameterRotator(); //Install neuro modules NeuroModuleCollection(); StandardTagCollection(); //Enable NeuroModulation NeuroModulatorManager::getInstance(); Fitness::install(); new FitnessLogger(); NeuroFitnessPrototypes(); Statistics::getStatisticsManager(); UniversalNeuroScriptLoader(); ScriptedModelLoader(); //Add plugin to calculate the open degrees of freedom of the network during evolution. new NetworkDegreeOfFreedomCalculator(); //add simple fitness logger CommandLineArgument *useSimpleFitnessLogger = new CommandLineArgument("simpleFitnessLogger", "sfl", "<logfile name>", "Logs all fitness values of all fitness functions " "incrementally to a file.", 1, 0, true, false); if(useSimpleFitnessLogger->getNumberOfEntries() != 0 && !useSimpleFitnessLogger->getEntryParameters(0).empty()) { new SimpleFitnessLogger(useSimpleFitnessLogger->getEntryParameters(0).at(0)); } else if(NerdConstants::HackMode == true) { //HACK MODE remove! new SimpleFitnessLogger("simpleFitnessLog.txt"); } return true; }
bool JanEvolution::buildEvolutionSystem() { World *world = new World("Main"); Population *population = new Population("HumanoidControllers"); world->addPopulation(population); IdentityGenotypePhenotypeMapper *mapper = new IdentityGenotypePhenotypeMapper(); population->setGenotypePhenotypeMapper(mapper); new ENS3EvolutionAlgorithm(world); world->setEvaluationMethod(new LocalNetworkInSimulationEvaluationMethod()); Evolution::getEvolutionManager()->addEvolutionWorld(world); //Add statistics calculator. Statistics::getStatisticsManager()->addGenerationStatistics( new BasicNeuralNetworkStatistics(*population)); FitnessFunction *fitness = 0; CommandLineArgument *fitnessFunctionArg = new CommandLineArgument( "fitness", "fit", "<prototypeName> <fitnessFunctionName>", "Creates a copy of <prototypeName> and uses it for the population" " with the given <fitnessFunctionName>.", 2, 0, true); QList<QString> fitArguments = fitnessFunctionArg->getEntryParameters(0); if(fitArguments.size() > 1) { fitness = Fitness::getFitnessManager() ->createFitnessFunctionFromPrototype(fitArguments.at(0), fitArguments.at(1)); if(fitness == 0) { cerr << "Failed to create FitnessFunction prototype [" << fitArguments.at(0).toStdString().c_str() << endl; } } if(fitness == 0) { fitness = Fitness::getFitnessManager() ->createFitnessFunctionFromPrototype("Script", "Script"); } population->addFitnessFunction(fitness); TournamentSelectionMethod *tournament = new TournamentSelectionMethod(5); PoissonDistributionRanking *poissonDistribution = new PoissonDistributionRanking(); population->addSelectionMethod(tournament); population->addSelectionMethod(poissonDistribution); tournament->setResponsibleFitnessFunction(fitness); poissonDistribution->setResponsibleFitnessFunction(fitness); poissonDistribution->getPopulationProportion()->set(0.0); //add individual statistics StandardIndividualStatistics indStatistics(population); NeuralNetworkIndividualStatistics neuroStatistics(population); return true; }
int run_video_mode(const Configuration &cfg, const CommandLineArgument<std::string> &image_argument, const CommandLineArgument<std::string> &landmarks_argument) { FaceTracker *tracker = LoadFaceTracker(cfg.model_pathname.c_str()); FaceTrackerParams *tracker_params = LoadFaceTrackerParams(cfg.params_pathname.c_str()); assert(tracker); assert(tracker_params); cv::VideoCapture input(image_argument->c_str()); if (!input.isOpened()) throw make_runtime_error("Unable to open video file '%s'", image_argument->c_str()); cv::Mat image; std::vector<char> pathname_buffer; pathname_buffer.resize(1000); input >> image; int frame_number = 1; while ((image.rows > 0) && (image.cols > 0)) { if (cfg.verbose) { printf(" Frame number %d\r", frame_number); fflush(stdout); } cv::Mat_<uint8_t> gray_image; if (image.type() == cv::DataType<cv::Vec<uint8_t,3> >::type) cv::cvtColor(image, gray_image, CV_BGR2GRAY); else if (image.type() == cv::DataType<uint8_t>::type) gray_image = image; else throw make_runtime_error("Do not know how to convert video frame to a grayscale image."); int result = tracker->Track(gray_image, tracker_params); std::vector<cv::Point_<double> > shape; std::vector<cv::Point3_<double> > shape3D; Pose pose; if (result >= cfg.tracking_threshold) { shape = tracker->getShape(); shape3D = tracker->get3DShape(); pose = tracker->getPose(); } else { tracker->Reset(); } if (!have_argument_p(landmarks_argument)) { display_data(cfg, image, shape, pose); } else if (shape.size() > 0) { snprintf(pathname_buffer.data(), pathname_buffer.size(), landmarks_argument->c_str(), frame_number); if (cfg.save_3d_points) save_points3(pathname_buffer.data(), shape3D); else save_points(pathname_buffer.data(), shape); if (cfg.verbose) display_data(cfg, image, shape, pose); } else if (cfg.verbose) { display_data(cfg, image, shape, pose); } input >> image; frame_number++; } delete tracker; delete tracker_params; return 0; }
void AbstractCIDModule::parseCommandLine(const int32_t &argc, char **argv) throw (InvalidArgumentException) { if (argc <= 1) { errno = 0; OPENDAVINCI_CORE_THROW_EXCEPTION(InvalidArgumentException, "Invalid number of arguments. At least a conference group id (--cid=) needed."); } CommandLineParser cmdParser; cmdParser.addCommandLineArgument("id"); cmdParser.addCommandLineArgument("cid"); cmdParser.addCommandLineArgument("freq"); cmdParser.addCommandLineArgument("verbose"); cmdParser.addCommandLineArgument("profiling"); cmdParser.parse(argc, argv); CommandLineArgument cmdArgumentID = cmdParser.getCommandLineArgument("id"); CommandLineArgument cmdArgumentCID = cmdParser.getCommandLineArgument("cid"); CommandLineArgument cmdArgumentFREQ = cmdParser.getCommandLineArgument("freq"); CommandLineArgument cmdArgumentVERBOSE = cmdParser.getCommandLineArgument("verbose"); CommandLineArgument cmdArgumentPROFILING = cmdParser.getCommandLineArgument("profiling"); if (cmdArgumentID.isSet()) { m_identifier = cmdArgumentID.getValue<string>(); } if (cmdArgumentFREQ.isSet()) { m_frequency = cmdArgumentFREQ.getValue<float>(); if ( fabs(m_frequency) < 1e-5 ) { errno = 0; OPENDAVINCI_CORE_THROW_EXCEPTION(InvalidArgumentException, "Runtime frequency must be greater than 0."); } } else { clog << "No runtime frequency set. Assuming a frequency of 1 Hz." << endl; } if (cmdArgumentCID.isSet()) { m_CID = cmdArgumentCID.getValue<int>(); if ( (m_CID <= 1) || (m_CID >= 254) ) { errno = 0; OPENDAVINCI_CORE_THROW_EXCEPTION(InvalidArgumentException, "The conference group id has to be in range [2, 254]."); } m_mulitcastGroup = "225.0.0." + cmdArgumentCID.getValue<string>(); } else { errno = 0; OPENDAVINCI_CORE_THROW_EXCEPTION(InvalidArgumentException, "No conference group id specified"); } if (cmdArgumentVERBOSE.isSet()) { m_verbose = true; } if (cmdArgumentPROFILING.isSet()) { m_profiling = true; } }
void AbstractCIDModule::parseCommandLine(const int32_t &argc, char **argv) throw (InvalidArgumentException) { if (argc <= 1) { errno = 0; OPENDAVINCI_CORE_THROW_EXCEPTION(InvalidArgumentException, "Invalid number of arguments. At least a conference group id (--cid=) needed."); } CommandLineParser cmdParser; cmdParser.addCommandLineArgument("id"); cmdParser.addCommandLineArgument("cid"); cmdParser.addCommandLineArgument("freq"); cmdParser.addCommandLineArgument("verbose"); cmdParser.addCommandLineArgument("profiling"); cmdParser.addCommandLineArgument("realtime"); cmdParser.parse(argc, argv); CommandLineArgument cmdArgumentID = cmdParser.getCommandLineArgument("id"); CommandLineArgument cmdArgumentCID = cmdParser.getCommandLineArgument("cid"); CommandLineArgument cmdArgumentFREQ = cmdParser.getCommandLineArgument("freq"); CommandLineArgument cmdArgumentVERBOSE = cmdParser.getCommandLineArgument("verbose"); CommandLineArgument cmdArgumentPROFILING = cmdParser.getCommandLineArgument("profiling"); CommandLineArgument cmdArgumentREALTIME = cmdParser.getCommandLineArgument("realtime"); if (cmdArgumentVERBOSE.isSet()) { AbstractCIDModule::m_verbose = cmdArgumentVERBOSE.getValue<int32_t>();; } if (cmdArgumentID.isSet()) { m_identifier = cmdArgumentID.getValue<string>(); } if (cmdArgumentFREQ.isSet()) { m_frequency = cmdArgumentFREQ.getValue<float>(); if ( fabs(m_frequency) < 1e-5 ) { errno = 0; OPENDAVINCI_CORE_THROW_EXCEPTION(InvalidArgumentException, "Runtime frequency must be greater than 0."); } } else { CLOG << "No runtime frequency set. Assuming a frequency of 1 Hz." << endl; } if (cmdArgumentCID.isSet()) { m_CID = cmdArgumentCID.getValue<int>(); if ( (m_CID <= 1) || (m_CID >= 254) ) { errno = 0; OPENDAVINCI_CORE_THROW_EXCEPTION(InvalidArgumentException, "The conference group id has to be in range [2, 254]."); } m_multicastGroup = "225.0.0." + cmdArgumentCID.getValue<string>(); } else { errno = 0; OPENDAVINCI_CORE_THROW_EXCEPTION(InvalidArgumentException, "No conference group id specified"); } if (cmdArgumentPROFILING.isSet()) { m_profiling = true; } if (cmdArgumentREALTIME.isSet()) { errno = 0; #ifdef HAVE_LINUX_RT int val = cmdArgumentREALTIME.getValue<int>(); if ( (val < 1) || (val > 49) ) { OPENDAVINCI_CORE_THROW_EXCEPTION(InvalidArgumentException, "The realtime scheduling priority has to be in range [1, 49]."); } m_realtime = true; m_realtimePriority = val; #else OPENDAVINCI_CORE_THROW_EXCEPTION(InvalidArgumentException, "Realtime is only available on Linux with rt-preempt."); #endif } }
void SuperComponent::parseAdditionalCommandLineParameters(const int &argc, char **argv) { CommandLineParser cmdParser; cmdParser.addCommandLineArgument("managed"); cmdParser.addCommandLineArgument("logfile"); cmdParser.addCommandLineArgument("loglevel"); cmdParser.parse(argc, argv); CommandLineArgument cmdArgumentLOGFILE = cmdParser.getCommandLineArgument("logfile"); CommandLineArgument cmdArgumentLOGLEVEL = cmdParser.getCommandLineArgument("loglevel"); CommandLineArgument cmdArgumentMANAGED = cmdParser.getCommandLineArgument("managed"); // Check the log level. if (cmdArgumentLOGLEVEL.isSet()) { string logLevel = cmdArgumentLOGLEVEL.getValue<string>(); if (core::strings::StringToolbox::equalsIgnoreCase(logLevel, "none")) { m_logLevel = coredata::LogMessage::NONE; } if (core::strings::StringToolbox::equalsIgnoreCase(logLevel, "info")) { m_logLevel = coredata::LogMessage::INFO; } if (core::strings::StringToolbox::equalsIgnoreCase(logLevel, "warn")) { m_logLevel = coredata::LogMessage::WARN; } if (core::strings::StringToolbox::equalsIgnoreCase(logLevel, "debug")) { m_logLevel = coredata::LogMessage::DEBUG; } } // Create a log file. if (cmdArgumentLOGFILE.isSet()) { string logFilename = cmdArgumentLOGFILE.getValue<string>(); if (m_logLevel > 0) { OPENDAVINCI_CORE_DELETE_POINTER(m_logFile); m_logFile = new fstream(); if (m_logFile != NULL) { m_logFile->open(logFilename.c_str(), ios::out | ios::app); if ((m_logFile != NULL) && !m_logFile->good()) { OPENDAVINCI_CORE_DELETE_POINTER(m_logFile); } } } } // Check the centrally maintained managed level. if (cmdArgumentMANAGED.isSet()) { string managedLevel = cmdArgumentMANAGED.getValue<string>(); core::strings::StringToolbox::trim(managedLevel); if (core::strings::StringToolbox::equalsIgnoreCase(managedLevel, "none")) { m_managedLevel = coredata::dmcp::ServerInformation::ML_NONE; } if (core::strings::StringToolbox::equalsIgnoreCase(managedLevel, "pulse")) { m_managedLevel = coredata::dmcp::ServerInformation::ML_PULSE; } if (core::strings::StringToolbox::equalsIgnoreCase(managedLevel, "pulse_shift")) { m_managedLevel = coredata::dmcp::ServerInformation::ML_PULSE_SHIFT; m_shiftMicroseconds = 10 * 1000; try { m_shiftMicroseconds = m_configuration.getValue<uint32_t>("odsupercomponent.pulseshift.shift"); } catch(...) { CLOG1 << "[odsupercomponent]: Value for 'odsupercomponent.pulseshift.shift' not found in configuration, using " << m_shiftMicroseconds << " as default." << endl; } } if (core::strings::StringToolbox::equalsIgnoreCase(managedLevel, "pulse_time")) { m_managedLevel = coredata::dmcp::ServerInformation::ML_PULSE_TIME; } if (core::strings::StringToolbox::equalsIgnoreCase(managedLevel, "pulse_time_ack") || core::strings::StringToolbox::equalsIgnoreCase(managedLevel, "simulation") || core::strings::StringToolbox::equalsIgnoreCase(managedLevel, "simulation_rt")) { if (core::strings::StringToolbox::equalsIgnoreCase(managedLevel, "pulse_time_ack")) { m_managedLevel = coredata::dmcp::ServerInformation::ML_PULSE_TIME_ACK; } if (core::strings::StringToolbox::equalsIgnoreCase(managedLevel, "simulation")) { m_managedLevel = coredata::dmcp::ServerInformation::ML_SIMULATION; } if (core::strings::StringToolbox::equalsIgnoreCase(managedLevel, "simulation_rt")) { m_managedLevel = coredata::dmcp::ServerInformation::ML_SIMULATION_RT; } m_timeoutACKMilliseconds = 1000; m_yieldMicroseconds = 5 * 1000; try { m_timeoutACKMilliseconds = m_configuration.getValue<uint32_t>("odsupercomponent.pulsetimeack.timeout"); } catch(...) { CLOG1 << "[odsupercomponent]: Value for 'odsupercomponent.pulsetimeack.timeout' not found in configuration, using " << m_timeoutACKMilliseconds << " as default." << endl; } try { m_yieldMicroseconds = m_configuration.getValue<uint32_t>("odsupercomponent.pulsetimeack.yield"); } catch(...) { CLOG1 << "[odsupercomponent]: Value for 'odsupercomponent.pulsetimeack.yield' not found in configuration, using " << m_yieldMicroseconds << " as default." << endl; } try { string s = m_configuration.getValue<string>("odsupercomponent.pulsetimeack.exclude"); transform(s.begin(), s.end(), s.begin(), ::tolower); m_modulesToIgnore = core::strings::StringToolbox::split(s, ','); } catch(...) { // If "odsupercomponent.pulsetimeack.exclude" is not specified, just ignore exception. } } } }
// Helpers int run_lists_mode(const Configuration &cfg, const CommandLineArgument<std::string> &image_argument, const CommandLineArgument<std::string> &landmarks_argument) { FaceTracker * tracker = LoadFaceTracker(cfg.model_pathname.c_str()); FaceTrackerParams *tracker_params = LoadFaceTrackerParams(cfg.params_pathname.c_str()); std::list<std::string> image_pathnames = read_list(image_argument->c_str()); std::list<std::string> landmark_pathnames; if (have_argument_p(landmarks_argument)) { landmark_pathnames = read_list(landmarks_argument->c_str()); if (landmark_pathnames.size() != image_pathnames.size()) throw make_runtime_error("Number of pathnames in list '%s' does not match the number in '%s'", image_argument->c_str(), landmarks_argument->c_str()); } std::list<std::string>::const_iterator image_it = image_pathnames.begin(); std::list<std::string>::const_iterator landmarks_it = landmark_pathnames.begin(); const int number_of_images = image_pathnames.size(); int current_image_index = 1; for (; image_it != image_pathnames.end(); image_it++) { if (cfg.verbose) { printf(" Image %d/%d\r", current_image_index, number_of_images); fflush(stdout); } current_image_index++; cv::Mat image; cv::Mat_<uint8_t> gray_image = load_grayscale_image(image_it->c_str(), &image); int result = tracker->NewFrame(gray_image, tracker_params); std::vector<cv::Point_<double> > shape; std::vector<cv::Point3_<double> > shape3D; Pose pose; if (result >= cfg.tracking_threshold) { shape = tracker->getShape(); shape3D = tracker->get3DShape(); pose = tracker->getPose(); } else { tracker->Reset(); } if (!have_argument_p(landmarks_argument)) { display_data(cfg, image, shape, pose); } else if (shape.size() > 0) { if (cfg.save_3d_points) save_points3(landmarks_it->c_str(), shape3D); else save_points(landmarks_it->c_str(), shape); if (cfg.verbose) display_data(cfg, image, shape, pose); } else if (cfg.verbose) { display_data(cfg, image, shape, pose); } if (have_argument_p(landmarks_argument)) landmarks_it++; } delete tracker; delete tracker_params; return 0; }
/** * Constructs a new NeuroEvolutionSelector. */ NeuroEvolutionSelector::NeuroEvolutionSelector(EvaluationMethod *evaluationMethod) { //TODO Currently only a single world with a single population is supported. //Select evolution algorithm CommandLineArgument *evoAlgorithmArg = new CommandLineArgument( "evolutionAlgorithm", "evo", "<algorithmName> <controlledAgent> <populationName>", "Uses the evolution algorithm with the given <algorithmName> " "to evolve controllers for agent <controlledAgent> (optional). " "Optionally the population name can be set with <populationName>.", 1, 2, true); CommandLineArgument *fitnessFunctionArg = new CommandLineArgument( "fitness", "fit", "<prototypeName> <fitnessFunctionName> <population>", "Creates a copy of <prototypeName> and uses it " " with the given <fitnessFunctionName>. The <population>" " is a number and specifies the population in which the fitness function is used.", 2, 1, true); //ensure that there is at least on world, even if not specified via command line. bool createDefaultWorld = false; if(evoAlgorithmArg->getNumberOfEntries() == 0) { createDefaultWorld = true; } int scriptFitnessCounter = 0; QList<QString> evoWorldNames; for(int evoCount = 0; evoCount < evoAlgorithmArg->getNumberOfEntries() || createDefaultWorld; ++evoCount) { QString worldName = "Main"; QString popName = "Controllers"; if(evoCount > 0) { worldName = "Pop" + QString::number(evoCount); } if(evoCount > 0) { popName = "Controllers" + QString::number(evoCount); } QList<QString> evoArguments = evoAlgorithmArg->getEntryParameters(evoCount); if(evoArguments.size() >= 3) { worldName = evoArguments[2]; QString name = worldName; int counter = 1; while(evoWorldNames.contains(worldName)) { worldName = name + QString::number(counter); counter++; } evoWorldNames.append(worldName); } World *world = new World(worldName); Population *population = new Population(popName, world); world->addPopulation(population); if(evoCount == 0) { world->setEvaluationMethod(evaluationMethod); } else { world->setEvaluationMethod(0); } Evolution::getEvolutionManager()->addEvolutionWorld(world); //Install Fitness FitnessFunction *fitness = 0; for(int i = 0; i < fitnessFunctionArg->getNumberOfEntries(); ++i) { QList<QString> fitArguments = fitnessFunctionArg->getEntryParameters(i); if((evoCount == 0 && fitArguments.size() <= 2) || (fitArguments.size() > 2 && fitArguments.at(2).toInt() == evoCount)) { if(fitArguments.size() > 1) { fitness = Fitness::getFitnessManager() ->createFitnessFunctionFromPrototype(fitArguments.at(0), fitArguments.at(1)); if(fitness == 0) { cerr << "Failed to create FitnessFunction prototype [" << fitArguments.at(0).toStdString().c_str() << endl; } } if(fitness != 0) { population->addFitnessFunction(fitness); } } } if(fitness == 0) { QString scriptName = "Script"; if(scriptFitnessCounter > 0) { scriptName += QString::number(scriptFitnessCounter); } scriptFitnessCounter++; fitness = Fitness::getFitnessManager() ->createFitnessFunctionFromPrototype("Script", scriptName); population->addFitnessFunction(fitness); } if(evoArguments.size() >= 1 && evoArguments.at(0).trimmed() == "ens3") { ENS3EvolutionAlgorithm evo(world); } else if(evoArguments.size() >= 1 && evoArguments.at(0).trimmed() == "neat") { NeatAlgorithm evo(world); } else if(evoArguments.size() < 1 || (evoArguments.size() >= 1 && (evoArguments.at(0).trimmed() == "mens" || evoArguments.at(0).trimmed() == "icone"))) { ModularNeuroEvolution1 evo(world); } if(evoArguments.size() >= 2) { world->getControlleAgentValue()->set(evoArguments.at(1)); } //add individual statistics StandardIndividualStatistics indStatistics(population); NeuralNetworkIndividualStatistics neuroStatistics(population); //Add neuralNetworkStatustic calculator. Statistics::getStatisticsManager()->addGenerationStatistics( new BasicNeuralNetworkStatistics(*population)); createDefaultWorld = false; } }
bool EvolutionOperatorTestApplication::setupApplication() { bool ok = true; //Choose Physics Engine (or external Yars simulator) CommandLineArgument *physicsArg = new CommandLineArgument("physics", "p", "<physicsLibrary>", "Uses <physicsLibrary> as physics engine. " "Currently there are [ode, yars].", 1,0, true); if(physicsArg->getNumberOfEntries() != 0 && !physicsArg->getEntryParameters(0).empty() && physicsArg->getEntryParameters(0).at(0).trimmed() == "yars") { YarsCommunication(); } else { //install ODE PhysicsLayer ODE_Physics(); } EvolutionSimulationPrototypes(); //install file parser new SimpleObjectFileParser(); //Install file interface for HTTPS communication. //new LoadAndStoreValueManagerPerGeneration(); //Install fitness prototypes NeuroFitnessPrototypes(); //Install standard NN functions and objects. StandardNeuralNetworkFunctions(); //Install constraint manager. StandardConstraintCollection(); //Install neuro modules NeuroModuleCollection(); //Install network attribute characterizer new NeuralNetworkAttributes(); //Install statistics logger to save the current statistics to a file. new StatisticsLogger(Evolution::getEvolutionManager()->getEvolutionWorkingDirectory()); //Install and initialize the settings logger (logging of settings history). SettingsLogger *settingsLogger = new SettingsLogger(); settingsLogger->addValues("(?!.*/Evo/.*/Fitness/.*/Fitness/.*)(?!.*/Performance/.*)/Evo/.*/Algorithm/.*"); settingsLogger->addValues("(?!.*/Evo/.*/Fitness/.*/Fitness/.*)(?!.*/Performance/.*)/Evo/.*/Pop/.*"); settingsLogger->addValues("/Evo/.*/Fitness/.*/Fitness/CalculationMode"); settingsLogger->addValues("/Control/NumberOfSteps"); settingsLogger->addValues("/Control/NumberOfTries"); new FramesPerSecondCounter(); new SimObjectGroupPrinter(); new SaveBestNetworksHandler(3); if(!buildSimulationModel()) { Core::log("LocalNNSimulatorEvolutionApplication: " "Problem while building the simulation model."); ok = false; } if(!buildEvolutionSystem()) { Core::log("LocalNNSimulatorEvolutionApplication: " "Problem while building the evolution system."); ok = false; } mRunner = new EvolutionRunner(); return ok; }
bool NerdNeuroEvoApplication::setupApplication() { bool ok = true; //Choose Physics Engine (or external Yars simulator) CommandLineArgument *physicsArg = new CommandLineArgument("physics", "p", "<physicsLibrary>", "Uses <physicsLibrary> as physics engine. " "Currently there are [ode, yars].", 1,0, true); if(physicsArg->getNumberOfEntries() != 0 && !physicsArg->getEntryParameters(0).empty() && physicsArg->getEntryParameters(0).at(0).trimmed() == "yars") { YarsCommunication(); } else if(physicsArg->getNumberOfEntries() != 0 && !physicsArg->getEntryParameters(0).empty() && physicsArg->getEntryParameters(0).at(0).trimmed() == "s2d") { Simple2D_Physics(); } else { //install ODE PhysicsLayer ODE_Physics(); } EvolutionSimulationPrototypes(); //install file parser new SimpleObjectFileParser(); //Install file interface for HTTPS communication. //new LoadAndStoreValueManagerPerGeneration(); //Install fitness prototypes NeuroFitnessPrototypes(); //Install standard NN functions and objects. StandardNeuralNetworkFunctions(); //Install constraint manager. StandardConstraintCollection(); //Install neuro modules NeuroModuleCollection(); StandardTagCollection(); //Enable NeuroModulation NeuroModulatorManager::getInstance(); //Install network attribute characterizer new NeuralNetworkAttributes(); new AutoStoreNetworksHelper(); //Install statistics logger to save the current statistics to a file. new StatisticsLogger(Evolution::getEvolutionManager()->getEvolutionWorkingDirectoryValue()); new EvolutionTerminationTrigger(); //Install and initialize the settings logger (logging of settings history). SettingsLogger *settingsLogger = new SettingsLogger(); settingsLogger->addValues("(?!.*/Evo/.*/Fitness/.*/Fitness/.*)(?!.*/Performance/.*)/Evo/.*/Algorithm/.*"); settingsLogger->addValues("(?!.*/Evo/.*/Fitness/.*/Fitness/.*)(?!.*/Performance/.*)/Evo/.*/Pop/.*"); settingsLogger->addValues("/Evo/.*/Fitness/.*/Fitness/CalculationMode"); settingsLogger->addValues("/Control/NumberOfSteps"); settingsLogger->addValues("/Control/NumberOfTries"); new TerminateTryCollisionRule(); new StepsPerSecondCounter(); new SimObjectGroupPrinter(); new SaveBestNetworksHandler(3); //add motor model rotation new ModelParameterRotator(); //allow neural networks for other agents outside of the evolution. new NetworkAgentControlParser(); UniversalNeuroScriptLoader(); ScriptedModelLoader(); //Add plugin to calculate the open degrees of freedom of the network during evolution. new NetworkDegreeOfFreedomCalculator(); if(!buildSimulationModel()) { Core::log("NerdNeuroEvo: " "Problem while building the simulation model."); ok = false; } if(!buildEvolutionSystem()) { Core::log("NerdNeuroEvo: " "Problem while building the evolution system."); ok = false; } mRunner = new EvolutionRunner(); return ok; }
bool NetworkDynamicsPlotterApplication::setupApplication() { bool ok = true; //install network characterizer new NeuralNetworkAttributes(); StandardTagCollection(); NeuroModuleCollection(); DynamicsPlotCollection(); if(mEnableSimulator) { new SimObjectGroupPrinter(); //Choose Physics Engine (or external Yars simulator) CommandLineArgument *physicsArg = new CommandLineArgument("physics", "p", "<physicsLibrary>", "Uses <physicsLibrary> as physics engine. " "Currently there are [ode, yars].", 1,0, true); if(physicsArg->getNumberOfEntries() != 0 && !physicsArg->getEntryParameters(0).empty() && physicsArg->getEntryParameters(0).at(0).trimmed() == "yars") { YarsCommunication(); } else if(physicsArg->getNumberOfEntries() != 0 && !physicsArg->getEntryParameters(0).empty() && physicsArg->getEntryParameters(0).at(0).trimmed() == "s2d") { Simple2D_Physics(); } else { //install ODE PhysicsLayer ODE_Physics(); } //install file parser new SimpleObjectFileParser(); new StepsPerSecondCounter(); //Priovide the -net required to load a network for one or more agents. new NetworkAgentControlParser(); new ModelParameterRotator(); ScriptedModelLoader(); } UniversalNeuroScriptLoader(); //load a network if given. CommandLineArgument *netArg = new CommandLineArgument("loadNetwork", "net", "<networkFile", "Loads a NeuralNetwork to the NetworkEditor", 1, 0, false, true); //Only provide a -net to load a network (or create a default in case no -net is given) when //NOT using a physical simulation. if(!mEnableSimulator) { if(netArg->getNumberOfEntries() > 0) { QStringList files = netArg->getEntryParameters(0); if(files.size() > 0) { QString errorMessage; QList<QString> warnings; NeuralNetwork *net = NeuralNetworkIO::createNetworkFromFile(files.at(0), &errorMessage, &warnings); if(errorMessage != "") { Core::log("Error while loading net: " + errorMessage, true); } if(!warnings.empty()) { for(QListIterator<QString> j(warnings); j.hasNext();) { Core::log("Warning: " + j.next(), true); } } if(dynamic_cast<ModularNeuralNetwork*>(net) != 0) { Neuro::getNeuralNetworkManager()->addNeuralNetwork(net); } } } else { Neuro::getNeuralNetworkManager()->addNeuralNetwork(new ModularNeuralNetwork( AdditiveTimeDiscreteActivationFunction(), TransferFunctionTanh(), SimpleSynapseFunction())); } } mExecutionLoop = new PlotterExecutionLoop(); new MatlabExporter(); return ok; }