void TrecDocumentProcessorTestCase::testProcessGZipFile()
{
    TrecDocumentProcessor processor;
    processor.init(m_pDocSchema.get(), m_pDocTemp.get());
    
    DocumentSource docSource(m_pDocSchema.get());
    RawDocumentPtr pRawDoc = new RawDocument();
    pRawDoc->setPath(getTestPath() + "/1.gz");
    docSource.setRawDocument(pRawDoc);

    Answer ans;
    makeAnswer(TEST_FILE2, ans);

    size_t i = 0;
    do
    {
        processor.process(docSource);

        DocumentPtr pDoc = docSource.stealLastDocument();
        CPPUNIT_ASSERT(pDoc);

        Document::Iterator it = pDoc->iterator();
        while (it.hasNext())
        {
            const Field* pField = it.next();
            CPPUNIT_ASSERT_EQUAL(ans[i].first, pField->getFieldSchema()->getName());
            CPPUNIT_ASSERT_EQUAL(ans[i].second, std::string(pField->getValue().c_str()));
            ++i;
        }
    } while(docSource.toBeContinued());
    CPPUNIT_ASSERT_EQUAL(ans.size(), i);
}
void StandardDocumentProcessorTestCase::testProcessWithEmptyField()
{
    String sPath = writeTestFile("file_with_empty_field.txt", TEST_FILE_WITH_EMPTY_FIELD);

    StandardDocumentProcessor processor;
    processor.init(m_pDocSchema.get());
    
    DocumentSource docSource(m_pDocSchema.get());
    RawDocumentPtr pRawDoc = new RawDocument();
    pRawDoc->setPath(sPath);
    docSource.setRawDocument(pRawDoc);

    processor.process(docSource);

    DocumentPtr pDoc = docSource.stealLastDocument();
    CPPUNIT_ASSERT(pDoc.isNotNull());

    Answer ans;
    makeAnswer(TEST_FILE_WITH_EMPTY_FIELD, ans);

    Document::Iterator it = pDoc->iterator();
    CPPUNIT_ASSERT_EQUAL(ans.size(), it.size());
    size_t i = 0;
    while (it.hasNext())
    {
        const Field* pField = it.next();
//        cout << ans[i].first << " : " << ans[i].second << endl;
        CPPUNIT_ASSERT_EQUAL(ans[i].first, pField->getFieldSchema()->getName());
        CPPUNIT_ASSERT_EQUAL(ans[i].second, std::string(pField->getValue().c_str()));
        ++i;
    }
}
Esempio n. 3
0
vector<Answer> Question::get_answers()
{
	const char* answers_file = Configuration::configuration->get_a_file();
	ifstream in(answers_file, ios::in | ios::binary);
	if (!in.is_open())
	{
		//ИСКЛЮЧЕНИЕ
	}
	TestingSystem::answer_msg a_msg;
	string s;
	vector<Answer> result;
	while (in.cur!= in.eof())
	{
		char c;
		in.read((char*)&c, sizeof c);
		s+=c;
		if (!a_msg.ParseFromString(s))
			a_msg.set_id(-1);
		else
		{
			s = "";
			if (a_msg.q_id() == getID())
			{
				Answer a;
				a.set_contents(a_msg.body());
				a.set_correct(a_msg.correct());
				a.set_q_id(getID());
				a.setID(a_msg.id());
				result.push_back(a);
			}
		}
	}
	in.close();
	return result;
}
void StandardDocumentProcessorTestCase::testProcessMultiFile()
{
    string sPath = writeTestFile("file2.txt", TEST_FILE2);

    StandardDocumentProcessor processor;
    processor.init(m_pDocSchema.get());
    
    DocumentSource docSource(m_pDocSchema.get());

    Answer ans;
    makeAnswer(TEST_FILE2, ans);
    RawDocumentPtr pRawDoc = new RawDocument();
    pRawDoc->setPath(sPath);
    docSource.setRawDocument(pRawDoc);

    size_t i = 0;
    do
    {
        processor.process(docSource);

        DocumentPtr pDoc = docSource.stealLastDocument();
        CPPUNIT_ASSERT(pDoc.isNotNull());

        Document::Iterator it = pDoc->iterator();
        while (it.hasNext())
        {
            const Field* pField = it.next();
            CPPUNIT_ASSERT_EQUAL(ans[i].first, pField->getFieldSchema()->getName());
            CPPUNIT_ASSERT_EQUAL(ans[i].second, std::string(pField->getValue().c_str()));
            ++i;
        }
    } while(docSource.toBeContinued());
    CPPUNIT_ASSERT_EQUAL(ans.size(), i);
}
void TrecDocumentProcessorTestCase::testProcessFileMisField()
{
    string sPath = writeTestFile("trec_file3.txt", TEST_FILE_MISS_FIELD);

    TrecDocumentProcessor processor;
    processor.init(m_pDocSchema.get(), m_pDocTemp.get());
    
    DocumentSource docSource(m_pDocSchema.get());
    RawDocumentPtr pRawDoc = new RawDocument();
    pRawDoc->setPath(sPath);
    docSource.setRawDocument(pRawDoc);

    processor.process(docSource);

    DocumentPtr pDoc = docSource.stealLastDocument();
    CPPUNIT_ASSERT(pDoc);

    Answer ans;
    makeAnswer(TEST_FILE_MISS_FIELD, ans);

    Document::Iterator it = pDoc->iterator();
    CPPUNIT_ASSERT_EQUAL(ans.size(), it.size());
    size_t i = 0;
    while (it.hasNext())
    {
        const Field* pField = it.next();
//        cout << ans[i].first << " : " << ans[i].second << endl;
        CPPUNIT_ASSERT_EQUAL(ans[i].first, pField->getFieldSchema()->getName());
        CPPUNIT_ASSERT_EQUAL(ans[i].second, std::string(pField->getValue().c_str()));
        ++i;
    }
}
void DolphinSolver::solve(const PlayBoard<H, W>& board)
{
    const std::vector<AnswerTreeBoard<H, W>> input = {AnswerTreeBoard<H, W>(AnswerTreeBoardBase<H, W>(board))};
    const AnswerTreeBoard<H, W> result = compute(input, board.height()/2-2, board.width()/2-2, 4, 4);
    Answer answer = result.buildAnswer();
    answer.optimize();
    onCreatedAnswer(answer);
}
Esempio n. 7
0
bool KnowledgeBase::IsSatisfiable(const Argument& arg)
{
  // get answer
  Answer *ans = GetAnswer(arg, VariableMap(), std::set<size_t>());
  // return if any valid substitution exists
  bool res = ans->next();
  delete ans;
  return res;
}
Esempio n. 8
0
bool KnowledgeBase::IsSatisfiable(const std::string& s_arg)
{
  Argument arg(s_arg, symbol_table, true, log);
  // get answer
  Answer *ans = GetAnswer(arg, VariableMap(), std::set<size_t>());
  // return if any valid substitution exists
  bool res = ans->next();
  delete ans;
  return res;
}
 /**
  * Applies validation on block
  * @param block
  * @return Answer containing found error if any
  */
 Answer validate(const interface::EmptyBlock &block) const {
   Answer answer;
   ReasonsGroupType reason;
   reason.first = "EmptyBlock";
   field_validator_.validateCreatedTime(reason, block.createdTime());
   field_validator_.validateHeight(reason, block.height());
   if (not reason.second.empty()) {
     answer.addReason(std::move(reason));
   }
   return answer;
 }
