Nemo  2.4.1
Simulate forward-in-time genetic evolution in a spatially explicit, individual-based stochastic simulator
SimRunner Class Reference

Performs the setup of the Metapop and SimComponents and runs the simulation. More...

#include <simulation.h>

+ Inheritance diagram for SimRunner:
+ Collaboration diagram for SimRunner:

Public Member Functions

 SimRunner (Metapop *pop)
 
 ~SimRunner ()
 Dstror. More...
 
bool init ()
 Checks simulation parameters and init the FileServices with the base filename. More...
 
bool init_components (map< string, string > &simparams)
 Performs the initialization of the different components of the simulation. More...
 
void setLifeCycle ()
 Sets the list of LifeCyckeEvent's currently active. More...
 
void setForFirstGeneration ()
 Sets the population and the services ready for the first generation of a new replicate. More...
 
void init_random_seed ()
 Initialize the seed of the random generator. More...
 
void expandPreservedMacros ()
 Expands the macros that were preserved by the P() macro in the input file. More...
 
void reset ()
 Resets all the parameters to the unset state, resets the services. More...
 
std::string setElapsedTime (clock_t time)
 Compute and print the simulation's elapsed time to stdout. More...
 
void register_component (SimComponent *cmpt)
 Register the different Handler's attached to a SimComponent. More...
 
void register_component_handlers ()
 Register all the Handlers of the currently active simulation components. More...
 
void reset_services ()
 Resets the FileServices and StatServices. More...
 
FileServicesget_FileServices ()
 Returns the FileServices. More...
 
StatServicesget_StatServices ()
 Returns the StatServices. More...
 
list< StatRecBase * > get_allRegisteredStats ()
 Returns the complete list of the stat recorders loaded after parameters initialization. More...
 
bool run (int ARGC, char **ARGV)
 First loop of the simulation, performs the simulations stored in the ParamManager base class. More...
 
bool run ()
 First loop of the simulation, performs the simulations stored in the ParamManager base class. More...
 
bool run_event (string &name)
 Execute one specific life cycle event, if present in the list of current events. More...
 
void step (unsigned int nb_gen)
 Iterates the life cycle. More...
 
void attach_pop (Metapop *pop)
 Attach a pop to the simulation. More...
 
Metapopget_pop ()
 Accessor to the pop ptr. More...
 
bool build_pop ()
 Calls the Metapop init procedure with current traits and LCEs. More...
 
void setCurrentGeneration (unsigned int gen)
 
unsigned int getCurrentGeneration ()
 
void setGenerations (unsigned int gen)
 
unsigned int getGenerations ()
 
void setCurrentReplicate (unsigned int repl)
 
unsigned int getCurrentReplicate ()
 
void setReplicates (unsigned int repl)
 
unsigned int getReplicates ()
 
int getCurrentRankInLifeCycle ()
 
void printLogHeader ()
 
void printLog ()
 
void runPostExec ()
 Run the post-exec script after all simulations have finished. More...
 
void runPostExecReplicateWise ()
 Run the post-exec script after each replicate, adds filename and replicate number as args. More...
 
Main loops
void Replicate_LOOP ()
 Replicate loop, iterates the life cycle _replicates times. More...
 
void Cycle (char *startTime)
 Life cycle loop, executes the list of LCEs _generations times. More...
 
- Public Member Functions inherited from SimBuilder
 SimBuilder ()
 
 SimBuilder (const SimBuilder &SB)
 copy cstor. More...
 
 ~SimBuilder ()
 
bool build_currentParams (map< string, string > &simparams)
 Builds the list of parameters from user's defined input parameters. More...
 
map< trait_t, TraitPrototype * > & build_currentTraits ()
 Selects the trait prototypes that have their parameters set. More...
 
void build_LifeCycle ()
 Selects the life cycle events that have their parameters set. More...
 
TraitPrototypeget_current_trait (trait_t type)
 Accessor to the list of current trait prototypes. More...
 
TraitPrototypeget_current_traitWithParameter (string &param)
 Accessor to the current trait prototypes conditioned on ownership of a specified parameter. More...
 
LifeCycleEventget_current_event (string &name)
 Accessor to the list of current LCEs. More...
 
LifeCycleEventget_current_eventWithParameter (string &param)
 Accessor to the current LCEs conditioned on ownership of a specified parameter. More...
 
list< ParamSet * > & get_currentParams ()
 Accessor to the list of the selected parameter sets. More...
 
age_t getFirstRequiredAgeInLifeCycle ()
 
- Public Member Functions inherited from ParamManager
 ParamManager ()
 Cstor. More...
 
 ~ParamManager ()
 
void add_paramset (ParamSet *paramset)
 Adds a ParamSet to the list of the parameter sets of the simulation. More...
 
ParamSetget_paramset (string &name)
 Looks for paramset with "name" in the list of parameter sets. More...
 
void build_allParams ()
 Clears and fills the _allParams list with the ParamSet's of the simulation components. More...
 
list< ParamSet * > & get_allParams ()
 Accessor of the whole list of the parameter sets. More...
 
bool set_parameters (map< string, string > &simparams, bool silent)
 Sets the parameters of the simulation with the argument strings given in input. More...
 
bool param_consistency_check ()
 Checks if all the mandatory parameters are set so that the simulation can be launched. More...
 
void build_records (map< string, vector< string > > &initParams)
 Builds the list of simulation parameters from the parsed input file(s). More...
 
list< map< string, string > > & get_simRecords ()
 Accessor to the simulations parameter list. More...
 
map< string, string > & get_firstRecord ()
 Accessor to the first element in the simulations parameter list. More...
 
int get_nbSims ()
 Accessor to the size of the simulations parameter list, i.e. More...
 
- Public Member Functions inherited from ComponentManager
 ComponentManager ()
 
 ~ComponentManager ()
 
void build_component_list ()
 Clears and builds the list of all components from the lists of trait prototype templates and life cycle event templates. More...
 
void add_component (SimComponent *cmpt)
 Push a component at the back of the component list. More...
 
void add_trait (TraitPrototype *trait)
 Add a trait prototype to the template and component lists. More...
 
void add_LCE (LifeCycleEvent *event)
 Add a life cycle event to the template and component lists. More...
 
TraitPrototypeget_trait (string name)
 Search for component with "name" in the trait prototype list. More...
 
LifeCycleEventget_LCE (string name)
 Search for component with "name" in the life cycle events list. More...
 

Public Attributes

FileServices _FileServices
 
StatServices _StatServices
 
UpdaterServices _ParamUpdaterManager
 

Private Attributes

MPImanager_my_mpi_manager
 
Metapop_thePop
 
std::string _logfile
 
char _startTime [20]
 
char _endTime [20]
 
std::string _simElapsedTime
 
clock_t _meanReplElapsedTime
 Clock counter, for logging. More...
 
unsigned int _meanGenLength
 Generation counter, for logging. More...
 
unsigned int _generations
 Number of generations to iterate. More...
 
unsigned int _replicates
 Number of replicates to iterate. More...
 
unsigned int _currentReplicate
 The current replicate in the replicate loop, starts at 1. More...
 
unsigned int _currentGeneration
 The current generation in the generation loop, starts at 1. More...
 
int _currentRankInLifeCycle
 The current rank in the life cycle, corresponds to the rank of the current LCE, before it executes. More...
 
unsigned long _random_seed
 The startup random seed of the random generator. More...
 
std::string _modeArg
 The run mode ('overwrite', 'run', 'skip', 'dryrun', 'create_init'). More...
 
unsigned int _mode
 The run mode code (0 = run, 1 = overwrite, 2 = skip, 3 = dryrun, 4 = create_init) More...
 
bool _doRun
 Boolean set when not in dryrun mode. More...
 
