Пример #1
0
void Step::evaluate(Node* context, NodeSet& nodes) const
{
    nodesInAxis(context, nodes);
    
    EvaluationContext& evaluationContext = Expression::evaluationContext();
    
    for (unsigned i = 0; i < m_predicates.size(); i++) {
        Predicate* predicate = m_predicates[i];

        NodeSet newNodes;
        if (!nodes.isSorted())
            newNodes.markSorted(false);

        evaluationContext.size = nodes.size();
        evaluationContext.position = 1;
        for (unsigned j = 0; j < nodes.size(); j++) {
            Node* node = nodes[j];

            Expression::evaluationContext().node = node;
            EvaluationContext backupCtx = evaluationContext;
            if (predicate->evaluate())
                newNodes.append(node);

            evaluationContext = backupCtx;
            ++evaluationContext.position;
        }

        nodes.swap(newNodes);
    }
}
Пример #2
0
shared_ptr<ActionObject> HingeEffector::GetActionObject(const Predicate& predicate)
{
    for(;;)
        {
            if (mJoint.get() == 0)
                {
                    break;
                }

            if (predicate.name != GetPredicate())
                {
                    GetLog()->Error()
                        << "ERROR: (HingeEffector) invalid predicate"
                        << predicate.name << "\n";
                    break;
                }

            Predicate::Iterator iter = predicate.begin();

            float velocity;
            if (! predicate.AdvanceValue(iter, velocity))
                {
                    GetLog()->Error()
                        << "ERROR: (HingeEffector) motor velocity expected\n";
                    break;
                }

            return shared_ptr<HingeAction>(new HingeAction(GetPredicate(),velocity));
        }

    return shared_ptr<ActionObject>();
}
Пример #3
0
void copyConsTest()
{
	char str[100];
	while (gets(str)) {
		Parser p(str);

		Formula *f = p.parse();
		f->print();
		puts("");
		
		Predicate *pred = f->getPredicate();
		Term *t = pred->getTermList()->getList()->at(0);

		puts("here");
		Term w = *t;
		w.print();
		puts("here");
		w.setName("chan");
		w.print();
		puts("");

		f->print();
		puts("");
	}
}
Пример #4
0
void Parser::parseParamList(vector<Token>& toParse, Predicate& p)
{
	fillmyToken(toParse);
	if(myToken.myType == STRING)
	{
		match(STRING);
		Parameter param(myToken.data, myToken.myType);
		p.addParameter(param);
		domain.insert(myToken.data);
	}
	else
	{
		match(ID);
		Parameter param(myToken.data, myToken.myType);
		p.addParameter(param);
	}

	fillmyToken(toParse);
	if(myToken.myType == COMMA)	//more parameters to read
	{
		advanceIndex();
		parseParamList(toParse, p);
	}
	else
	{
		//do nothing; no more parameters
	}

}
Пример #5
0
/*
 * Fa il parsing della RHS della regola
 */
