9#include <boost/filesystem.hpp>
10#include <libxml++/libxml++.h>
29namespace fs = boost::filesystem;
32 std::ifstream file_stream(file.c_str());
34 throw IOError(
"The file '" + file +
"' could not be loaded.");
37 stream << file_stream.rdbuf();
44 if (format ==
"none") {
46 inext = fs::path(file).extension().string();
50 if (inext ==
".json" || format ==
"json") {
53 }
else if (inext ==
".py" || format ==
"py") {
60 std::stringstream input;
65std::vector<AgentSpec>
ParseSpecs(std::set<std::string> agent_set) {
66 std::vector<AgentSpec> specs;
68 for (
const std::string& spec_str : agent_set) {
75std::vector<AgentSpec>
ParseSpecs(std::string infile, std::string format) {
76 std::stringstream input;
82 std::set<std::string> unique;
84 std::string p =
"/simulation/archetypes/spec";
86 for (
int i = 0; i < n; ++i) {
88 unique.insert(spec.
str());
91 if (unique.size() == 0) {
92 throw ValidationError(
"failed to parse archetype specs from input file");
95 std::vector<AgentSpec> specs =
ParseSpecs(unique);
101 std::string schema_path, std::vector<AgentSpec> specs) {
106 std::stringstream schema(
"");
108 std::string master = schema.str();
110 std::map<std::string, std::string> subschemas;
113 subschemas[
"region"] =
"";
114 subschemas[
"inst"] =
"";
115 subschemas[
"facility"] =
"";
117 for (
int i = 0; i < specs.size(); ++i) {
119 subschemas[m->
kind()] +=
"<element name=\"" + specs[i].alias() +
"\">\n";
121 subschemas[m->
kind()] +=
"</element>\n";
126 std::map<std::string, std::string>::iterator it;
127 for (it = subschemas.begin(); it != subschemas.end(); ++it) {
128 std::string search_str =
129 std::string(
"@") + it->first + std::string(
"_REFS@");
130 size_t pos = master.find(search_str);
131 if (pos != std::string::npos) {
132 master.replace(pos, search_str.size(), it->second);
140 std::vector<AgentSpec> specs =
147 std::string format) {
148 std::vector<AgentSpec> specs =
ParseSpecs(infile, format);
155 std::string basis_str = qe->
GetString(
"basis");
156 if (basis_str ==
"atom") {
158 }
else if (basis_str ==
"mass") {
161 throw IOError(basis_str +
" basis is not 'mass' or 'atom'.");
166 std::string query =
"nuclide";
169 for (
int i = 0; i < nnucs; i++) {
172 value = strtod(nuclide->
GetString(
"comp").c_str(), NULL);
185 std::string schema_file,
186 const std::string input_file,
187 const std::string format,
bool ms_print)
194 std::stringstream input;
199 std::stringstream ss;
200 parser_->Document()->write_to_stream_formatted(ss);
201 ctx_->NewDatum(
"InputFiles")->AddVal(
"Data",
Blob(ss.str()))->Record();
233 std::string query =
"/*/commodity";
235 std::map<std::string, double> commod_priority;
238 int num_commods = xqe.
NMatches(query);
239 for (
int i = 0; i < num_commods; i++) {
243 commod_priority[name] = priority;
247 std::map<std::string, double>::iterator it;
248 for (it = commod_priority.begin(); it != commod_priority.end(); ++it) {
249 ctx_->NewDatum(
"CommodPriority")
250 ->AddVal(
"Commodity", it->first)
251 ->AddVal(
"SolutionPriority", it->second)
256 string config =
"config";
257 string greedy =
"greedy";
258 string coinor =
"coin-or";
259 string solver_name = greedy;
261 if (xqe.
NMatches(
"/*/control/solver") == 1) {
262 qe = xqe.
SubTree(
"/*/control/solver");
271 std::stringstream ss;
272 ss <<
"You have set allow_exclusive_orders to False."
273 <<
" Many archetypes (e.g., :cycamore:Reactor) will not work"
274 <<
" as intended with this feature turned off.";
278 ctx_->NewDatum(
"SolverInfo")
279 ->AddVal(
"Solver", solver_name)
280 ->AddVal(
"ExclusiveOrders", exclusive)
284 if (solver_name == greedy) {
285 query = string(
"/*/control/solver/config/greedy/preconditioner");
287 ctx_->NewDatum(
"GreedySolverInfo")
288 ->AddVal(
"Preconditioner", precon_name)
290 }
else if (solver_name == coinor) {
291 query = string(
"/*/control/solver/config/coin-or/timeout");
293 query = string(
"/*/control/solver/config/coin-or/verbose");
295 query = string(
"/*/control/solver/config/coin-or/mps");
297 ctx_->NewDatum(
"CoinSolverInfo")
298 ->AddVal(
"Timeout", timeout)
299 ->AddVal(
"Verbose", verbose)
303 throw ValueError(
"unknown solver name: " + solver_name);
308 std::map<std::string, double>* commod_priority) {
309 double max = std::max_element(commod_priority->begin(),
310 commod_priority->end(),
311 SecondLT<std::pair<std::string, double>>())
317 std::map<std::string, double>::iterator it;
318 for (it = commod_priority->begin(); it != commod_priority->end(); ++it) {
319 if (it->second < 1) {
320 it->second = max + 1;
322 CLOG(
LEV_INFO1) <<
"Commodity priority for " << it->first <<
" is "
330 std::string query =
"/*/recipe";
331 int num_recipes = xqe.
NMatches(query);
332 for (
int i = 0; i < num_recipes; i++) {
334 std::string name = qe->
GetString(
"name");
338 ctx_->AddRecipe(name, comp);
347 std::string query =
"/*/package";
348 int num_packages = xqe.
NMatches(query);
349 for (
int i = 0; i < num_packages; i++) {
357 qe,
"fill_max", std::numeric_limits<double>::max());
359 std::string strategy =
362 ctx_->AddPackage(name, fill_min, fill_max, strategy);
369 std::string query =
"/*/transportunit";
370 int num_transport_units = xqe.
NMatches(query);
371 for (
int i = 0; i < num_transport_units; i++) {
379 qe,
"fill_max", std::numeric_limits<double>::max());
381 std::string strategy =
384 ctx_->AddTransportUnit(name, fill_min, fill_max, strategy);
390 for (
int i = 0; i < specs.size(); ++i) {
391 specs_[specs[i].alias()] = specs[i];
396 std::map<std::string, std::string> schema_paths;
397 schema_paths[
"Region"] =
"/*/region";
398 schema_paths[
"Inst"] =
"/*/region/institution";
399 schema_paths[
"Facility"] =
"/*/facility";
404 std::string prototype;
405 std::map<std::string, std::string>::iterator it;
406 for (it = schema_paths.begin(); it != schema_paths.end(); it++) {
407 int num_agents = xqe.
NMatches(it->second);
408 for (
int i = 0; i < num_agents; i++) {
418 agent->Agent::InfileToDb(qe,
DbInit(agent,
true));
423 std::vector<Cond> conds;
424 conds.push_back(
Cond(
"SimId",
"==",
rec_->sim_id()));
425 conds.push_back(
Cond(
"SimTime",
"==",
static_cast<int>(0)));
426 conds.push_back(
Cond(
"AgentId",
"==", agent->
id()));
431 agent->Agent::InitFrom(&pi);
435 ctx_->AddPrototype(prototype, agent);
440 int nregions = xqe.
NMatches(schema_paths[
"Region"]);
441 for (
int i = 0; i < nregions; ++i) {
443 std::string region_proto = qe->
GetString(
"name");
446 int ninsts = qe->
NMatches(
"institution");
447 for (
int j = 0; j < ninsts; ++j) {
449 std::string inst_proto = qe2->
GetString(
"name");
452 int nfac = qe2->
NMatches(
"initialfacilitylist/entry");
453 for (
int k = 0; k < nfac; ++k) {
455 std::string fac_proto = qe3->
GetString(
"prototype");
457 int number = atoi(qe3->
GetString(
"number").c_str());
458 for (
int z = 0; z < number; ++z) {
469 if (parent != NULL) {
470 parent->BuildNotify(m);
477 std::string query =
"/*/control";
481 if (qe->
NMatches(
"simhandle") > 0) {
486 std::string dur_str = qe->
GetString(
"duration");
487 int dur = strtol(dur_str.c_str(), NULL, 10);
489 std::string m0_str = qe->
GetString(
"startmonth");
490 int m0 = strtol(m0_str.c_str(), NULL, 10);
492 std::string y0_str = qe->
GetString(
"startyear");
493 int y0 = strtol(y0_str.c_str(), NULL, 10);
497 SimInfo si(dur, y0, m0, handle, d);
The abstract base class used by all types of agents that live and interact in a simulation.
virtual void InitFrom(QueryableBackend *b)
Intializes an agent's internal state from the database.
virtual void Build(Agent *parent)
Called when the agent enters the smiulation as an active participant and is only ever called once.
virtual std::string schema()
Returns an agent's xml rng schema for initializing from input files.
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...
const std::string kind() const
Returns a string that describes the agent subclass (e.g.
virtual const int id() const
The agent instance's unique ID within a simulation.
A type to represent variable-length array of bytes for dumping to a cyclus output 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
static Ptr CreateFromAtom(CompMap v)
Creates a new composition from v with its components having appropriate atom-based ratios.
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 DelAgent(Agent *m)
Destructs and cleans up m (and it's children recursively).
DbInit provides an interface for agents to record data to the output db that automatically injects th...
static Agent * Make(Context *ctx, AgentSpec spec)
Returns a newly constructed agent for the given module spec.
static const bool kDefaultExclusive
default value to allow exclusive orders or not
for failed reading/writing to files, network connections, etc..
A class for extracting information from a given XML parser.
virtual int NMatches(std::string query)
investigates the current status and returns the number of elements matching a query
virtual std::string GetElementName(int index=0)
investigates the current status and returns a string representing the name of a given index
InfileTree * SubTree(std::string query, int index=0)
populates a child infile based on a query and index
virtual std::string GetString(std::string query, int index=0)
investigates the current status and returns a string representing the content of a query at a given i...
static Ptr & unpackaged()
Wrapper class for QueryableBackends that injects prefix in front of the title/table for every query b...
Interface implemented by backends that support rudimentary querying.
Collects and manages output data generation for the cyclus core and agents during a simulation.
Container for a static simulation-global parameters that both describe the simulation and affect its ...
double eps_rsrc
Epsilon for resources in the simulation.
bool explicit_inventory_compact
True if per-agent inventories should be explicitly queried/recorded every time step in a table (i....
double eps
Epsilon in the simulation.
uint64_t stride
Stride length.
uint64_t dt
Duration in seconds of a single time step in the simulation.
uint64_t seed
Seed for random number generator.
bool explicit_inventory
True if per-agent inventories should be explicitly queried/recorded every time step in a table (i....
static void Snapshot(Context *ctx)
Records a snapshot of the current state of the simulation being managed by ctx into the simulation's ...
Controls simulation timestepping and inter-timestep phases.
For validating files received via IO.
For values that are too big, too small, etc.
XMLFileLoader(Recorder *r, QueryableBackend *b, std::string schema_file, const std::string input_file="", const std::string format="none", bool ms_print=false)
Create a new loader reading from the xml simulation input file and writing to and initializing the ba...
void LoadPackages()
Loads packages.
void LoadRecipes()
Method to load recipes from either the primary input file or a recipeBook catalog.
std::string format_
the input file format
void LoadControlParams()
Method to load the simulation control parameters.
boost::shared_ptr< XMLParser > parser_
the parser
void LoadSolver()
Method to load the simulation exchange solver.
void LoadSpecs()
Load agent specs from the input file to a map by alias.
bool ms_print_
flag to indicate printing master schema
virtual std::string master_schema()
std::string schema_path_
filepath to the schema
void LoadTransportUnits()
Loads Transport Units.
std::map< std::string, AgentSpec > specs_
virtual void LoadInitialAgents()
Creates all initial agent instances from the input file.
Agent * BuildAgent(std::string proto, Agent *parent)
Creates and builds an agent, notifying its parent.
void ProcessCommodities(std::map< std::string, double > *commodity_priority)
Processes commodity priorities, such that any without a defined priority (i.e., are nonpositive),...
std::string file_
the input file name
virtual void LoadSim()
Load an entire simulation from the inputfile.
A helper class to hold xml file data and provide automatic validation.
void Init(const std::stringstream &input)
initializes a parser with an xml snippet
const uint64_t kDefaultSeed
const uint64_t kDefaultStride
const uint64_t kDefaultTimeStepDur
Code providing rudimentary logging capability for the Cyclus core.
taken directly from OsiSolverInterface.cpp on 2/17/14 from https://projects.coin-or....
void LoadRawStringstreamFromFile(std::stringstream &stream, std::string file)
Reads the given file path into the passed stream without modification.
std::set< std::string > DiscoverSpecsInCyclusPath()
Discover archetype specifications that live recursively in CYCLUS_PATH directories.
Composition::Ptr ReadRecipe(InfileTree *qe)
Creates a composition from the recipe in the query engine.
double cy_eps_rsrc
epsilon values to be used by resources
double cy_eps
generic epsilon values
void LoadStringstreamFromFile(std::stringstream &stream, std::string file, std::string format)
Reads the given file path as XML into the passed stream.
std::vector< AgentSpec > ParseSpecs(std::set< std::string > agent_set)
Returns a list of the full module+agent spec for all agents in the given set of agent names.
@ LEV_DEBUG3
debugging information
@ LEV_INFO1
Information helpful for simulation users and developers alike.
std::map< Nuc, double > CompMap
a raw definition of nuclides and corresponding (dimensionless quantities).
std::string LoadStringFromFile(std::string file, std::string format)
Reads the given file path and returns an XML string.
double eps()
a generic epsilon value
std::string BuildMasterSchema(std::string schema_path, std::vector< AgentSpec > specs)
Builds and returns a master cyclus input xml schema that includes the sub-schemas defined by the prov...
T OptionalQuery(InfileTree *tree, std::string query, T default_val)
a query method for optional parameters
void Warn(const std::string &msg)
Issue a warning with the approriate message, accoring to the current warning settings.
a less-than comparison for pairs