CYCLUS
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 "recorder.h"
20 
21 const uint64_t kDefaultTimeStepDur = 2629846;
22 
23 class SimInitTest;
24 
25 namespace cyclus {
26 
27 class Datum;
28 class ExchangeSolver;
29 class Recorder;
30 class Trader;
31 class Timer;
32 class TimeListener;
33 class SimInit;
34 
35 /// Container for a static simulation-global parameters that both describe
36 /// the simulation and affect its behavior.
37 class SimInfo {
38  public:
39  /// @brief constructs a SimInfo instance with default variables
40  /// @return a SimInfo instance
41  SimInfo();
42 
43  /// @brief constructs a SimInfo instance using some default variables
44  /// @param dur simulation duration in number of timesteps
45  /// @param y0 start year for the simulation
46  /// @param m0 start month for the simulation
47  /// @param handle is this simulation's unique simulation handle
48  /// @return a SimInfo instance
49  SimInfo(int dur, int y0 = 2010, int m0 = 1,
50  std::string handle = "");
51 
52  /// @brief constructs a SimInfo instance using no default variables
53  /// @param dur simulation duration in number of timesteps
54  /// @param y0 start year for the simulation
55  /// @param m0 start month for the simulation
56  /// @param handle is this simulation's unique simulation handle
57  /// @param d the decay data member, "never" for no decay. "manual" otherwise
58  /// @return a SimInfo instance
59  SimInfo(int dur, int y0, int m0,
60  std::string handle, std::string d);
61 
62  /// @brief constructs a SimInfo instance
63  /// @param dur simulation duration in number of timesteps
64  /// @param parent_sim the uuid of the parent simulation
65  /// @param branch_time
66  /// @param parent_type a string indicating the type of the parent simulation
67  /// @param handle is this simulation's unique simulation handle
68  /// @return a SimInfo instance
69  SimInfo(int dur, boost::uuids::uuid parent_sim,
70  int branch_time, std::string parent_type,
71  std::string handle = "");
72 
73  /// user-defined label associated with a particular simulation
74  std::string handle;
75 
76  /// "manual" if use of the decay function is allowed, "never" otherwise
77  std::string decay;
78 
79  /// length of the simulation in timesteps (months)
80  int duration;
81 
82  /// start year for the simulation (e.g. 1973);
83  int y0;
84 
85  /// start month for the simulation: Jan = 1, ..., Dec = 12
86  int m0;
87 
88  /// id for the parent simulation if any
89  boost::uuids::uuid parent_sim;
90 
91  /// One of "init", "branch", "restart" indicating the relationship of this
92  /// simulation to its parent simulation.
93  std::string parent_type;
94 
95  /// timestep at which simulation branching occurs if any
97 
98  /// Duration in seconds of a single time step in the simulation.
99  uint64_t dt;
100 
101  /// Epsilon in the simulation.
102  double eps;
103 
104  /// Epsilon for resources in the simulation.
105  double eps_rsrc;
106 
107  /// True if per-agent inventories should be explicitly queried/recorded
108  /// every time step in a table (i.e. agent ID, Time, Nuclide, Quantity).
110 
111  /// True if per-agent inventories should be explicitly queried/recorded
112  /// every time step in a table (i.e. agent ID, Time, Quantity,
113  /// Composition-object and/or reference).
115 };
116 
117 /// A simulation context provides access to necessary simulation-global
118 /// functions and state. All code that writes to the output database, needs to
119 /// know simulation time, creates/builds facilities, and/or uses loaded
120 /// composition recipes will need a context pointer. In general, all global
121 /// state should be accessed through a simulation context.
122 ///
123 /// @warning the context takes ownership of and manages the lifetime/destruction
124 /// of all agents constructed with it (including Cloned agents). Agents should
125 /// generally NEVER be allocated on the stack.
126 /// @warning the context takes ownership of the solver and will manage its
127 /// destruction.
128 class Context {
129  public:
130  friend class ::SimInitTest;
131  friend class SimInit;
132  friend class Agent;
133  friend class Timer;
134 
135  /// Creates a new context working with the specified timer and datum manager.
136  /// The timer does not have to be initialized (yet).
137  Context(Timer* ti, Recorder* rec);
138 
139  /// Clean up resources including destructing the solver and all agents the
140  /// context is aware of.
141  ~Context();
142 
143  /// See Recorder::sim_id documentation.
144  boost::uuids::uuid sim_id();
145 
146  /// Adds a prototype to a simulation-wide accessible list, a prototype **can
147  /// not** be added more than once.
148  /// @param name the prototype name
149  /// @param m a pointer to the agent prototype
150  /// @param overwrite, allow overwrites to the prototype listing, default: false
151  /// @throws if overwrite is false and a prototype name has already been added
152  /// @{
153  void AddPrototype(std::string name, Agent* m);
154  void AddPrototype(std::string name, Agent* m, bool overwrite);
155  /// @}
156 
157  /// Registers an agent as a participant in resource exchanges. Agents should
158  /// register from their Deploy method.
159  inline void RegisterTrader(Trader* e) {
160  traders_.insert(e);
161  }
162 
163  /// Unregisters an agent as a participant in resource exchanges.
164  inline void UnregisterTrader(Trader* e) {
165  traders_.erase(e);
166  }
167 
168  /// @return the current set of traders registered for resource exchange.
169  inline const std::set<Trader*>& traders() const {
170  return traders_;
171  }
172 
173  /// Create a new agent by cloning the named prototype. The returned agent is
174  /// not initialized as a simulation participant.
175  ///
176  /// @warning this method should generally NOT be used by agents.
177  template <class T>
178  T* CreateAgent(std::string proto_name) {
179  if (protos_.count(proto_name) == 0) {
180  throw KeyError("Invalid prototype name " + proto_name);
181  }
182 
183  Agent* m = protos_[proto_name];
184  T* casted(NULL);
185  Agent* clone = m->Clone();
186  casted = dynamic_cast<T*>(clone);
187  if (casted == NULL) {
188  DelAgent(clone);
189  throw CastError("Invalid cast for prototype " + proto_name);
190  }
191  return casted;
192  }
193 
194  /// Destructs and cleans up m (and it's children recursively).
195  ///
196  /// @warning this method should generally NOT be used by agents.
197  void DelAgent(Agent* m);
198 
199  /// Schedules the named prototype to be built for the specified parent at
200  /// timestep t. The default t=-1 results in the build being scheduled for the
201  /// next build phase (i.e. the start of the next timestep).
202  void SchedBuild(Agent* parent, std::string proto_name, int t = -1);
203 
204  /// Schedules the given Agent to be decommissioned at the specified timestep
205  /// t. The default t=-1 results in the decommission being scheduled for the
206  /// next decommission phase (i.e. the end of the current timestep).
207  void SchedDecom(Agent* m, int time = -1);
208 
209  /// Adds a composition recipe to a simulation-wide accessible list.
210  /// Agents should NOT add their own recipes.
211  void AddRecipe(std::string name, Composition::Ptr c);
212 
213  /// Retrieve a registered recipe. This is intended for retrieving
214  /// compositions loaded from an input file(s) at the start of a
215  /// simulation and NOT for communicating compositions between facilities
216  /// during the simulation.
217  Composition::Ptr GetRecipe(std::string name);
218 
219  /// Registers an agent to receive tick/tock notifications every timestep.
220  /// Agents should register from their Deploy method.
221  void RegisterTimeListener(TimeListener* tl);
222 
223  /// Removes an agent from receiving tick/tock notifications.
224  /// Agents should unregister from their Decommission method.
225  void UnregisterTimeListener(TimeListener* tl);
226 
227  /// Initializes the simulation time parameters. Should only be called once -
228  /// NOT idempotent.
229  void InitSim(SimInfo si);
230 
231  /// Returns the current simulation timestep.
232  virtual int time();
233 
234  /// Returns the duration of a single time step in seconds.
235  inline uint64_t dt() {return si_.dt;};
236 
237  /// Return static simulation info.
238  inline SimInfo sim_info() const {
239  return si_;
240  }
241 
242  /// See Recorder::NewDatum documentation.
243  Datum* NewDatum(std::string title);
244 
245  /// Schedules a snapshot of simulation state to output database to occur at
246  /// the beginning of the next timestep.
247  void Snapshot();
248 
249  /// Schedules the simulation to be terminated at the end of this timestep.
250  void KillSim();
251 
252  /// @return the next transaction id
253  inline int NextTransactionID() {
254  return trans_id_++;
255  }
256 
257  /// Returns the exchange solver associated with this context
259  if (solver_ == NULL) {
260  solver_ = new GreedySolver(false, NULL);
261  }
262  return solver_;
263  }
264 
265  /// sets the solver associated with this context
266  void solver(ExchangeSolver* solver) {
267  solver_ = solver;
268  solver_->sim_ctx(this);
269  }
270 
271  /// @return the number of agents of a given prototype currently in the
272  /// simulation
273  inline int n_prototypes(std::string type) {
274  return n_prototypes_[type];
275  }
276 
277  /// @return the number of agents of a given implementation currently in the
278  /// simulation
279  inline int n_specs(std::string impl) {
280  return n_specs_[impl];
281  }
282 
283  private:
284  /// Registers an agent as a participant in the simulation.
285  inline void RegisterAgent(Agent* a) {
286  n_prototypes_[a->prototype()]++;
287  n_specs_[a->spec()]++;
288  }
289 
290  /// Unregisters an agent as a participant in the simulation.
291  inline void UnregisterAgent(Agent* a) {
292  n_prototypes_[a->prototype()]--;
293  n_specs_[a->spec()]--;
294  }
295 
296  /// contains archetype specs of all agents for which version have already
297  /// been recorded in the db
298  std::set<std::string> rec_ver_;
299 
300  std::map<std::string, Agent*> protos_;
301  std::map<std::string, Composition::Ptr> recipes_;
302  std::set<Agent*> agent_list_;
303  std::set<Trader*> traders_;
304  std::map<std::string, int> n_prototypes_;
305  std::map<std::string, int> n_specs_;
306 
307  SimInfo si_;
308  Timer* ti_;
309  ExchangeSolver* solver_;
310  Recorder* rec_;
311  int trans_id_;
312 };
313 
314 } // namespace cyclus
315 
316 #endif // CYCLUS_SRC_CONTEXT_H_
int n_prototypes(std::string type)
Definition: context.h:273
void RegisterTrader(Trader *e)
Registers an agent as a participant in resource exchanges.
Definition: context.h:159
boost::shared_ptr< Composition > Ptr
Definition: composition.h:43
std::string handle
user-defined label associated with a particular simulation
Definition: context.h:74
int branch_time
timestep at which simulation branching occurs if any
Definition: context.h:96
double eps
Epsilon in the simulation.
Definition: context.h:102
std::string name(int nuc)
Definition: pyne.cc:2940
const std::set< Trader * > & traders() const
Definition: context.h:169
int duration
length of the simulation in timesteps (months)
Definition: context.h:80
A simple API for agents that wish to exchange resources in the simulation.
Definition: trader.h:24
int y0
start year for the simulation (e.g. 1973);
Definition: context.h:83
For failed casts that shouldn&#39;t.
Definition: error.h:65
const std::string prototype() const
Returns the agent&#39;s prototype.
Definition: agent.h:347
bool explicit_inventory
True if per-agent inventories should be explicitly queried/recorded every time step in a table (i...
Definition: context.h:109
void sim_ctx(Context *c)
simulation context get/set
std::string spec()
The string representation of the agent spec that uniquely identifies the concrete agent class/module...
Definition: agent.h:358
void solver(ExchangeSolver *solver)
sets the solver associated with this context
Definition: context.h:266
uint64_t dt
Duration in seconds of a single time step in the simulation.
Definition: context.h:99
Used to specify and send a collection of key-value pairs to the Recorder for recording.
Definition: datum.h:15
const uint64_t kDefaultTimeStepDur
Definition: context.h:21
void UnregisterTrader(Trader *e)
Unregisters an agent as a participant in resource exchanges.
Definition: context.h:164
int parent(int nuc, unsigned int rx, std::string z="n")
Definition: pyne.cc:6621
boost::uuids::uuid parent_sim
id for the parent simulation if any
Definition: context.h:89
T * CreateAgent(std::string proto_name)
Create a new agent by cloning the named prototype.
Definition: context.h:178
std::string decay
"manual" if use of the decay function is allowed, "never" otherwise
Definition: context.h:77
double eps_rsrc
Epsilon for resources in the simulation.
Definition: context.h:105
int NextTransactionID()
Definition: context.h:253
int n_specs(std::string impl)
Definition: context.h:279
int m0
start month for the simulation: Jan = 1, ..., Dec = 12
Definition: context.h:86
SimInfo()
constructs a SimInfo instance with default variables
Definition: context.cc:18
Collects and manages output data generation for the cyclus core and agents during a simulation...
Definition: recorder.h:45
std::string parent_type
One of "init", "branch", "restart" indicating the relationship of this simulation to its parent simul...
Definition: context.h:93
uint64_t dt()
Returns the duration of a single time step in seconds.
Definition: context.h:235
The TimeListener class is an inheritable class for any Agent that requires knowlege of ticks and tock...
Definition: time_listener.h:23
virtual Agent * Clone()=0
Returns a newly created/allocated prototype that is an exact copy of this.
Container for a static simulation-global parameters that both describe the simulation and affect its ...
Definition: context.h:37
A simulation context provides access to necessary simulation-global functions and state...
Definition: context.h:128
bool explicit_inventory_compact
True if per-agent inventories should be explicitly queried/recorded every time step in a table (i...
Definition: context.h:114
The abstract base class used by all types of agents that live and interact in a simulation.
Definition: agent.h:51
taken directly from OsiSolverInterface.cpp on 2/17/14 from https://projects.coin-or.org/Osi/browser/trunk.
Definition: agent.cc:14
a very simple interface for solving translated resource exchanges
Handles initialization of a simulation from the output database.
Definition: sim_init.h:24
ExchangeSolver * solver()
Returns the exchange solver associated with this context.
Definition: context.h:258
SimInfo sim_info() const
Return static simulation info.
Definition: context.h:238
For failed retrieval/insertion of key-based data into/from data structures.
Definition: error.h:47
The GreedySolver provides the implementation for a "greedy" solution to a resource exchange graph...
Definition: greedy_solver.h:63
Controls simulation timestepping and inter-timestep phases.
Definition: timer.h:22