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 simulation
45/// 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 must
93 /// 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., resides
291 /// 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 implement
298 /// this function, they must call their superclass' Build function at the
299 /// 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 END of
322 /// 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() {
335 return "<text />\n";
336 }
337
338 /// Returns an agent's json annotations for all state variables and any other
339 /// information the developer wishes to provide. All concrete agents should
340 /// override this function.
343 }
344
345 /// Returns the agent's prototype.
346 inline const std::string prototype() const { return prototype_; }
347
348 /// Sets the agent's prototype. This should generally NEVER be called
349 /// explicitly by code outside the cyclus kernel.
350 inline void prototype(std::string p) { prototype_ = p; }
351
352 /// The agent instance's unique ID within a simulation.
353 virtual const int id() const { return id_; }
354
355 /// The string representation of the agent spec that uniquely identifies the
356 /// concrete agent class/module. See CEP21 for details..
357 inline std::string spec() { return spec_; }
358
359 /// Sets this agent's agent spec. This should generally NEVER be called
360 /// explicitly by code outside the cyclus kernel.
361 inline void spec(std::string new_impl) { spec_ = new_impl; }
362
363 /// Returns a string that describes the agent subclass (e.g. Region,
364 /// Facility, etc.)
365 inline const std::string kind() const { return kind_; }
366
367 /// Returns this agent's simulation context.
368 inline Context* context() const { return ctx_; }
369
370 /// Description of this agent.
371 virtual std::string str();
372
373 /// Returns parent of this agent. Returns NULL if the agent has no parent.
374 inline Agent* parent() const { return parent_; }
375
376 /// Returns the id for this agent's parent. Returns -1 if this agent has no
377 /// parent.
378 inline const int parent_id() const { return parent_id_; }
379
380 /// Returns the time step at which this agent's Build function was called (-1 if
381 /// the agent has never been built).
382 inline const int enter_time() const { return enter_time_; }
383
384 ///Sets the number of time steps this agent operates between building and
385 /// decommissioning (-1 if the agent has an infinite lifetime). This should
386 /// generally only be called BEFORE an agent is added to a context as a
387 /// prototype. Throws ValueError if the agent has already been deployed.
388 void lifetime(int n_timesteps);
389
390 /// Sets the number of time steps this agent operates between building and
391 /// decommissioning (-1 if the agent has an infinite lifetime).
392 void lifetime_force(int n_timesteps);
393
394 /// Returns the number of time steps this agent operates between building and
395 /// decommissioning (-1 if the agent has an infinite lifetime).
396 inline const int lifetime() const { return lifetime_; }
397
398 /// Returns the default time step at which this agent will exit the
399 /// simulation (-1 if the agent has an infinite lifetime).
400 ///
401 /// Deomissioning happens at the end of a time step. With a lifetime of 1, we
402 /// expect an agent to go through only 1 entire time step. In this case, the
403 /// agent should be decommissioned on the same time step it was
404 /// created. Therefore, for agents with non-infinite lifetimes, the exit_time
405 /// will be the enter time plus its lifetime less 1.
406 inline const int exit_time() const {
407 if (lifetime() == -1)
408 return -1;
409 return enter_time_ + lifetime_ - 1;
410 }
411
412 /// Returns a list of children this agent has
413 inline const std::set<Agent*>& children() const { return children_; }
414
415 protected:
416 /// Initializes a agent by copying parameters from the passed agent m. This
417 /// function must be implemented by all agents. This function must call the
418 /// superclass' InitFrom function. The InitFrom function should only initialize
419 /// this class' members - not inherited state. The superclass InitFrom should
420 /// generally be called before any other work is done.
421 ///
422 /// @param m the agent containing state that should be used to initialize this
423 /// agent.
424 ///
425 /// Example:
426 ///
427 /// @code
428 /// class MyAgentClass : virtual public cyclus::Facility {
429 /// // ...
430 ///
431 /// void InitFrom(MyAgentClass* m) {
432 /// cyclus::Facility::InitFrom(m); // call superclass' InitFrom
433 /// // now do MyAgentClass' initialitions, e.g.:
434 /// my_var_ = m->my_var_;
435 /// // ...
436 /// };
437 ///
438 /// // ...
439 /// };
440 /// @endcode
441 void InitFrom(Agent* m);
442
443 /// adds agent-specific information prefix to an error message
444 virtual std::string InformErrorMsg(std::string msg);
445
446 /// describes the agent subclass (e.g. Region, Inst, etc.). The in-kernel
447 /// subclasses must set this variable in their constructor(s).
448 std::string kind_;
449
450 private:
451 /// length of time this agent is intended to operate
452 int lifetime_;
453
454 /// Prevents creation/use of copy constructors (including in subclasses).
455 /// Cloning and InitFrom should be used instead.
456 Agent(const Agent& m) {}
457
458 /// adds an agent to the transaction table
459 void AddToTable();
460
461 /// connects an agent to its parent.
462 void Connect(Agent* parent);
463
464 /// Stores the next available facility ID
465 static int next_id_;
466
467 /// children of this agent
468 std::set<Agent*> children_;
469
470 /// parent of this agent
471 Agent* parent_;
472
473 /// parent's ID of this agent
474 /// Note: we keep the parent id in the agent so we can reference it
475 /// even if the parent is deallocated.
476 int parent_id_;
477
478 /// born on date of this agent
479 int enter_time_;
480
481 std::string prototype_;
482
483 /// concrete type of a agent (e.g. "MyReactorAgent")
484 std::string spec_;
485
486 /// an instance-unique ID for the agent
487 int id_;
488
489 Context* ctx_;
490};
491
492} // namespace cyclus
493
494#endif // CYCLUS_SRC_AGENT_H_
Represents a JSON value.
Definition pyne.h:3225
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:341
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:406
virtual void InitFrom(QueryableBackend *b)
Intializes an agent's internal state from the database.
Definition agent.cc:45
const std::string prototype() const
Returns the agent's prototype.
Definition agent.h:346
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:153
std::string spec()
The string representation of the agent spec that uniquely identifies the concrete agent class/module.
Definition agent.h:357
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:59
const int parent_id() const
Returns the id for this agent's parent.
Definition agent.h:378
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:208
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:361
Context * context() const
Returns this agent's simulation context.
Definition agent.h:368
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:139
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:36
const int lifetime() const
Returns the number of time steps this agent operates between building and decommissioning (-1 if the ...
Definition agent.h:396
const std::set< Agent * > & children() const
Returns a list of children this agent has.
Definition agent.h:413
const std::string kind() const
Returns a string that describes the agent subclass (e.g.
Definition agent.h:365
virtual const int id() const
The agent instance's unique ID within a simulation.
Definition agent.h:353
virtual void Decommission()
Decommissions the agent, removing it from the simulation.
Definition agent.cc:182
void prototype(std::string p)
Sets the agent's prototype.
Definition agent.h:350
virtual void Snapshot(DbInit di)=0
Snapshots agent-internal state to the database via the DbInit var di.
Definition agent.cc:52
std::string PrintChildren()
recursively prints the parent-child tree
Definition agent.cc:193
virtual ~Agent()
Removes references to self from simulation context, parent, children, etc.
Definition agent.cc:72
bool InFamilyTree(Agent *other)
returns true if this agent is in the parent-child family tree of an other agent
Definition agent.cc:149
friend class SimInit
Definition agent.h:51
std::string kind_
describes the agent subclass (e.g.
Definition agent.h:448
virtual void EnterNotify()
Called to give the agent an opportunity to register for services (e.g.
Definition agent.cc:166
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:374
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:96
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:382
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:129
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:115
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:145
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:3145
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