Esempio n. 1
0
// Standard function takes the query as an input and evaluates the associated function
void KBModActionPlugin::ExecuteAtom::execute(Environment& environment,
		RegistryPtr pregistry, const Tuple& parms,
		const InterpretationConstPtr interpretationPtr) {

	Registry& registry = *pregistry;

	assert(parms.size() > 0);

	std::string command;
	for (int i = 0; i < parms.size(); i++) {
		if (parms[i].isIntegerTerm()) {
			std::ostringstream a_int;
			a_int << parms[i].address;
			std::string int_str = a_int.str();
			command += int_str;
		} else if (parms[i].isConstantTerm() || parms[i].isVariableTerm()) {
			std::string termStr = registry.getTermStringByID(parms[i]);
			command += termStr;
		} else {
			std::string termStr = registry.getTermStringByID(parms[i]);
			if (termStr[0] != '\"' || termStr[termStr.size() - 1] != '\"') {
				throw PluginError(
						"The parameter of the atom #execute should be a quoted string!");
			}
			command += termStr.substr(1, termStr.size() - 2);
		}
	}

	system(command.c_str());

}
Esempio n. 2
0
// accepted options: --choice-enable
//
// processes options for this plugin, and removes recognized options from pluginOptions
// (do not free the pointers, the const char* directly come from argv)
void ChoicePlugin::processOptions(
std::list<const char*>& pluginOptions,
ProgramCtx& ctx)
{
    ChoicePlugin::CtxData& ctxdata = ctx.getPluginData<ChoicePlugin>();
    ctxdata.enabled = true;

    typedef std::list<const char*>::iterator Iterator;
    Iterator it;
    WARNING("create (or reuse, maybe from potassco?) cmdline option processing facility")
        it = pluginOptions.begin();
    while( it != pluginOptions.end() ) {
        bool processed = false;
        const std::string str(*it);
        if( boost::starts_with(str, "--choice-enable" ) ) {
            std::string m = str.substr(std::string("--choice-enable").length());
            if (m == "" || m == "=true") {
                ctxdata.enabled = true;
            }
            else if (m == "=false") {
                ctxdata.enabled = false;
            }
            else {
                std::stringstream ss;
                ss << "Unknown --choice-enable option: " << m;
                throw PluginError(ss.str());
            }
            processed = true;
        }

        if( processed ) {
            // return value of erase: element after it, maybe end()
            DBGLOG(DBG,"ChoicePlugin successfully processed option " << str);
            it = pluginOptions.erase(it);
        }
        else {
            it++;
        }
    }
}
Esempio n. 3
0
PluginConverterPtr
MCSIEPlugin::createConverter(ProgramCtx& ctx)
{
  ProgramCtxData& pcd = ctx.getPluginData<MCSIE>();
  if( pcd.isEnabled() )
  {
    switch(pcd.getMode())
    {
    case ProgramCtxData::DIAGREWRITING:
      return PluginConverterPtr(new InputConverterDiagnoses(pcd));
    case ProgramCtxData::EXPLREWRITING:
      return PluginConverterPtr(new InputConverterExplanations(pcd));
    case ProgramCtxData::EQREWRITING:
      return PluginConverterPtr(new InputConverterOPEquilibria(pcd));
    default:
      throw PluginError("MCSIEPlugin::createConverter encountered unknown mode!");
    }
  }
  else
  {
    return PluginConverterPtr();
  }
}
Esempio n. 4
0
// accepted options: --query-enables --query-brave --query-cautious
//
// processes options for this plugin, and removes recognized options from pluginOptions
// (do not free the pointers, the const char* directly come from argv)
void QueryPlugin::processOptions(
std::list<const char*>& pluginOptions,
ProgramCtx& ctx)
{
    QueryPlugin::CtxData& ctxdata = ctx.getPluginData<QueryPlugin>();
    ctxdata.enabled = false;

    typedef std::list<const char*>::iterator Iterator;
    Iterator it;
    WARNING("create (or reuse, maybe from potassco?) cmdline option processing facility")
        it = pluginOptions.begin();
    while( it != pluginOptions.end() ) {
        bool processed = false;
        const std::string str(*it);
        if( boost::starts_with(str, "--query-enable" ) ) {
            std::string m = str.substr(std::string("--query-enable").length());
            if (m == "" || m == "=true") {
                ctxdata.enabled = true;
            }
            else if (m == "=false") {
                ctxdata.enabled = false;
            }
            else {
                std::stringstream ss;
                ss << "Unknown --strongnegation-enable option: " << m;
                throw PluginError(ss.str());
            }
            processed = true;
        }
        else if( str == "--query-brave" ) {
            ctxdata.mode = CtxData::BRAVE;
            processed = true;
        }
        else if( str == "--query-cautious" ) {
            ctxdata.mode = CtxData::CAUTIOUS;
            processed = true;
        }
        else if( str == "--query-all" ) {
            ctxdata.allWitnesses = true;
            processed = true;
        }

        if( processed ) {
            // return value of erase: element after it, maybe end()
            DBGLOG(DBG,"QueryPlugin successfully processed option " << str);
            it = pluginOptions.erase(it);
        }
        else {
            it++;
        }
    }

    // some checks
    if( ctxdata.mode != CtxData::DEFAULT ) {
        if( !ctxdata.enabled ) {
            LOG(WARNING,"querying mode selected, but plugin not enabled "
                "(automatically enabling)");
            ctxdata.enabled = true;
        }
    }
    if( ctxdata.enabled && ctxdata.mode == CtxData::DEFAULT )
        throw FatalError("querying plugin enabled but no querying mode selected");
}
      void
      UniqueLinSolveAtom::retrieve(const Query& query, 
			       Answer& answer) throw (PluginError)
      {
	Tuple parms = query.getInputTuple();
	
	std::string matrixPred = "";
	std::string constantPred = "";
	int argc = 2;
	char* argv[] = {"-linkname", "math -mathlink"};

	//check number and type of arguments
	if (parms.size()!= 2)
	  {
	    throw PluginError("Wrong number of arguments");
	  }
	else
	  {
	    if(parms[0].isSymbol() && parms[1].isSymbol()) 
	      {
		matrixPred = parms[0].getString();
		//std::cout << "Matrixpraedikat: " << matrixPred << std::endl;
		constantPred = parms[1].getString();
		//std::cout << "Vektorpraedikat: " << vectorPred << std::endl;
	      }
	    else
	      {
		throw PluginError("Wrong type of arguments");
	      }
	  }
	//get complete Interpretation of given predicates in query
	AtomSet totalInt = query.getInterpretation();
	AtomSet matrixInt;
	AtomSet constantInt;
      
	if (totalInt.empty()) 
	  {
	    throw PluginError("Could not find any interpretion");
	  }
	else 
	  {
	    // separate interpretation into facts of first predicate (matrix)
	    totalInt.matchPredicate(matrixPred, matrixInt);
	    // and into facts of second predicate (vector)
	    totalInt.matchPredicate(constantPred, constantInt);
	  }
	
	int mRows = 0;
	int mColumns = 0;
	int cRows = 0;
	int cColumns = 0;
	evaluateMatrix(matrixInt, mRows, mColumns);
	evaluateVector(constantInt, cRows, cColumns);
	
	if(mRows != cRows) throw PluginError("Coefficient matrix and target vector(s) or matrix do not have the same dimensions.");

	std::vector <std::vector <std::string> > matrix(mRows);
	for(int i = 0; i < mRows; i++)
	  matrix[i].resize(mColumns);
	
	std::vector <std::vector <std::string> > constants(cRows);
	for (int i = 0; i < cRows; i++)
	  constants[i].resize(cColumns);

	//write the values of the Atoms in the Interpretation into std::vectors for further processing
	convertMatrixToVector(matrixInt, mRows, mColumns, matrix);
	convertMatrixToVector(constantInt, cRows, cColumns, constants); 

	//check if matrix and target vector or matrix are fully defined
	checkVector(matrix, mRows, mColumns, matrixPred);
	checkVector(constants, cRows, cColumns, constantPred);
	 
	//convert matrix to MatrixRank-expression and calculate rank of coefficient matrix A 
	std::string coeffMRankExpr = toMatrixRankExpr(matrix, mRows, mColumns);
	//std::cout << "MatrixRank expression: " << coeffMRankExpr << std::endl;
	int coeffMRank = calculateRank(argc, argv, coeffMRankExpr);

	//convert matrix A and target b to MatrixRank-expression and calculate rank
	//of extended coefficient matrix [A,b]
	std::string extendedMRankExpr = toMatrixRankExpr(matrix, mRows, mColumns, constants, cRows, cColumns);
	//std::cout << "Extended MatrixRank expression: " << extendedMRankExpr << std::endl;
	int extCoeffMRank = calculateRank(argc, argv, extendedMRankExpr);

	//compare calculated ranks and number of matrix colums, iff they are equal, 
	//a unique solution for the matrix equation exists
	if ((coeffMRank == extCoeffMRank) && (coeffMRank == mColumns))
	  {
	    std::string linSolExpr = toLinearSolveExpr(matrix, mRows, mColumns, constants, cRows, cColumns);
	    std::vector <std::string> result;
	    result = calculateSolution(argc, argv, linSolExpr);
	    if(result.size() != mColumns*cColumns)
	      throw PluginError("Wrong number of arguments in result vector");
	    Tuple out;
	    int index = 0;

	    //fill the result values with correct indices into Tuple out
	    //and add all Tuples to Answer
	    for (int r = 1; r <= mColumns; r++)
	      {
		for(int c = 1; c<= cColumns; c++)
		  {
		    out.push_back(Term(r));
		    out.push_back(Term(c));
		    out.push_back(Term(result[index],true));
		    answer.addTuple(out);
		    out.clear();
		    index++;
		  }
	      }
	  }
      }      