list<PredicateCall>
Parser::parse_rule_rhs(list<Token> token_list) {
  list<Token>::iterator token_iterator = token_list.begin();
  list<Token> predicate_tokens;
  list<PredicateCall> rhs;
  uint32_t read_tokens = 0;

  if (token_iterator == token_list.end())
    throw ParseError("empty right hand side");

  while (token_iterator != token_list.end()) {
    predicate_tokens = BUILD_TOKEN_BLOCK(token_iterator, string(1, LNG_STMT_END).c_str(), TKN_OPERATOR, token_list.end());
    Predicate pred = this->parse_predicate(predicate_tokens, predicate_tokens.begin(), &read_tokens);
    token_iterator = this->advance_iterator(token_iterator, read_tokens);
    ++token_iterator;
    read_tokens = 0;

    if ((token_iterator->get_type() == TKN_OPERATOR) &&
        (!token_iterator->get_value().compare(string(1, LNG_STMT_END)))) {
      ++token_iterator;
    } else if (token_iterator == token_list.end()) {
      throw ParseError("expected ; as predicate separator", (*(--token_iterator)).get_line_no());
    }

    PredicateCall call;
    call.set_name(pred.get_name());
    call.set_parameters(pred.get_parameters());
    rhs.push_back(call);
  }
  return rhs;
};
Пример #6
0
void Step::evaluate(EvaluationContext& evaluationContext, Node* context, NodeSet& nodes) const
{
    evaluationContext.position = 0;

    nodesInAxis(evaluationContext, context, nodes);

    // Check predicates that couldn't be merged into node test.
    for (unsigned i = 0; i < m_predicates.size(); i++) {
        Predicate* predicate = m_predicates[i].get();

        OwnPtrWillBeRawPtr<NodeSet> newNodes(NodeSet::create());
        if (!nodes.isSorted())
            newNodes->markSorted(false);

        for (unsigned j = 0; j < nodes.size(); j++) {
            Node* node = nodes[j];

            evaluationContext.node = node;
            evaluationContext.size = nodes.size();
            evaluationContext.position = j + 1;
            if (predicate->evaluate(evaluationContext))
                newNodes->append(node);
        }

        nodes.swap(*newNodes);
    }
}
ProteinList_Filter::Impl::Impl(ProteinListPtr _original, const Predicate& predicate)
:   original(_original), getSequence(false)
{
    if (!original.get()) throw runtime_error("[ProteinList_Filter] Null pointer");

    // iterate through the proteins, using predicate to build the sub-list
    for (size_t i=1, end=original->size(); i<=end; ++i)
    {
        if (predicate.done()) break;

        ProteinPtr protein = original->protein(i-1, getSequence);
        tribool accepted = predicate.accept(*protein);

        if (accepted || getSequence) // if still indeterminate with getSequence = true, it passes the filter by default
        {
            pushProtein(*protein);            
        }
        else if (!accepted)
        {
            // do nothing 
        }
        else // indeterminate and !getSequence
        {
            // try again with getSequence = true
            getSequence = true;
            --i;
        }
    }
}
Пример #8
0
void Step::evaluate(Node* context, NodeSet& nodes) const
{
    EvaluationContext& evaluationContext = Expression::evaluationContext();
    evaluationContext.position = 0;

    nodesInAxis(context, nodes);

    // Check predicates that couldn't be merged into node test.
    for (unsigned i = 0; i < m_predicates.size(); i++) {
        Predicate* predicate = m_predicates[i].get();

        NodeSet newNodes;
        if (!nodes.isSorted())
            newNodes.markSorted(false);

        for (unsigned j = 0; j < nodes.size(); j++) {
            Node* node = nodes[j];

            evaluationContext.node = node;
            evaluationContext.size = nodes.size();
            evaluationContext.position = j + 1;
            if (predicate->evaluate())
                newNodes.append(node);
        }

        nodes.swap(newNodes);
    }
}
Пример #9
0
/*
 * Caller is responsible for deleting returned Predicate* if necessary
 */