Esempio n. 10
0
void
ArgumentsAtom::retrieve(const Query& query, Answer& answer) throw (PluginError)
{
	RegistryPtr reg = query.interpretation->getRegistry();

	// Extract answer index, answerset index and predicate to retrieve
	int answerindex = query.input[0].address;
	int answersetindex = query.input[1].address;
	ID predicate = query.input[2];

	// check index validity
	if (answerindex < 0 || answerindex >= resultsetCache.size()){
		throw PluginError("An invalid answer handle was passed to atom &arguments");
	}else if(answersetindex < 0 || answersetindex >= resultsetCache[answerindex].size()){
		throw PluginError("An invalid answer-set handle was passed to atom &arguments");
	}else{
		int runningindex = 0;

		// Go through all atoms of the given answer_set
		for(Interpretation::Storage::enumerator it =
		    (resultsetCache[answerindex])[answersetindex]->getStorage().first();
		    it != (resultsetCache[answerindex])[answersetindex]->getStorage().end(); ++it){

			ID ogid(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG, *it);
			const OrdinaryAtom& ogatom = reg->ogatoms.getByID(ogid);

			// If the atom is built upon the given predicate, return it's parameters
			if (ogatom.tuple[0] == predicate){
				// special case of index "s": positive or strongly negated
				Tuple ts;
				ts.push_back(ID::termFromInteger(runningindex));
				Term t(ID::MAINKIND_TERM | ID::SUBKIND_TERM_CONSTANT, "s");
				ts.push_back(reg->storeTerm(t));
				ts.push_back(ID::termFromInteger(/*it->isStronglyNegated() ? 1 :*/ 0));	// TODO: check if the atom is strongly negated
				answer.get().push_back(ts);

				// Go through all parameters
				for (int i = 1; i < ogatom.tuple.size(); ++i){
					Tuple t;
					t.push_back(ID::termFromInteger(runningindex));
					t.push_back(ID::termFromInteger(i - 1));
					t.push_back(ogatom.tuple[i]);
					answer.get().push_back(t);
				}
				runningindex++;
			}
		}
	}
}
      /**
       * Applies validation to given query
       * @param qry - query to validate
       * @return Answer containing found error if any
       */
      Answer validate(const interface::BlocksQuery &qry) const {
        Answer answer;
        std::string qry_reason_name = "Blocks query";
        ReasonsGroupType qry_reason(qry_reason_name, GroupedReasons());

        field_validator_.validateCreatorAccountId(qry_reason,
                                                  qry.creatorAccountId());
        field_validator_.validateCreatedTime(qry_reason, qry.createdTime());
        field_validator_.validateCounter(qry_reason, qry.queryCounter());

        if (not qry_reason.second.empty()) {
          answer.addReason(std::move(qry_reason));
        }
        return answer;
      }
