CYCLUS
Loading...
Searching...
No Matches
context.h
Go to the documentation of this file.
1#ifndef CYCLUS_SRC_CONTEXT_H_
2#define CYCLUS_SRC_CONTEXT_H_
3
4#include <map>
5#include <set>
6#include <string>
7#include <stdint.h>
8
9#ifndef CYCPP
10// The cyclus preprocessor cannot handle this file since there are two
11// unmatch open braces '{' inside of strings that don't have cooresponding
12// closed braces '}'
13#include <boost/uuid/uuid_generators.hpp>
14#endif
15
16#include "composition.h"
17#include "agent.h"
18#include "greedy_solver.h"
19#include "pyhooks.h"
20#include "recorder.h"
21#include "package.h"
22
23// Defined as 4 seconds longer than a Gaussian year (to make division by 12
24// a round number)
25const uint64_t cyclusYear = 31558200;
26
27const uint64_t kDefaultTimeStepDur = cyclusYear / 12;
28
29const uint64_t kDefaultSeed = 20160212;
30
31const uint64_t kDefaultStride = 10000;
32
33class SimInitTest;
34
35namespace cyclus {
36
37class Datum;
38class ExchangeSolver;
39class Recorder;
40class Trader;
41class Timer;
42class TimeListener;
43class SimInit;
44class DynamicModule;
45class RandomNumberGenerator;
46
47/// Container for a static simulation-global parameters that both describe
48/// the simulation and affect its behavior.
49class SimInfo {
50 public:
51 /// @brief constructs a SimInfo instance with default variables
52 /// @return a SimInfo instance
53 SimInfo();
54
55 /// @brief constructs a SimInfo instance using some default variables
56 /// @param dur simulation duration in number of timesteps
57 /// @param y0 start year for the simulation
58 /// @param m0 start month for the simulation
59 /// @param handle is this simulation's unique simulation handle
60 /// @return a SimInfo instance
61 SimInfo(int dur, int y0 = 2010, int m0 = 1, std::string handle = "");
62
63 /// @brief constructs a SimInfo instance using no default variables
64 /// @param dur simulation duration in number of timesteps
65 /// @param y0 start year for the simulation
66 /// @param m0 start month for the simulation
67 /// @param handle is this simulation's unique simulation handle
68 /// @param d the decay data member, "never" for no decay. "manual" otherwise
69 /// @return a SimInfo instance
70 SimInfo(int dur, int y0, int m0, std::string handle, std::string d);
71
72 /// @brief constructs a SimInfo instance
73 /// @param dur simulation duration in number of timesteps
74 /// @param parent_sim the uuid of the parent simulation
75 /// @param branch_time
76 /// @param parent_type a string indicating the type of the parent simulation
77 /// @param handle is this simulation's unique simulation handle
78 /// @return a SimInfo instance
79 SimInfo(int dur, boost::uuids::uuid parent_sim, int branch_time,
80 std::string parent_type, std::string handle = "");
81
82 /// user-defined label associated with a particular simulation
83 std::string handle;
84
85 /// "manual" if use of the decay function is allowed, "never" otherwise
86 std::string decay;
87
88 /// length of the simulation in timesteps (months)
90
91 /// start year for the simulation (e.g. 1973);
92 int y0;
93
94 /// start month for the simulation: Jan = 1, ..., Dec = 12
95 int m0;
96
97 /// id for the parent simulation if any
98 boost::uuids::uuid parent_sim;
99
100 /// One of "init", "branch", "restart" indicating the relationship of this
101 /// simulation to its parent simulation.
102 std::string parent_type;
103
104 /// timestep at which simulation branching occurs if any
106
107 /// Duration in seconds of a single time step in the simulation.
108 uint64_t dt;
109
110 /// Epsilon in the simulation.
111 double eps;
112
113 /// Epsilon for resources in the simulation.
114 double eps_rsrc;
115
116 /// True if per-agent inventories should be explicitly queried/recorded
117 /// every time step in a table (i.e. agent ID, Time, Nuclide, Quantity).
119
120 /// True if per-agent inventories should be explicitly queried/recorded
121 /// every time step in a table (i.e. agent ID, Time, Quantity,
122 /// Composition-object and/or reference).
124
125 /// Seed for random number generator
126 uint64_t seed;
127
128 /// Stride length. Currently unused, but available for future development
129 /// that may wish to initiate multiple random number generators from the
130 /// same seed, skipping forward in the sequence by the stride length times
131 /// some parameter, such as the agent_id.
132 uint64_t stride;
133};
134
135/// A simulation context provides access to necessary simulation-global
136/// functions and state. All code that writes to the output database, needs to
137/// know simulation time, creates/builds facilities, and/or uses loaded
138/// composition recipes will need a context pointer. In general, all global
139/// state should be accessed through a simulation context.
140///
141/// @warning the context takes ownership of and manages the lifetime/destruction
142/// of all agents constructed with it (including Cloned agents). Agents should
143/// generally NEVER be allocated on the stack.
144/// @warning the context takes ownership of the solver and will manage its
145/// destruction.
146class Context {
147 public:
148 friend class ::SimInitTest;
149 friend class SimInit;
150 friend class Agent;
151 friend class Timer;
152
153 /// Creates a new context working with the specified timer and datum manager.
154 /// The timer does not have to be initialized (yet).
155 Context(Timer* ti, Recorder* rec);
156
157 /// Clean up resources including destructing the solver and all agents the
158 /// context is aware of.
159 ~Context();
160
161 /// See Recorder::sim_id documentation.
162 boost::uuids::uuid sim_id();
163
164 /// Adds a prototype to a simulation-wide accessible list, a prototype **can
165 /// not** be added more than once.
166 /// @param name the prototype name
167 /// @param m a pointer to the agent prototype
168 /// @param overwrite, allow overwrites to the prototype listing, default:
169 /// false
170 /// @throws if overwrite is false and a prototype name has already been added
171 /// @{
172 void AddPrototype(std::string name, Agent* m);
173 void AddPrototype(std::string name, Agent* m, bool overwrite);
174 /// @}
175
176 /// Registers an agent as a participant in resource exchanges. Agents should
177 /// register from their Deploy method.
178 inline void RegisterTrader(Trader* e) { traders_.insert(e); }
179
180 /// Unregisters an agent as a participant in resource exchanges.
181 inline void UnregisterTrader(Trader* e) { traders_.erase(e); }
182
183 /// @return the current set of traders registered for resource exchange.
184 inline const std::set<Trader*>& traders() const { return traders_; }
185
186 /// Create a new agent by cloning the named prototype. The returned agent is
187 /// not initialized as a simulation participant.
188 ///
189 /// @warning this method should generally NOT be used by agents.
190 template <class T> T* CreateAgent(std::string proto_name) {
191 if (protos_.count(proto_name) == 0) {
192 throw KeyError("Invalid prototype name " + proto_name);
193 }
194
195 Agent* m = protos_[proto_name];
196 if (m == NULL) {
197 throw KeyError("Null prototype for " + proto_name);
198 }
199 T* casted(NULL);
200 Agent* clone = m->Clone();
201 if (clone == NULL) {
202 throw StateError("Clone operation failed for " + proto_name);
203 }
204 casted = dynamic_cast<T*>(clone);
205 if (casted == NULL) {
206 PyDelAgent(clone->id());
207 DelAgent(clone);
208 throw CastError("Invalid cast for prototype " + proto_name);
209 }
210 return casted;
211 }
212
213 /// Destructs and cleans up m (and it's children recursively).
214 ///
215 /// @warning this method should generally NOT be used by agents.
216 void DelAgent(Agent* m);
217
218 /// Schedules the named prototype to be built for the specified parent at
219 /// timestep t. The default t=-1 results in the build being scheduled for the
220 /// next build phase (i.e. the start of the next timestep).
221 void SchedBuild(Agent* parent, std::string proto_name, int t = -1);
222
223 /// Schedules the given Agent to be decommissioned at the specified timestep
224 /// t. The default t=-1 results in the decommission being scheduled for the
225 /// next decommission phase (i.e. the end of the current timestep).
226 void SchedDecom(Agent* m, int time = -1);
227
228 /// Adds a composition recipe to a simulation-wide accessible list.
229 /// Agents should NOT add their own recipes.
230 void AddRecipe(std::string name, Composition::Ptr c);
231
232 /// Retrieve a registered recipe. This is intended for retrieving
233 /// compositions loaded from an input file(s) at the start of a
234 /// simulation and NOT for communicating compositions between facilities
235 /// during the simulation.
236 Composition::Ptr GetRecipe(std::string name);
237
238 /// Registers an agent to receive tick/tock notifications every timestep.
239 /// Agents should register from their Deploy method.
241
242 /// Removes an agent from receiving tick/tock notifications.
243 /// Agents should unregister from their Decommission method.
245
246 /// Initializes the simulation time parameters. Should only be called once -
247 /// NOT idempotent.
248 void InitSim(SimInfo si);
249
250 /// Returns the current simulation timestep.
251 virtual int time();
252
253 /// Adds a package type to a simulation-wide accessible list.
254 /// Agents should NOT add their own packages.
255 void AddPackage(std::string name, double fill_min = 0,
256 double fill_max = std::numeric_limits<double>::max(),
257 std::string strategy = "first");
258
259 /// Records package information. Should be used first on unpackaged, then
260 /// to record user-declared packages
262
263 /// Retrieve a registered package.
264 Package::Ptr GetPackage(std::string name);
265
266 /// Adds a transport unit type to a simulation-wide accessible list.
267 /// Agents should NOT add their own transport units.
268 void AddTransportUnit(std::string name, int fill_min = 0,
269 int fill_max = std::numeric_limits<int>::max(),
270 std::string strategy = "first");
271
272 /// Records transport unit information. Should be used first on unrestricted,
273 /// then to record user-declared transport units
275
276 /// Retrieve a registered transport unit.
277 TransportUnit::Ptr GetTransportUnit(std::string name);
278
279 int random();
280
281 /// Generates a random number on the range [0,1)]
282 double random_01();
283
284 /// Returns a random number from a uniform integer distribution.
285 int random_uniform_int(int low, int high);
286
287 /// Returns a random number from a uniform real distribution.
288 double random_uniform_real(double low, double high);
289
290 /// Returns a random number from a normal distribution.
291 double random_normal_real(double mean, double std_dev, double low = 0,
292 double high = std::numeric_limits<double>::max());
293
294 /// Returns a random number from a lognormal distribution.
295 int random_normal_int(double mean, double std_dev, int low = 0,
296 int high = std::numeric_limits<int>::max());
297
298 /// Returns the duration of a single time step in seconds.
299 inline uint64_t dt() { return si_.dt; };
300
301 /// Returns the seed for the random number generator.
302 inline uint64_t seed() { return si_.seed; };
303
304 /// Returns the stride for the random number generator.
305 inline uint64_t stride() { return si_.stride; };
306
307 /// Return static simulation info.
308 inline SimInfo sim_info() const { return si_; }
309
310 /// See Recorder::NewDatum documentation.
311 Datum* NewDatum(std::string title);
312
313 /// Schedules a snapshot of simulation state to output database to occur at
314 /// the beginning of the next timestep.
315 void Snapshot();
316
317 /// Schedules the simulation to be terminated at the end of this timestep.
318 void KillSim();
319
320 /// @return the next transaction id
321 inline int NextTransactionID() { return trans_id_++; }
322
323 /// Returns the exchange solver associated with this context
325 if (solver_ == NULL) {
326 solver_ = new GreedySolver(false, NULL);
327 }
328 return solver_;
329 }
330
331 /// sets the solver associated with this context
333 solver_ = solver;
334 solver_->sim_ctx(this);
335 }
336
337 /// @return the number of agents of a given prototype currently in the
338 /// simulation
339 inline int n_prototypes(std::string type) { return n_prototypes_[type]; }
340
341 /// @return the number of agents of a given implementation currently in the
342 /// simulation
343 inline int n_specs(std::string impl) { return n_specs_[impl]; }
344
345 private:
346 /// Registers an agent as a participant in the simulation.
347 inline void RegisterAgent(Agent* a) {
348 n_prototypes_[a->prototype()]++;
349 n_specs_[a->spec()]++;
350 }
351
352 /// Unregisters an agent as a participant in the simulation.
353 inline void UnregisterAgent(Agent* a) {
354 n_prototypes_[a->prototype()]--;
355 n_specs_[a->spec()]--;
356 }
357
358 /// contains archetype specs of all agents for which version have already
359 /// been recorded in the db
360 std::set<std::string> rec_ver_;
361
362 std::map<std::string, Agent*> protos_;
363 std::map<std::string, Composition::Ptr> recipes_;
364 std::map<std::string, Package::Ptr> packages_;
365 std::map<std::string, TransportUnit::Ptr> transport_units_;
366 std::set<Agent*> agent_list_;
367 std::set<Trader*> traders_;
368 std::map<std::string, int> n_prototypes_;
369 std::map<std::string, int> n_specs_;
370
371 SimInfo si_;
372 Timer* ti_;
373 ExchangeSolver* solver_;
374 Recorder* rec_;
375 int trans_id_;
376 RandomNumberGenerator* rng_;
377};
378
379} // namespace cyclus
380
381#endif // CYCLUS_SRC_CONTEXT_H_
The abstract base class used by all types of agents that live and interact in a simulation.
Definition agent.h:50
const std::string prototype() const
Returns the agent's prototype.
Definition agent.h:342
std::string spec()
The string representation of the agent spec that uniquely identifies the concrete agent class/module.
Definition agent.h:353
virtual Agent * Clone()=0
Returns a newly created/allocated prototype that is an exact copy of this.
virtual const int id() const
The agent instance's unique ID within a simulation.
Definition agent.h:349
For failed casts that shouldn't.
Definition error.h:61
boost::shared_ptr< Composition > Ptr
Definition composition.h:43
void UnregisterTrader(Trader *e)
Unregisters an agent as a participant in resource exchanges.
Definition context.h:181
Context(Timer *ti, Recorder *rec)
Creates a new context working with the specified timer and datum manager.
Definition context.cc:84
int NextTransactionID()
Definition context.h:321
const std::set< Trader * > & traders() const
Definition context.h:184
T * CreateAgent(std::string proto_name)
Create a new agent by cloning the named prototype.
Definition context.h:190
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
void RegisterTrader(Trader *e)
Registers an agent as a participant in resource exchanges.
Definition context.h:178
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
uint64_t stride()
Returns the stride for the random number generator.
Definition context.h:305
friend class Timer
Definition context.h:151
ExchangeSolver * solver()
Returns the exchange solver associated with this context.
Definition context.h:324
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
void solver(ExchangeSolver *solver)
sets the solver associated with this context
Definition context.h:332
SimInfo sim_info() const
Return static simulation info.
Definition context.h:308
uint64_t dt()
Returns the duration of a single time step in seconds.
Definition context.h:299
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
friend class SimInit
Definition context.h:149
uint64_t seed()
Returns the seed for the random number generator.
Definition context.h:302
int n_prototypes(std::string type)
Definition context.h:339
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
int n_specs(std::string impl)
Definition context.h:343
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
a very simple interface for solving translated resource exchanges
The GreedySolver provides the implementation for a "greedy" solution to a resource exchange graph.
For failed retrieval/insertion of key-based data into/from data structures.
Definition error.h:43
boost::shared_ptr< Package > Ptr
Definition package.h:21
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
For failed object state expectations.
Definition error.h:49
The TimeListener class is an inheritable class for any Agent that requires knowlege of ticks and tock...
A simple API for agents that wish to exchange resources in the simulation.
Definition trader.h:24
boost::shared_ptr< TransportUnit > Ptr
Definition package.h:131
const uint64_t kDefaultSeed
Definition context.h:29
const uint64_t kDefaultStride
Definition context.h:31
const uint64_t cyclusYear
Definition context.h:25
const uint64_t kDefaultTimeStepDur
Definition context.h:27
taken directly from OsiSolverInterface.cpp on 2/17/14 from https://projects.coin-or....
Definition agent.cc:14
void PyDelAgent(int i)
Removes a single Python agent from the reference cache.
Definition pyhooks.cc:107