CYCLUS
context.cc
Go to the documentation of this file.
1 #include "context.h"
2 
3 #include <vector>
4 #include <boost/uuid/uuid_generators.hpp>
5 
6 #include "error.h"
7 #include "exchange_solver.h"
8 #include "logger.h"
9 #include "pyhooks.h"
10 #include "sim_init.h"
11 #include "timer.h"
12 #include "version.h"
13 
14 namespace cyclus {
15 
16 double cy_eps = 1e-6;
17 double cy_eps_rsrc = 1e-6;
18 
20  : duration(0),
21  y0(0),
22  m0(0),
24  decay("manual"),
25  branch_time(-1),
26  explicit_inventory(false),
27  explicit_inventory_compact(false),
28  parent_sim(boost::uuids::nil_uuid()),
29  parent_type("init") {}
30 
32  : duration(dur),
33  y0(y0),
34  m0(m0),
36  decay("manual"),
37  branch_time(-1),
38  handle(handle),
39  explicit_inventory(false),
41  parent_sim(boost::uuids::nil_uuid()),
42  parent_type("init") {}
43 
45  : duration(dur),
46  y0(y0),
47  m0(m0),
49  decay(d),
50  branch_time(-1),
51  handle(handle),
52  explicit_inventory(false),
54  parent_sim(boost::uuids::nil_uuid()),
55  parent_type("init") {}
56 
57 SimInfo::SimInfo(int dur, boost::uuids::uuid parent_sim,
60  : duration(dur),
61  y0(-1),
62  m0(-1),
64  decay("manual"),
65  parent_sim(parent_sim),
66  parent_type(parent_type),
67  branch_time(branch_time),
68  explicit_inventory(false),
70  handle(handle) {}
71 
73  : ti_(ti),
74  rec_(rec),
75  solver_(NULL),
76  trans_id_(0),
77  si_(0) {}
78 
80  if (solver_ != NULL) {
81  delete solver_;
82  }
83 
84  // initiate deletion of agents that don't have parents.
85  // dealloc will propagate through hierarchy as agents delete their children
86  std::vector<Agent*> to_del;
87  std::set<Agent*>::iterator it;
88  for (it = agent_list_.begin(); it != agent_list_.end(); ++it) {
89  if ((*it)->parent() == NULL) {
90  to_del.push_back(*it);
91  }
92  }
93  for (int i = 0; i < to_del.size(); ++i) {
94  DelAgent(to_del[i]);
95  }
96 }
97 
99  int n = agent_list_.erase(m);
100  if (n == 1) {
101  PyDelAgent(m->id());
102  delete m;
103  m = NULL;
104  }
105 }
106 
107 void Context::SchedBuild(Agent* parent, std::string proto_name, int t) {
108  if (t == -1) {
109  t = time() + 1;
110  }
111  int pid = (parent != NULL) ? parent->id() : -1;
112  ti_->SchedBuild(parent, proto_name, t);
113  NewDatum("BuildSchedule")
114  ->AddVal("ParentId", pid)
115  ->AddVal("Prototype", proto_name)
116  ->AddVal("SchedTime", time())
117  ->AddVal("BuildTime", t)
118  ->Record();
119 }
120 
121 void Context::SchedDecom(Agent* m, int t) {
122  if (t == -1) {
123  t = time();
124  }
125  ti_->SchedDecom(m, t);
126  NewDatum("DecomSchedule")
127  ->AddVal("AgentId", m->id())
128  ->AddVal("SchedTime", time())
129  ->AddVal("DecomTime", t)
130  ->Record();
131 }
132 
133 boost::uuids::uuid Context::sim_id() {
134  return rec_->sim_id();
135 }
136 
138  AddPrototype(name, p, false);
139 }
140 
141 void Context::AddPrototype(std::string name, Agent* p, bool overwrite) {
142  if (!overwrite && protos_.find(name) != protos_.end()) {
143  throw KeyError("Prototype name " + name + " has already been added" +
144  " and cannot be overwritten.");
145  }
146 
147  protos_[name] = p;
148  // explicit snapshot required for in situ (non-xml) prototype addition
150  NewDatum("Prototypes")
151  ->AddVal("Prototype", name)
152  ->AddVal("AgentId", p->id())
153  ->AddVal("Spec", p->spec())
154  ->Record();
155 
156  std::string spec = p->spec();
157  if (rec_ver_.count(spec) == 0) {
158  rec_ver_.insert(spec);
159  NewDatum("AgentVersions")
160  ->AddVal("Spec", spec)
161  ->AddVal("Version", p->version())
162  ->Record();
163  }
164 }
165 
167  recipes_[name] = c;
168  NewDatum("Recipes")
169  ->AddVal("Recipe", name)
170  ->AddVal("QualId", c->id())
171  ->Record();
172 }
173 
175  if (recipes_.count(name) == 0) {
176  throw KeyError("Invalid recipe name " + name);
177  }
178  return recipes_[name];
179 }
180 
182  NewDatum("Info")
183  ->AddVal("Handle", si.handle)
184  ->AddVal("InitialYear", si.y0)
185  ->AddVal("InitialMonth", si.m0)
186  ->AddVal("Duration", si.duration)
187  ->AddVal("ParentSimId", si.parent_sim)
188  ->AddVal("ParentType", si.parent_type)
189  ->AddVal("BranchTime", si.branch_time)
190  ->AddVal("CyclusVersion", std::string(version::core()))
191  ->AddVal("CyclusVersionDescribe", std::string(version::describe()))
192  ->AddVal("SqliteVersion", std::string(version::sqlite3()))
193  ->AddVal("Hdf5Version", std::string(version::hdf5()))
194  ->AddVal("BoostVersion", std::string(version::boost()))
195  ->AddVal("LibXML2Version", std::string(version::xml2()))
196  ->AddVal("CoinCBCVersion", std::string(version::coincbc()))
197  ->Record();
198 
199  NewDatum("DecayMode")
200  ->AddVal("Decay", si.decay)
201  ->Record();
202 
203  NewDatum("InfoExplicitInv")
204  ->AddVal("RecordInventory", si.explicit_inventory)
205  ->AddVal("RecordInventoryCompact", si.explicit_inventory_compact)
206  ->Record();
207 
208  // TODO: when the backends get uint64_t support, the static_cast here should
209  // be removed.
210  NewDatum("TimeStepDur")
211  ->AddVal("DurationSecs", static_cast<int>(si.dt))
212  ->Record();
213 
214  NewDatum("Epsilon")
215  ->AddVal("GenericEpsilon", si.eps)
216  ->AddVal("ResourceEpsilon", si.eps_rsrc)
217  ->Record();
218 
219  NewDatum("XMLPPInfo")
220  ->AddVal("LibXMLPlusPlusVersion", std::string(version::xmlpp()))
221  ->Record();
222 
223  si_ = si;
224  ti_->Initialize(this, si);
225 }
226 
228  return ti_->time();
229 }
230 
232  ti_->RegisterTimeListener(tl);
233 }
234 
236  ti_->UnregisterTimeListener(tl);
237 }
238 
240  return rec_->NewDatum(title);
241 }
242 
244  ti_->Snapshot();
245 }
246 
248  ti_->KillSim();
249 }
250 
251 } // namespace cyclus
virtual std::string version()
Definition: agent.h:65
Composition::Ptr GetRecipe(std::string name)
Retrieve a registered recipe.
Definition: context.cc:174
boost::uuids::uuid sim_id()
returns the unique id associated with this cyclus simulation.
Definition: recorder.cc:49
boost::shared_ptr< Composition > Ptr
Definition: composition.h:43
void AddRecipe(std::string name, Composition::Ptr c)
Adds a composition recipe to a simulation-wide accessible list.
Definition: context.cc:166
Definition: any.hpp:72
std::string handle
user-defined label associated with a particular simulation
Definition: context.h:76
int branch_time
timestep at which simulation branching occurs if any
Definition: context.h:98
double cy_eps
generic epsilon values
Definition: context.cc:16
const char * xmlpp()
Definition: version.cc:67
const char * xml2()
Definition: version.cc:63
double eps
Epsilon in the simulation.
Definition: context.h:104
void RegisterTimeListener(TimeListener *agent)
Registers an agent to receive tick/tock notifications every timestep.
Definition: timer.cc:182
boost::uuids::uuid sim_id()
See Recorder::sim_id documentation.
Definition: context.cc:133
virtual const int id() const
The agent instance&#39;s unique ID within a simulation.
Definition: agent.h:354
std::string name(int nuc)
Definition: pyne.cc:2940
int duration
length of the simulation in timesteps (months)
Definition: context.h:82
void Snapshot()
Schedules a snapshot of simulation state to output database to occur at the beginning of the next tim...
Definition: timer.h:57
void UnregisterTimeListener(TimeListener *tl)
Removes an agent from receiving tick/tock notifications.
Definition: timer.cc:186
void UnregisterTimeListener(TimeListener *tl)
Removes an agent from receiving tick/tock notifications.
Definition: context.cc:235
int y0
start year for the simulation (e.g. 1973);
Definition: context.h:85
bool explicit_inventory
True if per-agent inventories should be explicitly queried/recorded every time step in a table (i...
Definition: context.h:111
const char * describe()
Definition: version.cc:34
std::string spec()
The string representation of the agent spec that uniquely identifies the concrete agent class/module...
Definition: agent.h:358
void InitSim(SimInfo si)
Initializes the simulation time parameters.
Definition: context.cc:181
~Context()
Clean up resources including destructing the solver and all agents the context is aware of...
Definition: context.cc:79
uint64_t dt
Duration in seconds of a single time step in the simulation.
Definition: context.h:101
Context(Timer *ti, Recorder *rec)
Creates a new context working with the specified timer and datum manager.
Definition: context.cc:72
virtual int time()
Returns the current simulation timestep.
Definition: context.cc:227
Used to specify and send a collection of key-value pairs to the Recorder for recording.
Definition: datum.h:15
const uint64_t kDefaultTimeStepDur
Definition: context.h:22
int parent(int nuc, unsigned int rx, std::string z="n")
Definition: pyne.cc:6621
struct pyne::decay decay
a struct matching the &#39;/decay/decays&#39; table in nuc_data.h5.
void Initialize(Context *ctx, SimInfo si)
Sets intial time-related parameters for the simulation.
Definition: timer.cc:239
boost::uuids::uuid parent_sim
id for the parent simulation if any
Definition: context.h:91
const char * core()
Definition: version.cc:38
const char * coincbc()
Definition: version.cc:76
Datum * AddVal(const char *field, boost::spirit::hold_any val, std::vector< int > *shape=NULL)
Add an arbitrary field-value pair to the datum.
Definition: datum.cc:22
void AddPrototype(std::string name, Agent *m)
Adds a prototype to a simulation-wide accessible list, a prototype can not be added more than once...
Definition: context.cc:137
std::string decay
"manual" if use of the decay function is allowed, "never" otherwise
Definition: context.h:79
double eps_rsrc
Epsilon for resources in the simulation.
Definition: context.h:107
int m0
start month for the simulation: Jan = 1, ..., Dec = 12
Definition: context.h:88
const char * boost()
Definition: version.cc:42
SimInfo()
constructs a SimInfo instance with default variables
Definition: context.cc:19
Collects and manages output data generation for the cyclus core and agents during a simulation...
Definition: recorder.h:45
double cy_eps_rsrc
epsilon values to be used by resources
Definition: context.cc:17
std::string parent_type
One of "init", "branch", "restart" indicating the relationship of this simulation to its parent simul...
Definition: context.h:95
void RegisterTimeListener(TimeListener *tl)
Registers an agent to receive tick/tock notifications every timestep.
Definition: context.cc:231
int time()
Returns the current time, in months since the simulation started.
Definition: timer.cc:228
The TimeListener class is an inheritable class for any Agent that requires knowlege of ticks and tock...
Definition: time_listener.h:23
Datum * NewDatum(std::string title)
Creates a new datum namespaced under the specified title.
Definition: recorder.cc:69
Container for a static simulation-global parameters that both describe the simulation and affect its ...
Definition: context.h:39
Code providing rudimentary logging capability for the Cyclus core.
bool explicit_inventory_compact
True if per-agent inventories should be explicitly queried/recorded every time step in a table (i...
Definition: context.h:116
The abstract base class used by all types of agents that live and interact in a simulation.
Definition: agent.h:51
taken directly from OsiSolverInterface.cpp on 2/17/14 from https://projects.coin-or.org/Osi/browser/trunk.
Definition: agent.cc:14
void KillSim()
Schedules the simulation to be terminated at the end of this timestep.
Definition: timer.h:60
void Record()
Record this datum to its Recorder.
Definition: datum.cc:35
void PyDelAgent(int i)
Removes a single Python agent from the reference cache.
Definition: pyhooks.cc:129
void SchedBuild(Agent *parent, std::string proto_name, int t)
Schedules the named prototype to be built for the specified parent at timestep t. ...
Definition: timer.cc:190
void Snapshot()
Schedules a snapshot of simulation state to output database to occur at the beginning of the next tim...
Definition: context.cc:243
void KillSim()
Schedules the simulation to be terminated at the end of this timestep.
Definition: context.cc:247
void SchedDecom(Agent *m, int time)
Schedules the given Agent to be decommissioned at the specified timestep t.
Definition: timer.cc:197
static void SnapAgent(Agent *m)
Records a snapshot of the agent&#39;s current internal state into the simulation&#39;s output database...
Definition: sim_init.cc:122
const char * hdf5()
Definition: version.cc:50
Datum * NewDatum(std::string title)
See Recorder::NewDatum documentation.
Definition: context.cc:239
For failed retrieval/insertion of key-based data into/from data structures.
Definition: error.h:47
const char * sqlite3()
Definition: version.cc:46
void SchedDecom(Agent *m, int time=-1)
Schedules the given Agent to be decommissioned at the specified timestep t.
Definition: context.cc:121
void DelAgent(Agent *m)
Destructs and cleans up m (and it&#39;s children recursively).
Definition: context.cc:98
void SchedBuild(Agent *parent, std::string proto_name, int t=-1)
Schedules the named prototype to be built for the specified parent at timestep t. ...
Definition: context.cc:107
Controls simulation timestepping and inter-timestep phases.
Definition: timer.h:22