Esempio n. 12
0
int main() {
	gets(input + 1);
	n = strlen(input + 1);
	pPower[0] = 1ULL;
	for (int i = 1; i <= n; ++i) {
		pPower[i] = pPower[i - 1] * P;
		prefix[i] = prefix[i - 1] * P + input[i];
	}
	for (int i = n; i >= 1; --i) {
		suffix[i] = suffix[i + 1] * P + input[i];
	}
	for (int i = n, j = 1; i >= 1; --i) {
		int length = n - i + 1;
		for (; j <= n && (j < length || hashValue(prefix, j - length, j, length) != hashValue(suffix, n + 1, i, length)); j++);
		earliest[i] = j;
	}
	Answer result;
	result.normalize();
	for (int i = 1; i <= n; ++i) {
		int longest = 1, l = 2, r = min(i, n - i + 1), pos = n + 1;
		while (l <= r) {
			int mid = l + r >> 1;
			if (hashValue(prefix, i - mid, i, mid) == hashValue(suffix, i + mid, i, mid))
				longest = mid, l = mid + 1;
			else
				r = mid - 1;
		}
		l = i + longest, r = n;
		while (l <= r) {
			int mid = l + r >> 1;
			if (earliest[mid] <= i - longest)
				pos = mid, r = mid - 1;
			else
				l = mid + 1;
		}
		Answer temp;
		temp.v.push_back(Interval(i - longest + 1, i + longest - 1));
		if (pos <= n) {
			temp.v.push_back(Interval(pos, n));
			temp.v.push_back(Interval(earliest[pos] - (n - pos), earliest[pos]));
		}
		temp.normalize();
		update(result, temp);
	}
	printf("%d\n", (int)result.v.size());
	for (int i = 0; i < (int)result.v.size(); ++i)
		printf("%d %d\n", result.v[i].first, result.v[i].second - result.v[i].first + 1);
}
Esempio n. 13
0
void
CallHexFileAtom::retrieve(const Query& query, Answer& answer) throw (PluginError)
{
	RegistryPtr reg = query.interpretation->getRegistry();

	std::string programpath;
	std::string cmdargs;
	InterpretationConstPtr inputfacts = query.interpretation;
	try{
		const Tuple& params = query.input;

		// load program
		programpath = reg->terms.getByID(params[0]).getUnquotedString();

		// Retrieve command line arguments
		if (params.size() > 1 + arity){
			cmdargs = reg->terms.getByID(params[1 + arity]).getUnquotedString();
		}

		// Build hex call identifier
		HexCall hc(HexCall::HexFile, programpath, cmdargs, inputfacts);

		// request entry from cache (this will automatically add it if it's not contained yet)
		Tuple out;
		out.push_back(ID::termFromInteger(resultsetCache[hc]));
		answer.get().push_back(out);
	}catch(PluginError){
		throw;
	}catch(...){
		std::stringstream msg;
		msg << "Nested Hex program \"" << programpath << "\" failed. Command line arguments were: " << cmdargs;
		throw PluginError(msg.str());
	}
}
Esempio n. 14
0
void
PredicatesAtom::retrieve(const Query& query, Answer& answer) throw (PluginError)
{
	RegistryPtr reg = query.interpretation->getRegistry();

	// Retrieve answer index and answer-set index
	int answerindex = query.input[0].address;
	int answersetindex = query.input[1].address;

	// check index validity
	if (answerindex < 0 || answerindex >= resultsetCache.size()){
		throw PluginError("An invalid answer handle was passed to atom &predicates");
	}else if(answersetindex < 0 || answersetindex >= resultsetCache[answerindex].size()){
		throw PluginError("An invalid answer-set handle was passed to atom &predicates");
	}else{
		// Go through all atoms of the given answer_set
		for(Interpretation::Storage::enumerator it =
		    (resultsetCache[answerindex])[answersetindex]->getStorage().first();
		    it != (resultsetCache[answerindex])[answersetindex]->getStorage().end(); ++it){

			if (!reg->ogatoms.getIDByAddress(*it).isAuxiliary()){
				ID ogid(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG, *it);
				const OrdinaryAtom& ogatom = reg->ogatoms.getByID(ogid);

				Tuple t;
				t.push_back(ogatom.tuple[0]);
				t.push_back(ID::termFromInteger(ogatom.tuple.size() - 1));
				answer.get().push_back(t);
			}
		}
	}
}
Esempio n. 15
0
	virtual void retrieve(const Query& q, Answer& a) throw (dlvhex::PluginError)
  {
    // get input
    assert(q.input.size() == 1);
    ID pred = q.input[0];

    // get outputs
    assert(q.pattern.size() == outputSize);

    // build unifier
    OrdinaryAtom unifier(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYN);
    unifier.tuple.push_back(pred);
    unifier.tuple.insert(unifier.tuple.begin(), q.pattern.begin(), q.pattern.end());

    // check if <pred>(pattern) part of interpretation (=forward <pred> via external atom)
    assert(q.interpretation != 0);
    const Interpretation::Storage& bits = q.interpretation->getStorage();
    for(Interpretation::Storage::enumerator it = bits.first();
        it != bits.end(); ++it)
    {
      const OrdinaryAtom& ogatom = registry->ogatoms.getByID(ID(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG, *it));
      if( ogatom.unifiesWith(unifier) )
      {
        Tuple partial;
        partial.insert(partial.begin(), ogatom.tuple.begin()+1, ogatom.tuple.end());
        a.get().push_back(partial);
      }
    }
  }