std::string _postexec_script
 The path to the script to be executed after last simulation. More...
 
std::string _postexec_args
 Arguments to pass to the post-exec script. More...
 
bool _do_postexec_replicatewise
 Boolean to trigger replicate-wise execution of post script. More...
 
bool _do_postexec
 Boolean set when a post-exec script must be executed. More...
 

Additional Inherited Members

- Protected Types inherited from SimBuilder
typedef map< int, LifeCycleEvent * >::const_iterator LCE_ITER
 
typedef map< trait_t, TraitPrototype * >::const_iterator TRAIT_ITER
 
- Protected Attributes inherited from SimBuilder
list< ParamSet * > _currentParams
 List of the selected simulation components from the user defined input parameters. More...
 
map< trait_t, TraitPrototype * > _currentTraits
 List of the selected trait prototypes from the user defined input parameters. More...
 
map< int, LifeCycleEvent * > _LifeCycle
 List of the selected life cycle events from the user defined input parameters. More...
 
- Protected Attributes inherited from ParamManager
list< ParamSet * > _allParams
 A list of all the parameter sets of all the simulation components loaded in the _component list of the ComponentManager. More...
 
map< string, string > _inputParams
 A map of the parameters and their arguments of the current (running) simulation. More...
 
map< unsigned int, list< pair< string, string > > > _temporalParams
 Lists of parameters to be updated during a simulation indexed by generation update time. More...
 
list< map< string, string > > _simRecords
 Sets of parameters of all the simulations to perform. More...
 
ParamSet _paramSet
 The ParamSet param set of the simulation. More...
 
- Protected Attributes inherited from ComponentManager
list< SimComponent * > _components
 List of all the simulation components. More...
 
list< TraitPrototype * > _TTrait_Templates
 List of all trait prototypes of the simulation, a subset of _components list. More...
 
list< LifeCycleEvent * > _LCE_Templates
 List of all the life-cycle events of the simulation, a subset of _components list. More...
 

Detailed Description

Performs the setup of the Metapop and SimComponents and runs the simulation.

This class implements the two main loops of a simulation, the replicate and the generation loops. The replicate loop iterates the generation loop which itself iterates the life cycle loop composed of the LCEs selected by the user. A SimRunner brings together the basic simulation components and a metapopulation on which they act. It perfoms the setups necessary to have a Metapop ready for the simulation and runs the different simulations stored in its ParamManager base class. Also hosts the file and stat services.

Constructor & Destructor Documentation

◆ SimRunner()

SimRunner::SimRunner ( Metapop pop)
inline
108  {
109  attach_pop(pop);
110  }
void attach_pop(Metapop *pop)
Attach a pop to the simulation.
Definition: simulation.h:173
MPImanager * _my_mpi_manager
Definition: simulation.h:55
bool _do_postexec_replicatewise
Boolean to trigger replicate-wise execution of post script.
Definition: simulation.h:93
bool _do_postexec
Boolean set when a post-exec script must be executed.
Definition: simulation.h:95

References attach_pop().

◆ ~SimRunner()

SimRunner::~SimRunner ( )

Dstror.

180 {
181 #ifdef _DEBUG_
182  message("SimRunner::~SimRunner\n");
183 #endif
184 
185  reset();
186 
187 }
void reset()
Resets all the parameters to the unset state, resets the services.
Definition: simulation.cc:191
void message(const char *message,...)
Definition: output.cc:39

References message(), and reset().

Member Function Documentation

◆ attach_pop()

void SimRunner::attach_pop ( Metapop pop)
inline

Attach a pop to the simulation.

Adds it to the components list.

Parameters
popptr to the pop object
173 {_thePop = pop;this->_components.push_back(_thePop);}
list< SimComponent * > _components
List of all the simulation components.
Definition: basicsimulation.h:70
Metapop * _thePop
Definition: simulation.h:57

References ComponentManager::_components, and _thePop.

Referenced by SimRunner().

+ Here is the caller graph for this function:

◆ build_pop()

bool SimRunner::build_pop ( )

Calls the Metapop init procedure with current traits and LCEs.

◆ Cycle()

void SimRunner::Cycle ( char *  startTime)

Life cycle loop, executes the list of LCEs _generations times.

Parameters
startTimethe starting time of the current replicate.
674 {
675 
676  time_t t;
677  // ------------------------------ CYCLE --------------------------------
678 
680 
681  // -------------------------- PRINT STUFF ------------------------------
682 #if !defined(LOW_VERBOSE) && !defined(USE_MPI)
683 
684  if( !(_currentGeneration % 100) || _currentGeneration < 100){
685  //update timer:
686  t = time(0);
687  strftime(startTime, 10, "%H:%M:%S", localtime(&t));
688 
689  message("\r replicate %i/%i [%s] %i/%i", _currentReplicate, _replicates
690  ,startTime, _currentGeneration, _generations);
691 
692  fflush(stdout);
693  }
694 #endif
695 
696 #ifdef _DEBUG_
697  message("____Generation %i/%i____\n", _currentGeneration, _generations);
698 #endif
699 
700  // -------------------------- STEP ONE GEN ------------------------------
702 
703  // do one iteration of the life cycle:
704  if(_thePop->isAlive())
705 
706  step(1);
707 
708  else {
709 #if !defined(LOW_VERBOSE) && !defined(USE_MPI)
710  message("\r replicate %i/%i [%s] %i/%i -> Pop extinction !\n", _currentReplicate, _replicates
711  ,startTime, _currentGeneration, _generations);
712 #endif
714  break;
715  }
716 
717  }
718  // --------------------------- END OF CYCLE --------------------------
719 }
void setCurrentGeneration(unsigned int gen)
Definition: metapop.h:297
bool isAlive()
Checks if the population still contains at least one individual in any sex or age class.
Definition: metapop.h:308
unsigned int _replicates
Number of replicates to iterate.
Definition: simulation.h:73
void step(unsigned int nb_gen)
Iterates the life cycle.
Definition: simulation.cc:743
unsigned int _generations
Number of generations to iterate.
Definition: simulation.h:71
unsigned int _currentReplicate
The current replicate in the replicate loop, starts at 1.
Definition: simulation.h:75
unsigned int _currentGeneration
The current generation in the generation loop, starts at 1.
Definition: simulation.h:77

References _currentGeneration, _currentReplicate, _generations, _replicates, _thePop, Metapop::isAlive(), message(), Metapop::setCurrentGeneration(), and step().

Referenced by Replicate_LOOP().

+ Here is the caller graph for this function:

◆ expandPreservedMacros()

void SimRunner::expandPreservedMacros ( )

Expands the macros that were preserved by the P() macro in the input file.

Called right after init_random_seed() so that stochastic macros (rexp, rnorm, ...) draw from the RNG seeded with the input random_seed, making them reproducible. Iterates all current parameters and re-sets any flagged with a preserved macro using the expanded value.

353 {
354  // The RNG is now seeded from the input value. Expand the macros that the P() macro kept
355  // un-expanded at parse time (flagged on their Param) and re-set the parameter with the
356  // resolved value. The expanded string carries no preserve sentinel, so the re-set goes
357  // through Param::set's normal path (validation / temporal parsing).
358  StreamParser parser("");
359 
360  list< ParamSet* >& params = get_currentParams();
361 
362  for(list< ParamSet* >::iterator ps = params.begin(); ps != params.end(); ps++) {
363 
364  map< string, Param* >& pmap = (*ps)->getAllParams();
365 
366  for(map< string, Param* >::iterator p = pmap.begin(); p != pmap.end(); p++) {
367 
368  if( !p->second->hasPreservedMacro() ) continue;
369 
370  string errmsg;
371  string expanded = parser.expandMacros( p->second->getInputArg() );
372 
373  if( !p->second->set( expanded, errmsg ) )
374  fatal("could not expand preserved macro for parameter \"%s\": %s\n",
375  p->first.c_str(), errmsg.c_str());
376  }
377  }
378 }
list< ParamSet * > & get_currentParams()
Accessor to the list of the selected parameter sets.
Definition: basicsimulation.h:213
Read parameters from a text buffer.
Definition: paramsparser.h:146
void fatal(const char *str,...)
Definition: output.cc:99

