Beispiel #1
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);
			}
		}
	}
}
Beispiel #2
0
Tuple Database::joinTuple(set<pair<int, int>> pairs, Tuple t1, Tuple t2){
	Tuple newTuple;
	for (int i = 0; i<t1.size(); i++){
		newTuple.push_back(t1[i]);
	}
	for (auto i : t2){
		newTuple.push_back(i);
	}
	return newTuple;
}
Beispiel #3
0
Tuple Relation::do_product(Tuple t1, Tuple t2) {
	Tuple t = Tuple();
	for (auto item : t1) {
		t.push_back(item);
	}
	for (auto item2 : t2) {
		t.push_back(item2);
	}
	return t;
}
Beispiel #4
0
void Join::execProject(const Tuple &left_tuple,
                       const Tuple &right_tuple,
                       Tuple &output_tuple) const
{
    output_tuple.clear();

    for (ColID i = 0; i < numOutputCols(); ++i) {
        if (selected_input_col_ids_[i] < left_child_->numOutputCols()) {
            output_tuple.push_back(left_tuple[selected_input_col_ids_[i]]);
        } else {
            output_tuple.push_back(right_tuple[selected_input_col_ids_[i]
                                   - left_child_->numOutputCols()]);
        }
    }
}
Beispiel #5
0
Tuple Interpretter::predToTuple(Predicate query) {
    Tuple out;
    for (auto item : query.getParams()) {
        out.push_back(item.toString());
    }
    return out;
}
Beispiel #6
0
void
TestRacerNRQL::runRacerRetrieveTest()
{
  std::stringstream sst;

  Tuple tup;
  tup.push_back(Term("X"));
  tup.push_back(Term("Y"));

  AtomSet as;
  AtomPtr ap1(new Atom("foo(X)"));
  AtomPtr ap2(new Atom("moo(X,Y)"));
  as.insert(ap1);
  as.insert(ap2);

  KBManager kb("DEFAULT");
  DLQuery::shared_pointer dlq(new DLQuery(Ontology::createOntology(test),as,tup));
  Query q(kb,dlq,Term(""),Term(""),Term(""),Term(""),AtomSet());

  NRQLRetrieve<NRQLConjunctionBuilder> nrql(q);

  sst << nrql;
     
  std::string s = sst.str();
 
  std::cout << s << std::endl;

  CPPUNIT_ASSERT(s == "(retrieve ($?X $?Y) (and ($?X $?Y |http://www.test.com/test#moo|) ($?X |http://www.test.com/test#foo|)) :abox DEFAULT)");
}
Beispiel #7
0
void SimpleFilter::precalculate(int order, int mask)
{
  if (mask & (H2D_FN_DX | H2D_FN_DY | H2D_FN_DXX | H2D_FN_DYY | H2D_FN_DXY))
    error("Filter not defined for derivatives.");

  Quad2D* quad = quads[cur_quad];
  int np = quad->get_num_points(order);
  Node* node = new_node(H2D_FN_VAL, np);

  // precalculate all solutions
  for (int i = 0; i < num; i++)
    sln[i]->set_quad_order(order, item[i]);

  for (int j = 0; j < num_components; j++)
  {
    // obtain corresponding tables
    scalar* tab[10];
    for (int i = 0; i < num; i++)
    {
      int a = 0, b = 0, mask = item[i];
      if (mask >= 0x40) { a = 1; mask >>= 6; }
      while (!(mask & 1)) { mask >>= 1; b++; }
      tab[i] = sln[i]->get_values(num_components == 1 ? a : j, b);
      if (tab[i] == NULL) error("Value of 'item%d' is incorrect in filter definition.", i+1);
    }

		Tuple<scalar*> values;
		for(int i = 0; i < this->num; i++)
			values.push_back(tab[i]);

    // apply the filter
		filter_fn(np, values, node->values[j][0]);
  }
Relation Relation::project(vector<int>& index1)
{
	Relation temp;

	Tuple tempTuplele;

	for(int i=0; i<index1.size(); i++)
	{
		temp.my_values.ADD(my_values.scheme_string(index1[i]));
	}

	for (set<Tuple>::iterator it = Tuple_Set.begin(); it != Tuple_Set.end(); ++it)
	{
		for(int i = 0; i < index1.size(); i++)
		{
			tempTuplele.push_back((*it)[index1[i]]);
		}

		temp.Tuple_Set.insert(tempTuplele);
		tempTuplele.clear();
	}

	temp.my_name = my_name;

	return temp;
}
Beispiel #9
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());
	}
}
Beispiel #10
0
void Interpretter::evalRules(vector <Rule>& rulelist) {

    for (Rule rule : rulelist) {
        cout << rule.toString();
        output += rule.toString();
        
        //get the first rule, then iterate thru the rest, adding to the new "joined" Relation
        Relation joined = db[rule.getPredicates()[0].getID()];
        
        // set a joined scheme, based on predicate[0]'s params. And give it to me in tuple format
        joined.redoScheme(rule.getPredicates()[0].getParams());
        if (rulelist.size() > 1) {
            vector <Relation> processedPreds;
            if (rule.getPredicates().size() > 1) {
                
                //for each Predicate (after the first) in the rule
                for (int i = 1; i < rule.getPredicates().size(); i++) {
                    Relation r = db[rule.getPredicates()[i].getID()];
                    Tuple predT = predToTuple(rule.getPredicates()[i]);
                    
                    Relation selected = r.select(predT);
                    //output += selected.toString();
                    
                    //Relation projected = selected.project(predT);
                    //output += projected.toString();
                    
                    Relation renamed = selected.rename(predT);
                    processedPreds.push_back(renamed);
                    joined = joined.join(renamed);
                }
            }
        }

        Tuple renameScheme;
        //cout << "rule.getName() = " << rule.getName() << endl;
        for (auto item : rule.getParams()) {
            renameScheme.push_back(item.getVal());
        }
        //cout << "joined" << joined.toString();
        Relation projectRule = joined.project2(renameScheme); //project with the original columns
        //Relation renameRule = projectRule.rename(renameScheme); // use the original scheme
        //cout << renameRule.toString();
        int prevSize = db[rule.getName()].getRelSize();
        for (auto tuple : projectRule.getTuples()) {

            db[rule.getName()].add(tuple);

            //if it actually added
            if (db[rule.getName()].getRelSize() > prevSize) {
                output += db[rule.getName()].tupleToString(tuple);
                prevSize = db[rule.getName()].getRelSize();
                addedTuples++;
            }
        }
        
    }
}
packToken lazy_class_exec(packMap scope) {
  packMap _this = scope->find("this")->asMap();
  Function* func = (*_this)["func"].asFunc();
  packList args = (*_this)["args"].asList();

  Tuple tuple;
  // Copy the tokens from this.args:
  for (packToken item : args->list) {
    tuple.push_back(item);
  }

  // Copy the tokens received as exec() arguments:
  args = scope->find("arglist")->asList();
  for (packToken item : args->list) {
    tuple.push_back(item);
  }

  return Function::call(_this, func, &tuple, packMap(scope->parent));
}
Beispiel #12
0
void Database::initFacts(vector<Predicate> facts){
	for(int i = 0; i < (int)facts.size(); i++){
		Predicate r = facts[i];
		string name = r.getID();
		Tuple t;
		for(int j = 0; j < (int)r.getParameters().size(); j++)
			t.push_back(r.getParameters()[j].getValue());
		addTuple(name, t);
	}
}
Beispiel #13
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);
    }
  }