Esempio n. 16
0
int main(int argc, char* argv[]) {
  Test test;
  Solution sol;
  Answer ans;
  chrono::time_point<chrono::system_clock> ts0, ts1, ts2, ts3, ts4;
  ofstream outfile;
  outfile.open("output.txt");

  ts0 = std::chrono::system_clock::now();
  vector<int> tin = test.generate();

  ts1 = std::chrono::system_clock::now();
  vector<int> touts = sol.maxSlidingWindow(tin, TK);

  ts2 = std::chrono::system_clock::now();
  vector<int> touta = ans.maxSlidingWindow(tin, TK);

  ts3 = std::chrono::system_clock::now();
  if (touts.size() != touta.size()) {
    cout << "Error, solution size not equal" << endl;
    return -1;
  } else {
    for(int i=0; i<touts.size(); i++) {
      if (touts[i] != touta[i]) {
        cout << "Error, solution vector item: " << i << " not equal" << endl;
        return -2;
      } else {
        outfile << touts[i] << endl;
      }
    }
  }
  ts4 = std::chrono::system_clock::now();
  chrono::duration<double> e10 = ts1-ts0;
  chrono::duration<double> e21 = ts2-ts1;
  chrono::duration<double> e32 = ts3-ts2;
  chrono::duration<double> e43 = ts4-ts3;
  cout << argv[0] << " All test passed ~" << endl;
  cout << argv[0] << " Elapsed time generate test case:   " << e10.count() << endl;
  cout << argv[0] << " Elapsed time my solution O(N):     " << e21.count() << endl;
  cout << argv[0] << " Elapsed time official O(N) answer: " << e32.count() << endl;
  cout << argv[0] << " Elapsed time comparison result:    " << e43.count() << endl;

  outfile.close();
  return 0;
}
Esempio n. 17
0
std::list<Argument*> KnowledgeBase::Ask(const Argument& arg,
                                        bool checkForDoubles)
{
  std::list<Argument*> out;

  // get answer
  Answer *ans = GetAnswer(arg, VariableMap(), std::set<size_t>());
  // get all the valid substitution and add them to list

  if(!checkForDoubles)
  {
    while(ans->next())
    {
      Argument* temp = Unify::GetSubstitutedArgument(&arg, ans->GetVariableMap());
      out.push_back(temp);
    }
  }
  else
  {
    std::set<std::string> str_ans;
    while(ans->next())
    {
      Argument* temp = Unify::GetSubstitutedArgument(&arg, ans->GetVariableMap());
      std::stringstream stream;
      stream << *temp;

      //SymbolDecodeStream sds(symbol_table);
      //sds << *temp << endl;

      if(str_ans.find(stream.str()) == str_ans.end())
      {
        out.push_back(temp);
        str_ans.insert(stream.str());
      }
      else delete temp;
    }
  }
  // delete answer
  delete ans;

  return out;
}
Esempio n. 18
0
      /**
       * Applies validation to given query
       * @param qry - query to validate
       * @return Answer containing found error if any
       */
      Answer validate(const interface::Query &qry) const {
        Answer answer;
        std::string qry_reason_name = "Query";
        ReasonsGroupType qry_reason(qry_reason_name, GroupedReasons());

        field_validator_.validateCreatorAccountId(qry_reason,
                                                  qry.creatorAccountId());
        field_validator_.validateCreatedTime(qry_reason, qry.createdTime());
        field_validator_.validateCounter(qry_reason, qry.queryCounter());

        if (not qry_reason.second.empty()) {
          answer.addReason(std::move(qry_reason));
        }

        auto reason = boost::apply_visitor(query_field_validator_, qry.get());
        if (not reason.second.empty()) {
          answer.addReason(std::move(reason));
        }

        return answer;
      }