References ParamsParser::expandMacros(), fatal(), and SimBuilder::get_currentParams().

Referenced by init_components().

+ Here is the caller graph for this function:

◆ get_allRegisteredStats()

list<StatRecBase*> SimRunner::get_allRegisteredStats ( )
inline

Returns the complete list of the stat recorders loaded after parameters initialization.

157 {return _StatServices.getAllStats();}
StatServices _StatServices
Definition: simulation.h:101
list< StatRecBase * > getAllStats()
Definition: statservices.cc:404

References _StatServices, and StatServices::getAllStats().

◆ get_FileServices()

FileServices* SimRunner::get_FileServices ( )
inline

Returns the FileServices.

153 {return &_FileServices;}
FileServices _FileServices
Definition: simulation.h:99

References _FileServices.

Referenced by Metapop::loadPopFromTraitFile().

+ Here is the caller graph for this function:

◆ get_pop()

Metapop* SimRunner::get_pop ( )
inline

Accessor to the pop ptr.

Returns
the pop ptr
177 {return _thePop;}

References _thePop.

Referenced by GenotyperFH::FHwrite(), GenotyperFH::prepare_data_table(), and GenotyperFH::print_PLINK().

+ Here is the caller graph for this function:

◆ get_StatServices()

StatServices* SimRunner::get_StatServices ( )
inline

Returns the StatServices.

155 {return &_StatServices;}

References _StatServices.

Referenced by LCE_StatServiceNotifier::LCE_StatServiceNotifier().

+ Here is the caller graph for this function:

◆ getCurrentGeneration()

unsigned int SimRunner::getCurrentGeneration ( )
inline
195 {return _currentGeneration;}

References _currentGeneration.

Referenced by SIMenv::getCurrentGeneration().

+ Here is the caller graph for this function:

◆ getCurrentRankInLifeCycle()

int SimRunner::getCurrentRankInLifeCycle ( )
inline
202 {return _currentRankInLifeCycle;}
int _currentRankInLifeCycle
The current rank in the life cycle, corresponds to the rank of the current LCE, before it executes.
Definition: simulation.h:79

References _currentRankInLifeCycle.

Referenced by SIMenv::getCurrentRankInLifeCycle().

+ Here is the caller graph for this function:

◆ getCurrentReplicate()

unsigned int SimRunner::getCurrentReplicate ( )
inline
199 {return _currentReplicate;}

References _currentReplicate.

Referenced by SIMenv::getCurrentReplicate().

+ Here is the caller graph for this function:

◆ getGenerations()

unsigned int SimRunner::getGenerations ( )
inline
197 {return _generations;}

References _generations.

Referenced by SIMenv::getGenerations().

+ Here is the caller graph for this function:

◆ getReplicates()

unsigned int SimRunner::getReplicates ( )
inline
201 {return _replicates;}

References _replicates.

Referenced by SIMenv::getReplicates().

+ Here is the caller graph for this function:

◆ init()

bool SimRunner::init ( )

Checks simulation parameters and init the FileServices with the base filename.

69 {
70  if( !(_paramSet.isSet("filename")) ) {
71  return error("parameter \"filename\" is not properly set!\n");
72  }
73 
75 
76  if(_paramSet.isSet("root_dir")) {
78  }
79 
80  if(_paramSet.isSet("run_mode")) {
81 
82  _modeArg = _paramSet.getArg("run_mode");
83 
84  if(_modeArg == "run"){
85 
87  _doRun = true;
88  _mode = 0;
89  SILENT_RUN = false; //declared in output.h
90 
91  } else if( _modeArg == "overwrite" ) {
92 
94  _doRun = true;
95  _mode = 1;
96  SILENT_RUN = false;
97 
98  } else if(_modeArg == "skip"){
99 
101  _doRun = true;
102  _mode = 2;
103  SILENT_RUN = false;
104 
105  } else if(_modeArg == "dryrun" || _modeArg == "dry"){
106 
108  _doRun = false;
109  _mode = 3;
110  SILENT_RUN = false;
111 
112  } else if(_modeArg == "create_init"){ //the logWriter creates an ini file, see FileServices::log_simparams()
113 
115  _doRun = false;
116  _mode = 4;
117  SILENT_RUN = false;
118 
119  } else if(_modeArg == "silent_run" || _modeArg == "silent"){
120 
121  _FileServices.setMode(2); // skip simulation if files from previous sims are found, o/w it hangs
122  _doRun = true;
123  _mode = 2;
124  SILENT_RUN = true;
125 
126  } else {
127 
128  error("simulation run mode \"%s\" unknown\n",_modeArg.c_str());
129 
130  return false;
131 
132  }
133  // else, set default run mode values (skip):
134  } else {
135  _modeArg = "skip";
136  _doRun = true;
138  SILENT_RUN = false;
139  }
140 
141  _replicates = (unsigned int)_paramSet.getValue("replicates");
142 
143  _generations = (unsigned int)_paramSet.getValue("generations");
144 
145 
146  if( _paramSet.isSet("logfile") ) {
147  _logfile = _paramSet.getArg("logfile");
148  } else {
149  _logfile = "nemo.log";
150  }
151 
152  // create the simulation logging file
153  printLogHeader();
154 
155  // set POSTEXEC options:
156  if( _paramSet.isSet("postexec_script") ) {
157  _postexec_script = _paramSet.getArg("postexec_script");
158  _do_postexec = true;
159 
160  if( _paramSet.isSet("postexec_args") )
161  _postexec_args = _paramSet.getArg("postexec_args");
162  else
163  _postexec_args = "";
164 
165  if( _paramSet.isSet("postexec_replicate_wise") )
167  else
169 
170 
171  } else
172  _do_postexec = false;
173 
174  return true;
175 }
void setBasename(string name)
Sets the base file name of the simulation.
Definition: fileservices.cc:514
void setMode(unsigned int m)
Mode setter, determines if file will get overwritten or not.
Definition: fileservices.h:118
void setRootDir(string name)
Sets the root directory of the simulation.
Definition: fileservices.cc:521
ParamSet _paramSet
The ParamSet param set of the simulation.
Definition: basicsimulation.h:150
string getArg(string name)
Accessor to the parameters argument string.
Definition: param.h:309
double getValue(string name)
Accessor the parameters value.
Definition: param.h:311
bool isSet()
Accessor to the status flag.
Definition: param.h:297
std::string _postexec_args
Arguments to pass to the post-exec script.
Definition: simulation.h:91
unsigned int _mode
The run mode code (0 = run, 1 = overwrite, 2 = skip, 3 = dryrun, 4 = create_init)
Definition: simulation.h:85
std::string _logfile
Definition: simulation.h:59
bool _doRun
Boolean set when not in dryrun mode.
Definition: simulation.h:87
std::string _postexec_script
The path to the script to be executed after last simulation.
Definition: simulation.h:89
std::string _modeArg
The run mode ('overwrite', 'run', 'skip', 'dryrun', 'create_init').
Definition: simulation.h:83
void printLogHeader()
Definition: simulation.cc:785
bool SILENT_RUN
Definition: output.cc:36
int error(const char *str,...)
Definition: output.cc:78