Beispiel #14
0
Tuple Relation::join_tuples(Tuple t1, Tuple t2, std::vector<std::pair<int, int>> common_attributes) {
	Tuple t = Tuple();

	for (auto item : t1) {
		t.push_back(item);
	}

	int num_attributes = t2.size();

	for (int i = 0; i < num_attributes; i++) {
		// Make sure you aren't adding common attributes twice
		bool is_common_attribute = false;
		for (auto pair : common_attributes) {
			if (i == pair.second)
				is_common_attribute = true;
		}

		if (!is_common_attribute) {
			t.push_back(t2.at(i));
		}
	}

	return t;
}
Beispiel #15
0
Relation Relation::project(vector<int> &indexList){
	Relation r = Relation(name);
	for(int i = 0; i < (int)indexList.size(); i++)
		r.schema.attributes.push_back(schema.attributes[indexList[i]]);
	if(indexList.size() != 0){
		set<Tuple>::iterator it;
		for(it = tuples.begin(); it != tuples.end(); it++){
			Tuple newTuple = Tuple();
			for(int j = 0; j < (int)indexList.size(); j++)
				newTuple.push_back((*it)[indexList[j]]);
			r.tuples.insert(newTuple);
		}
	}
	return r;

}
Beispiel #16
0
Relation Relation::project(std::vector<int> indices) {
	Relation temp = Relation(this->name);

	int num_indices = indices.size();
	for (int i = 0; i < num_indices; i++) {
		temp.scheme.push_back(this->scheme.at(indices.at(i)));
	}

	for (Tuple tuple : this->tuples) {
		Tuple t;
		for (int i = 0; i < num_indices; i++) {
			t.push_back(tuple.at(indices.at(i)));
		}
		temp.tuples.insert(t);
	}

	return temp;
}
Beispiel #17
0
void Paving::save(const std::string filename, const Names &titles, const Names &names) const {
  if (empty()) return;
  Tuple vs;
  for (nat v = 0; v < names.size(); ++v) {
    nat n = varbox_.var(names[v]);
    if (n < nvars())
      vs.push_back(n);
  }
  std::ostringstream os;
  os << filename;
  for (nat i = 0; i < vs.size(); ++i)
    os << "_" << varbox_.name(vs[i]);
  os << ".dat";
  if (vs.empty()) {
    vs.resize(varbox_.size());
    for (nat v = 0; v < varbox_.size(); ++v)
      vs[v] = v;
  }
  std::ofstream f;
  f.open(os.str().c_str(), std::ofstream::out);
  f << "## File: " << os.str() << std::endl;
  f << "## Type: " << type_ << std::endl;
  f << "## Vars:" << std::endl;
  nat width = 2 * Kodiak::precision();
  for (nat i = 0; i < vs.size(); ++i)
    f << std::setw(width) << varbox_.name(vs[i]);
  f << std::endl;
  for (nat i = 0; i < vs.size(); ++i)
    f << std::setw(width) << varbox_.box()[vs[i]].inf();
  f << std::endl;
  for (nat i = 0; i < vs.size(); ++i)
    f << std::setw(width) << varbox_.box()[vs[i]].sup();
  f << std::endl;
  f << std::endl;
  for (nat i = 0; i < titles.size(); ++i) {
    f << "## " << titles[i] << ": " << size(i) << " boxes " << std::endl;
    if (i < boxes_.size() && boxes_[i].size() > 0)
      save_boxes(f, boxes_[i], vs, width);
    else
      f << std::endl;
  }
  f.close();
  std::cout << "Kodiak (save): Boxes were saved in file " << os.str() << std::endl;
}
Beispiel #18
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");
  }
