CYCLUS
Loading...
Searching...
No Matches
agent.h
Go to the documentation of this file.
1#ifndef CYCLUS_SRC_AGENT_H_
2#define CYCLUS_SRC_AGENT_H_
3
4#include <map>
5#include <set>
6#include <string>
7#include <vector>
8
9#include "db_init.h"
10#include "dynamic_module.h"
11#include "infile_tree.h"
12#include "exchange_context.h"
13#include "pyne.h"
14#include "query_backend.h"
15#include "resource.h"
16#include "state_wrangler.h"
17#include "economic_entity.h"
18
19// Undefines isnan from pyne
20#ifdef isnan
21#undef isnan
22#endif
23
24class SimInitTest;
25
26namespace cyclus {
27
28class Ider {
29 public:
30 virtual const int id() const = 0;
31};
32
33class Material;
34class Product;
35
36/// map<inventory_name, vector<resources_in_inventory> >. Used by agents in
37/// their #SnapshotInv and #InitInv functions for saving+loading their internal
38/// resource inventories.
39typedef std::map<std::string, std::vector<Resource::Ptr>> Inventories;
40
41/// The abstract base class used by all types of agents
42/// that live and interact in a simulation.
43///
44/// There are several functions that must be implemented in support of
45/// simulation initialization, snapshotting and restart: #InfileToDb,
46/// InitFrom(QueryableBackend*), #Snapshot, #SnapshotInv, and #InitInv. These
47/// functions all do inter-related things. Notably, the #InfileToDb, #InitFrom,
48/// and #Snapshot functions must all write/read to/from the same database tables
49/// (and table schemas).
50class Agent : public StateWrangler, virtual public Ider, public EconomicEntity {
51 friend class SimInit;
52 friend class ::SimInitTest;
53
54 public:
55 /// Creates a new agent that is managed by the given context. Note that the
56 /// context takes ownership of its agents' memory and so agents should
57 /// generally never be created on the stack.
58 Agent(Context* ctx);
59
60 /// Removes references to self from simulation context, parent, children,
61 /// etc. All subclass destructors should also be virtual.
62 virtual ~Agent();
63
64 virtual std::string version() { return "unspecified"; }
65
66 /// Returns a newly created/allocated prototype that is an exact copy of this.
67 /// All initialization and state cloning operations should be done in the
68 /// agent's InitFrom(Agent*) function. The new agent instance should NOT be
69 /// created using a default copy-constructor. New agent instances should
70 /// generally be created using a constructor that takes a single Context
71 /// argument (the same context of the agent being cloned). Example:
72 ///
73 /// @code
74 /// class MyAgentClass : virtual public Agent {
75 /// ...
76 ///
77 /// virtual Agent* Clone() {
78 /// MyAgentClass* m = new MyAgentClass(context());
79 /// m->InitFrom(this);
80 /// return m;
81 /// };
82 ///
83 /// ...
84 /// };
85 /// @endcode
86 virtual Agent* Clone() = 0;
87
88 /// Translates info for the agent from an input file to the database by
89 /// reading parameters from the passed InfileTree (parsed from xml) and
90 /// recording data via the DbInit variable. The simulation id and agent id
91 /// are automatically injected in all data transfered to the database through
92 /// DbInit. This function must be implemented by all agents. This function
93 /// must call the superclass' InfileToDb function before doing any other work.
94 ///
95 /// Agent parameters in the InfileTree are scoped in the "agent/*/" path.
96 /// The superclass InitFrom expects the scope InfileTree passed to it to be
97 /// unchanged from the agent's InfileTree arg.
98 ///
99 ///
100 /// Example:
101 ///
102 /// @code
103 /// class MyAgentClass : virtual public cyclus::Facility {
104 /// // ...
105 ///
106 /// void InfileToDb(cyclus::InfileTree* tree, cyclus::DbInit di) {
107 /// cyclus::Facility::InitFrom(tree);
108 ///
109 /// // now do MyAgentClass' initialitions, e.g.:
110 /// tree = tree->Query("agent/*"); // rescope the InfileTree
111 ///
112 /// // retrieve all agent params
113 /// std::string recipe = tree->GetString("recipe");
114 /// std::string in_commod = tree->GetString("in_commod");
115 /// double cap = cyclus::Query<double>(tree, "cap");
116 /// di.NewDatum("MyAgentTable1")
117 /// ->AddVal("recipe", recipe)
118 /// ->AddVal("in_commod", in_commod)
119 /// ->AddVal("cap", cap)
120 /// ->Record();
121 /// // ...
122 /// };
123 ///
124 /// // ...
125 /// };
126 /// @endcode
127 ///
128 /// @warning because 'SimId' 'SimTime', and 'AgentId' fields are automatically
129 /// injected, those labels cannot be used for any other fields.
130 ///
131 /// @warning this function MUST NOT modify the agent's state.
132 virtual void InfileToDb(InfileTree* qe, DbInit di);
133
134 /// Intializes an agent's internal state from the database. Appropriate
135 /// simulation id, agent id, and time filters are automatically included in
136 /// all queries. If the agent is a direct subclass of the Agent class, than
137 /// it should NOT call its superclass' InitFrom(QueryableBackend*) function.
138 /// If, however, it is a subclasses other Agent subclasses (e.g. subclass of
139 /// Facility, Region, etc.), then it MUST call its superclass'
140 /// InitFrom(QueryableBackend*) function. Example:
141 ///
142 /// @code
143 /// class MyAgentClass : virtual public cyclus::Facility {
144 /// // ...
145 ///
146 /// void InitFrom(cyclus::QueryableBackend* b) {
147 /// cyclus::Facility::InitFrom(b);
148 ///
149 /// cyclus::QueryResult qr = b->Query("MyAgentTable1", NULL);
150 /// recipe = qr.GetVal<std::string>("recipe");
151 /// in_commod = qr.GetVal<std::string>("in_commod");
152 /// cap = qr.GetVal<double>("cap");
153 ///
154 /// // ...
155 /// };
156 ///
157 /// std::string recipe;
158 /// std::string in_commod;
159 /// double cap;
160 ///
161 /// // ...
162 /// };
163 ///
164 /// @endcode
165 ///
166 /// @warning Agents should NOT create any resource objects in this function.
167 virtual void InitFrom(QueryableBackend* b);
168
169 /// Snapshots agent-internal state to the database via the DbInit var di. The
170 /// simulation id , agent id, and the simulation time are automatically
171 /// injected in all information transfered to the database through DbInit.
172 /// If the agent is a direct subclass of the Agent class, than it should NOT
173 /// call its superclass' Snapshot function. If, however, it subclasses
174 /// other Agent subclasses (e.g. subclass of Facility, Region, etc.), then it
175 /// MUST call its superclass' Snapshot function. Example:
176 ///
177 /// @code
178 /// class MyAgentClass : virtual public cyclus::Facility {
179 /// // ...
180 ///
181 /// void Snapshot(cyclus::DbInit di) {
182 /// cyclus::Facility::Snapshot(di);
183 ///
184 /// di.NewDatum("MyAgentTable1")
185 /// ->AddVal("recipe", recipe)
186 /// ->AddVal("in_commod", in_commod)
187 /// ->AddVal("cap", cap)
188 /// ->Record();
189 ///
190 /// // ...
191 /// };
192 ///
193 /// std::string recipe;
194 /// std::string in_commod;
195 /// double cap;
196 ///
197 /// // ...
198 /// };
199 ///
200 /// @endcode
201 ///
202 /// @warning because 'SimId' 'SimTime', and 'AgentId' fields are automatically
203 /// injected, those labels cannot be used for any other fields.
204 ///
205 /// @warning This function MUST NOT modify the agent's internal state.
206 /// @warning Do not record any information via the context's NewDatum
207 /// function.
208 virtual void Snapshot(DbInit di) = 0;
209
210 /// Provides an agent's initial inventory of resources before a simulation
211 /// begins. The resources are keyed in the same way as given in the agent's
212 /// SnapshotInv function. Agents should iterate through each named inventory
213 /// provided and populate their corresponding resource containers with the
214 /// given resources.
215 ///
216 /// @code
217 /// class MyAgentClass : virtual public cyclus::Facility {
218 /// // ...
219 ///
220 /// void InitInv(cyclus::Inventories& inv) {
221 /// buf1.Push(inv["buf1"]);
222 /// buf2.Push(inv["buf2"]);
223 ///
224 /// // ...
225 /// };
226 ///
227 /// cyclus::toolkit::ResBuf<Material> buf1;
228 /// cyclus::toolkit::ResBuf<Material> buf2;
229 ///
230 /// // ...
231 /// };
232 ///
233 /// @endcode
234 ///
235 /// @warning agents should not modify any state outside the container filling
236 virtual void InitInv(Inventories& inv) = 0;
237
238 /// Snapshots an agent's resource inventories to the database. The set of
239 /// resources in each container should be stored under a string key unique
240 /// for that container that will be used when re-initializing inventories for
241 /// restarted simulations in the InitInv function.
242 ///
243 /// @code
244 /// class MyAgentClass : virtual public cyclus::Facility {
245 /// // ...
246 ///
247 /// cyclus::Inventories SnapshotInv() {
248 /// cyclus::Inventories invs;
249 /// cyclus::toolkit::ResVec rs = buf1.PopNRes(buf1.count());
250 /// buf1.Push(rs); // Snapshot must not change agent's state
251 /// invs["buf1"] = rs;
252 /// rs = buf2.PopNRes(buf2.count());
253 /// buf2.Push(rs); // Snapshot must not change agent's state
254 /// invs["buf2"] = rs;
255 ///
256 /// // ...
257 ///
258 /// return invs;
259 /// };
260 ///
261 /// cyclus::toolkit::ResBuf<Material> buf1;
262 /// cyclus::toolkit::ResBuf<Material> buf2;
263 ///
264 /// // ...
265 /// };
266 ///
267 /// @endcode
268 ///
269 /// @warning This function MUST NOT modify the agent's internal state.
271
272 /// recursively prints the parent-child tree
273 std::string PrintChildren();
274
275 /// returns a vector of strings representing the parent-child tree
276 /// at the node for Agent m
277 /// @param m the agent node to base as the root of this print tree
278 std::vector<std::string> GetTreePrintOuts(Agent* m);
279
280 /// returns true if this agent is in the parent-child family tree of an other
281 /// agent
282 /// @param other the other agent
283 bool InFamilyTree(Agent* other);
284
285 /// returns true if this agent is an ancestor of an other agent (i.e., resides
286 /// above an other agent in the family tree)
287 /// @param other the other agent
288 bool AncestorOf(Agent* other);
289
290 /// returns true if this agent is an decendent of an other agent (i.e.,
291 /// resides below an other agent in the family tree)
292 /// @param other the other agent
293 bool DecendentOf(Agent* other);
294
295 /// Called when the agent enters the smiulation as an active participant and
296 /// is only ever called once. Agents should NOT register for services (such
297 /// as ticks/tocks and resource exchange) in this function. If agents
298 /// implement this function, they must call their superclass' Build function
299 /// at the BEGINING of their Build function.
300 ///
301 /// @param parent this agent's parent. NULL if this agent has no parent.
302 virtual void Build(Agent* parent);
303
304 /// Called to give the agent an opportunity to register for services (e.g.
305 /// ticks/tocks and resource exchange). Note that this may be called more
306 /// than once, and so agents should track their registrations carefully. If
307 /// agents implement this function, they must call their superclass's
308 /// EnterNotify function at the BEGINNING of their EnterNotify function.
309 virtual void EnterNotify();
310
311 /// Called when a new child of this agent has just been built. It is possible
312 /// for this function to be called before the simulation has started when
313 /// initially existing agents are being setup.
314 virtual void BuildNotify(Agent* m) {}
315
316 /// Called when a child of this agent is about to be decommissioned.
317 virtual void DecomNotify(Agent* m) {}
318
319 /// Decommissions the agent, removing it from the simulation. Results in
320 /// destruction of the agent object. If agents write their own Decommission
321 /// function, they must call their superclass' Decommission function at the
322 /// END of their Decommission function.
323 virtual void Decommission();
324
325 /// default implementation for material preferences.
327
328 /// default implementation for material preferences.
330
331 /// Returns an agent's xml rng schema for initializing from input files. All
332 /// concrete agents should override this function. This must validate the same
333 /// xml input that the InfileToDb function receives.
334 virtual std::string schema() { return "<text />\n"; }
335
336 /// Returns an agent's json annotations for all state variables and any other
337 /// information the developer wishes to provide. All concrete agents should
338 /// override this function.
340
341 /// Returns the agent's prototype.
342 inline const std::string prototype() const { return prototype_; }
343
344 /// Sets the agent's prototype. This should generally NEVER be called
345 /// explicitly by code outside the cyclus kernel.
346 inline void prototype(std::string p) { prototype_ = p; }
347
348 /// The agent instance's unique ID within a simulation.
349 virtual const int id() const { return id_; }
350
351 /// The string representation of the agent spec that uniquely identifies the
352 /// concrete agent class/module. See CEP21 for details..
353 inline std::string spec() { return spec_; }
354
355 /// Sets this agent's agent spec. This should generally NEVER be called
356 /// explicitly by code outside the cyclus kernel.
357 inline void spec(std::string new_impl) { spec_ = new_impl; }
358
359 /// Returns a string that describes the agent subclass (e.g. Region,
360 /// Facility, etc.)
361 inline const std::string kind() const { return kind_; }
362
363 /// Returns this agent's simulation context.
364 inline Context* context() const { return ctx_; }
365
366 /// Description of this agent.
367 virtual std::string str();
368
369 /// Returns parent of this agent. Returns NULL if the agent has no parent.
370 inline Agent* parent() const { return parent_; }
371
372 /// Returns the id for this agent's parent. Returns -1 if this agent has no
373 /// parent.
374 inline const int parent_id() const { return parent_id_; }
375
376 /// Returns the time step at which this agent's Build function was called (-1
377 /// if the agent has never been built).
378 inline const int enter_time() const { return enter_time_; }
379
380 /// Sets the number of time steps this agent operates between building and
381 /// decommissioning (-1 if the agent has an infinite lifetime). This should
382 /// generally only be called BEFORE an agent is added to a context as a
383 /// prototype. Throws ValueError if the agent has already been deployed.
384 void lifetime(int n_timesteps);
385
386 /// Sets the number of time steps this agent operates between building and
387 /// decommissioning (-1 if the agent has an infinite lifetime).
388 void lifetime_force(int n_timesteps);
389
390 /// Returns the number of time steps this agent operates between building and
391 /// decommissioning (-1 if the agent has an infinite lifetime).
392 inline const int lifetime() const { return lifetime_; }
393
394 /// Returns the default time step at which this agent will exit the
395 /// simulation (-1 if the agent has an infinite lifetime).
396 ///
397 /// Deomissioning happens at the end of a time step. With a lifetime of 1, we
398 /// expect an agent to go through only 1 entire time step. In this case, the
399 /// agent should be decommissioned on the same time step it was
400 /// created. Therefore, for agents with non-infinite lifetimes, the exit_time
401 /// will be the enter time plus its lifetime less 1.
402 inline const int exit_time() const {
403 if (lifetime() == -1) return -1;
404 return enter_time_ + lifetime_ - 1;
405 }
406
407 /// Returns a list of children this agent has
408 inline const std::set<Agent*>& children() const { return children_; }
409
410 protected:
411 /// Initializes a agent by copying parameters from the passed agent m. This
412 /// function must be implemented by all agents. This function must call the
413 /// superclass' InitFrom function. The InitFrom function should only
414 /// initialize this class' members - not inherited state. The superclass
415 /// InitFrom should generally be called before any other work is done.
416 ///
417 /// @param m the agent containing state that should be used to initialize this
418 /// agent.
419 ///
420 /// Example:
421 ///
422 /// @code
423 /// class MyAgentClass : virtual public cyclus::Facility {
424 /// // ...
425 ///
426 /// void InitFrom(MyAgentClass* m) {
427 /// cyclus::Facility::InitFrom(m); // call superclass' InitFrom
428 /// // now do MyAgentClass' initialitions, e.g.:
429 /// my_var_ = m->my_var_;
430 /// // ...
431 /// };
432 ///
433 /// // ...
434 /// };
435 /// @endcode
436 void InitFrom(Agent* m);
437
438 /// adds agent-specific information prefix to an error message
439 virtual std::string InformErrorMsg(std::string msg);
440
441 /// describes the agent subclass (e.g. Region, Inst, etc.). The in-kernel
442 /// subclasses must set this variable in their constructor(s).
443 std::string kind_;
444
445 private:
446 /// length of time this agent is intended to operate
447 int lifetime_;
448
449 /// Prevents creation/use of copy constructors (including in subclasses).
450 /// Cloning and InitFrom should be used instead.
451 Agent(const Agent& m) {}
452
453 /// adds an agent to the transaction table
454 void AddToTable();
455
456 /// connects an agent to its parent.
457 void Connect(Agent* parent);
458
459 /// Stores the next available facility ID
460 static int next_id_;
461
462 /// children of this agent
463 std::set<Agent*> children_;
464
465 /// parent of this agent
466 Agent* parent_;
467
468 /// parent's ID of this agent
469 /// Note: we keep the parent id in the agent so we can reference it
470 /// even if the parent is deallocated.
471 int parent_id_;
472
473 /// born on date of this agent
474 int enter_time_;
475
476 std::string prototype_;
477
478 /// concrete type of a agent (e.g. "MyReactorAgent")
479 std::string spec_;
480
481 /// an instance-unique ID for the agent
482 int id_;
483
484 Context* ctx_;
485};
486
487} // namespace cyclus
488
489#endif // CYCLUS_SRC_AGENT_H_
Represents a JSON value.
Definition pyne.h:3088
The abstract base class used by all types of agents that live and interact in a simulation.
Definition agent.h:50
virtual Json::Value annotations()
Returns an agent's json annotations for all state variables and any other information the developer w...
Definition agent.h:339
virtual void DecomNotify(Agent *m)
Called when a child of this agent is about to be decommissioned.
Definition agent.h:317
virtual void BuildNotify(Agent *m)
Called when a new child of this agent has just been built.
Definition agent.h:314
const int exit_time() const
Returns the default time step at which this agent will exit the simulation (-1 if the agent has an in...
Definition agent.h:402
virtual void InitFrom(QueryableBackend *b)
Intializes an agent's internal state from the database.
Definition agent.cc:44
const std::string prototype() const
Returns the agent's prototype.
Definition agent.h:342
virtual void Build(Agent *parent)
Called when the agent enters the smiulation as an active participant and is only ever called once.
Definition agent.cc:144
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.
Agent(Context *ctx)
Creates a new agent that is managed by the given context.
Definition agent.cc:58
const int parent_id() const
Returns the id for this agent's parent.
Definition agent.h:374
virtual std::string schema()
Returns an agent's xml rng schema for initializing from input files.
Definition agent.h:334
virtual void InitInv(Inventories &inv)=0
Provides an agent's initial inventory of resources before a simulation begins.
std::vector< std::string > GetTreePrintOuts(Agent *m)
returns a vector of strings representing the parent-child tree at the node for Agent m
Definition agent.cc:199
virtual void AdjustMatlPrefs(PrefMap< Material >::type &prefs)
default implementation for material preferences.
Definition agent.h:326
void spec(std::string new_impl)
Sets this agent's agent spec.
Definition agent.h:357
Context * context() const
Returns this agent's simulation context.
Definition agent.h:364
bool DecendentOf(Agent *other)
returns true if this agent is an decendent of an other agent (i.e., resides below an other agent in t...
Definition agent.cc:131
virtual void InfileToDb(InfileTree *qe, DbInit di)
Translates info for the agent from an input file to the database by reading parameters from the passe...
Definition agent.cc:35
const int lifetime() const
Returns the number of time steps this agent operates between building and decommissioning (-1 if the ...
Definition agent.h:392
const std::set< Agent * > & children() const
Returns a list of children this agent has.
Definition agent.h:408
const std::string kind() const
Returns a string that describes the agent subclass (e.g.
Definition agent.h:361
virtual const int id() const
The agent instance's unique ID within a simulation.
Definition agent.h:349
virtual void Decommission()
Decommissions the agent, removing it from the simulation.
Definition agent.cc:173
void prototype(std::string p)
Sets the agent's prototype.
Definition agent.h:346
virtual void Snapshot(DbInit di)=0
Snapshots agent-internal state to the database via the DbInit var di.
Definition agent.cc:51
std::string PrintChildren()
recursively prints the parent-child tree
Definition agent.cc:184
virtual ~Agent()
Removes references to self from simulation context, parent, children, etc.
Definition agent.cc:71
bool InFamilyTree(Agent *other)
returns true if this agent is in the parent-child family tree of an other agent
Definition agent.cc:140
friend class SimInit
Definition agent.h:51
std::string kind_
describes the agent subclass (e.g.
Definition agent.h:443
virtual void EnterNotify()
Called to give the agent an opportunity to register for services (e.g.
Definition agent.cc:157
virtual std::string version()
Definition agent.h:64
Agent * parent() const
Returns parent of this agent. Returns NULL if the agent has no parent.
Definition agent.h:370
virtual void AdjustProductPrefs(PrefMap< Product >::type &prefs)
default implementation for material preferences.
Definition agent.h:329
virtual std::string str()
Description of this agent.
Definition agent.cc:95
virtual std::string InformErrorMsg(std::string msg)
adds agent-specific information prefix to an error message
Definition agent.cc:27
const int enter_time() const
Returns the time step at which this agent's Build function was called (-1 if the agent has never been...
Definition agent.h:378
bool AncestorOf(Agent *other)
returns true if this agent is an ancestor of an other agent (i.e., resides above an other agent in th...
Definition agent.cc:122
void lifetime_force(int n_timesteps)
Sets the number of time steps this agent operates between building and decommissioning (-1 if the age...
Definition agent.cc:110
virtual Inventories SnapshotInv()=0
Snapshots an agent's resource inventories to the database.
A simulation context provides access to necessary simulation-global functions and state.
Definition context.h:146
DbInit provides an interface for agents to record data to the output db that automatically injects th...
Definition db_init.h:14
virtual const int id() const =0
A class for extracting information from a given XML parser.
Definition infile_tree.h:22
The material class is primarily responsible for enabling basic material manipulation while helping en...
Definition material.h:71
A Product is a general type of resource in the Cyclus simulation, and is a catch-all for non-standard...
Definition product.h:18
Interface implemented by backends that support rudimentary querying.
An abjstract interface that must be implemented by all simulation agents and all agent member variabl...
@ objectValue
object value (collection of name/value pairs).
Definition pyne.h:3019
taken directly from OsiSolverInterface.cpp on 2/17/14 from https://projects.coin-or....
Definition agent.cc:14
std::map< std::string, std::vector< Resource::Ptr > > Inventories
map<inventory_name, vector<resources_in_inventory> >.
Definition agent.h:39
int CapacityConstraint< T >::next_id_
std::map< Request< T > *, std::map< Bid< T > *, double > > type