28 InitBase(b, r->
sim_id(), 0);
34 " tested. Its behavior may change in future"
37 InitBase(b, sim_id, t);
45 int t, boost::uuids::uuid new_sim_id) {
46 throw Error(
"simulation branching feature not implemented");
49void SimInit::InitBase(
QueryableBackend* b, boost::uuids::uuid simid,
int t) {
52 std::vector<Cond> conds;
53 conds.push_back(
Cond(
"SimId",
"==", simid));
82 std::set<Agent*> mlist = ctx->agent_list_;
83 std::set<Agent*>::iterator it;
84 for (it = mlist.begin(); it != mlist.end(); ++it) {
94 ->
AddVal(
"Object", std::string(
"Agent"))
95 ->
AddVal(
"NextId", Agent::next_id_)
99 ->
AddVal(
"Object", std::string(
"Transaction"))
100 ->
AddVal(
"NextId", ctx->trans_id_)
104 ->
AddVal(
"Object", std::string(
"Composition"))
105 ->
AddVal(
"NextId", Composition::next_id_)
109 ->
AddVal(
"Object", std::string(
"ResourceState"))
110 ->
AddVal(
"NextId", Resource::nextstate_id_)
114 ->
AddVal(
"Object", std::string(
"ResourceObj"))
115 ->
AddVal(
"NextId", Resource::nextobj_id_)
119 ->
AddVal(
"Object", std::string(
"Product"))
120 ->
AddVal(
"NextId", Product::next_qualid_)
127 m->Agent::Snapshot(
DbInit(m,
true));
133 Inventories::iterator it;
134 for (it = invs.begin(); it != invs.end(); ++it) {
135 std::string name = it->first;
136 std::vector<Resource::Ptr> inv = it->second;
137 for (
int i = 0; i < inv.size(); ++i) {
138 ctx->
NewDatum(
"AgentStateInventories")
140 ->AddVal(
"SimTime", ctx->
time())
141 ->AddVal(
"InventoryName", name)
142 ->
AddVal(
"ResourceId", inv[i]->state_id())
148void SimInit::LoadInfo() {
150 int dur = qr.
GetVal<
int>(
"Duration");
151 int y0 = qr.
GetVal<
int>(
"InitialYear");
152 int m0 = qr.
GetVal<
int>(
"InitialMonth");
153 std::string h = qr.
GetVal<std::string>(
"Handle");
155 std::string d = dq.
GetVal<std::string>(
"Decay");
156 si_ =
SimInfo(dur, y0, m0, h, d);
158 si_.seed = qr.
GetVal<
int>(
"Seed");
159 si_.stride = qr.
GetVal<
int>(
"Stride");
161 si_.parent_sim = qr.
GetVal<boost::uuids::uuid>(
"ParentSimId");
163 qr = b_->
Query(
"TimeStepDur", NULL);
166 si_.dt = qr.
GetVal<
int>(
"DurationSecs");
168 qr = b_->
Query(
"Epsilon", NULL);
169 si_.eps = qr.
GetVal<
double>(
"GenericEpsilon");
170 si_.eps_rsrc = qr.GetVal<
double>(
"ResourceEpsilon");
172 qr = b_->
Query(
"InfoExplicitInv", NULL);
173 si_.explicit_inventory = qr.
GetVal<
bool>(
"RecordInventory");
174 si_.explicit_inventory_compact = qr.GetVal<
bool>(
"RecordInventoryCompact");
179void SimInit::LoadRecipes() {
182 qr = b_->
Query(
"Recipes", NULL);
183 }
catch (std::exception err) {
187 for (
int i = 0; i < qr.rows.size(); ++i) {
188 std::string recipe = qr.
GetVal<std::string>(
"Recipe", i);
189 int stateid = qr.GetVal<
int>(
"QualId", i);
195void SimInit::LoadPackages() {
198 qr = b_->
Query(
"Packages", NULL);
199 }
catch (std::exception err) {
203 for (
int i = 0; i < qr.rows.size(); ++i) {
204 std::string
name = qr.GetVal<std::string>(
"PackageName", i);
205 double fill_min = qr.GetVal<
double>(
"FillMin", i);
206 double fill_max = qr.GetVal<
double>(
"FillMax", i);
207 std::string strategy = qr.GetVal<std::string>(
"Strategy", i);
210 ctx_->
AddPackage(name, fill_min, fill_max, strategy);
218void SimInit::LoadTransportUnits() {
221 qr = b_->
Query(
"TransportUnits", NULL);
222 }
catch (std::exception err) {
226 for (
int i = 0; i < qr.rows.size(); ++i) {
227 std::string
name = qr.GetVal<std::string>(
"TransportUnitName", i);
228 int fill_min = qr.GetVal<
int>(
"FillMin", i);
229 int fill_max = qr.GetVal<
int>(
"FillMax", i);
230 std::string strategy = qr.GetVal<std::string>(
"Strategy", i);
241void* SimInit::LoadPreconditioner(std::string name) {
245 map<string, double> commod_order;
247 QueryResult qr = b_->
Query(
"CommodPriority", NULL);
248 for (
int i = 0; i < qr.rows.size(); ++i) {
249 std::string commod = qr.
GetVal<
string>(
"Commodity", i);
250 double order = qr.GetVal<
double>(
"SolutionOrder", i);
251 commod_order[commod] = order;
253 }
catch (std::exception err) {
258 if (name ==
"greedy") {
259 precon =
new GreedyPreconditioner(commod_order,
262 throw ValueError(
"The name of the preconditioner was not recognized, "
263 "got '" + name +
"'.");
268ExchangeSolver* SimInit::LoadGreedySolver(
bool exclusive,
269 std::set<std::string> tables) {
272 ExchangeSolver* solver;
274 string precon_name =
string(
"greedy");
276 string solver_info =
string(
"GreedySolverInfo");
277 if (0 < tables.count(solver_info)) {
278 QueryResult qr = b_->
Query(solver_info, NULL);
279 if (qr.rows.size() > 0) {
280 precon_name = qr.
GetVal<
string>(
"Preconditioner");
284 precon = LoadPreconditioner(precon_name);
285 if (precon == NULL) {
286 solver =
new GreedySolver(exclusive);
288 solver =
new GreedySolver(exclusive,
289 reinterpret_cast<GreedyPreconditioner*
>(precon));
294ExchangeSolver* SimInit::LoadCoinSolver(
bool exclusive,
295 std::set<std::string> tables) {
297 ExchangeSolver* solver;
301 std::string solver_info =
"CoinSolverInfo";
302 if (0 < tables.count(solver_info)) {
303 QueryResult qr = b_->
Query(solver_info, NULL);
304 timeout = qr.
GetVal<
double>(
"Timeout");
305 verbose = qr.GetVal<
bool>(
"Verbose");
306 mps = qr.GetVal<
bool>(
"Mps");
311 solver =
new ProgSolver(
"cbc", timeout, exclusive, verbose, mps);
314 throw cyclus::Error(
"Cyclus was not compiled with COIN support, cannot load solver.");
318void SimInit::LoadSolverInfo() {
322 ExchangeSolver* solver;
324 bool exclusive_orders;
328 set<string> tables = b_->
Tables();
329 string solver_info =
string(
"SolverInfo");
330 if (0 < tables.count(solver_info)) {
331 QueryResult qr = b_->
Query(solver_info, NULL);
332 if (qr.rows.size() > 0) {
333 solver_name = qr.
GetVal<
string>(
"Solver");
334 exclusive_orders = qr.GetVal<
bool>(
"ExclusiveOrders");
338 if (solver_name ==
"greedy") {
339 solver = LoadGreedySolver(exclusive_orders, tables);
340 }
else if (solver_name ==
"coin-or") {
341 solver = LoadCoinSolver(exclusive_orders, tables);
343 throw ValueError(
"The name of the solver was not recognized, "
344 "got '" + solver_name +
"'.");
350void SimInit::LoadPrototypes() {
351 QueryResult qr = b_->
Query(
"Prototypes", NULL);
352 for (
int i = 0; i < qr.rows.size(); ++i) {
353 std::string proto = qr.
GetVal<std::string>(
"Prototype", i);
354 int agentid = qr.GetVal<
int>(
"AgentId", i);
355 std::string impl = qr.GetVal<std::string>(
"Spec", i);
356 AgentSpec spec(impl);
364 std::vector<Cond> conds;
365 conds.push_back(Cond(
"AgentId",
"==", agentid));
366 CondInjector ci(b_, conds);
367 PrefixInjector
pi(&ci,
"AgentState");
370 m->Agent::InitFrom(&pi);
372 pi = PrefixInjector(&ci,
"AgentState" + spec.Sanitize());
378void SimInit::LoadInitialAgents() {
385 std::vector<Cond> conds;
386 conds.push_back(Cond(
"EnterTime",
"<=", t_));
387 QueryResult qentry = b_->
Query(
"AgentEntry", &conds);
388 std::map<int, int> parentmap;
389 std::map<int, Agent*> unbuilt;
390 for (
int i = 0; i < qentry.rows.size(); ++i) {
391 if (t_ > 0 && qentry.GetVal<
int>(
"EnterTime", i) == t_) {
395 int id = qentry.
GetVal<
int>(
"AgentId", i);
396 std::vector<Cond> conds;
397 conds.push_back(Cond(
"AgentId",
"==",
id));
398 conds.push_back(Cond(
"ExitTime",
"<", t_));
400 QueryResult qexit = b_->
Query(
"AgentExit", &conds);
401 if (qexit.rows.size() != 0) {
404 }
catch (std::exception err) {}
408 std::string proto = qentry.
GetVal<std::string>(
"Prototype", i);
409 std::string impl = qentry.GetVal<std::string>(
"Spec", i);
410 AgentSpec spec(impl);
414 m->prototype_ = proto;
416 m->enter_time_ = qentry.GetVal<
int>(
"EnterTime", i);
418 parentmap[
id] = qentry.GetVal<
int>(
"ParentId", i);
422 conds.push_back(Cond(
"SimTime",
"==", t_));
423 CondInjector ci(b_, conds);
424 PrefixInjector
pi(&ci,
"AgentState");
425 m->Agent::InitFrom(&pi);
426 pi = PrefixInjector(&ci,
"AgentState" + spec.Sanitize());
431 std::map<int, Agent*>::iterator it = unbuilt.begin();
432 std::vector<Agent*> enter_list;
433 while (unbuilt.size() > 0) {
435 Agent* m = it->second;
436 int parentid = parentmap[
id];
438 if (parentid == -1) {
443 enter_list.push_back(m);
444 }
else if (agents_.count(parentid) > 0) {
445 m->Connect(agents_[parentid]);
449 enter_list.push_back(m);
453 if (it == unbuilt.end()) {
454 it = unbuilt.begin();
460 for (
int i = 0; i < enter_list.size(); ++i) {
461 enter_list[i]->EnterNotify();
465void SimInit::LoadInventories() {
466 std::map<int, Agent*>::iterator it;
467 for (it = agents_.begin(); it != agents_.end(); ++it) {
468 Agent* m = it->second;
469 std::vector<Cond> conds;
470 conds.push_back(Cond(
"SimTime",
"==", t_));
471 conds.push_back(Cond(
"AgentId",
"==", m->id()));
474 qr = b_->
Query(
"AgentStateInventories", &conds);
475 }
catch (std::exception err) {
return;}
478 for (
int i = 0; i < qr.rows.size(); ++i) {
479 std::string inv_name = qr.
GetVal<std::string>(
"InventoryName", i);
480 int state_id = qr.GetVal<
int>(
"ResourceId", i);
481 invs[inv_name].push_back(LoadResource(ctx_, b_, state_id));
487void SimInit::LoadBuildSched() {
488 std::vector<Cond> conds;
489 conds.push_back(Cond(
"BuildTime",
">", t_));
492 qr = b_->
Query(
"BuildSchedule", &conds);
493 }
catch (std::exception err) {
return;}
495 for (
int i = 0; i < qr.rows.size(); ++i) {
496 int t = qr.
GetVal<
int>(
"BuildTime", i);
497 int parentid = qr.GetVal<
int>(
"ParentId", i);
498 std::string proto = qr.GetVal<std::string>(
"Prototype", i);
499 ctx_->
SchedBuild(agents_[parentid], proto, t);
503void SimInit::LoadDecomSched() {
504 std::vector<Cond> conds;
505 conds.push_back(Cond(
"DecomTime",
">=", t_));
508 qr = b_->
Query(
"DecomSchedule", &conds);
509 }
catch (std::exception err) {
return;}
511 for (
int i = 0; i < qr.rows.size(); ++i) {
512 int t = qr.
GetVal<
int>(
"DecomTime", i);
513 int agentid = qr.GetVal<
int>(
"AgentId", i);
518void SimInit::LoadNextIds() {
519 std::vector<Cond> conds;
520 conds.push_back(Cond(
"Time",
"==", t_));
521 QueryResult qr = b_->
Query(
"NextIds", &conds);
522 for (
int i = 0; i < qr.rows.size(); ++i) {
523 std::string obj = qr.
GetVal<std::string>(
"Object", i);
524 if (obj ==
"Agent") {
525 Agent::next_id_ = qr.GetVal<
int>(
"NextId", i);
526 }
else if (obj ==
"Transaction") {
527 ctx_->trans_id_ = qr.GetVal<
int>(
"NextId", i);
528 }
else if (obj ==
"Composition") {
529 Composition::next_id_ = qr.GetVal<
int>(
"NextId", i);
530 }
else if (obj ==
"ResourceState") {
531 Resource::nextstate_id_ = qr.GetVal<
int>(
"NextId", i);
532 }
else if (obj ==
"ResourceObj") {
533 Resource::nextobj_id_ = qr.GetVal<
int>(
"NextId", i);
534 }
else if (obj ==
"Product") {
535 Product::next_qualid_ = qr.GetVal<
int>(
"NextId", i);
537 throw IOError(
"Unexpected value in NextIds table: " + obj);
551 m->tracker_.DontTrack();
565 p->tracker_.DontTrack();
571 std::vector<Cond> conds;
572 conds.push_back(
Cond(
"ResourceId",
"==", state_id));
575 int obj_id = qr.
GetVal<
int>(
"ObjId");
579 r = LoadMaterial(ctx, b, state_id);
581 r = LoadProduct(ctx, b, state_id);
583 throw IOError(
"Invalid resource type in output database: " + type);
586 r->state_id_ = state_id;
593 std::vector<Cond> conds;
594 conds.push_back(Cond(
"ResourceId",
"==", state_id));
595 QueryResult qr =
b->Query(
"MaterialInfo", &conds);
596 int prev_decay = qr.GetVal<
int>(
"PrevDecayTime");
600 conds.push_back(Cond(
"ResourceId",
"==", state_id));
601 qr =
b->Query(
"Resources", &conds);
602 double qty = qr.GetVal<
double>(
"Quantity");
603 int stateid = qr.GetVal<
int>(
"QualId");
607 Agent* dummy =
new Dummy(ctx);
609 mat->prev_decay_time_ = prev_decay;
610 ctx->DelAgent(dummy);
615Composition::Ptr SimInit::LoadComposition(QueryableBackend* b,
int stateid) {
616 std::vector<Cond> conds;
617 conds.push_back(Cond(
"QualId",
"==", stateid));
618 QueryResult qr =
b->Query(
"Compositions", &conds);
620 for (
int i = 0; i < qr.rows.size(); ++i) {
621 int nucid = qr.GetVal<
int>(
"NucId", i);
622 double mass_frac = qr.GetVal<
double>(
"MassFrac", i);
623 cm[nucid] = mass_frac;
633 std::vector<Cond> conds;
634 conds.push_back(Cond(
"ResourceId",
"==", state_id));
635 QueryResult qr =
b->Query(
"Resources", &conds);
636 double qty = qr.GetVal<
double>(
"Quantity");
637 int stateid = qr.GetVal<
int>(
"QualId");
641 conds.push_back(Cond(
"QualId",
"==", stateid));
642 qr =
b->Query(
"Products", &conds);
643 std::string quality = qr.GetVal<std::string>(
"Quality");
646 Product::qualids_[quality] = stateid;
648 Agent* dummy =
new Dummy(ctx);
650 ctx->DelAgent(dummy);
a holding class for information related to a TradeExecutor
The abstract base class used by all types of agents that live and interact in a simulation.
Context * context() const
Returns this agent's simulation context.
virtual const int id() const
The agent instance's unique ID within a simulation.
virtual void Snapshot(DbInit di)=0
Snapshots agent-internal state to the database via the DbInit var di.
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...
virtual Inventories SnapshotInv()=0
Snapshots an agent's resource inventories to the database.
static Ptr CreateFromMass(CompMap v)
Creates a new composition from v with its components having appropriate mass-based ratios.
boost::shared_ptr< Composition > Ptr
Wrapper class for QueryableBackends that injects a set of Cond's into every query before being execut...
Represents a condition used to filter rows returned by a query.
A simulation context provides access to necessary simulation-global functions and state.
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.
Datum * NewDatum(std::string title)
See Recorder::NewDatum documentation.
ExchangeSolver * solver()
Returns the exchange solver associated with this context.
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.
void AddRecipe(std::string name, Composition::Ptr c)
Adds a composition recipe to a simulation-wide accessible list.
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.
void RecordTransportUnit(TransportUnit::Ptr)
Records transport unit information.
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.
virtual int time()
Returns the current simulation timestep.
void RecordPackage(Package::Ptr)
Records package information.
void SchedDecom(Agent *m, int time=-1)
Schedules the given Agent to be decommissioned at the specified timestep t.
void InitSim(SimInfo si)
Initializes the simulation time parameters.
Datum * AddVal(const char *field, boost::spirit::hold_any val, std::vector< int > *shape=NULL)
Add an arbitrary field-value pair to the datum.
void Record()
Record this datum to its Recorder.
DbInit provides an interface for agents to record data to the output db that automatically injects th...
Dummy * Clone()
Returns a newly created/allocated prototype that is an exact copy of this.
static Agent * Make(Context *ctx, AgentSpec spec)
Returns a newly constructed agent for the given module spec.
A generic mechanism to manually manage exceptions.
static const ResourceType kType
boost::shared_ptr< Material > Ptr
static Ptr Create(Agent *creator, double quantity, Composition::Ptr c, std::string package_name=Package::unpackaged_name())
Creates a new material resource that is "live" and tracked.
static Ptr & unpackaged()
static std::string unpackaged_name()
static Ptr Create(Agent *creator, double quantity, std::string quality, std::string package_name=Package::unpackaged_name())
Creates a new product that is "live" and tracked.
boost::shared_ptr< Product > Ptr
static const ResourceType kType
static const int kDefaultTimeout
Meta data and results of a query.
T GetVal(std::string field, int row=0)
Convenience method for retrieving a value from a specific row and named field (column).
Interface implemented by backends that support rudimentary querying.
virtual QueryResult Query(std::string table, std::vector< Cond > *conds)=0
Return a set of rows from the specificed table that match all given conditions.
virtual std::set< std::string > Tables()=0
Return a set of all table names currently in the database.
Collects and manages output data generation for the cyclus core and agents during a simulation.
boost::uuids::uuid sim_id()
returns the unique id associated with this cyclus simulation.
void Flush()
Flushes all buffered Datum objects and flushes all registered backends.
The Region class is the abstract class/interface used by all region agents.
boost::shared_ptr< Resource > Ptr
Container for a static simulation-global parameters that both describe the simulation and affect its ...
boost::uuids::uuid parent_sim
id for the parent simulation if any
std::string parent_type
One of "init", "branch", "restart" indicating the relationship of this simulation to its parent simul...
int branch_time
timestep at which simulation branching occurs if any
static Product::Ptr BuildProduct(QueryableBackend *b, int resid)
Convenience function for reconstructing an untracked product object with the given resource state id ...
void Restart(QueryableBackend *b, boost::uuids::uuid sim_id, int t)
EXPERIMENTAL (might not work properly).
void Init(Recorder *r, QueryableBackend *b)
Initialize a simulation with data from b for simulation id in r.
static void SnapAgent(Agent *m)
Records a snapshot of the agent's current internal state into the simulation's output database.
static void Snapshot(Context *ctx)
Records a snapshot of the current state of the simulation being managed by ctx into the simulation's ...
static Material::Ptr BuildMaterial(QueryableBackend *b, int resid)
Convenience function for reconstructing an untracked material object with the given resource state id...
void Branch(QueryableBackend *b, boost::uuids::uuid prev_sim_id, int t, boost::uuids::uuid new_sim_id)
NOT IMPLEMENTED.
Controls simulation timestepping and inter-timestep phases.
static std::string unrestricted_name()
static Ptr & unrestricted()
taken directly from OsiSolverInterface.cpp on 2/17/14 from https://projects.coin-or....
std::map< Nuc, double > CompMap
a raw definition of nuclides and corresponding (dimensionless quantities).
std::vector< typename T::Ptr > ResCast(std::vector< Resource::Ptr > rs)
Casts a vector of Resources into a vector of a specific resource type T.
std::map< std::string, std::vector< Resource::Ptr > > Inventories
map<inventory_name, vector<resources_in_inventory> >.
void Warn(const std::string &msg)
Issue a warning with the approriate message, accoring to the current warning settings.
std::string name(int nuc)
double b(int nuc)
Computes the scattering length [cm] from the coherent and incoherent components.
const double pi
pi = 3.14159265359