References _do_postexec, _do_postexec_replicatewise, _doRun, _FileServices, _generations, _logfile, _mode, _modeArg, ParamManager::_paramSet, _postexec_args, _postexec_script, _replicates, error(), ParamSet::getArg(), ParamSet::getValue(), ParamSet::isSet(), printLogHeader(), FileServices::setBasename(), FileServices::setMode(), FileServices::setRootDir(), and SILENT_RUN.

Referenced by init_components().

+ Here is the caller graph for this function:

◆ init_components()

bool SimRunner::init_components ( map< string, string > &  simparams)

Performs the initialization of the different components of the simulation.

Builds the list of the simulation parameters and load the components that have their ParamSet in the set state. Builds the population, the TraitPrototype, and life cycle, register the various services and init the StatServices and ParameterUpdaterManager.

Parameters
simparamsthe hashtable containing the parameters and their arguments parsed from the init file
253 {
254 #ifdef _DEBUG_
255  message("SimRunner::init_components\n");
256 #endif
257  //first reset all paramSets and services (clear the handlers' lists)
258  reset();
259 
262 
263 #ifdef _DEBUG_
264  message("SimRunner::init_components: building current params\n");
265 #endif
266 
267  //build the list of active component parameters from the simulation record:
268  if(!this->build_currentParams(simparams)){
269  error("SimRunner::init_components:couldn't build current params\n");
270  return false;
271  }
272 
273  //initialize the random generator's seed:
274  //if(_myenv->isMaster()) // in MPI context, all processes must initialize the generator
276 
277  //the RNG is now seeded from the input value: expand any macros that the P() macro preserved
278  //in the input file, so stochastic macros draw reproducibly from the seeded generator:
280 
281  //init the sim and pop (set parameters from input values)
282  if( !init() || !_thePop->init() ) return false;
283 
284  //propagate replicate and generation numbers to metapop, often used by LCEs
287 
288  //the traits and LCEs components are set only after the simulation and
289  //population parameters are set
290 
291  //build the Individual prototype, and init the TTraits
292  //---> SimComponents::setParameters() is called here, this will also build the genetic map
294 
295  //build the list of life cycle events, and init LCEs
296  //---> SimComponent::setParameters() is called here
297  setLifeCycle( );
298 
299  //load the stat-, file-, and updater-handlers of the simulation components:
301 
302  //StatServices: build the lists of stat recorders:
303  if( !_StatServices.init() ) return false;
304 
305  if( !_ParamUpdaterManager.init() ) return false;
306 
309  updater->setManager( &_ParamUpdaterManager );
310  updater->init(_thePop);
311  _LifeCycle[ -1 ] = updater; //this is never destroyed...
312  }
313 
314  return true;
315 }
virtual void set_pop_ptr(Metapop *pop)
Sets the Metapop reference.
Definition: fileservices.h:115
void makePrototype(map< trait_t, TraitPrototype * > TTlist)
Creates the individuals prototype from the selected trait prototypes.
Definition: indfactory.cc:49
Calls the UpdaterServices to notify its components of a generation change.
Definition: servicenotifiers.h:40
void setManager(UpdaterServices *mng)
Definition: servicenotifiers.h:50
virtual void init(Metapop *popPtr)
Sets the pointer to the current Metapop and the trait link if applicable.
Definition: lifecycleevent.h:113
void setReplicates(unsigned int repl)
Definition: metapop.h:273
bool init()
Inits the population parameters from the ParamSet and builds the pop (adds patches),...
Definition: metapop.cc:96
void setGenerations(unsigned int gen)
Definition: metapop.h:271
bool build_currentParams(map< string, string > &simparams)
Builds the list of parameters from user's defined input parameters.
Definition: basicsimulation.cc:889
map< int, LifeCycleEvent * > _LifeCycle
List of the selected life cycle events from the user defined input parameters.
Definition: basicsimulation.h:223
map< trait_t, TraitPrototype * > & build_currentTraits()
Selects the trait prototypes that have their parameters set.
Definition: basicsimulation.cc:915
UpdaterServices _ParamUpdaterManager
Definition: simulation.h:103
void expandPreservedMacros()
Expands the macros that were preserved by the P() macro in the input file.
Definition: simulation.cc:352
bool init()
Checks simulation parameters and init the FileServices with the base filename.
Definition: simulation.cc:68
void setLifeCycle()
Sets the list of LifeCyckeEvent's currently active.
Definition: simulation.cc:242
void init_random_seed()
Initialize the seed of the random generator.
Definition: simulation.cc:319
void register_component_handlers()
Register all the Handlers of the currently active simulation components.
Definition: simulation.cc:229
virtual bool init()
Definition: statservices.cc:46
void set_pop_ptr(Metapop *pop)
Definition: statservices.h:107
bool hasTemporals()
Checks if any updater has been uploaded.
Definition: updaterservices.h:91
virtual bool init()
Definition: updaterservices.cc:38

References _FileServices, _generations, SimBuilder::_LifeCycle, _ParamUpdaterManager, _replicates, _StatServices, _thePop, SimBuilder::build_currentParams(), SimBuilder::build_currentTraits(), error(), expandPreservedMacros(), UpdaterServices::hasTemporals(), Metapop::init(), init(), StatServices::init(), UpdaterServices::init(), LifeCycleEvent::init(), init_random_seed(), IndFactory::makePrototype(), message(), register_component_handlers(), reset(), FileServices::set_pop_ptr(), StatServices::set_pop_ptr(), Metapop::setGenerations(), setLifeCycle(), LCE_ParamUpdaterNotifier::setManager(), and Metapop::setReplicates().

Referenced by run().

+ Here is the caller graph for this function:

◆ init_random_seed()

void SimRunner::init_random_seed ( )

Initialize the seed of the random generator.

320 {
321  if(_myenv->isMaster()) {
322 
323  if(this->_paramSet.isSet("random_seed")) {
324 
325  _random_seed = (unsigned long) this->_paramSet.getValue("random_seed");
326 
327  message( "setting random seed from input value: %i\n", _random_seed);
328 
329  } else {
330  //set the random seed from the current time
331  _random_seed = 2*time(0)+1;
332 
333  message( "setting random seed from current time: %i\n", _random_seed);
334  }
335  }
336 
337 #if defined(USE_MPI) && defined(HAS_SPRNG)
338 
339  // broadcast the random seed, needs to be equal on all processes with SPRNG
340  MPI_Bcast(&_random_seed,1,MPI_LONG,0,MPI_COMM_WORLD );
341 
342 #else
343 #endif
344 
345  //initialization in any case
347 
348 }
bool isMaster() const
Definition: MPImanager.h:127
static void init(unsigned long seed)
Initialize the random generator's seed.
Definition: Uniform.h:81
unsigned long _random_seed
The startup random seed of the random generator.
Definition: simulation.h:81
MPIenv * _myenv
Definition: MPImanager.cc:35

References _myenv, ParamManager::_paramSet, _random_seed, ParamSet::getValue(), RAND::init(), MPIenv::isMaster(), ParamSet::isSet(), and message().

Referenced by init_components().

+ Here is the caller graph for this function:

◆ printLog()