Predicate* Domain::getNonEvidenceAtom(const int& index) const
{
  int predId = -1;
  int numAtomsPerPred;
  int numAtoms = 0;
  for (int i = 0; i < getNumPredicates(); i++)
  {
    numAtomsPerPred = (*numNonEvidAtomsPerPred_)[i];
    if (numAtoms + numAtomsPerPred >= index + 1)
    {
      predId = i;
      break;
    }
    numAtoms += numAtomsPerPred;
  }
  assert(predId >= 0);

    // Get the newIndex-th grounding of f.o. pred with id predId   
  Predicate* pred = createPredicate(predId, false);
    // Not all groundings of pred are non-evidence, so we need the while loop
  bool foundNE = false;
  while(!foundNE)
  {
    for (int i = 0; i < pred->getNumTerms(); i++)
    {
      int termType = pred->getTermTypeAsInt(i);
      const Array<int>* constantsByType = getConstantsByType(termType);
      int constIdx = random() % constantsByType->size();
      pred->setTermToConstant(i, (*constantsByType)[constIdx]);
    }
    assert(pred->isGrounded());
    if (!db_->getEvidenceStatus(pred)) foundNE = true;
  }
  return pred;
}
Пример #10
0
shared_ptr<ActionObject>
PanTiltEffector::GetActionObject(const Predicate& predicate)
{
    if (predicate.name != GetPredicate())
    {
        GetLog()->Error() << "ERROR: (PanTiltEffector) invalid predicate"
                          << predicate.name << "\n";
        return shared_ptr<ActionObject>();
    }

    Predicate::Iterator iter = predicate.begin();

    float pan;
    if (! predicate.AdvanceValue(iter, pan))
    {
        GetLog()->Error() << "ERROR: (PanTiltEffector) 2 float parameters expected\n";
        return shared_ptr<ActionObject>(new ActionObject(GetPredicate()));
    }
    float tilt;
    if (! predicate.AdvanceValue(iter, tilt))
    {
        GetLog()->Error() << "ERROR: (PanTiltEffector) float parameter expected\n";
        return shared_ptr<ActionObject>(new ActionObject(GetPredicate()));
    }
    return shared_ptr<ActionObject>(new PanTiltAction(GetPredicate(),pan,tilt));
}
Пример #11
0
//the contribution of the factor itself
void Factor::initFactorMesssages()
{
    Predicate *pred;
    int numPreds = clause_->getNumPredicates();
    int stateCnt = (int)pow(2.0, numPreds);
    factorMsgs_ = new double[stateCnt];
    bool isSatisfied;
    for (int state = 0; state < stateCnt; state++)
    {
        isSatisfied = false;
        for (int predno = 0; predno < numPreds; predno++)
        {
            pred = clause_->getPredicate(predno);
            bool predBit = state & (1<<predno);
            if (pred->getSense() == predBit)
            {
                isSatisfied = true;
                break;
            }
        }

        if (isSatisfied)
        {
            // Always 1
            // MS: should be weight of clause in ground network (super or ground)
            factorMsgs_[state] = clause_->getWt();
        }
        else
        {
            factorMsgs_[state] = 0;
        }
    }
}
Пример #12
0
boost::shared_ptr<ActionObject>
SceneEffector::GetActionObject(const Predicate& predicate)
{
    if (predicate.name != GetPredicate())
        {
            GetLog()->Error() << "(SceneEffector) ERROR: invalid predicate"
                              << predicate.name << "\n";
            return boost::shared_ptr<ActionObject>();
        }

    string scene;
    if (! predicate.GetValue(predicate.begin(), scene))
        {
            GetLog()->Error()
                << "ERROR: (SceneEffector) scene filename expected\n";
            return boost::shared_ptr<ActionObject>();
        };

    boost::shared_ptr<ParameterList> parameters(
        new ParameterList(predicate.parameter));
    parameters->Pop_Front();

    return boost::shared_ptr<ActionObject>(
        new SceneAction(GetPredicate(), scene, parameters));
}
Пример #13
0
double Matcher::predicateMatchScore
( const Predicate& sp, 
  const Predicate& tp ) const 
{
  map<Predicate, Predicate>::const_iterator sp_pos = matchedPreds.find(sp);
  map<Predicate, Predicate>::const_iterator tp_pos = matchedPreds.find(tp);
  if (sp_pos != matchedPreds.end() and sp_pos->second != tp) {
    return 0;
  }
  if (tp_pos != matchedPreds.end() and tp_pos->second != sp) {
    return 0;
  }
  if (sp.get_arity() == 0 and tp.get_arity() == 0) {
    return 1;
  }
  
  set<PlaceType> spTypes = sourcePreds.find(sp)->second;
  set<PlaceType> tpTypes = targetPreds.find(tp)->second;
  
  vector<PlaceType> intersection;
  set_intersection(spTypes.begin(), spTypes.end(), 
                   tpTypes.begin(), tpTypes.end(), 
                   back_inserter(intersection));
  double score = intersection.size() / (spTypes.size() + tpTypes.size());
  return score;
}
Пример #14
0
boost::shared_ptr<ActionObject>
SayEffector::GetActionObject(const Predicate& predicate)
{
    if (predicate.name != GetPredicate())
    {
        GetLog()->Error() << "ERROR: (SayEffector) invalid predicate"
                          << predicate.name << "\n";

        // some error happened
        return boost::shared_ptr<ActionObject>();
    }

    Predicate::Iterator iter = predicate.begin();

    std::string message;
    if (! predicate.AdvanceValue(iter, message))
    {
        GetLog()->Error()
            << "ERROR: (SayEffector) said message expected\n";

        // some error happened
        return boost::shared_ptr<ActionObject>();
    }

    // construct the SayAction object
    return boost::shared_ptr<SayAction>(new SayAction(GetPredicate(), message));

}
Пример #15
0
Predicate* PredicateTable::getPredicate(index_object id) {

	Predicate p;
	p.setIndex(id);

	Predicate *p_finded = *hash.find(&p);
	return p_finded;
}
Пример #16
0
void Database::initSchemes(vector<Predicate> schemes){
	for(int i = 0; i < (int)schemes.size(); i++){
		Predicate r = schemes[i];
		Relation r1(r.getID());
		for(int j = 0; j < (int)r.getParameters().size(); j++)
			r1.addParam(r.getParameters()[j].getValue());
		relations.push_back(r1);
	}
}
Пример #17
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);
	}
}
Пример #18
0
TEST_F(ExpressionOperatorTests, GreaterThanOperator_Expression_Getter_ReturnsCorrectPredicate)
{
	Expression<TestExpressionEntity, std::int32_t> expr = ::MakeExpression(&TestExpressionEntity::SetterGetterGetter);

	Predicate<TestExpressionEntity> setterGetterIsGreaterThanSetterGetter = expr > &TestExpressionEntity::SetterGetterGetter;

	SqlPredicate predicate = setterGetterIsGreaterThanSetterGetter.GetSqlPredicate(_registry);

	EXPECT_EQ(0, predicate.GetNumberOfParameters());
	EXPECT_EQ("(TestTable.SetterGetter > TestTable.SetterGetter)", predicate.GetPredicate());
}
Пример #19
0
TEST_F(ExpressionOperatorTests, NotEqualOperator_Expression_Constant_ReturnsCorrectPredicate)
{
	Expression<TestExpressionEntity, std::int32_t> expr = ::MakeExpression(&TestExpressionEntity::SetterGetterGetter);

	Predicate<TestExpressionEntity> setterGetterIsNotEqualToSix = expr != 6;

	SqlPredicate predicate = setterGetterIsNotEqualToSix.GetSqlPredicate(_registry);

	EXPECT_EQ(1, predicate.GetNumberOfParameters());
	EXPECT_EQ("(TestTable.SetterGetter <> ?)", predicate.GetPredicate());
}
Пример #20
0
TEST_F(ExpressionOperatorTests, EqualOperator_Expression_ConstReferenceGetter_ReturnsCorrectPredicate)
{
	Expression<TestExpressionEntity, std::int32_t> expr = ::MakeExpression(&TestExpressionEntity::SetterGetterGetter);

	Predicate<TestExpressionEntity> setterGetterIsEqualToSetterConstReferenceGetter = expr == &TestExpressionEntity::SetterConstReferenceGetterGetter;

	SqlPredicate predicate = setterGetterIsEqualToSetterConstReferenceGetter.GetSqlPredicate(_registry);

	EXPECT_EQ(0, predicate.GetNumberOfParameters());
	EXPECT_EQ("(TestTable.SetterGetter = TestTable.SetterConstReferenceGetter)", predicate.GetPredicate());
}
Пример #21
0
TEST_F(ExpressionOperatorTests, NotEqualToOperator_Expression_null_ReturnsCorrectPredicate)
{
	Expression<TestExpressionEntity, std::int32_t> expr = ::MakeExpression(&TestExpressionEntity::SetterGetterGetter);

	Predicate<TestExpressionEntity> nullIsNotEqualToSetterGetter = (expr != nullptr);

	SqlPredicate predicate = nullIsNotEqualToSetterGetter.GetSqlPredicate(_registry);

	EXPECT_EQ(0, predicate.GetNumberOfParameters());
	EXPECT_EQ("(TestTable.SetterGetter IS NOT NULL)", predicate.GetPredicate());
}
Пример #22
0
TEST_F(ExpressionOperatorTests, OrOperator_Constant_Exoression_ReturnsCorrectPredicate)
{
	Expression<TestExpressionEntity, std::int32_t> expr = ::MakeExpression(&TestExpressionEntity::SetterGetterGetter);

	Predicate<TestExpressionEntity> falsOrSetterGetterIsEqualToSix = false || (expr == 6);

	SqlPredicate predicate = falsOrSetterGetterIsEqualToSix.GetSqlPredicate(_registry);

	EXPECT_EQ(2, predicate.GetNumberOfParameters());
	EXPECT_EQ("(? OR (TestTable.SetterGetter = ?))", predicate.GetPredicate());
}
Пример #23
0
TEST_F(ExpressionOperatorTests, GreaterThanOrEqualToOperator_Expression_Field_ReturnsCorrectPredicate)
{
	Expression<TestExpressionEntity, std::int32_t> expr = ::MakeExpression(&TestExpressionEntity::SetterGetterGetter);

	Predicate<TestExpressionEntity> setterGetterIsGreaterThanOrEqualToField = expr >= &TestExpressionEntity::_field;

	SqlPredicate predicate = setterGetterIsGreaterThanOrEqualToField.GetSqlPredicate(_registry);

	EXPECT_EQ(0, predicate.GetNumberOfParameters());
	EXPECT_EQ("(TestTable.SetterGetter >= TestTable.Field)", predicate.GetPredicate());
}
Пример #24
0
TEST_F(ExpressionOperatorTests, OrOperator_Exoression_Expression_ReturnsCorrectPredicate)
{
	Expression<TestExpressionEntity, std::int32_t> expr = ::MakeExpression(&TestExpressionEntity::SetterGetterGetter);

	Predicate<TestExpressionEntity> setterGetterIsEqualToSixAndOrSetterGetterIsNotEqualToFortyTwo = (expr == 6) || (expr != 42);

	SqlPredicate predicate = setterGetterIsEqualToSixAndOrSetterGetterIsNotEqualToFortyTwo.GetSqlPredicate(_registry);

	EXPECT_EQ(2, predicate.GetNumberOfParameters());
	EXPECT_EQ("((TestTable.SetterGetter = ?) OR (TestTable.SetterGetter <> ?))", predicate.GetPredicate());
}
Пример #25
0
TEST_F(ExpressionOperatorTests, OrOperator_Exoression_Constant_ReturnsCorrectPredicate)
{
	Expression<TestExpressionEntity, std::int32_t> expr = ::MakeExpression(&TestExpressionEntity::SetterGetterGetter);

	Predicate<TestExpressionEntity> setterGetterIsEqualToSixOrTrue = (expr == 6) || true;

	SqlPredicate predicate = setterGetterIsEqualToSixOrTrue.GetSqlPredicate(_registry);

	EXPECT_EQ(2, predicate.GetNumberOfParameters());
	EXPECT_EQ("((TestTable.SetterGetter = ?) OR ?)", predicate.GetPredicate());
}
Пример #26
0
  //Caller is responsible for deleting returned pointer
