Skip to content

Commit

Permalink
exception handling for input file read errors
Browse files Browse the repository at this point in the history
  • Loading branch information
amit133 committed Jan 6, 2017
1 parent e35f157 commit 0dbcf5a
Show file tree
Hide file tree
Showing 2 changed files with 150 additions and 148 deletions.
278 changes: 139 additions & 139 deletions examples/smp/libsrc/smp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,7 @@ void SMPState::setAccomodate(const KMatrix & aMat) {

VctrPstn SMPState::getIdeal(unsigned int n) const
{
return ideals[n];
return ideals[n];
}
void SMPState::addPstn(Position* ap) {
auto sp = (VctrPstn*)ap;
Expand Down Expand Up @@ -936,129 +936,129 @@ void SMPModel::sankeyOutput(string inputCSV) const {
// JAH 20160801 changed to refer to model sqlFlags vector to decide
// whether or not to populate the table
void SMPModel::showVPHistory() const {
assert(numAct == actrs.size());
assert(numDim == dimName.size());

// first need to get the group ID for this table
// so then we can get the flag to populate the table or not
// note the implicit assumption that there will never be 43+ groups :-)
unsigned int grpID = 42;
for (unsigned int t = 0; t<KTables.size(); t++)
{
if (KTables[t]->tabName == "VectorPosition")
{
grpID = KTables[t]->tabGrpID;
break;
}
}
// be sure that it found this table
assert(grpID != 42);
assert(grpID < sqlFlags.size());

// JAH 20160801 only populate the table if this group is turned on
if (sqlFlags[grpID])
{
assert(nullptr != smpDB);
char* zErrMsg = nullptr;

//createSQL(Model::NumTables + 0); // Make sure VectorPosition table is present
auto sqlBuff = newChars(sqlBuffSize);
sprintf(sqlBuff,
"INSERT INTO VectorPosition (ScenarioId, Turn_t, Act_i, Dim_k, Pos_Coord, Idl_Coord) VALUES ('%s', ?1, ?2, ?3, ?4, ?5)",
scenId.c_str());

assert(nullptr != smpDB);
const char* insStr = sqlBuff;
sqlite3_stmt *insStmt;
sqlite3_prepare_v2(smpDB, insStr, strlen(insStr), &insStmt, NULL);
assert(nullptr != insStmt); //make sure it is ready

// Prepared statements cache the execution plan for a query after the query optimizer has
// found the best plan, so there is no big gain with simple insertions.
// What makes a huge difference is bundling a few hundred into one atomic "transaction".
// For this case, runtime droped from 62-65 seconds to 0.5-0.6 (vs. 0.30-0.33 with no SQL at all).

sqlite3_exec(smpDB, "BEGIN TRANSACTION", NULL, NULL, &zErrMsg);

// show positions over time
for (unsigned int i = 0; i < numAct; i++) {
for (unsigned int k = 0; k < numDim; k++) {
printf("%s , %s , ", actrs[i]->name.c_str(), dimName[k].c_str());
for (unsigned int t = 0; t < history.size(); t++) {
auto st = history[t];
auto pit = st->pstns[i];
auto vpit = (const VctrPstn*)pit;
auto sst = ((const SMPState*)st);
auto vidl = sst->getIdeal(i);
assert(1 == vpit->numC());
assert(numDim == vpit->numR());
printf("%5.1f , ", 100 * (*vpit)(k, 0)); // have to print "100.0" sometimes
int rslt = 0;
rslt = sqlite3_bind_int(insStmt, 1, t);
assert(SQLITE_OK == rslt);
rslt = sqlite3_bind_int(insStmt, 2, i);
assert(SQLITE_OK == rslt);
rslt = sqlite3_bind_int(insStmt, 3, k);
assert(SQLITE_OK == rslt);
const double pCoord = (*vpit)(k, 0);
rslt = sqlite3_bind_double(insStmt, 4, pCoord);
assert(SQLITE_OK == rslt);
const double iCoord = vidl(k, 0);
rslt = sqlite3_bind_double(insStmt, 5, iCoord);
assert(SQLITE_OK == rslt);
rslt = sqlite3_step(insStmt);
assert(SQLITE_DONE == rslt);
sqlite3_clear_bindings(insStmt);
assert(SQLITE_DONE == rslt);
rslt = sqlite3_reset(insStmt);
assert(SQLITE_OK == rslt);
}
cout << endl;
}
}

sqlite3_exec(smpDB, "END TRANSACTION", NULL, NULL, &zErrMsg);
sqlite3_finalize(insStmt); // finalize statement to avoid resource leaks
cout << endl;

delete sqlBuff;
sqlBuff = nullptr;
}

// show probabilities over time.
// Note that we have to set the aUtil matrices for the last one.
vector<KMatrix> prbHist = {};
vector<VUI> unqHist = {};
for (unsigned int t = 0; t < history.size(); t++) {
auto sst = (SMPState*)history[t];
assert(numAct == sst->aUtil.size()); // should be fully initialized
auto pn = sst->pDist(-1);
auto pdt = std::get<0>(pn); // note that these are unique positions
auto unq = std::get<1>(pn);
prbHist.push_back(pdt);
unqHist.push_back(unq);
}

auto probIT = [this, prbHist, unqHist](unsigned int i, unsigned int t) {
auto pdt = prbHist[t];
auto unq = unqHist[t];
auto sst = ((const SMPState*)(history[t]));
double pr = sst->posProb(i, unq, pdt);
return pr;
};

// TODO: displaying the probabilities of actors winning is a bit odd,
// as we display the probability of their position winning. As multiple
// actors often occupy the equivalent positions, this means the displayed probabilities
// will often add up to more than 1.
for (unsigned int i = 0; i < numAct; i++) {
printf("%s , prob , ", actrs[i]->name.c_str());
for (unsigned int t = 0; t < history.size(); t++) {
printf("%.4f , ", probIT(i, t)); // prbHist[t](i, 0),
}
cout << endl << flush;
}
return;
assert(numAct == actrs.size());
assert(numDim == dimName.size());

// first need to get the group ID for this table
// so then we can get the flag to populate the table or not
// note the implicit assumption that there will never be 43+ groups :-)
unsigned int grpID = 42;
for (unsigned int t = 0; t<KTables.size(); t++)
{
if (KTables[t]->tabName == "VectorPosition")
{
grpID = KTables[t]->tabGrpID;
break;
}
}
// be sure that it found this table
assert(grpID != 42);
assert(grpID < sqlFlags.size());

// JAH 20160801 only populate the table if this group is turned on
if (sqlFlags[grpID])
{
assert(nullptr != smpDB);
char* zErrMsg = nullptr;

//createSQL(Model::NumTables + 0); // Make sure VectorPosition table is present
auto sqlBuff = newChars(sqlBuffSize);
sprintf(sqlBuff,
"INSERT INTO VectorPosition (ScenarioId, Turn_t, Act_i, Dim_k, Pos_Coord, Idl_Coord) VALUES ('%s', ?1, ?2, ?3, ?4, ?5)",
scenId.c_str());

assert(nullptr != smpDB);
const char* insStr = sqlBuff;
sqlite3_stmt *insStmt;
sqlite3_prepare_v2(smpDB, insStr, strlen(insStr), &insStmt, NULL);
assert(nullptr != insStmt); //make sure it is ready

// Prepared statements cache the execution plan for a query after the query optimizer has
// found the best plan, so there is no big gain with simple insertions.
// What makes a huge difference is bundling a few hundred into one atomic "transaction".
// For this case, runtime droped from 62-65 seconds to 0.5-0.6 (vs. 0.30-0.33 with no SQL at all).

sqlite3_exec(smpDB, "BEGIN TRANSACTION", NULL, NULL, &zErrMsg);

// show positions over time
for (unsigned int i = 0; i < numAct; i++) {
for (unsigned int k = 0; k < numDim; k++) {
printf("%s , %s , ", actrs[i]->name.c_str(), dimName[k].c_str());
for (unsigned int t = 0; t < history.size(); t++) {
auto st = history[t];
auto pit = st->pstns[i];
auto vpit = (const VctrPstn*)pit;
auto sst = ((const SMPState*)st);
auto vidl = sst->getIdeal(i);
assert(1 == vpit->numC());
assert(numDim == vpit->numR());
printf("%5.1f , ", 100 * (*vpit)(k, 0)); // have to print "100.0" sometimes
int rslt = 0;
rslt = sqlite3_bind_int(insStmt, 1, t);
assert(SQLITE_OK == rslt);
rslt = sqlite3_bind_int(insStmt, 2, i);
assert(SQLITE_OK == rslt);
rslt = sqlite3_bind_int(insStmt, 3, k);
assert(SQLITE_OK == rslt);
const double pCoord = (*vpit)(k, 0);
rslt = sqlite3_bind_double(insStmt, 4, pCoord);
assert(SQLITE_OK == rslt);
const double iCoord = vidl(k, 0);
rslt = sqlite3_bind_double(insStmt, 5, iCoord);
assert(SQLITE_OK == rslt);
rslt = sqlite3_step(insStmt);
assert(SQLITE_DONE == rslt);
sqlite3_clear_bindings(insStmt);
assert(SQLITE_DONE == rslt);
rslt = sqlite3_reset(insStmt);
assert(SQLITE_OK == rslt);
}
cout << endl;
}
}

sqlite3_exec(smpDB, "END TRANSACTION", NULL, NULL, &zErrMsg);
sqlite3_finalize(insStmt); // finalize statement to avoid resource leaks
cout << endl;

delete sqlBuff;
sqlBuff = nullptr;
}

// show probabilities over time.
// Note that we have to set the aUtil matrices for the last one.
vector<KMatrix> prbHist = {};
vector<VUI> unqHist = {};
for (unsigned int t = 0; t < history.size(); t++) {
auto sst = (SMPState*)history[t];
assert(numAct == sst->aUtil.size()); // should be fully initialized
auto pn = sst->pDist(-1);
auto pdt = std::get<0>(pn); // note that these are unique positions
auto unq = std::get<1>(pn);
prbHist.push_back(pdt);
unqHist.push_back(unq);
}

auto probIT = [this, prbHist, unqHist](unsigned int i, unsigned int t) {
auto pdt = prbHist[t];
auto unq = unqHist[t];
auto sst = ((const SMPState*)(history[t]));
double pr = sst->posProb(i, unq, pdt);
return pr;
};

// TODO: displaying the probabilities of actors winning is a bit odd,
// as we display the probability of their position winning. As multiple
// actors often occupy the equivalent positions, this means the displayed probabilities
// will often add up to more than 1.
for (unsigned int i = 0; i < numAct; i++) {
printf("%s , prob , ", actrs[i]->name.c_str());
for (unsigned int t = 0; t < history.size(); t++) {
printf("%.4f , ", probIT(i, t)); // prbHist[t](i, 0),
}
cout << endl << flush;
}
return;
}

SMPModel * SMPModel::initModel(vector<string> aName, vector<string> aDesc, vector<string> dName,
Expand Down Expand Up @@ -1125,17 +1125,17 @@ void SMPModel::setDBPath(std::string dbName)
}
void SMPModel::displayModelPrams(SMPModel *md0)
{
cout << "Model Paramaters getting used to run the model...\n";
cout << "VictoryProbModel: " << md0->vpm << endl;
cout << "VotingRule: " << md0->vrCltn << endl;
cout << "PCEModel: " << md0->pcem << endl;
cout << "StateTransitions: " << md0->stm << endl;
cout << "BigRRange: " << md0->bigRRng << endl;
cout << "BigRAdjust: " << md0->bigRAdj << endl;
cout << "ThirdPartyCommit: " << md0->tpCommit << endl;
cout << "InterVecBrgn: " << md0->ivBrgn << endl;
cout << "BargnModel: " << md0->brgnMod << endl;
cout << flush;
cout << "Model Paramaters getting used to run the model...\n";
cout << "VictoryProbModel: " << md0->vpm << endl;
cout << "VotingRule: " << md0->vrCltn << endl;
cout << "PCEModel: " << md0->pcem << endl;
cout << "StateTransitions: " << md0->stm << endl;
cout << "BigRRange: " << md0->bigRRng << endl;
cout << "BigRAdjust: " << md0->bigRAdj << endl;
cout << "ThirdPartyCommit: " << md0->tpCommit << endl;
cout << "InterVecBrgn: " << md0->ivBrgn << endl;
cout << "BargnModel: " << md0->brgnMod << endl;
cout << flush;
}

string SMPModel::runModel(vector<bool> sqlFlags, string dbFilePath,
Expand All @@ -1159,7 +1159,7 @@ string SMPModel::runModel(vector<bool> sqlFlags, string dbFilePath,
assert((fileExt == "csv") || (fileExt == "xml"));

if (fileExt == "xml") {
md0 = SMPModel::xmlRead(inputDataFile, sqlFlags);
md0 = xmlRead(inputDataFile, sqlFlags);

if (0 == seed) {
md0->rng->setSeed(0); // random and irreproducible
Expand Down Expand Up @@ -1193,16 +1193,16 @@ string SMPModel::csvReadExec(uint64_t seed, string inputCSV, vector<bool> f, str
if (false == par.empty()) {
SMPModel::updateModelParameters(md0, par);
}
SMPModel::displayModelPrams(md0);
configExec(md0);
displayModelPrams(md0);
configExec(md0);
md0->releaseDB();
return md0->getScenarioID();
}

string SMPModel::xmlReadExec(string inputXML, vector<bool> f, string dbFilePath) {
SMPModel::setDBPath(dbFilePath);
md0 = SMPModel::xmlRead(inputXML, f);
SMPModel::displayModelPrams(md0);
displayModelPrams(md0);
configExec(md0);
md0->releaseDB();
return md0->getScenarioID();
Expand Down
20 changes: 11 additions & 9 deletions examples/smp/libsrc/smpread.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -258,23 +258,25 @@ SMPModel * SMPModel::xmlRead(string fName, vector<bool> f) {
d1.LoadFile(fName.c_str());
auto eid = d1.ErrorID();
if (0 != eid) {
cout << "tinyxml2 ErrorID: " << eid << endl;
throw KException(d1.GetErrorStr1());
string errMsg = string("Tinyxml2 ErrorID: ") + std::to_string(eid)
+ ", Error Name: " + d1.ErrorName()
+ " " + d1.GetErrorStr1();
throw KException(errMsg);
}
// missing data causes the missing XMLElement* to come back as nullptr
XMLElement* scenEl = d1.FirstChildElement("Scenario");
assert(nullptr != scenEl);
auto scenNameEl = getFirstChild(scenEl, "name");
sName = scenNameEl->GetText();
printf("Name of scenario: %s\n", sName);
cout << "Name of scenario: " << sName << endl;
auto scenDescEl = getFirstChild(scenEl, "desc");
sn2 = scenDescEl->GetText();
assert(!sn2.empty());
auto seedEl = getFirstChild(scenEl, "prngSeed");
const char* sd2 = seedEl->GetText();
assert(nullptr != sd2);
seed = std::stoull(sd2);
printf("Read PRNG seed: %020llu \n", seed);
cout << "Read PRNG seed: " << seed << endl;

auto modelParamsEl = getFirstChild(scenEl, "ModelParameters");
if (nullptr == modelParamsEl) {
Expand All @@ -284,10 +286,9 @@ SMPModel * SMPModel::xmlRead(string fName, vector<bool> f) {
function <string (const char*)> showChild = [getFirstChild, modelParamsEl](const char* name ) {
auto el = getFirstChild(modelParamsEl, name);
if (nullptr == el) {
throw (KException("SMPModel::xmlRead - failed to find required XML element"));
throw (KException(string("SMPModel::xmlRead - failed to find required XML element: ") + name));
}
string s = el->GetText();
cout << " " << name << ": " << s << endl << flush;
return s;
};
cout << "Reading model parameters from XML scenario ..." << endl << flush;
Expand Down Expand Up @@ -318,7 +319,7 @@ SMPModel * SMPModel::xmlRead(string fName, vector<bool> f) {
numDim++;
dEl = dEl->NextSiblingElement("dName");
}
printf("Found %u dimensions \n", numDim);
cout << "Found " << numDim << " dimensions" << endl;
}
catch (...)
{
Expand All @@ -342,8 +343,7 @@ SMPModel * SMPModel::xmlRead(string fName, vector<bool> f) {
{
throw (KException("SMPModel::readXML: Error reading Actors data"));
}
printf("Found %u actors \n", numAct);
cout << endl;
cout << "Found " << numAct << " actors" << endl;


capM = KMatrix(numAct, 1);
Expand Down Expand Up @@ -459,10 +459,12 @@ SMPModel * SMPModel::xmlRead(string fName, vector<bool> f) {
catch (const KException& ke)
{
cout << "Caught KException in SMPModel::readXML: " << ke.msg << endl << flush;
exit(-1);
}
catch (...)
{
cout << "Caught unidentified exception in SMPModel::readXML" << endl << flush;
exit(-1);
}

posM = posM / 100.0;
Expand Down

0 comments on commit 0dbcf5a

Please sign in to comment.