Beispiel #19
0
ConstraintTree::ConstraintTree (vector<vector<string>> names)
{
  assert (names.empty() == false);
  assert (names.front().empty() == false);  
  unsigned nrLvs = names[0].size();
  for (size_t i = 0; i < nrLvs; i++) {
    logVars_.push_back (LogVar (i));
  }
  root_      = new CTNode (0, 0);
  logVarSet_ = LogVarSet (logVars_);
  for (size_t i = 0; i < names.size(); i++) {
    Tuple t;
    for (size_t j = 0; j < names[i].size(); j++) {
      assert (names[i].size() == nrLvs);
      t.push_back (LiftedUtils::getSymbol (names[i][j]));	
    }
    addTuple (t);
  }
}
Beispiel #20
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);
		}
	}
}
Beispiel #21
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++;
			}
		}
	}
}
Beispiel #22
0
void
TestRacerNRQL::runRacerPremiseRetrieveTest()
{
  std::stringstream sst;

  Tuple tup;
  tup.push_back(Term("X"));
  tup.push_back(Term("Y"));

  AtomSet as;
  AtomPtr ap1(new Atom("foo(X)"));
  AtomPtr ap2(new Atom("moo(X,Y)"));
  as.insert(ap1);
  as.insert(ap2);

  AtomSet ints;
  AtomPtr ap4(new Atom("pc(foo,a)"));
  AtomPtr ap5(new Atom("pr(moo,a,b)"));
  ints.insert(ap4);
  ints.insert(ap5);

  KBManager kb("DEFAULT");
  DLQuery::shared_pointer dlq(new DLQuery(Ontology::createOntology(test),as,tup));
  Query q(kb,dlq,Term("pc"),Term(""),Term("pr"),Term(""),ints);

  NRQLRetrieveUnderPremise<NRQLConjunctionBuilder> nrql(q);

  sst << nrql;
     
  std::string s = sst.str();
 
  std::cout << s << std::endl;

  URI u(testuri, true); // absolute pathname
  CPPUNIT_ASSERT(s == "(retrieve-under-premise ((related |http://www.test.com/test#a| |http://www.test.com/test#b| |http://www.test.com/test#moo|) (instance |http://www.test.com/test#a| |http://www.test.com/test#foo|)) ($?X $?Y) (and ($?X $?Y |http://www.test.com/test#moo|) ($?X |http://www.test.com/test#foo|)) :abox |" + u.getString() + "|)");
}
Beispiel #23
0
TupleSet
ConstraintTree::tupleSet (const LogVars& originalLvs)
{
  LogVars uniqueLvs;
  for (size_t i = 0; i < originalLvs.size(); i++) {
    if (Util::contains (uniqueLvs, originalLvs[i]) == false) {
      uniqueLvs.push_back (originalLvs[i]);
    }
  }

  Tuples tuples;
  moveToTop (uniqueLvs);
  unsigned stopLevel = uniqueLvs.size();
  getTuples (root_, Tuples(), stopLevel, tuples, CTNodes() = {});

  if (originalLvs.size() != uniqueLvs.size()) {
    vector<size_t> indexes;
    indexes.reserve (originalLvs.size());
    for (size_t i = 0; i < originalLvs.size(); i++) {
      indexes.push_back (Util::indexOf (uniqueLvs, originalLvs[i]));
    }
    Tuples tuples2;
    tuples2.reserve (tuples.size());
    for (size_t i = 0; i < tuples.size(); i++) {
      Tuple t;
      t.reserve (originalLvs.size());
      for (size_t j = 0; j < originalLvs.size(); j++) {
        t.push_back (tuples[i][indexes[j]]);
      }
      tuples2.push_back (t);
    }
    return TupleSet (tuples2);
  }

  return TupleSet (tuples);
}
      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++;
		  }
	      }
	  }
      }      