void SimRunner::printLog ( )
814 {
815  ofstream FH(_logfile.c_str(),ios::app);
816 
817  if(!FH.is_open()){
818  error("could not open simulation logfile \"%s\"\n",_logfile.c_str());
819  return;
820  }
821 
822  FH<<"| ";
823  FH.width(40);
824  FH.setf(ios::left,ios::adjustfield);
826 
827  FH <<"| "<< _startTime <<" | "<< _endTime <<" | ";
828 
829  FH.width(10);
830  FH.setf(ios::right,ios::adjustfield);
831  FH<< _simElapsedTime <<" | ";
832 
833  FH.width(9);
834  FH << _replicates <<" | ";
835 
836  FH.width(10);
837  FH << setElapsedTime( _meanReplElapsedTime ) << " | ";
838 
839  FH.width(8);
840  FH << _meanGenLength <<" | ";
841 
842  FH<<" "<<MAIN_VERSION<<"."<<MINOR_VERSION<<"."<<REVISION<<RELEASE
843  <<" "<<VERSION_DATE;
844 
845  FH<<" | ";
846  FH.width(20);
847  FH.setf(ios::left,ios::adjustfield);
848  char* host;
849  if( (host = getenv("HOST")) != NULL )
850  FH << host << " |";
851  else if ( (host = getenv("HOSTNAME")) != NULL )
852  FH << host << " |";
853  else
854  FH << "-" << " |";
855 
857 
858  for(;file != last; file++)
859  FH << " \"" << (*file)->get_extension() << "\":" << (*file)->get_path();
860 
861  FH << std::endl;
862 
863  FH.close();
864 }
file_it getFirstWriter()
Accessor to first element of the list of output FileHandlers.
Definition: fileservices.h:139
file_it getLastWriter()
Accessor to last element of the list of output FileHandlers.
Definition: fileservices.h:142
std::list< FileHandler * >::const_iterator file_it
Definition: fileservices.h:94
string & getBaseFileName()
Accessor to the base file name of the simulation.
Definition: fileservices.cc:474
clock_t _meanReplElapsedTime
Clock counter, for logging.
Definition: simulation.h:65
char _startTime[20]
Definition: simulation.h:61
std::string setElapsedTime(clock_t time)
Compute and print the simulation's elapsed time to stdout.
Definition: simulation.cc:760
unsigned int _meanGenLength
Generation counter, for logging.
Definition: simulation.h:67
char _endTime[20]
Definition: simulation.h:61
std::string _simElapsedTime
Definition: simulation.h:63
#define VERSION_DATE
Definition: version.h:29
#define MINOR_VERSION
Definition: version.h:26
#define RELEASE
Definition: version.h:28
#define MAIN_VERSION
Definition: version.h:25
#define REVISION
Definition: version.h:27

References _endTime, _FileServices, _logfile, _meanGenLength, _meanReplElapsedTime, _replicates, _simElapsedTime, _startTime, error(), FileServices::getBaseFileName(), FileServices::getFirstWriter(), FileServices::getLastWriter(), MAIN_VERSION, MINOR_VERSION, RELEASE, REVISION, setElapsedTime(), and VERSION_DATE.

Referenced by run().

+ Here is the caller graph for this function:

◆ printLogHeader()

void SimRunner::printLogHeader ( )
786 {
787  ofstream FH;
788  ifstream IF;
789  //check is the logfile already exists:
790  IF.open(_logfile.c_str(),ios::in);
791  if(IF){
792  IF.close();
793  return;
794  }
795  IF.close();
796 
797  FH.open(_logfile.c_str(),ios::out);
798  if(!FH) {
799  error("could not create simulation logfile \"%s\"\n",_logfile.c_str());
800  return;
801  }
802 
803  FH<<"--- N E M O ---\n"
804  <<" LOGFILE\n\n\n";
805  FH<<"| basename | start time | stop time | e-time CPU |"
806  <<" repl done | rpl e-time | mean gen | version | hostname | output files \n";
807 
808  FH.close();
809 }

References _logfile, and error().

Referenced by init().

+ Here is the caller graph for this function:

◆ register_component()

void SimRunner::register_component ( SimComponent cmpt)

Register the different Handler's attached to a SimComponent.

Parameters
cmpta SimComponent
221 {
222  _FileServices.load(cmpt);
223  _StatServices.load(cmpt);
225 }
virtual void load(SimComponent *sc)
Tells the SimComponent to load its file handlers.
Definition: fileservices.cc:81
virtual void load(SimComponent *sc)
tell the SimComponent to load its stat handlers
Definition: statservices.cc:169
virtual void load(SimComponent *sc)
Loads the updaters in case a component's parameter has temporal arguments.
Definition: updaterservices.cc:81

References _FileServices, _ParamUpdaterManager, _StatServices, FileServices::load(), StatServices::load(), and UpdaterServices::load().

Referenced by register_component_handlers().

+ Here is the caller graph for this function:

◆ register_component_handlers()

void SimRunner::register_component_handlers ( )

Register all the Handlers of the currently active simulation components.

230 {
232 
233  for(TRAIT_ITER trait = _currentTraits.begin(); trait != _currentTraits.end(); trait++)
234  register_component(trait->second);
235 
236  for(LCE_ITER LCE = _LifeCycle.begin(); LCE != _LifeCycle.end(); LCE++)
237  register_component(LCE->second);
238 }
map< trait_t, TraitPrototype * > _currentTraits
List of the selected trait prototypes from the user defined input parameters.
Definition: basicsimulation.h:221
map< int, LifeCycleEvent * >::const_iterator LCE_ITER
Definition: basicsimulation.h:225
map< trait_t, TraitPrototype * >::const_iterator TRAIT_ITER
Definition: basicsimulation.h:226
void register_component(SimComponent *cmpt)
Register the different Handler's attached to a SimComponent.
Definition: simulation.cc:220

References SimBuilder::_currentTraits, SimBuilder::_LifeCycle, _thePop, and register_component().

Referenced by init_components().

+ Here is the caller graph for this function:

◆ Replicate_LOOP()

void SimRunner::Replicate_LOOP ( )

Replicate loop, iterates the life cycle _replicates times.


554 {
555 
556 #ifndef USE_MPI
557 
558  clock_t start;
559  clock_t stop;
560  time_t t;
561  char t_buff[10];
562 
564  _meanGenLength = 0;
565  _currentGeneration = 0;
566 
567  //---------------------------------- REPLICATE LOOP -------------------------------------
569 
570 
571  // -------------------------- PRINT STUFF ------------------------------
572  t=time(0);
573  //print some output:
574  strftime(t_buff,10,"%H:%M:%S",localtime(&t));
575 
576 #ifdef LOW_VERBOSE
577  message(" replicate %i/%i [%s] \n",_currentReplicate, _replicates, t_buff);
578 #else
579  message("\r replicate %i/%i [%s] 1/%i ",_currentReplicate, _replicates, t_buff, _generations);
580  fflush(stdout);
581 #endif
582 
583  //---------------- SET POPULATION FOR FIRST GENERATION ------------------
584 
586 
587  //--------------------------- GENERATION LOOP ---------------------------
588  start = clock();
589 
590  Cycle(t_buff);
591 
592  stop = clock();
593  //-----------------------------------------------------------------------
594 
595  _meanReplElapsedTime += (stop - start);
596 
598 
599  //call the file services to print the replicate stats in case of pop extinction
600  if( !_thePop->isAlive() && _currentGeneration-1 <= _generations ) {
604  }
605 
606  if( _do_postexec_replicatewise ) runPostExecReplicateWise(); //will execute on each node
607  }
608  //--------------------------------- /REPLICATE LOOP -------------------------------------
609 
616  }
617 
620 
621 #else
622  //else ifndef USE_MPI
623  //------------------------------- MPI REPLICATE LOOP ------------------------------------
625 
626  while ( _currentReplicate <= _replicates )
628 
630 
631  if( _myenv->isMaster() ) {
636 
637  //write the stat files, only if "save_stats" LCE is part of the life cycle
638  if(get_LCE("save_stats")->get_paramset()->isSet()) {
639  FileHandler& statWriter = dynamic_cast<LCE_StatServiceNotifier*> ( get_LCE("save_stats") )->getFH();
640  for (unsigned int i = 1; i <= _replicates; ++i) {
641  _currentReplicate = i;
642  statWriter.FHwrite();
643  }
644  }
645  }
646  //------------------------------ /MPI REPLICATE LOOP ------------------------------------
647 #endif
648  //endif USE_MPI
649 
650  //delete all individuals present in the population and delete the patches:
651  _thePop->clear();
652 }
LifeCycleEvent * get_LCE(string name)
Search for component with "name" in the life cycle events list.
Definition: basicsimulation.cc:78
Interface to handle file input/output for any SimComponent.
Definition: filehandler.h:52
virtual void FHwrite()=0
Default behavior of the class, called by Handler::update().
virtual void notify()
Definition: fileservices.cc:188
Initiates the StatServices' parameters (log time) when registering, calls StatServices::notify() when...
Definition: servicenotifiers.h:183
virtual unsigned int init(StatServices *StatManager)=0
virtual void iterate(SimRunner *_sim, StatServices *StatManager, unsigned int *_gen, unsigned int *_repl)=0
virtual void finish(StatServices *StatManager, unsigned int *_gen, unsigned int _repl)
void setCurrentReplicate(unsigned int repl)
Definition: metapop.h:296
void clear()
Called at the end of each simulation, empties the pop and the garbage collector; the Individuals are ...
Definition: metapop.cc:1191
ParamSet * get_paramset(string &name)
Looks for paramset with "name" in the list of parameter sets.
Definition: basicsimulation.cc:233
void setForFirstGeneration()
Sets the population and the services ready for the first generation of a new replicate.
Definition: simulation.cc:656
void Cycle(char *startTime)
Life cycle loop, executes the list of LCEs _generations times.
Definition: simulation.cc:673
void runPostExecReplicateWise()
Run the post-exec script after each replicate, adds filename and replicate number as args.
Definition: simulation.cc:893

