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