Predicate* Domain::createPredicate(const int& predId, 
                                   const bool& includeEqualPreds) const
{
  const PredicateTemplate* pt = getPredicateTemplate(predId);
  if (!includeEqualPreds && pt->isEqualPredicateTemplate()) return NULL;
  Predicate* pred = new Predicate(pt);
  pred->setSense(true);
  for (int j = 0; j < pt->getNumTerms(); j++)
    pred->appendTerm(new Term(-(j+1), (void*)pred, true));
  return pred;
}
Пример #27
0
		Value Value::PredicateExpr(Predicate predicate, const Type* const boolType) {
			if (predicate.isTrue()) {
				return Value::Constant(Constant::True(), boolType);
			} else if (predicate.isFalse()) {
				return Value::Constant(Constant::False(), boolType);
			} else if (predicate.isVariable()) {
				return Value::TemplateVarRef(predicate.variableTemplateVar(), boolType);
			}
			
			Value value(PREDICATE, boolType, ExitStates::Normal());
			value.impl_->predicate = make_optional(std::move(predicate));
			return value;
		}
Пример #28
0
		bool Predicate::operator==(const Predicate& other) const {
			if (kind() != other.kind()) {
				return false;
			}
			
			switch (kind()) {
				case TRUE:
				case FALSE:
				case SELFCONST:
				{
					return true;
				}
				case AND:
				{
					return andLeft() == other.andLeft() && andRight() == other.andRight();
				}
				case OR:
				{
					return orLeft() == other.orLeft() && orRight() == other.orRight();
				}
				case SATISFIES:
				{
					return satisfiesType() == other.satisfiesType() &&
						satisfiesRequirement() == other.satisfiesRequirement();
				}
				case VARIABLE:
				{
					return variableTemplateVar() == other.variableTemplateVar();
				}
			}
			
			locic_unreachable("Unknown predicate kind.");
		}
