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