Beispiel #25
0
int main(int argc, char* argv[]) {
  std::string file_name;
  if (argc < 2) {
    std::cerr << "please specify the file name" << std::endl;
    return 1;
  }
  file_name = argv[1];
  std::ifstream infile;
#ifdef _MSC_VER
  // handling file names with non-ascii characters
  wchar_t *wcstring = new wchar_t[file_name.size()+1];
  setlocale(LC_ALL, ".OCP");
  mbstowcs(wcstring, file_name.c_str(), file_name.size()+1);
  infile.open(wcstring);
  delete[] wcstring;
  setlocale(LC_ALL, "");
#else  // _MSC_VER
  infile.open(file_name.c_str());
#endif  // _MSC_VER
  if (!infile.is_open()) {
    std::cerr << "cannot open the input file" << std::endl;
    return 1;
  }
  SUTModel sut_model;
  Assembler assembler;
  try {
    ct::lexer lexer(&infile);
    assembler.setErrLogger(boost::shared_ptr<ErrLogger>(new ErrLogger_Cerr()));
    yy::ct_parser parser(lexer,
                         sut_model.param_specs_,
                         sut_model.strengths_, 
                         sut_model.seeds_,
                         sut_model.constraints_,
                         assembler);
    parser.parse();
  } catch (std::runtime_error e) {
    std::cerr << e.what() << std::endl;
  } catch (...) {
    std::cerr << "unhandled exception when parsing input file" << std::endl;
    std::cerr << "exiting" << std::endl;
    return 1;
  }
  if (assembler.numErrs() > 0) {
    std::cerr << assembler.numErrs() << " errors in the input file, exiting" << std::endl;
    return 2;
  }
  std::cout << "successfully parsed the input file" << std::endl;
  std::cout << "# parameters:  " << sut_model.param_specs_.size() << std::endl;
  std::cout << "# strengths:   " << sut_model.strengths_.size() << std::endl;
  std::cout << "# seeds:       " << sut_model.seeds_.size() << std::endl;
  std::cout << "# constraints: " << sut_model.constraints_.size() << std::endl;
  
  std::vector<RawStrength> raw_strengths;
  TuplePool tuple_pool;
  for (std::size_t i = 0; i < sut_model.strengths_.size(); ++i) {
    attach_2_raw_strength(sut_model.strengths_[i], raw_strengths);
  }
  for (std::size_t i = 0; i < raw_strengths.size(); ++i) {
    Tuple tuple;
    for (std::size_t j = 0; j < raw_strengths[i].size(); ++j) {
      tuple.push_back(PVPair(raw_strengths[i][j], 0));
    }
    if (tuple.size() <= 0) {
      continue;
    }
    do {
      tuple_pool.insert(tuple);
    } while (tuple.to_the_next_tuple(sut_model.param_specs_));
  }
  std::cout << "# target combinations: " << tuple_pool.size() << std::endl;
  
  TuplePool forbidden_tuple_pool;
  for (std::size_t i = 0; i < sut_model.constraints_.size(); ++i) {
    std::set<std::size_t> rel_pids;
    sut_model.constraints_[i]->touch_pids(sut_model.param_specs_, rel_pids);
    Tuple tuple;
    for (std::set<std::size_t>::const_iterator iter = rel_pids.begin(); iter != rel_pids.end(); iter++) {
      tuple.push_back(PVPair(*iter, 0));
    }
    do {
      EvalType_Bool result = sut_model.constraints_[i]->Evaluate(sut_model.param_specs_, tuple);
      if (!result.is_valid_ || !result.value_) {
        forbidden_tuple_pool.insert(tuple);
      }
    } while (tuple.to_the_next_tuple_with_ivld(sut_model.param_specs_));
  }
  std::cout << "# forbidden combinations: " << forbidden_tuple_pool.size() << std::endl;
  return 0;
}
Beispiel #26
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);
			}
		}
	}
}