Пример #29
0
void Step::optimize()
{
    // Evaluate predicates as part of node test if possible to avoid building unnecessary NodeSets.
    // E.g., there is no need to build a set of all "foo" nodes to evaluate "foo[@bar]", we can check the predicate while enumerating.
    // This optimization can be applied to predicates that are not context node list sensitive, or to first predicate that is only context position sensitive, e.g. foo[position() mod 2 = 0].
    Vector<Predicate*> remainingPredicates;
    for (size_t i = 0; i < m_predicates.size(); ++i) {
        Predicate* predicate = m_predicates[i];
        if ((!predicate->isContextPositionSensitive() || m_nodeTest.mergedPredicates().isEmpty()) && !predicate->isContextSizeSensitive() && remainingPredicates.isEmpty()) {
            m_nodeTest.mergedPredicates().append(predicate);
        } else
            remainingPredicates.append(predicate);
    }
    swap(remainingPredicates, m_predicates);
}
Пример #30
0
bool ColouredGraphNodePredicates::isEquivalentTo(const Predicate& predicate, int invariables, const std::vector<const Object*>& objects) const
{
	if (predicate.getName() != predicates_->getName() || predicate.getArity() != predicates_->getArity() || invariables != invariables_ || objects_.size() != objects.size())
	{
		return false;
	}
	
	for (unsigned int i = 0; i < objects.size(); ++i)
	{
		if ((int)i != invariables && objects[i] != objects_[i])
		{
			return false;
		}
	}
	return true;
}