References _currentGeneration, _currentReplicate, _do_postexec_replicatewise, _FileServices, _generations, _meanGenLength, _meanReplElapsedTime, _my_mpi_manager, _myenv, _replicates, _StatServices, _thePop, Metapop::clear(), Cycle(), FileHandler::FHwrite(), MPImanager::finish(), ComponentManager::get_LCE(), ParamManager::get_paramset(), MPImanager::init(), Metapop::isAlive(), MPIenv::isMaster(), MPImanager::iterate(), message(), FileServices::notify(), runPostExecReplicateWise(), Metapop::setCurrentGeneration(), Metapop::setCurrentReplicate(), and setForFirstGeneration().

Referenced by run().

+ Here is the caller graph for this function:

◆ reset()

void SimRunner::reset ( )

Resets all the parameters to the unset state, resets the services.

192 {
193 #ifdef _DEBUG_
194  message("SimRunner::reset\n");
195 #endif
196  //reset all the parameter to the "unset" state
197  list<ParamSet*>::iterator current_paramset = this->_allParams.begin();
198  while(current_paramset != this->_allParams.end()) {
199  (*current_paramset)->reset();
200  current_paramset++;
201  }
202 
203  reset_services();
204 }
list< ParamSet * > _allParams
A list of all the parameter sets of all the simulation components loaded in the _component list of th...
Definition: basicsimulation.h:142
void reset_services()
Resets the FileServices and StatServices.
Definition: simulation.cc:208

References ParamManager::_allParams, message(), and reset_services().

Referenced by init_components(), and ~SimRunner().

+ Here is the caller graph for this function:

◆ reset_services()

void SimRunner::reset_services ( )

Resets the FileServices and StatServices.

209 {
213 #ifdef _DEBUG_
214  message("SimRunner::reset_services::done\n");
215 #endif
216 }
virtual void reset()
Clears the list of FileHandlers.
Definition: fileservices.cc:402
virtual void reset()
clear the list of StatHandler
Definition: statservices.cc:207
virtual void reset()
Clears the containers.
Definition: updaterservices.cc:60

References _FileServices, _ParamUpdaterManager, _StatServices, message(), FileServices::reset(), StatServices::reset(), and UpdaterServices::reset().

Referenced by reset().

+ Here is the caller graph for this function:

◆ run() [1/2]

bool SimRunner::run ( )

First loop of the simulation, performs the simulations stored in the ParamManager base class.

434 {
435  time_t t;
436  unsigned int sim = 0, simnbre = _simRecords.size();
437 
438  list< map< string,string > >::iterator currentSim = _simRecords.begin();
439 
440  //first loop: perform all simulations contained in _simRecords:
441  //---------------------------------------------------------------------------------------
442  while(currentSim != _simRecords.end()) {
443 
444  sim++;
445 
446  //clear and build the lists of traits, LCEs, stats and files handlers, random seed
447  //create trait prototypes and the genetic map within IndFactory::makePrototype
448  if(!init_components(*currentSim)) return false;
449 
450  //output a few info:
451  if ( _myenv->isMaster() ) {
452 
453  t = time(NULL);
454 
455  strftime(_startTime, 20, "%d-%m-%Y %H:%M:%S", localtime(&t));
456 
457  message("\n--- SIMULATION %i/%i ---- [ %s ]\n\n",sim,simnbre,_FileServices.getBaseFileName().c_str());
458  message(" start: %s\n",_startTime);
459  message(" mode: %s\n",_modeArg.c_str());
460  message(" population: 2 stages, %i patch%s",
461  _thePop->getPatchNbr(), (_thePop->getPatchNbr() > 1 ? "es" : ""));
462 
463  // Wright-Fisher population?
464  if(get_LCE("breed")->get_parameter("mating_isWrightFisher")->isSet() ||
465  get_LCE("breed_selection")->get_parameter("mating_isWrightFisher")->isSet())
466  message(", Wright-Fisher\n");
467  else
468  message(", non Wright-Fisher\n");
469 
470  message(" traits: ");
471 
472  map<trait_t, TraitPrototype* >::iterator trait = _currentTraits.begin();
473 
474  while(trait != _currentTraits.end()) {
475  message("%s",trait->first.c_str());
476  message("(%i)", _thePop->getTraitIndex(trait->first.c_str()));
477  trait++;
478  if(trait != _currentTraits.end()) message(", ");
479  }
480 
481  message("\n LCEs: ");
482 
483  LCE_ITER LCE = _LifeCycle.begin();
484  while( LCE != _LifeCycle.end()) {
485  message("%s(%i)",LCE->second->get_event_name().c_str(),LCE->first);
486  LCE++;
487  if(LCE != _LifeCycle.end()) message(", ");
488  }
489 
490  message("\n");
491  }
492 
493  //init the file services:
494  //->files check, false means the user wants to skip this simulation.
495  if( !(_FileServices.init(this->_currentParams)) ) {
496  currentSim++;
498  continue;
499  }
500 
501  // Load the population from a source file?
502  if(_thePop->isSourceLoad()) {
503  message(" loading population from: %s (%s)\n",_thePop->getSourceName().c_str(),
504  _thePop->getSourceFileType().c_str());
505  } // endif isSourceLoad
506 
507  if ( _myenv->isMaster() ) message("\n");
508 
509  //->save simulation parameters in log files, add the current random seed
510  // this is where ini files are created in `run_mode create_init' (mode == 4)
512  _FileServices.log("#random_seed "+tstring::ulong2str( _random_seed ));
513 
514  clock_t start = clock();
515 
516  //run the simulation
517  //-------------------------------------------------------------------------------------
518  if(_doRun) Replicate_LOOP( );
519 
520  clock_t stop = clock();
521 
522  t = time(NULL);
523 
524  strftime(_endTime, 20, "%d-%m-%Y %H:%M:%S", localtime(&t));
525 
526  _simElapsedTime = setElapsedTime(stop - start);
527 
528  if ( _myenv->isMaster() && _mode != 3 && _mode != 4) {
529  printLog();
530  message("\n\n end: %s\n",_endTime);
531  message("--- done (CPU time: %ss)\n",_simElapsedTime.c_str());
532  //don't log this when in 'dryrun' or 'create_init' mode:
533  _FileServices.log("\n# simulation finished " + string(_endTime));
534  _FileServices.log("# CPU time used: " + _simElapsedTime + "s");
535  }
536 
538 
539  // free all allocated memory of the random number generator
540  // it will be re-allocated in `init_components -> ini_random_seed'
541  RAND::free();
542 
543  currentSim++;
544  }
545  //---------------------------------------------------------------------------------------
546  if( _do_postexec && _myenv->isMaster() ) runPostExec();
547 
548  return true;
549 }
void log(string message)
Write to the parameter logfile.
Definition: fileservices.cc:435
virtual bool init()
Definition: fileservices.h:100
void log_simparams()
Saves the current simulation parameters to the default parameter logfile.
Definition: fileservices.cc:425
int getTraitIndex(trait_t type)
Gives the index of trait with type.
Definition: indfactory.cc:127
void clearPrototype()
Reset the trait prototypes, mostly done to unregister the genetic maps.
Definition: indfactory.cc:102
bool isSourceLoad()
Definition: metapop.h:281
unsigned int getPatchNbr()
Definition: metapop.h:275
string getSourceFileType()
Definition: metapop.h:283
string getSourceName()
Definition: metapop.h:282
list< map< string, string > > _simRecords
Sets of parameters of all the simulations to perform.
Definition: basicsimulation.h:148
static void free()
Memory de-allocation.
Definition: Uniform.h:110
void runPostExec()
Run the post-exec script after all simulations have finished.
Definition: simulation.cc:868
bool init_components(map< string, string > &simparams)
Performs the initialization of the different components of the simulation.
Definition: simulation.cc:252
void printLog()
Definition: simulation.cc:813
void Replicate_LOOP()
Replicate loop, iterates the life cycle _replicates times.
Definition: simulation.cc:553
static string ulong2str(const unsigned long i)
Writes an integer value into a string.
Definition: tstring.h:104