/**
 * @brief Best Model Selector, Execution Schedule Builder, Execute Actions on Environment
 */
void ActionPluginFinalCallback::operator()() {
	DBGLOG(DBG, "\nActionPluginFinalCallback called");

	if (ctxData.nameBestModelSelectorMap.count(
			ctxData.getBestModelSelectorSelected()) == 0)
		throw PluginError("The BestModelSelector chosen doesn't exist");

	ctxData.nameBestModelSelectorMap[ctxData.getBestModelSelectorSelected()]->getBestModel(
			ctxData.iteratorBestModel, ctxData.bestModelsContainer);

	std::stringstream ss;
	(*ctxData.iteratorBestModel)->interpretation->print(ss);
	DBGLOG(DBG, "\nBestModel selected: " << ss.str());

	DBGLOG(DBG, "\nCall the executionModeController");
	std::multimap<int, Tuple> multimapOfExecution;
	executionModeController(multimapOfExecution);

	DBGLOG(DBG, "\nThe MultiMapOfExecution:");
	DBGLOG(DBG, "Precedence\tTuple");
	std::multimap<int, Tuple>::iterator itMMOE;
	for (itMMOE = multimapOfExecution.begin();
			itMMOE != multimapOfExecution.end(); itMMOE++) {
		const Tuple& tempTuple = itMMOE->second;
		std::stringstream ss;
		printTuple(ss, tempTuple, registryPtr);
		DBGLOG(DBG, itMMOE->first << "\t\t" << ss.str());
	}

	if (ctxData.nameExecutionScheduleBuilderMap.count(
			ctxData.getExecutionScheduleBuilderSelected()) == 0)
		throw PluginError("The ExecutionScheduleBuilder chosen doesn't exist");

	DBGLOG(DBG, "\nCall the executionScheduleBuilder");
	std::list < std::set<Tuple> > listOfExecution;
	ctxData.nameExecutionScheduleBuilderMap[ctxData.getExecutionScheduleBuilderSelected()]->rewrite(
			multimapOfExecution, listOfExecution, (*(ctxData.iteratorBestModel))->interpretation);

	DBGLOG(DBG, "\nThe ListOfExecution:");
	std::list<std::set<Tuple> >::iterator itLOE;
	for (itLOE = listOfExecution.begin(); itLOE != listOfExecution.end();
			itLOE++) {
		std::set < Tuple > &tempSet = (*itLOE);
		for (std::set<Tuple>::iterator itLOEs = tempSet.begin();
				itLOEs != tempSet.end(); itLOEs++) {
			const Tuple& tempTuple = (*itLOEs);
			std::stringstream ss;
			printTuple(ss, tempTuple, registryPtr);
			DBGLOG(DBG, ss.str());
		}
	}

	DBGLOG(DBG,
			"\nControl if the order of Set in the List corresponds to their precedence");
	if (checkIfTheListIsCorrect(multimapOfExecution, listOfExecution)) {
		DBGLOG(DBG, "The List is correct");
	} else {
		DBGLOG(DBG, "The List isn't correct");
		throw PluginError(
				"The order of Set in the ListOfExecution doens't correspond to their precedence");
	}

	DBGLOG(DBG, "\nExecute the actions in the right order");

	for (itLOE = listOfExecution.begin(); itLOE != listOfExecution.end();
			itLOE++) {

		std::set < Tuple > &tempSet = (*itLOE);

		for (std::set<Tuple>::iterator itLOEs = tempSet.begin();
				itLOEs != tempSet.end(); itLOEs++) {

			const Tuple& tempTuple = (*itLOEs);

			if (*tempTuple.begin() == ctxData.getIDContinue()) {
				ctxData.continueIteration = true;
				continue;
			} else if (*tempTuple.begin() == ctxData.getIDStop()) {
				ctxData.stopIteration = true;
				continue;
			}

			Tuple tupleForExecute;
			tupleForExecute.insert(tupleForExecute.begin(),
					tempTuple.begin() + 1, tempTuple.end());

			std::stringstream ss;
			printTuple(ss, tempTuple, registryPtr);
			DBGLOG(DBG, "tupleForExecute: " << ss.str());
			ss.str("");
			printTuple(ss, tupleForExecute, registryPtr);
			DBGLOG(DBG, "tempTuple: " << ss.str());

			std::map<std::string, PluginActionBasePtr>::iterator it =
					ctxData.namePluginActionBaseMap.find(
							registryPtr->getTermStringByID(*tempTuple.begin()));

			if (it != ctxData.namePluginActionBaseMap.end())
				it->second->execute(programCtx,
						(*(ctxData.iteratorBestModel))->interpretation,
						tupleForExecute);
			else
				DBGLOG(DBG,
						"For the action '"
								<< registryPtr->getTermStringByID(
										*tempTuple.begin())
								<< "' wasn't found a definition");

		}
	}

	DBGLOG(DBG, "\nCheck Iteration");
	if (ctxData.getIterationType() == DEFAULT && ctxData.continueIteration)
		programCtx.config.setOption("RepeatEvaluation", 1);
	else if (ctxData.getIterationType() != DEFAULT && ctxData.stopIteration)
		programCtx.config.setOption("RepeatEvaluation", 0);
	else if (ctxData.getIterationType() == INFINITE)
		programCtx.config.setOption("RepeatEvaluation", 1);
	else if (ctxData.getIterationType() == FIXED) {
		if (!ctxData.getTimeDuration().is_not_a_date_time()) {
			boost::posix_time::time_duration diff =
					boost::posix_time::second_clock::local_time()
							- ctxData.getStartingTime();
			if (diff > ctxData.getTimeDuration())
				programCtx.config.setOption("RepeatEvaluation", 0);
			else if (ctxData.getNumberIterations() != -1) {
				programCtx.config.setOption("RepeatEvaluation",
						ctxData.getNumberIterations());
				ctxData.decreaseNumberIterations();
			} else
				programCtx.config.setOption("RepeatEvaluation", 1);
		}
	}

	if (programCtx.config.getOption("RepeatEvaluation") > 0) {

		DBGLOG(DBG, "\nIncrease iteration in the UtilitiesPlugin");
		ctxData.increaseIteration(programCtx);

		DBGLOG(DBG, "\nClear data structures");
		ctxData.clearDataStructures();

		ctxData.continueIteration = false;
		ctxData.stopIteration = false;

		DBGLOG(DBG, "\nReset cache");
		programCtx.resetCacheOfPlugins();

	}

}
/**
 * @brief function that fill the multimap (passed as parameter) with Precedence attribute and Action Tuple checking the Action Option attribute
 */