Esempio n. 19
0
/*! エントリポイント
 * \param [in] argc 引数の数
 * \param [in] argv コマンド文字列の配列
 */
int main(int argc, const char *argv[])
{
	using namespace std;
	// オプション解析
	signal(SIGINT, interrupt);
	vector<string> args;
	for(int i = 1;i < argc;i++){
		args.push_back(argv[i]);
	}
	options = parse_options(args);
	if(options["stat"] != "ok"){
		return -1;
	}

	// IOストリーム用意
	boost::shared_ptr<istream> ifs;
	boost::shared_ptr<ostream> ofs;
	if(options["input"] != ""){
		ifs.reset(new ifstream(options["input"].c_str(), ios::in));
	}else{
		ifs.reset(&cin, noop());
	}
	if(options["output"] != ""){
		ofs.reset(new ofstream(options["output"].c_str(), ios::out));
	}else{
		ofs.reset(&cout, noop());
	}

	Problem problem(ifs);
	Answer answer;

	if(options["bruteforce"] != "") Solve<AlgorithmBruteForce>(problem, answer);
	Solve<AlgorithmFillOne>(problem, answer);

	answer.Output(ofs);

	return (0);
}
Esempio n. 20
0
void AnswerCsvWriter::write( std::ostream& output, const Answer& answer ) {
	Epoch e;
	const Scenario& scenario = answer.scenario();
	std::stringstream csvHeadStream, csvDataStream;
	bool done = false;

	csvHeadStream << "epoch";

	for(e = 0; e <= scenario.epoch(); ++e) {
		csvDataStream << ToolBox::typToStr(e);

		for(Scenario::GoalIterator iter = scenario.beginGoal(); iter != scenario.endGoal(); ++iter) {
			const gum::Potential<FIXED_PRECISION>& p = answer.marginal(*iter, e);
			const gum::DiscreteVariable& v = p.variable(0);
			gum::Instantiation i(p);

			for ( i.setFirst(); !i.end(); ++i ) {
				std::string value = ToolBox::typToStr( p[i] );
				std::string label = v.label(i.val( (gum::Idx) 0 )); // TODO peut on mieux faire ??

				if(!done) {
					csvHeadStream << ";" + ( *iter ) + "=" + label;
				}

				csvDataStream << ";" + value;
			}

		}

		done = true;
		csvDataStream << std::endl;
	}

	output << csvHeadStream.str() << std::endl << csvDataStream.str();

}
void TrecDocumentProcessorTestCase::makeAnswer(const std::string& str, Answer& ans)
{
    XMLDocumentWrapper xmlDoc;
    xmlDoc.parse(str);
    
    for (XMLNodeWrapperPtr pDocNode = xmlDoc.firstNode();
         pDocNode; pDocNode = pDocNode->nextSibling())
    {
        for (XMLNodeWrapperPtr pChildNode = pDocNode->firstNode();
             pChildNode; pChildNode = pChildNode->nextSibling())
        {
            ans.push_back(make_pair(pChildNode->getName(), pChildNode->getValue()));
        }
    }
}
void StandardDocumentProcessorTestCase::makeAnswer(const std::string& str, Answer& ans)
{
    StringTokenizer st(str, "\n", StringTokenizer::TOKEN_IGNORE_EMPTY);
    for (size_t i = 0; i < st.getNumTokens(); ++i)
    {
        StringTokenizer st2(st[i], "\n", StringTokenizer::TOKEN_IGNORE_EMPTY);
        for (size_t j = 1; j < st2.getNumTokens(); ++j)
        {
            StringTokenizer st3(st2[j], "=", StringTokenizer::TOKEN_IGNORE_EMPTY);
            string sVal = st3[1].substr(0, st3[1].length() - 1);
            if (!sVal.empty())
            {
                ans.push_back(make_pair(st3[0], sVal));
            }
        }
    }             
}
Esempio n. 23
0
	virtual void retrieve(const Query& q, Answer& a) throw (dlvhex::PluginError)
  {
    // get input
    assert(checkInputArity(q.input.size()));
    assert(checkOutputArity(getExtSourceProperties(), q.pattern.size()));

    ID idoutput = registry->ogatoms.getIDByTuple(q.input);
    // no ogatom -> cannot be in interpretation
    if( idoutput == ID_FAIL )
      return;

    assert(q.interpretation != 0);
    if( q.interpretation->getFact(idoutput.address) )
    {
      // success = found = true!
      a.get().push_back(Tuple());
    }
  }
