CYCLUS
Loading...
Searching...
No Matches
context.cc
Go to the documentation of this file.
1#include "platform.h"
2#include "context.h"
3
4#include <vector>
5#include <boost/uuid/uuid_generators.hpp>
6#if CYCLUS_IS_PARALLEL
7#include <omp.h>
8#endif // CYCLUS_IS_PARALLEL
9
10#include "error.h"
11#include "exchange_solver.h"
12#include "logger.h"
13#include "pyhooks.h"
14#include "sim_init.h"
15#include "timer.h"
17#include "version.h"
18
19namespace cyclus {
20
21double cy_eps = 1e-6;
22double cy_eps_rsrc = 1e-6;
23
25 : duration(0),
26 y0(0),
27 m0(0),
29 decay("manual"),
30 branch_time(-1),
31 explicit_inventory(false),
33 parent_sim(boost::uuids::nil_uuid()),
34 parent_type("init"),
37
38SimInfo::SimInfo(int dur, int y0, int m0, std::string handle)
39 : duration(dur),
40 y0(y0),
41 m0(m0),
43 decay("manual"),
44 branch_time(-1),
46 explicit_inventory(false),
48 parent_sim(boost::uuids::nil_uuid()),
49 parent_type("init"),
52
53SimInfo::SimInfo(int dur, int y0, int m0, std::string handle, std::string d)
54 : duration(dur),
55 y0(y0),
56 m0(m0),
58 decay(d),
59 branch_time(-1),
61 explicit_inventory(false),
63 parent_sim(boost::uuids::nil_uuid()),
64 parent_type("init"),
67
68SimInfo::SimInfo(int dur, boost::uuids::uuid parent_sim, int branch_time,
69 std::string parent_type, std::string handle)
70 : duration(dur),
71 y0(-1),
72 m0(-1),
74 decay("manual"),
78 explicit_inventory(false),
83
85 : ti_(ti), rec_(rec), solver_(NULL), trans_id_(0), si_(0) {
86 rng_ = new RandomNumberGenerator();
87}
88
90 if (solver_ != NULL) {
91 delete solver_;
92 }
93 if (rng_ != NULL) {
94 delete rng_;
95 }
96 // initiate deletion of agents that don't have parents.
97 // dealloc will propagate through hierarchy as agents delete their children
98 std::vector<Agent*> to_del;
99 std::set<Agent*>::iterator it;
100 for (it = agent_list_.begin(); it != agent_list_.end(); ++it) {
101 if ((*it)->parent() == NULL) {
102 to_del.push_back(*it);
103 }
104 }
105 for (int i = 0; i < to_del.size(); ++i) {
106 DelAgent(to_del[i]);
107 }
108}
109
111 int n = agent_list_.erase(m);
112 if (n == 1) {
113 PyDelAgent(m->id());
114 delete m;
115 m = NULL;
116 }
117}
118
119void Context::SchedBuild(Agent* parent, std::string proto_name, int t) {
120#pragma omp critical
121 {
122 if (t == -1) {
123 t = time() + 1;
124 }
125 int pid = (parent != NULL) ? parent->id() : -1;
126 ti_->SchedBuild(parent, proto_name, t);
127 NewDatum("BuildSchedule")
128 ->AddVal("ParentId", pid)
129 ->AddVal("Prototype", proto_name)
130 ->AddVal("SchedTime", time())
131 ->AddVal("BuildTime", t)
132 ->Record();
133 }
134}
135
136void Context::SchedDecom(Agent* m, int t) {
137#pragma omp critical
138 {
139 if (t == -1) {
140 t = time();
141 }
142 ti_->SchedDecom(m, t);
143 NewDatum("DecomSchedule")
144 ->AddVal("AgentId", m->id())
145 ->AddVal("SchedTime", time())
146 ->AddVal("DecomTime", t)
147 ->Record();
148 }
149}
150
151boost::uuids::uuid Context::sim_id() {
152 return rec_->sim_id();
153}
154
155void Context::AddPrototype(std::string name, Agent* p) {
156 AddPrototype(name, p, false);
157}
158
159void Context::AddPrototype(std::string name, Agent* p, bool overwrite) {
160 if (!overwrite && protos_.find(name) != protos_.end()) {
161 throw KeyError("Prototype name " + name + " has already been added" +
162 " and cannot be overwritten.");
163 }
164
165 protos_[name] = p;
166 // explicit snapshot required for in situ (non-xml) prototype addition
168 NewDatum("Prototypes")
169 ->AddVal("Prototype", name)
170 ->AddVal("AgentId", p->id())
171 ->AddVal("Spec", p->spec())
172 ->Record();
173
174 std::string spec = p->spec();
175 if (rec_ver_.count(spec) == 0) {
176 rec_ver_.insert(spec);
177 NewDatum("AgentVersions")
178 ->AddVal("Spec", spec)
179 ->AddVal("Version", p->version())
180 ->Record();
181 }
182}
183
184void Context::AddRecipe(std::string name, Composition::Ptr c) {
185 recipes_[name] = c;
186 NewDatum("Recipes")
187 ->AddVal("Recipe", name)
188 ->AddVal("QualId", c->id())
189 ->Record();
190}
191
193 if (recipes_.count(name) == 0) {
194 throw KeyError("Invalid recipe name " + name);
195 }
196 return recipes_[name];
197}
198
199void Context::AddPackage(std::string name, double fill_min, double fill_max,
200 std::string strategy) {
201 if (packages_.count(name) == 0) {
202 Package::Ptr pkg = Package::Create(name, fill_min, fill_max, strategy);
203 packages_[name] = pkg;
204 RecordPackage(pkg);
205 } else {
206 throw KeyError("Package " + name + " already exists!");
207 }
208}
209
211 NewDatum("Packages")
212 ->AddVal("PackageName", pkg->name())
213 ->AddVal("FillMin", pkg->fill_min())
214 ->AddVal("FillMax", pkg->fill_max())
215 ->AddVal("Strategy", pkg->strategy())
216 ->Record();
217}
218
220 if (name == Package::unpackaged_name()) {
221 return Package::unpackaged();
222 }
223 if (packages_.size() == 0) {
224 throw KeyError("No user-created packages exist");
225 }
226 if (packages_.count(name) == 0) {
227 throw KeyError("Invalid package name " + name);
228 }
229 return packages_[name];
230}
231
232void Context::AddTransportUnit(std::string name, int fill_min, int fill_max,
233 std::string strategy) {
234 if (transport_units_.count(name) == 0) {
236 TransportUnit::Create(name, fill_min, fill_max, strategy);
237 transport_units_[name] = tu;
239 } else {
240 throw KeyError("TransportUnit " + name + " already exists!");
241 }
242}
243
245 NewDatum("TransportUnits")
246 ->AddVal("TransportUnitName", tu->name())
247 ->AddVal("FillMin", tu->fill_min())
248 ->AddVal("FillMax", tu->fill_max())
249 ->AddVal("Strategy", tu->strategy())
250 ->Record();
251}
252
253/// Retrieve a registered transport unit
255 if (name == TransportUnit::unrestricted_name()) {
257 }
258 if (transport_units_.size() == 0) {
259 throw KeyError("No user-created transport units exist");
260 }
261 if (transport_units_.count(name) == 0) {
262 throw KeyError("Invalid transport unit name " + name);
263 }
264 return transport_units_[name];
265}
266
268 NewDatum("Info")
269 ->AddVal("Handle", si.handle)
270 ->AddVal("InitialYear", si.y0)
271 ->AddVal("InitialMonth", si.m0)
272 ->AddVal("Duration", si.duration)
273 ->AddVal("Seed", static_cast<int>(si.seed))
274 ->AddVal("Stride", static_cast<int>(si.stride))
275 ->AddVal("ParentSimId", si.parent_sim)
276 ->AddVal("ParentType", si.parent_type)
277 ->AddVal("BranchTime", si.branch_time)
278 ->AddVal("CyclusVersion", std::string(version::core()))
279 ->AddVal("CyclusVersionDescribe", std::string(version::describe()))
280 ->AddVal("SqliteVersion", std::string(version::sqlite3()))
281 ->AddVal("Hdf5Version", std::string(version::hdf5()))
282 ->AddVal("BoostVersion", std::string(version::boost()))
283 ->AddVal("LibXML2Version", std::string(version::xml2()))
284 ->AddVal("CoinCBCVersion", std::string(version::coincbc()))
285 ->Record();
286
287 NewDatum("DecayMode")->AddVal("Decay", si.decay)->Record();
288
289 NewDatum("InfoExplicitInv")
290 ->AddVal("RecordInventory", si.explicit_inventory)
291 ->AddVal("RecordInventoryCompact", si.explicit_inventory_compact)
292 ->Record();
293
294 // TODO: when the backends get uint64_t support, the static_cast here should
295 // be removed.
296 NewDatum("TimeStepDur")
297 ->AddVal("DurationSecs", static_cast<int>(si.dt))
298 ->Record();
299
300 NewDatum("Epsilon")
301 ->AddVal("GenericEpsilon", si.eps)
302 ->AddVal("ResourceEpsilon", si.eps_rsrc)
303 ->Record();
304
305 NewDatum("XMLPPInfo")
306 ->AddVal("LibXMLPlusPlusVersion", std::string(version::xmlpp()))
307 ->Record();
308
309 si_ = si;
310 ti_->Initialize(this, si);
311 rng_->Initialize(si);
312}
313
315 return ti_->time();
316}
317
319 return rng_->random();
320}
321
323 return rng_->random_01();
324}
325
326int Context::random_uniform_int(int low, int high) {
327 return rng_->random_uniform_int(low, high);
328}
329
330double Context::random_uniform_real(double low, double high) {
331 return rng_->random_uniform_real(low, high);
332}
333
334double Context::random_normal_real(double mean, double std_dev, double low,
335 double high) {
336 return rng_->random_normal_real(mean, std_dev, low, high);
337}
338
339int Context::random_normal_int(double mean, double std_dev, int low, int high) {
340 return rng_->random_normal_int(mean, std_dev, low, high);
341}
342
344 ti_->RegisterTimeListener(tl);
345}
346
348 ti_->UnregisterTimeListener(tl);
349}
350
351Datum* Context::NewDatum(std::string title) {
352 return rec_->NewDatum(title);
353}
354
356 ti_->Snapshot();
357}
358
360 ti_->KillSim();
361}
362
363} // namespace cyclus
std::string spec()
The string representation of the agent spec that uniquely identifies the concrete agent class/module.
Definition agent.h:353
virtual const int id() const
The agent instance's unique ID within a simulation.
Definition agent.h:349
virtual std::string version()
Definition agent.h:64
boost::shared_ptr< Composition > Ptr
Definition composition.h:43
Context(Timer *ti, Recorder *rec)
Creates a new context working with the specified timer and datum manager.
Definition context.cc:84
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:119
void KillSim()
Schedules the simulation to be terminated at the end of this timestep.
Definition context.cc:359
Datum * NewDatum(std::string title)
See Recorder::NewDatum documentation.
Definition context.cc:351
boost::uuids::uuid sim_id()
See Recorder::sim_id documentation.
Definition context.cc:151
void Snapshot()
Schedules a snapshot of simulation state to output database to occur at the beginning of the next tim...
Definition context.cc:355
friend class Timer
Definition context.h:151
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:155
void DelAgent(Agent *m)
Destructs and cleans up m (and it's children recursively).
Definition context.cc:110
Composition::Ptr GetRecipe(std::string name)
Retrieve a registered recipe.
Definition context.cc:192
Package::Ptr GetPackage(std::string name)
Retrieve a registered package.
Definition context.cc:219
double random_01()
Generates a random number on the range [0,1)].
Definition context.cc:322
int random_normal_int(double mean, double std_dev, int low=0, int high=std::numeric_limits< int >::max())
Returns a random number from a lognormal distribution.
Definition context.cc:339
double random_normal_real(double mean, double std_dev, double low=0, double high=std::numeric_limits< double >::max())
Returns a random number from a normal distribution.
Definition context.cc:334
int random_uniform_int(int low, int high)
Returns a random number from a uniform integer distribution.
Definition context.cc:326
~Context()
Clean up resources including destructing the solver and all agents the context is aware of.
Definition context.cc:89
void AddRecipe(std::string name, Composition::Ptr c)
Adds a composition recipe to a simulation-wide accessible list.
Definition context.cc:184
void AddTransportUnit(std::string name, int fill_min=0, int fill_max=std::numeric_limits< int >::max(), std::string strategy="first")
Adds a transport unit type to a simulation-wide accessible list.
Definition context.cc:232
void RecordTransportUnit(TransportUnit::Ptr)
Records transport unit information.
Definition context.cc:244
TransportUnit::Ptr GetTransportUnit(std::string name)
Retrieve a registered transport unit.
Definition context.cc:254
void AddPackage(std::string name, double fill_min=0, double fill_max=std::numeric_limits< double >::max(), std::string strategy="first")
Adds a package type to a simulation-wide accessible list.
Definition context.cc:199
virtual int time()
Returns the current simulation timestep.
Definition context.cc:314
void RegisterTimeListener(TimeListener *tl)
Registers an agent to receive tick/tock notifications every timestep.
Definition context.cc:343
double random_uniform_real(double low, double high)
Returns a random number from a uniform real distribution.
Definition context.cc:330
friend class Agent
Definition context.h:150
void RecordPackage(Package::Ptr)
Records package information.
Definition context.cc:210
void SchedDecom(Agent *m, int time=-1)
Schedules the given Agent to be decommissioned at the specified timestep t.
Definition context.cc:136
void InitSim(SimInfo si)
Initializes the simulation time parameters.
Definition context.cc:267
void UnregisterTimeListener(TimeListener *tl)
Removes an agent from receiving tick/tock notifications.
Definition context.cc:347
Used to specify and send a collection of key-value pairs to the Recorder for recording.
Definition datum.h:15
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:21
void Record()
Record this datum to its Recorder.
Definition datum.cc:34
For failed retrieval/insertion of key-based data into/from data structures.
Definition error.h:43
static Ptr Create(std::string name, double fill_min=0, double fill_max=std::numeric_limits< double >::max(), std::string strategy="first")
Definition package.cc:9
static Ptr & unpackaged()
Definition package.cc:23
boost::shared_ptr< Package > Ptr
Definition package.h:21
static std::string unpackaged_name()
Definition package.h:68
Collects and manages output data generation for the cyclus core and agents during a simulation.
Definition recorder.h:45
Container for a static simulation-global parameters that both describe the simulation and affect its ...
Definition context.h:49
double eps_rsrc
Epsilon for resources in the simulation.
Definition context.h:114
int y0
start year for the simulation (e.g. 1973);
Definition context.h:92
int m0
start month for the simulation: Jan = 1, ..., Dec = 12
Definition context.h:95
bool explicit_inventory_compact
True if per-agent inventories should be explicitly queried/recorded every time step in a table (i....
Definition context.h:123
boost::uuids::uuid parent_sim
id for the parent simulation if any
Definition context.h:98
SimInfo()
constructs a SimInfo instance with default variables
Definition context.cc:24
double eps
Epsilon in the simulation.
Definition context.h:111
std::string handle
user-defined label associated with a particular simulation
Definition context.h:83
int duration
length of the simulation in timesteps (months)
Definition context.h:89
uint64_t stride
Stride length.
Definition context.h:132
uint64_t dt
Duration in seconds of a single time step in the simulation.
Definition context.h:108
uint64_t seed
Seed for random number generator.
Definition context.h:126
std::string decay
"manual" if use of the decay function is allowed, "never" otherwise
Definition context.h:86
std::string parent_type
One of "init", "branch", "restart" indicating the relationship of this simulation to its parent simul...
Definition context.h:102
int branch_time
timestep at which simulation branching occurs if any
Definition context.h:105
bool explicit_inventory
True if per-agent inventories should be explicitly queried/recorded every time step in a table (i....
Definition context.h:118
static void SnapAgent(Agent *m)
Records a snapshot of the agent's current internal state into the simulation's output database.
Definition sim_init.cc:124
The TimeListener class is an inheritable class for any Agent that requires knowlege of ticks and tock...
static std::string unrestricted_name()
Definition package.h:161
boost::shared_ptr< TransportUnit > Ptr
Definition package.h:131
static Ptr Create(std::string name, int fill_min=0, int fill_max=std::numeric_limits< int >::max(), std::string strategy="first")
create a new transport unit type.
Definition package.cc:119
static Ptr & unrestricted()
Definition package.cc:133
const uint64_t kDefaultSeed
Definition context.h:29
const uint64_t kDefaultStride
Definition context.h:31
const uint64_t kDefaultTimeStepDur
Definition context.h:27
Code providing rudimentary logging capability for the Cyclus core.
Definition any.hpp:72
const char * core()
Definition version.cc:38
const char * sqlite3()
Definition version.cc:46
const char * hdf5()
Definition version.cc:50
const char * xmlpp()
Definition version.cc:67
const char * xml2()
Definition version.cc:63
const char * describe()
Definition version.cc:34
const char * boost()
Definition version.cc:42
const char * coincbc()
Definition version.cc:76
taken directly from OsiSolverInterface.cpp on 2/17/14 from https://projects.coin-or....
Definition agent.cc:14
double cy_eps_rsrc
epsilon values to be used by resources
Definition context.cc:22
double cy_eps
generic epsilon values
Definition context.cc:21
void PyDelAgent(int i)
Removes a single Python agent from the reference cache.
Definition pyhooks.cc:107