References SimBuilder::_currentTraits, _do_postexec, _doRun, _endTime, _FileServices, SimBuilder::_LifeCycle, _mode, _modeArg, _myenv, _random_seed, _simElapsedTime, ParamManager::_simRecords, _startTime, _thePop, IndFactory::clearPrototype(), RAND::free(), ComponentManager::get_LCE(), FileServices::getBaseFileName(), Metapop::getPatchNbr(), Metapop::getSourceFileType(), Metapop::getSourceName(), IndFactory::getTraitIndex(), FileServices::init(), init_components(), MPIenv::isMaster(), Metapop::isSourceLoad(), FileServices::log(), FileServices::log_simparams(), message(), printLog(), Replicate_LOOP(), runPostExec(), setElapsedTime(), and tstring::ulong2str().

Referenced by run().

+ Here is the caller graph for this function:

◆ run() [2/2]

bool SimRunner::run ( int  ARGC,
char **  ARGV 
)

First loop of the simulation, performs the simulations stored in the ParamManager base class.

383 {
384 
385  //initialize the MPI environment:
386  _myenv = new MPIenv( &ARGC, &ARGV, _my_mpi_manager );
387 
388 
389  // initialize the random number generator with default seed
390  // it will be reinitialized later with user-provided seed, if any
391  RAND::init(time(0));
392 
393  //--------------------------------------------------------------------
394  if(_myenv->isMaster()) {
395 
396  START_MESSAGE();
397 
398  }
399 
400  //--------------------------------------------------------------------
401  //check for the presence of a metapop:
402  if(_thePop == NULL) fatal("SimRunner::run: no population is attached at startup!\n");
403 
404  //--------------------------------------------------------------------
405  //build the list of params from the components list
406  this->build_allParams();
407 
408  //--------------------------------------------------------------------
409  //get the input parameters from the input parameter file
410 
411  // create a stream parser attached to the file reader
412  FileParser Reader("");
413 
414  if (ARGC == 1)
415  build_records(Reader.getParsedParameters("Nemo2.ini")); // this calls StreamParser::ParamParser::getParsedParameters
416  else
417  for (int i = 1; i < ARGC; ++i)
418  build_records(Reader.getParsedParameters(ARGV[i]));
419 
420  //--------------------------------------------------------------------
421  //run the simulation
422  bool status = run();
423 
425 
426  delete _myenv;
427 
428  return status;
429 }
Text input parameter file parser.
Definition: fileparser.h:36
MPI environment setup.
Definition: MPImanager.h:121
static void finish(MPImanager *p)
Definition: MPImanager.cc:89
void build_records(map< string, vector< string > > &initParams)
Builds the list of simulation parameters from the parsed input file(s).
Definition: basicsimulation.cc:251
void build_allParams()
Clears and fills the _allParams list with the ParamSet's of the simulation components.
Definition: basicsimulation.cc:117
bool run()
First loop of the simulation, performs the simulations stored in the ParamManager base class.
Definition: simulation.cc:433
void START_MESSAGE()
Definition: version.h:32

References _my_mpi_manager, _myenv, _thePop, ParamManager::build_allParams(), ParamManager::build_records(), fatal(), MPIenv::finish(), ParamsParser::getParsedParameters(), RAND::init(), MPIenv::isMaster(), run(), and START_MESSAGE().

Referenced by main().

+ Here is the caller graph for this function:

◆ run_event()

bool SimRunner::run_event ( string &  name)

Execute one specific life cycle event, if present in the list of current events.

Parameters
namethe name of the (paramSet of the) LifeCycleEvent to execute.
724 {
725  //before calling that fction, first set the params and call init_components()!!
726 
727  LifeCycleEvent* event = this->get_current_event(name);
728 
729  if(event == NULL) {
730  error("SimRunner::run_event:event \"%s\" not found in set events!\n",name.c_str());
731  return false;
732  }
733 
734  if( !(event->get_paramset()->isSet()) ) return false;//highly unlikely!!
735 
736  event->execute();
737 
738  return true;
739 }
Base class of the Life Cycle Events, declares the LCE interface.
Definition: lifecycleevent.h:72
LifeCycleEvent * get_current_event(string &name)
Accessor to the list of current LCEs.
Definition: basicsimulation.cc:857

References error(), and SimBuilder::get_current_event().

◆ runPostExec()

void SimRunner::runPostExec ( )

Run the post-exec script after all simulations have finished.

869 {
870  ifstream script(_postexec_script.c_str(),ios::in);
871  string cmd;
872 
873  if(!script.is_open()) {
874  error("could not open post simulation shell script!\n");
875  return;
876  }
877 
878  message("Executing shell script \"%s\" ",_postexec_script.c_str());
879  fflush(stdout);
880 
881  cmd = "sh " + _postexec_script + " " + _postexec_args;
882 
883  if(system(cmd.c_str()) < 0){
884  error("execution of `sh %s %s' failed: %s\n",_postexec_script.c_str(), _postexec_args.c_str(),strerror(errno));
885  return;
886  }
887 
888  message("...done\n");
889 }

References _postexec_args, _postexec_script, error(), and message().

Referenced by run().

+ Here is the caller graph for this function:

◆ runPostExecReplicateWise()

void SimRunner::runPostExecReplicateWise ( )

Run the post-exec script after each replicate, adds filename and replicate number as args.

894 {
895  ifstream script(_postexec_script.c_str(),ios::in);
896  string cmd;
897 
898  if(!script.is_open()) {
899  error("could not open post simulation shell script!\n");
900  return;
901  }
902 
903  message("Executing shell script \"%s\" ",_postexec_script.c_str());
904  fflush(stdout);
905 
906  // runs the script with base sim filename and replicate number as two first arguments
908 
909  if(system(cmd.c_str()) < 0){
910  error("execution of `sh %s %s' failed: %s\n",_postexec_script.c_str(), _postexec_args.c_str(),strerror(errno));
911  return;
912  }
913 
914  message("...done\n");
915 }
static string int2str(const int i)
Writes an integer value into a string.
Definition: tstring.h:94