Esempio n. 24
0
void getAnswerInfo()
{
    QFile filename("Answer_Info.txt");
    int j=1;
    if(!filename.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        //QMessageBox::critical(NULL, QObject::tr("提示"), QObject::tr("文件不存在,无法打开文件"));
        //create the file
    }
    else
    {
        int id,prise;
        QString line,sid,answerid,answertime,answerinfo,answerprise;
        QTextStream in(&filename);
        while(!in.atEnd())
        {
            line = in.readLine().replace(QString("\n"),QString(""));
            if(j%5 == 1)
            {
                sid = line;
                id = sid.toInt();
                Answersubmit.setBasicInfoId(id);
                //UserId.push_back(id);
            }
            else if(j%5 == 2)
            {
                answerid=line;
                Answersubmit.setCreatUserId(answerid);
            }
            else if(j%5 == 3)
            {
                answertime=line;
                Answersubmit.setCreatTime(answertime);
            }
            else if(j%5 == 4)
            {
                answerprise = line;
                prise = answerprise.toInt();
                Answersubmit.setPraiseNum(prise);
            }
            else
            {
                answerinfo = line;
                Answersubmit.setBasicContent(answerinfo);
                SumAnswerList.push_back(Answersubmit);
                SumQuestionList[Answersubmit.getBasicInfoId()].addAnswer(SumAnswerList.size()-1);
            }
            j++;
        }
        filename.close();
    }
}
Esempio n. 25
0
	virtual void retrieve(const Query& q, Answer& a) throw (dlvhex::PluginError)
  {
    #if 0
    // get inputs
    assert(q.input.size() == 2);
    ID pred = q.input[0];
    ID cmp = q.input[1];
    LOG(INFO,"calculating above extatom for predicate " << pred << " and symbol " << cmp);
    const Term& cmpt = registry->terms.getByID(cmp);

    // get query
    assert(q.pattern.size() == 1);
    ID out = q.pattern.front();

    // build set of found targets
    assert(q.interpretation != 0);
    dlvhex::OrdinaryAtomTable::PredicateIterator it, it_end;
    assert(registry != 0);
    for(boost::tie(it, it_end) = registry->ogatoms.getRangeByPredicateID(pred);
        it != it_end; ++it)
    {
      const dlvhex::OrdinaryAtom& oatom = *it;

      // skip ogatoms not present in interpretation
      if( !q.interpretation->getFact(registry->ogatoms.getIDByStorage(oatom).address) )
        continue;

      // the edge predicate must be unary
      assert(oatom.tuple.size() == 2);
      const Term& t = registry->terms.getByID(oatom.tuple[1]);
      if( t.symbol >= cmpt.symbol )
      {
        if( (out.isTerm() && out.isVariableTerm()) ||
            (out == oatom.tuple[1]) )
        {
          Tuple t;
          t.push_back(oatom.tuple[1]);
          a.get().push_back(t);
        }
      }
    }
    #endif
    throw std::runtime_error("todo implement SenseNotArmed1PluginAtom::retrieve");
  }
