Nemo  2.4.2
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
107  {
108  attach_pop(pop);
109  }
void attach_pop(Metapop *pop)
Attach a pop to the simulation.
Definition: simulation.h:172
MPImanager * _my_mpi_manager
Definition: simulation.h:54
bool _do_postexec_replicatewise
Boolean to trigger replicate-wise execution of post script.
Definition: simulation.h:92
bool _do_postexec
Boolean set when a post-exec script must be executed.
Definition: simulation.h:94

References attach_pop().

◆ ~SimRunner()

SimRunner::~SimRunner ( )

Dstror.

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

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
172 {_thePop = pop;this->_components.push_back(_thePop);}
list< SimComponent * > _components
List of all the simulation components.
Definition: basicsimulation.h:69
Metapop * _thePop
Definition: simulation.h:56

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

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.

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

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.

156 {return _StatServices.getAllStats();}
StatServices _StatServices
Definition: simulation.h:100
list< StatRecBase * > getAllStats()
Definition: statservices.cc:403

References _StatServices, and StatServices::getAllStats().

◆ get_FileServices()

FileServices* SimRunner::get_FileServices ( )
inline

Returns the FileServices.

152 {return &_FileServices;}
FileServices _FileServices
Definition: simulation.h:98

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
176 {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.

154 {return &_StatServices;}

References _StatServices.

Referenced by LCE_StatServiceNotifier::LCE_StatServiceNotifier().

+ Here is the caller graph for this function:

◆ getCurrentGeneration()

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

References _currentGeneration.

Referenced by SIMenv::getCurrentGeneration().

+ Here is the caller graph for this function:

◆ getCurrentRankInLifeCycle()

int SimRunner::getCurrentRankInLifeCycle ( )
inline
201 {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:78

References _currentRankInLifeCycle.

Referenced by SIMenv::getCurrentRankInLifeCycle().

+ Here is the caller graph for this function:

◆ getCurrentReplicate()

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

References _currentReplicate.

Referenced by SIMenv::getCurrentReplicate().

+ Here is the caller graph for this function:

◆ getGenerations()

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

References _generations.

Referenced by SIMenv::getGenerations().

+ Here is the caller graph for this function:

◆ getReplicates()

unsigned int SimRunner::getReplicates ( )
inline
200 {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.

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

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

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.

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

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

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

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
220 {
221  _FileServices.load(cmpt);
222  _StatServices.load(cmpt);
224 }
virtual void load(SimComponent *sc)
Tells the SimComponent to load its file handlers.
Definition: fileservices.cc:80
virtual void load(SimComponent *sc)
tell the SimComponent to load its stat handlers
Definition: statservices.cc:168
virtual void load(SimComponent *sc)
Loads the updaters in case a component's parameter has temporal arguments.
Definition: updaterservices.cc:80

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.

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

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.


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

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.

191 {
192 #ifdef _DEBUG_
193  message("SimRunner::reset\n");
194 #endif
195  //reset all the parameter to the "unset" state
196  list<ParamSet*>::iterator current_paramset = this->_allParams.begin();
197  while(current_paramset != this->_allParams.end()) {
198  (*current_paramset)->reset();
199  current_paramset++;
200  }
201 
202  reset_services();
203 }
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:141
void reset_services()
Resets the FileServices and StatServices.
Definition: simulation.cc:207

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.

208 {
212 #ifdef _DEBUG_
213  message("SimRunner::reset_services::done\n");
214 #endif
215 }
virtual void reset()
Clears the list of FileHandlers.
Definition: fileservices.cc:401
virtual void reset()
clear the list of StatHandler
Definition: statservices.cc:206
virtual void reset()
Clears the containers.
Definition: updaterservices.cc:59

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.

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

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.

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

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

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

◆ runPostExec()

void SimRunner::runPostExec ( )

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

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

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.

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

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
760 {
761  int e_time = time / CLOCKS_PER_SEC;
762  int hour = e_time / 3600;
763  int minute = ((e_time % 3600) / 60);
764  int sec = (e_time % 3600) % 60;
765 
766  std::ostringstream out(ios::out);
767 
768  out.fill('0');
769  out.width(2);
770  out<<hour<<":";
771  out.width(2);
772  out<<minute<<":";
773  out.precision(2);
774  out.fill('0');
775  out.width(2);
776  out<<sec;
777 
778  return(out.str());
779 }

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.

656 {
658 
659  //reset temporal parameters/components to their first generation value/state
661 
662  //reset stat recording iterator to first occurrence
664 
665  //build metapopulation for the current replicate (build first generation)
667 
668 }
void setPopulation(unsigned int currentReplicate, unsigned int replicates)
Sets the population for the first generation of each replicates.
Definition: metapop.cc:706
void resetCurrentOccurrence()
Resets the occurrence iterator to the beginning of the list of generation occurrences.
Definition: statservices.h:136
virtual void notify()
Definition: updaterservices.h:76

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.

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

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.
743 {
744  LCE_ITER LCE = _LifeCycle.begin();
745 
746  while(LCE != _LifeCycle.end()) {
747  _currentRankInLifeCycle = LCE->second->get_rank();
748 #ifdef _DEBUG_
749  message("LCE rank %i: %s\n", _currentRankInLifeCycle, LCE->second->get_event_name().c_str());
750 #endif
751  LCE->second->execute();
752  _thePop->setCurrentAge(LCE->second);
753  LCE++;
754  }
755 }
void setCurrentAge(age_t age)
Sets the age flag.
Definition: metapop.h:301

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.2 by  doxygen 1.9.1

Catalogued on GSR