void ActionPluginFinalCallback::executionModeController(
		std::multimap<int, Tuple>& multimapOfExecution) {

	const AnswerSetPtr& bestModel = (*(ctxData.iteratorBestModel));

	// used to have only the Action Atoms
	InterpretationPtr intr = InterpretationPtr(new Interpretation(registryPtr));
	intr->getStorage() |= ctxData.myAuxiliaryPredicateMask.mask()->getStorage();
	intr->getStorage() &= bestModel->interpretation->getStorage();

	Interpretation::TrueBitIterator bit, bit_end;
	for (boost::tie(bit, bit_end) = intr->trueBits(); bit != bit_end; ++bit) {

		const OrdinaryAtom& oatom = registryPtr->ogatoms.getByAddress(*bit);
		const Tuple & tuple = oatom.tuple;

		int precedence, precedence_position = tuple.size() - 3;
		dlvhex::ID id_actionOption = tuple[tuple.size() - 4];

		Tuple action_tuple;

		for (int i = 1; i < tuple.size() - 4; i++)
			action_tuple.push_back(tuple[i]);

		if (tuple[precedence_position].isIntegerTerm()
				&& id_actionOption.isConstantTerm()) {

			precedence = tuple[precedence_position].address;

			DBGLOG(DBG,
					"actionOption: "
							<< registryPtr->getTermStringByID(id_actionOption));
			DBGLOG(DBG, "Precedence: " << precedence);

			if (id_actionOption == ctxData.getIDBrave())
				;
			else if (id_actionOption == ctxData.getIDCautious())
				if (!isPresentInAllAnswerSets(action_tuple)) {
					std::stringstream ss;
					printTuple(ss, action_tuple, registryPtr);
					DBGLOG(DBG,
							"This action atom isn't present in all AnswerSet: "
									<< ss.str());
					continue;
				} else if (id_actionOption == ctxData.getIDPreferredCautious())
					if (!isPresentInAllTheBestModelsAnswerSets(action_tuple)) {
						std::stringstream ss;
						printTuple(ss, action_tuple, registryPtr);
						DBGLOG(DBG,
								"This action atom isn't present in all BestModels AnswerSet: "
										<< ss.str());
						continue;
					} else
						throw PluginError(
								"Error in the selection of brave, cautious or preferred_cautious");

			multimapOfExecution.insert(
					std::pair<int, Tuple>(precedence, action_tuple));

		} else
			throw PluginError(
					"Precedence isn't Integer term or actionOption haven't a valid value");

	}

}