Esempio n. 26
0
void
AnswerSetsAtom::retrieve(const Query& query, Answer& answer) throw (PluginError)
{
	// Retrieve answer index
	int answerindex = query.input[0].address;

	// check index validity
	if (answerindex < 0 || answerindex >= resultsetCache.size()){
		throw PluginError("An invalid answer handle was passed to atom &answersets");
	}else{
		// Return handles to all answer-sets of the given answer (all integers from 0 to the number of answer-sets minus 1)
		int i = 0;
		for (HexAnswer::iterator it = resultsetCache[answerindex].begin(); it != resultsetCache[answerindex].end(); it++){
			Tuple out;
			out.push_back(ID::termFromInteger(i++));
			answer.get().push_back(out);
		}
	}
}
Esempio n. 27
0
	void add_answer(Answer & new_answer)
	{
		average_confidence *= answers.size();
		average_confidence += new_answer.confidence;
		if (new_answer.correct())
		{
			average_confidence_correct *= correct;
			average_confidence_correct += new_answer.confidence;
			correct++;
			average_confidence_correct /= correct;
		}
		else
		{
			average_confidence_wrong *= wrong;
			average_confidence_wrong += new_answer.confidence;
			wrong++;
			average_confidence_wrong /= wrong;
		}
		answers.push_back(new_answer);
		average_confidence /= answers.size();
	}
Esempio n. 28
0
	virtual void retrieve(const Query& q, Answer& a) throw (dlvhex::PluginError)
  {
    // get inputs
    assert(q.input.size() == 3);
    ID preddisarm = q.input[0];
    ID predlook = q.input[1];
    ID time = q.input[2];
    LOG(INFO,"calculating senseNotArmed2 extatom for " << preddisarm << "/" << predlook << "/" << time);

    // get outputs
    assert(q.pattern.size() == 0);

    // check if <preddisarm>(time) and <predlook>(time) part of interpretation
    Tuple tdisarm;
    tdisarm.push_back(preddisarm);
    tdisarm.push_back(time);
    ID iddisarm = registry->ogatoms.getIDByTuple(tdisarm);

    Tuple tlook;
    tlook.push_back(predlook);
    tlook.push_back(time);
    ID idlook = registry->ogatoms.getIDByTuple(tlook);

    if( iddisarm == ID_FAIL || idlook == ID_FAIL )
    {
      // cannot be part of interpretation -> return no tuple as condition not true
      return;
    }

    // check interpretation
    assert(q.interpretation != 0);
    if( q.interpretation->getFact(iddisarm.address) &&
        q.interpretation->getFact(idlook.address) )
    {
      // found both facts
      Tuple t;
      a.get().push_back(t);
    }
  }
