CYCLUS
Loading...
Searching...
No Matches
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"
13#include "version.h"
14
15namespace cyclus {
16
17double cy_eps = 1e-6;
18double cy_eps_rsrc = 1e-6;
19
21 : duration(0),
22 y0(0),
23 m0(0),
25 decay("manual"),
26 branch_time(-1),
27 explicit_inventory(false),
28 explicit_inventory_compact(false),
29 parent_sim(boost::uuids::nil_uuid()),
30 parent_type("init"),
31 seed(kDefaultSeed),
32 stride(kDefaultStride) {}
33
34SimInfo::SimInfo(int dur, int y0, int m0, std::string handle)
35 : duration(dur),
36 y0(y0),
37 m0(m0),
39 decay("manual"),
40 branch_time(-1),
41 handle(handle),
42 explicit_inventory(false),
43 explicit_inventory_compact(false),
44 parent_sim(boost::uuids::nil_uuid()),
45 parent_type("init"),
46 seed(kDefaultSeed),
47 stride(kDefaultStride) {}
48
49SimInfo::SimInfo(int dur, int y0, int m0, std::string handle, std::string d)
50 : duration(dur),
51 y0(y0),
52 m0(m0),
54 decay(d),
55 branch_time(-1),
56 handle(handle),
57 explicit_inventory(false),
58 explicit_inventory_compact(false),
59 parent_sim(boost::uuids::nil_uuid()),
60 parent_type("init"),
61 seed(kDefaultSeed),
62 stride(kDefaultStride) {}
63
64SimInfo::SimInfo(int dur, boost::uuids::uuid parent_sim,
65 int branch_time, std::string parent_type,
66 std::string handle)
67 : duration(dur),
68 y0(-1),
69 m0(-1),
71 decay("manual"),
72 parent_sim(parent_sim),
73 parent_type(parent_type),
74 branch_time(branch_time),
75 explicit_inventory(false),
76 explicit_inventory_compact(false),
77 handle(handle),
78 seed(kDefaultSeed),
79 stride(kDefaultStride) {}
80
82 : ti_(ti),
83 rec_(rec),
84 solver_(NULL),
85 trans_id_(0),
86 si_(0) {
87 rng_ = new RandomNumberGenerator();
88 }
89
91 if (solver_ != NULL) {
92 delete solver_;
93 }
94 if (rng_ != NULL) {
95 delete rng_;
96 }
97 // initiate deletion of agents that don't have parents.
98 // dealloc will propagate through hierarchy as agents delete their children
99 std::vector<Agent*> to_del;
100 std::set<Agent*>::iterator it;
101 for (it = agent_list_.begin(); it != agent_list_.end(); ++it) {
102 if ((*it)->parent() == NULL) {
103 to_del.push_back(*it);
104 }
105 }
106 for (int i = 0; i < to_del.size(); ++i) {
107 DelAgent(to_del[i]);
108 }
109}
110
112 int n = agent_list_.erase(m);
113 if (n == 1) {
114 PyDelAgent(m->id());
115 delete m;
116 m = NULL;
117 }
118}
119
120void Context::SchedBuild(Agent* parent, std::string proto_name, int t) {
121 if (t == -1) {
122 t = time() + 1;
123 }
124 int pid = (parent != NULL) ? parent->id() : -1;
125 ti_->SchedBuild(parent, proto_name, t);
126 NewDatum("BuildSchedule")
127 ->AddVal("ParentId", pid)
128 ->AddVal("Prototype", proto_name)
129 ->AddVal("SchedTime", time())
130 ->AddVal("BuildTime", t)
131 ->Record();
132}
133
134void Context::SchedDecom(Agent* m, int t) {
135 if (t == -1) {
136 t = time();
137 }
138 ti_->SchedDecom(m, t);
139 NewDatum("DecomSchedule")
140 ->AddVal("AgentId", m->id())
141 ->AddVal("SchedTime", time())
142 ->AddVal("DecomTime", t)
143 ->Record();
144}
145
146boost::uuids::uuid Context::sim_id() {
147 return rec_->sim_id();
148}
149
150void Context::AddPrototype(std::string name, Agent* p) {
151 AddPrototype(name, p, false);
152}
153
154void Context::AddPrototype(std::string name, Agent* p, bool overwrite) {
155 if (!overwrite && protos_.find(name) != protos_.end()) {
156 throw KeyError("Prototype name " + name + " has already been added" +
157 " and cannot be overwritten.");
158 }
159
160 protos_[name] = p;
161 // explicit snapshot required for in situ (non-xml) prototype addition
163 NewDatum("Prototypes")
164 ->AddVal("Prototype", name)
165 ->AddVal("AgentId", p->id())
166 ->AddVal("Spec", p->spec())
167 ->Record();
168
169 std::string spec = p->spec();
170 if (rec_ver_.count(spec) == 0) {
171 rec_ver_.insert(spec);
172 NewDatum("AgentVersions")
173 ->AddVal("Spec", spec)
174 ->AddVal("Version", p->version())
175 ->Record();
176 }
177}
178
179void Context::AddRecipe(std::string name, Composition::Ptr c) {
180 recipes_[name] = c;
181 NewDatum("Recipes")
182 ->AddVal("Recipe", name)
183 ->AddVal("QualId", c->id())
184 ->Record();
185}
186
188 if (recipes_.count(name) == 0) {
189 throw KeyError("Invalid recipe name " + name);
190 }
191 return recipes_[name];
192}
193
194void Context::AddPackage(std::string name, double fill_min, double fill_max,
195 std::string strategy) {
196 if (packages_.count(name) == 0) {
197 Package::Ptr pkg = Package::Create(name, fill_min, fill_max, strategy);
198 packages_[name] = pkg;
200 } else {
201 throw KeyError("Package " + name + " already exists!");
202 }
203}
204
206 NewDatum("Packages")
207 ->AddVal("PackageName", pkg->name())
208 ->AddVal("FillMin", pkg->fill_min())
209 ->AddVal("FillMax", pkg->fill_max())
210 ->AddVal("Strategy", pkg->strategy())
211 ->Record();
212}
213
215 if (name == Package::unpackaged_name()) {
216 return Package::unpackaged();
217 }
218 if (packages_.size() == 0 ) {
219 throw KeyError("No user-created packages exist");
220 }
221 if (packages_.count(name) == 0) {
222 throw KeyError("Invalid package name " + name);
223 }
224 return packages_[name];
225}
226
227void Context::AddTransportUnit(std::string name, int fill_min, int fill_max,
228 std::string strategy) {
229 if (transport_units_.count(name) == 0) {
230 TransportUnit::Ptr tu = TransportUnit::Create(name, fill_min, fill_max,
231 strategy);
232 transport_units_[name] = tu;
234 } else {
235 throw KeyError("TransportUnit " + name + " already exists!");
236 }
237}
238
240 NewDatum("TransportUnits")
241 ->AddVal("TransportUnitName", tu->name())
242 ->AddVal("FillMin", tu->fill_min())
243 ->AddVal("FillMax", tu->fill_max())
244 ->AddVal("Strategy", tu->strategy())
245 ->Record();
246}
247
248/// Retrieve a registered transport unit
250 if (name == TransportUnit::unrestricted_name()) {
252 }
253 if (transport_units_.size() == 0 ) {
254 throw KeyError("No user-created transport units exist");
255 }
256 if (transport_units_.count(name) == 0) {
257 throw KeyError("Invalid transport unit name " + name);
258 }
259 return transport_units_[name];
260}
261
262
264 NewDatum("Info")
265 ->AddVal("Handle", si.handle)
266 ->AddVal("InitialYear", si.y0)
267 ->AddVal("InitialMonth", si.m0)
268 ->AddVal("Duration", si.duration)
269 ->AddVal("Seed", static_cast<int>(si.seed))
270 ->AddVal("Stride", static_cast<int>(si.stride))
271 ->AddVal("ParentSimId", si.parent_sim)
272 ->AddVal("ParentType", si.parent_type)
273 ->AddVal("BranchTime", si.branch_time)
274 ->AddVal("CyclusVersion", std::string(version::core()))
275 ->AddVal("CyclusVersionDescribe", std::string(version::describe()))
276 ->AddVal("SqliteVersion", std::string(version::sqlite3()))
277 ->AddVal("Hdf5Version", std::string(version::hdf5()))
278 ->AddVal("BoostVersion", std::string(version::boost()))
279 ->AddVal("LibXML2Version", std::string(version::xml2()))
280 ->AddVal("CoinCBCVersion", std::string(version::coincbc()))
281 ->Record();
282
283 NewDatum("DecayMode")
284 ->AddVal("Decay", si.decay)
285 ->Record();
286
287 NewDatum("InfoExplicitInv")
288 ->AddVal("RecordInventory", si.explicit_inventory)
289 ->AddVal("RecordInventoryCompact", si.explicit_inventory_compact)
290 ->Record();
291
292 // TODO: when the backends get uint64_t support, the static_cast here should
293 // be removed.
294 NewDatum("TimeStepDur")
295 ->AddVal("DurationSecs", static_cast<int>(si.dt))
296 ->Record();
297
298 NewDatum("Epsilon")
299 ->AddVal("GenericEpsilon", si.eps)
300 ->AddVal("ResourceEpsilon", si.eps_rsrc)
301 ->Record();
302
303 NewDatum("XMLPPInfo")
304 ->AddVal("LibXMLPlusPlusVersion", std::string(version::xmlpp()))
305 ->Record();
306
307 si_ = si;
308 ti_->Initialize(this, si);
309 rng_->Initialize(si);
310
311}
312
314 return ti_->time();
315}
316
318 return rng_->random();
319}
320
322 return rng_->random_01();
323}
324
326 return rng_->random_uniform_int(low, high);
327}
328
329double Context::random_uniform_real(double low, double high) {
330 return rng_->random_uniform_real(low, high);
331}
332
333double Context::random_normal_real(double mean, double std_dev, double low,
334 double high) {
335 return rng_->random_normal_real(mean, std_dev, low, high);
336}
337
339 int high) {
340 return rng_->random_normal_int(mean, std_dev, low, high);
341}
342
346
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
The abstract base class used by all types of agents that live and interact in a simulation.
Definition agent.h:49
virtual const int id() const
The agent instance's unique ID within a simulation.
Definition agent.h:352
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:81
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:120
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:146
void Snapshot()
Schedules a snapshot of simulation state to output database to occur at the beginning of the next tim...
Definition context.cc:355
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:150
void DelAgent(Agent *m)
Destructs and cleans up m (and it's children recursively).
Definition context.cc:111
Composition::Ptr GetRecipe(std::string name)
Retrieve a registered recipe.
Definition context.cc:187
Package::Ptr GetPackage(std::string name)
Retrieve a registered package.
Definition context.cc:214
double random_01()
Generates a random number on the range [0,1)].
Definition context.cc:321
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:338
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:333
int random_uniform_int(int low, int high)
Returns a random number from a uniform integer distribution.
Definition context.cc:325
~Context()
Clean up resources including destructing the solver and all agents the context is aware of.
Definition context.cc:90
void AddRecipe(std::string name, Composition::Ptr c)
Adds a composition recipe to a simulation-wide accessible list.
Definition context.cc:179
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:227
void RecordTransportUnit(TransportUnit::Ptr)
Records transport unit information.
Definition context.cc:239
TransportUnit::Ptr GetTransportUnit(std::string name)
Retrieve a registered transport unit.
Definition context.cc:249
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:194
virtual int time()
Returns the current simulation timestep.
Definition context.cc:313
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:329
void RecordPackage(Package::Ptr)
Records package information.
Definition context.cc:205
void SchedDecom(Agent *m, int time=-1)
Schedules the given Agent to be decommissioned at the specified timestep t.
Definition context.cc:134
void InitSim(SimInfo si)
Initializes the simulation time parameters.
Definition context.cc:263
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: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
SimInfo()
constructs a SimInfo instance with default variables
Definition context.cc:20
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:228
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 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 RegisterTimeListener(TimeListener *agent)
Registers an agent to receive tick/tock notifications every timestep.
Definition timer.cc:182
void Initialize(Context *ctx, SimInfo si)
Sets intial time-related parameters for the simulation.
Definition timer.cc:239
void SchedDecom(Agent *m, int time)
Schedules the given Agent to be decommissioned at the specified timestep t.
Definition timer.cc:197
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:18
double cy_eps
generic epsilon values
Definition context.cc:17
void PyDelAgent(int i)
Removes a single Python agent from the reference cache.
Definition pyhooks.cc:85
T OptionalQuery(InfileTree *tree, std::string query, T default_val)
a query method for optional parameters