References _currentReplicate, _FileServices, _postexec_args, _postexec_script, error(), FileServices::getBaseFileName(), tstring::int2str(), and message().

Referenced by Replicate_LOOP().

+ Here is the caller graph for this function:

◆ setCurrentGeneration()

void SimRunner::setCurrentGeneration ( unsigned int  gen)
inline

◆ setCurrentReplicate()

void SimRunner::setCurrentReplicate ( unsigned int  repl)
inline

◆ setElapsedTime()

std::string SimRunner::setElapsedTime ( clock_t  time)

Compute and print the simulation's elapsed time to stdout.

Parameters
timeelapsed time in ticks count
761 {
762  int e_time = time / CLOCKS_PER_SEC;
763  int hour = e_time / 3600;
764  int minute = ((e_time % 3600) / 60);
765  int sec = (e_time % 3600) % 60;
766 
767  std::ostringstream out(ios::out);
768 
769  out.fill('0');
770  out.width(2);
771  out<<hour<<":";
772  out.width(2);
773  out<<minute<<":";
774  out.precision(2);
775  out.fill('0');
776  out.width(2);
777  out<<sec;
778 
779  return(out.str());
780 }

Referenced by printLog(), and run().

+ Here is the caller graph for this function:

◆ setForFirstGeneration()

void SimRunner::setForFirstGeneration ( )

Sets the population and the services ready for the first generation of a new replicate.

657 {
659 
660  //reset temporal parameters/components to their first generation value/state
662 
663  //reset stat recording iterator to first occurrence
665 
666  //build metapopulation for the current replicate (build first generation)
668 
669 }
void setPopulation(unsigned int currentReplicate, unsigned int replicates)
Sets the population for the first generation of each replicates.
Definition: metapop.cc:707
void resetCurrentOccurrence()
Resets the occurrence iterator to the beginning of the list of generation occurrences.
Definition: statservices.h:137
virtual void notify()
Definition: updaterservices.h:77

References _currentReplicate, _ParamUpdaterManager, _replicates, _StatServices, _thePop, UpdaterServices::notify(), StatServices::resetCurrentOccurrence(), Metapop::setCurrentGeneration(), and Metapop::setPopulation().

Referenced by Replicate_LOOP().

+ Here is the caller graph for this function:

◆ setGenerations()

void SimRunner::setGenerations ( unsigned int  gen)
inline

◆ setLifeCycle()

void SimRunner::setLifeCycle ( )

Sets the list of LifeCyckeEvent's currently active.

243 {
244  build_LifeCycle();
245 
246  for( LCE_ITER LCE = _LifeCycle.begin(); LCE != _LifeCycle.end(); LCE++)
247  LCE->second->init(_thePop);
248 }
void build_LifeCycle()
Selects the life cycle events that have their parameters set.
Definition: basicsimulation.cc:936

References SimBuilder::_LifeCycle, _thePop, and SimBuilder::build_LifeCycle().

Referenced by init_components().

+ Here is the caller graph for this function:

◆ setReplicates()

void SimRunner::setReplicates ( unsigned int  repl)
inline

◆ step()

void SimRunner::step ( unsigned int  nb_gen)

Iterates the life cycle.

Parameters
nb_gennumber of iterations to perform.
744 {
745  LCE_ITER LCE = _LifeCycle.begin();
746 
747  while(LCE != _LifeCycle.end()) {
748  _currentRankInLifeCycle = LCE->second->get_rank();
749 #ifdef _DEBUG_
750  message("LCE rank %i: %s\n", _currentRankInLifeCycle, LCE->second->get_event_name().c_str());
751 #endif
752  LCE->second->execute();
753  _thePop->setCurrentAge(LCE->second);
754  LCE++;
755  }
756 }
void setCurrentAge(age_t age)
Sets the age flag.
Definition: metapop.h:302

References _currentRankInLifeCycle, SimBuilder::_LifeCycle, _thePop, message(), and Metapop::setCurrentAge().

Referenced by Cycle().

+ Here is the caller graph for this function:

Member Data Documentation

◆ _currentGeneration

unsigned int SimRunner::_currentGeneration
private

The current generation in the generation loop, starts at 1.

Referenced by Cycle(), getCurrentGeneration(), Replicate_LOOP(), and setCurrentGeneration().

◆ _currentRankInLifeCycle

int SimRunner::_currentRankInLifeCycle
private

The current rank in the life cycle, corresponds to the rank of the current LCE, before it executes.

Referenced by getCurrentRankInLifeCycle(), and step().

◆ _currentReplicate

unsigned int SimRunner::_currentReplicate
private

The current replicate in the replicate loop, starts at 1.

Referenced by Cycle(), getCurrentReplicate(), Replicate_LOOP(), runPostExecReplicateWise(), setCurrentReplicate(), and setForFirstGeneration().

◆ _do_postexec

bool SimRunner::_do_postexec
private

Boolean set when a post-exec script must be executed.

Referenced by init(), and run().

◆ _do_postexec_replicatewise

bool SimRunner::_do_postexec_replicatewise
private

Boolean to trigger replicate-wise execution of post script.

Referenced by init(), and Replicate_LOOP().

◆ _doRun

bool SimRunner::_doRun
private

Boolean set when not in dryrun mode.

Referenced by init(), and run().

◆ _endTime

char SimRunner::_endTime[20]
private

Referenced by printLog(), and run().

◆ _FileServices

◆ _generations

unsigned int SimRunner::_generations
private

Number of generations to iterate.

Referenced by Cycle(), getGenerations(), init(), init_components(), Replicate_LOOP(), and setGenerations().

◆ _logfile

std::string SimRunner::_logfile
private

Referenced by init(), printLog(), and printLogHeader().

◆ _meanGenLength

unsigned int SimRunner::_meanGenLength
private

Generation counter, for logging.

Referenced by printLog(), and Replicate_LOOP().

◆ _meanReplElapsedTime

clock_t SimRunner::_meanReplElapsedTime
private

Clock counter, for logging.

Referenced by printLog(), and Replicate_LOOP().

◆ _mode

unsigned int SimRunner::_mode
private

The run mode code (0 = run, 1 = overwrite, 2 = skip, 3 = dryrun, 4 = create_init)

Referenced by init(), and run().

◆ _modeArg

std::string SimRunner::_modeArg
private

The run mode ('overwrite', 'run', 'skip', 'dryrun', 'create_init').

Referenced by init(), and run().

◆ _my_mpi_manager

MPImanager* SimRunner::_my_mpi_manager
private

Referenced by Replicate_LOOP(), and run().

◆ _ParamUpdaterManager

◆ _postexec_args

std::string SimRunner::_postexec_args
private

Arguments to pass to the post-exec script.

Referenced by init(), runPostExec(), and runPostExecReplicateWise().

◆ _postexec_script

std::string SimRunner::_postexec_script
private

The path to the script to be executed after last simulation.

Referenced by init(), runPostExec(), and runPostExecReplicateWise().

◆ _random_seed

unsigned long SimRunner::_random_seed
private

The startup random seed of the random generator.

Referenced by init_random_seed(), and run().

◆ _replicates

unsigned int SimRunner::_replicates
private

◆ _simElapsedTime

std::string SimRunner::_simElapsedTime
private

Referenced by printLog(), and run().

◆ _startTime

char SimRunner::_startTime[20]
private

Referenced by printLog(), and run().

◆ _StatServices

◆ _thePop


The documentation for this class was generated from the following files:

Generated for Nemo v2.4.1 by  doxygen 1.9.1

Catalogued on GSR