Esempio n. 29
0
      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++;
		  }
	      }
	  }
      }      
Esempio n. 30
0
void SimulatorAtom::retrieve(const Query& query, Answer& answer) throw (PluginError){

	RegistryPtr reg = query.interpretation->getRegistry();

	const Tuple& params = query.input;

	// get ASP filename
	std::string programpath = reg->terms.getByID(params[0]).getUnquotedString();

	// if we access this file for the first time, parse the content
	if (programs.find(programpath) == programs.end()){
		DBGLOG(DBG, "Parsing simulation program");
		InputProviderPtr ip(new InputProvider());
		ip->addFileInput(programpath);
		Logger::Levels l = Logger::Instance().getPrintLevels();	// workaround: verbose causes the parse call below to fail (registry pointer is 0)
		Logger::Instance().setPrintLevels(0);
		programs[programpath].changeRegistry(reg);
		ModuleHexParser hp;
		hp.parse(ip, programs[programpath]);
		Logger::Instance().setPrintLevels(l);
	}
	ProgramCtx& pc = programs[programpath];

	// construct edb
	DBGLOG(DBG, "Constructing EDB");
	InterpretationPtr edb = InterpretationPtr(new Interpretation(*pc.edb));

	// go through all input atoms
	DBGLOG(DBG, "Rewriting input");
	for(Interpretation::Storage::enumerator it =
	    query.interpretation->getStorage().first();
	    it != query.interpretation->getStorage().end(); ++it){

		ID ogid(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG, *it);
		const OrdinaryAtom& ogatom = reg->ogatoms.getByID(ogid);

		// check if the predicate matches any of the input parameters to simulator atom
		bool found = false;
		for (int inp = 1; inp < params.size(); ++inp){
			if (ogatom.tuple[0] == params[inp]){
				// replace the predicate by "in[inp]"
				std::stringstream inPredStr;
				inPredStr << "in" << inp;
				Term inPredTerm(ID::MAINKIND_TERM | ID::SUBKIND_TERM_CONSTANT, inPredStr.str());
				ID inPredID = reg->storeTerm(inPredTerm);
				OrdinaryAtom oareplace = ogatom;
				oareplace.tuple[0] = inPredID;

				// get ID of replaced atom
				ID oareplaceID = reg->storeOrdinaryGAtom(oareplace);

				// set this atom in the input interpretation
				edb->getStorage().set_bit(oareplaceID.address);
				found = true;
				break;
			}
		}
		assert(found);
	}

	DBGLOG(DBG, "Grounding simulation program");
	OrdinaryASPProgram program(pc.registry(), pc.idb, edb);
	InternalGrounderPtr ig = InternalGrounderPtr(new InternalGrounder(pc, program));
	OrdinaryASPProgram gprogram = ig->getGroundProgram();

	DBGLOG(DBG, "Evaluating simulation program");
	GenuineSolverPtr igas = GenuineSolver::getInstance(pc, gprogram);
	InterpretationPtr as = igas->getNextModel();
	if (as != InterpretationPtr()){

		// extract parameters from all atoms over predicate "out"
		DBGLOG(DBG, "Rewrting output");
		Term outPredTerm(ID::MAINKIND_TERM | ID::SUBKIND_TERM_CONSTANT, "out");
		ID outPredID = reg->storeTerm(outPredTerm);
		for(Interpretation::Storage::enumerator it =
		    as->getStorage().first();
		    it != as->getStorage().end(); ++it){

			ID ogid(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG, *it);
			const OrdinaryAtom& ogatom = reg->ogatoms.getByID(ogid);

			if (ogatom.tuple[0] == outPredID){
				Tuple t;
				for (int ot = 1; ot < ogatom.tuple.size(); ++ot){
					t.push_back(ogatom.tuple[ot]);
				}
				answer.get().push_back(t);
			}
		}
	}
}