Exemple #1
0
Node* Parser::Term()
{
	Node* pNode = Factor();
	EToken token = _scanner.Token();
	if (token == tMult || token == tDivide)
	{
		MultiNode* pMultiNode = new ProductNode(pNode);
		do
		{
			_scanner.Accept();
			Node* pRight = Factor();
			pMultiNode->AddChild (pRight, (token == tMult));
			token = _scanner.Token();
		}while (token == tMult || token == tDivide);
		pNode = pMultiNode;
	}
	return pNode;
	/*
	if (_scanner.Token() == tMult )
	{
		_scanner.Accept();
		Node* pRight = Term();
		pNode = new MultNode(pNode,pRight);
	}
	else if(_scanner.Token() == tDivide)
	{
		_scanner.Accept();
		Node* pRight = Term();
		pNode = new DivideNode (pNode, pRight );
	}
	return pNode;
	*/
}
Exemple #2
0
void TermPrime(void)
{
   switch (Symb.type) {
   case TIMES:
      /* T' -> * F BinOp T' */
      Symb = readLexem();
      Factor();
      Gener(BinOp, '*');      /* BinOp.dop = '*' */
      TermPrime();
      break;
   case DIVIDE:
      /* T' -> / F BinOp T' */
      Symb = readLexem();
      Factor();
      Gener(BinOp, '/');      /* BinOp.dop = '/' */
      TermPrime();
      break;
   case PLUS:
   case MINUS:
   case RPAR:
   case EOI:
      /* T' -> e */
      break;
   default:
      ExpansionError("T'", Symb.type);
   }
}
//16.<项>—> <因子> [ *|/  <因子> ]
Val Item(){
	Val v1 = Factor();

	while (lookahead == mutiply || lookahead == div){
		int op = lookahead;
		if (op == mutiply) match(mutiply);
		else match(div);
		Val v2 = Factor();


		quadruples.push_back(Quadruple(sno++, op == mutiply ? mutiply : div, v1, v2, temp));
		//生成四元式
		/*printf("%3d (%c,", sno++, op == mutiply ? '*' : '/');
		
		if (v1.type == 1) printf("%s", GetNameByID(v1.value1));
		else if (v1.type == 0)  printf("%d", v1.value1);
		else if (v1.type == 2) printf("%lf", v1.value2);
		else printf("t%d", v1.value1);
		printf(",");
		if (v2.type == 1) printf("%s", GetNameByID(v2.value1));
		else if (v2.type == 0) printf("%d", v2.value1);
		else if (v2.type == 2) printf("%lf", v2.value2);
		else printf("t%d", v2.value1);
		printf(",t%d)\n", temp);*/

		v1.type = -1;
		v1.value1 = temp++;

	}
	return v1;
}
result Term() {
    result lhs = Factor(), rhs;
    token op;
    if(lhs.error !=  ERR_NONE) {
        return lhs;
    }
    for(op = next_token(); op.type == TT_ASTERISK || op.type == TT_SLASH; op = next_token() ) { 
        rhs = Factor();
#ifdef DEBUG_1
        print_result("Term:lhs:", lhs);
        printf("Term:op:%d\n", op.type);
        print_result("Term:rhs:", rhs);
#endif
        if(rhs.error != ERR_NONE) {
            return rhs;
        }
        if(op.type == TT_ASTERISK) {
            lhs.value *= rhs.value;
        }
        else if(op.type == TT_SLASH) {
            if(rhs.value != 0) {
                lhs.value /= rhs.value;
            }
            else {
                return make_result(ERR_DIVISION_BY_ZERO, 0); 
            }
        }
        else {
            return make_result(ERR_UNEXPECTED_TOKEN, 0);
        }
    }
    rollback();
    return make_result(ERR_NONE, lhs.value);
}
Exemple #5
0
 void Polynomial<Degree>::getSolutions(const double& c,std::vector<double>& roots,const double& EPS) const {
   double r[4][2];
   int rCount=0;
   roots.clear();
   switch(Degree){
     case 1:
       rCount=Factor(coefficients[1],coefficients[0]-c,r,EPS);
       break;
     case 2:
       rCount=Factor(coefficients[2],coefficients[1],coefficients[0]-c,r,EPS);
       break;
     case 3:
       rCount=Factor(coefficients[3],coefficients[2],coefficients[1],coefficients[0]-c,r,EPS);
       break;
       //	case 4:
       //		rCount=Factor(coefficients[4],coefficients[3],coefficients[2],coefficients[1],coefficients[0]-c,r,EPS);
       //		break;
     default:
       printf("Can't solve polynomial of degree: %d\n",Degree);
   }
   for(int i=0;i<rCount;i++){
     if(fabs(r[i][1])<=EPS){
       roots.push_back(r[i][0]);
       //printf("%d] %f\t%f\n",i,r[i][0],(*this)(r[i][0])-c);
     }
   }
 }
Exemple #6
0
void HAK::construct() {
    // Create outer beliefs
    if( props.verbose >= 3 )
        cerr << "Constructing outer beliefs" << endl;
    _Qa.clear();
    _Qa.reserve(nrORs());
    for( size_t alpha = 0; alpha < nrORs(); alpha++ )
        _Qa.push_back( Factor( OR(alpha) ) );

    // Create inner beliefs
    if( props.verbose >= 3 )
        cerr << "Constructing inner beliefs" << endl;
    _Qb.clear();
    _Qb.reserve(nrIRs());
    for( size_t beta = 0; beta < nrIRs(); beta++ )
        _Qb.push_back( Factor( IR(beta) ) );

    // Create messages
    if( props.verbose >= 3 )
        cerr << "Constructing messages" << endl;
    _muab.clear();
    _muab.reserve( nrORs() );
    _muba.clear();
    _muba.reserve( nrORs() );
    for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
        _muab.push_back( vector<Factor>() );
        _muba.push_back( vector<Factor>() );
        _muab[alpha].reserve( nbOR(alpha).size() );
        _muba[alpha].reserve( nbOR(alpha).size() );
        foreach( const Neighbor &beta, nbOR(alpha) ) {
            _muab[alpha].push_back( Factor( IR(beta) ) );
            _muba[alpha].push_back( Factor( IR(beta) ) );
        }
    }
bool syntaxparser::TermPrime(){
	bool bTermPrime = false;
	if (lexeme == "*"){
		print();
		cout<<endl;
		Lexer();
		if(displayFlag){
			cout << "<TermPrime> ::= *<Factor><TermPrime>" << endl;
			printproduction("<TermPrime> ::= *<Factor><TermPrime>");
		}
		Factor();
		project3.gen_inst("MUL","-999");

		string type1, type2;

			type1 = project3.returnSymbolType(2);
			type2 = project3.returnSymbolType(3);

			if(type1 == "boolean")
				error("Cannot perform '*' on boolean");
			if (type2 == "boolean")
				error("Cannot perform '*' on boolean");

		TermPrime();	
		bTermPrime = true;		
	}
	else if (lexeme == "/"){
		print();
		cout<<endl;
		Lexer();
		if(displayFlag){
			cout << "<TermPrime> ::= /<Term><FactorPrime>" << endl;
			printproduction("<TermPrime> ::= /<Term><FactorPrime>");
		}
		bTermPrime = true;
		Factor();
		project3.gen_inst("DIV", "-999");

		string type1, type2;

			type1 = project3.returnSymbolType(2);
			type2 = project3.returnSymbolType(3);

			if(type1 == "boolean")
				error("Cannot perform '/' on boolean");
			if (type2 == "boolean")
				error("Cannot perform '/' on boolean");

		TermPrime();
	}
	else{
		bTermPrime = true;
		if(displayFlag){
			cout << "<TermPrime> ::= epsilon" << endl;
			printproduction("<TermPrime> ::= epsilon");
		}
	}
	return bTermPrime;
}
Exemple #8
0
// Solution taken from: http://mathworld.wolfram.com/QuarticEquation.html
// and http://www.csit.fsu.edu/~burkardt/f_src/subpak/subpak.f90
int Factor(double a4,double a3,double a2,double a1,double a0,double roots[4][2],const double& EPS){
	double R[2],D[2],E[2],R2[2];

	if(fabs(a4)<EPS){return Factor(a3,a2,a1,a0,roots,EPS);}
	a3/=a4;
	a2/=a4;
	a1/=a4;
	a0/=a4;

	Factor(1.0,-a2,a3*a1-4.0*a0,-a3*a3*a0+4.0*a2*a0-a1*a1,roots,EPS);

	R2[0]=a3*a3/4.0-a2+roots[0][0];
	R2[1]=0;
	Sqrt(R2,R);
	if(fabs(R[0])>10e-8){
		double temp1[2],temp2[2];
		double p1[2],p2[2];

		p1[0]=a3*a3*0.75-2.0*a2-R2[0];
		p1[1]=0;

		temp2[0]=((4.0*a3*a2-8.0*a1-a3*a3*a3)/4.0);
		temp2[1]=0;
		Divide(temp2,R,p2);

		Add     (p1,p2,temp1);
		Subtract(p1,p2,temp2);

		Sqrt(temp1,D);
		Sqrt(temp2,E);
	}
	else{
		R[0]=R[1]=0;
		double temp1[2],temp2[2];
		temp1[0]=roots[0][0]*roots[0][0]-4.0*a0;
		temp1[1]=0;
		Sqrt(temp1,temp2);
		temp1[0]=a3*a3*0.75-2.0*a2+2.0*temp2[0];
		temp1[1]=                  2.0*temp2[1];
		Sqrt(temp1,D);
		temp1[0]=a3*a3*0.75-2.0*a2-2.0*temp2[0];
		temp1[1]=                 -2.0*temp2[1];
		Sqrt(temp1,E);
	}

	roots[0][0]=-a3/4.0+R[0]/2.0+D[0]/2.0;
	roots[0][1]=        R[1]/2.0+D[1]/2.0;

	roots[1][0]=-a3/4.0+R[0]/2.0-D[0]/2.0;
	roots[1][1]=        R[1]/2.0-D[1]/2.0;

	roots[2][0]=-a3/4.0-R[0]/2.0+E[0]/2.0;
	roots[2][1]=       -R[1]/2.0+E[1]/2.0;

	roots[3][0]=-a3/4.0-R[0]/2.0-E[0]/2.0;
	roots[3][1]=       -R[1]/2.0-E[1]/2.0;
	return 4;
}
void Term()
{
	Factor();
	while(!strcmp(string[TokenCounter],"*"))
	{
		MulOp();
		Factor();
	}
}
Exemple #10
0
Factor LC::belief (const VarSet &ns) const {
    if( ns.size() == 0 )
        return Factor();
    else if( ns.size() == 1 )
        return beliefV( findVar( *(ns.begin()) ) );
    else {
        DAI_THROW(BELIEF_NOT_AVAILABLE);
        return Factor();
    }
}
Exemple #11
0
void Parser::Term(int &type) {
    int type1, op;
    Factor(type);
    while (la->kind == 7 || la->kind == 8) {
        MulOp(op);
        Factor(type1);
        if (type != integer || type1 != integer)
            Err(L"integer type expected");
        gen->Emit(op);
    }
}
void FirstFactor() {
  switch(Look) {
    case '+': 
      Match('+');
      Factor();
      break;
    case '-':
      NegFactor();
      break;
    default: Factor();
  }
}
Exemple #13
0
// This code has been copied from bp.cpp, except where comments indicate TRWBP-specific behaviour
Prob TRWBP::calcIncomingMessageProduct( size_t I, bool without_i, size_t i ) const {
    Real c_I = Weight(I); // TRWBP: c_I

    Factor Fprod( factor(I) );
    Prob &prod = Fprod.p();
    if( props.logdomain ) {
        prod.takeLog();
        prod /= c_I; // TRWBP
    } else
        prod ^= (1.0 / c_I); // TRWBP

    // Calculate product of incoming messages and factor I
    bforeach( const Neighbor &j, nbF(I) )
        if( !(without_i && (j == i)) ) {
            const Var &v_j = var(j);
            // prod_j will be the product of messages coming into j
            // TRWBP: corresponds to messages n_jI
            Prob prod_j( v_j.states(), props.logdomain ? 0.0 : 1.0 );
            bforeach( const Neighbor &J, nbV(j) ) {
                Real c_J = Weight(J);  // TRWBP
                if( J != I ) { // for all J in nb(j) \ I
                    if( props.logdomain )
                        prod_j += message( j, J.iter ) * c_J;
                    else
                        prod_j *= message( j, J.iter ) ^ c_J;
                } else if( c_J != 1.0 ) { // TRWBP: multiply by m_Ij^(c_I-1)
                    if( props.logdomain )
                        prod_j += message( j, J.iter ) * (c_J - 1.0);
                    else
                        prod_j *= message( j, J.iter ) ^ (c_J - 1.0);
                }
            }

            // multiply prod with prod_j
            if( !DAI_TRWBP_FAST ) {
                // UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION
                if( props.logdomain )
                    Fprod += Factor( v_j, prod_j );
                else
                    Fprod *= Factor( v_j, prod_j );
            } else {
                // OPTIMIZED VERSION
                size_t _I = j.dual;
                // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
                const ind_t &ind = index(j, _I);

                for( size_t r = 0; r < prod.size(); ++r )
                    if( props.logdomain )
                        prod.set( r, prod[r] + prod_j[ind[r]] );
                    else
                        prod.set( r, prod[r] * prod_j[ind[r]] );
            }
        }
Exemple #14
0
Expr *TermPrimed(Expr *du)
{
   switch (Symb.type) {
   case TIMES:
      Symb = readLexem();
      return TermPrimed(new Bop(Times, du, Factor()));
   case DIVIDE:
      Symb = readLexem();
      return ExpressionPrimed(new Bop(Divide, du, Factor()));
   default:
      return du;
   }
}
Exemple #15
0
void CParser::Term2()
{
	Factor();
	while (true)
	{
		switch (mLookahead)
		{
			case RAISE: Match(RAISE); Factor(); AddToken(opRaise); break;
			case '^': Match('^'); Factor(); AddToken(opRaise); break;
			default: return;
		}
	}
} // CParser::Term2
void ExactInf::construct() {
    // clear variable beliefs and reserve space
    _beliefsV.clear();
    _beliefsV.reserve( nrVars() );
    for( size_t i = 0; i < nrVars(); i++ )
        _beliefsV.push_back( Factor( var(i) ) );

    // clear factor beliefs and reserve space
    _beliefsF.clear();
    _beliefsF.reserve( nrFactors() );
    for( size_t I = 0; I < nrFactors(); I++ )
        _beliefsF.push_back( Factor( factor(I).vars() ) );
}
Exemple #17
0
TreeNode* Parser::signedFactor()
{
	// see if there is a tokPlus, tokMinus or tokNot infront of the factor
	TreeNode* node;
	switch (currentToken.type)
	{
		case tokPlus:
			matchToken(tokPlus);
			return Factor();
			break;

		case tokMinus:
			preservedToken = currentToken;
			matchToken(tokMinus);
			node = Factor();
			if (node->getType() == constantNode)
			{
				// in case of just a constant (-3) situation
				Value num = node->getValue();
				num.setNumber( -num.Number() );
				node->setValue(num);
				return node;
			}
			else
			{
				// in case of a variable or other situation (-a)
				TreeNode* minus = new TreeNode(preservedToken, minusNode);
				minus->appendChild(node);
				return minus;
			}
			break;

		case tokNot:
			preservedToken = currentToken;
			matchToken(tokNot);
			node = Factor();
			{ // extra scope needed to localize not_Node
				TreeNode* not_Node = new TreeNode(preservedToken, notNode);
				not_Node->appendChild(node);
				return not_Node;
			}
			break;

		default:
			// fall-through safety
			return Factor();
			break;
	}
}
Exemple #18
0
string Parser::Term() {

    _message.print(DBUG, "PARSER: In Term()\n");

    //Factor, { ( “*” | ”/” | “%” ), Factor }

    static tokenType firstSet[] = {SYM_PLUS, SYM_MINUS, SYM_NOT, SYM_OPEN, LIT_INT, LIT_FLOAT, LIT_STR, TOK_IDENT, (tokenType) - 1};

    static tokenType followSet[] = {SYM_PLUS, SYM_MINUS, SYM_NOT, SYM_LESS_EQ, SYM_LESS, SYM_GREATER_EQ, SYM_GREATER, SYM_EQUAL, SYM_NOT_EQ, SYM_AND, SYM_OR, SYM_ASSIGN, SYM_SEMICOLON, SYM_OPEN, SYM_SQ_OPEN, SYM_COMMA, SYM_CLOSE, (tokenType) - 1};

    string type, type1;

    if ( synchronized(firstSet, followSet, "Expected Term") ) {

        type = Factor();

        while ( _lookAhead.getTokenType() == SYM_MUL ||
                _lookAhead.getTokenType() == SYM_DIV ||
                _lookAhead.getTokenType() == SYM_MOD ) {
            bool isModOperation = false;
            if ( _lookAhead.getTokenType() == SYM_MUL) {
                match(SYM_MUL);
            } else if(_lookAhead.getTokenType() == SYM_DIV) {
                match(SYM_DIV);
            } else if(_lookAhead.getTokenType() == SYM_MOD) {
                match(SYM_MOD);
                isModOperation = true;
            }

            type1 = Factor();

            if((type == "f" && type1 == "i") ||
                    (type == "f" && type1 == "f") ||
                    (type == "i" && type1 == "f")) {
                type = "f";
                if (isModOperation) {
                    type = "i";
                }
            } else if(type == "i" && type1 == "i") {
                type = "i";
            } else {
                _message.print(ERROR, "SEMANTIC-ANALYZER: Semantic issue on line: %i col: %i. Incompatible operation", _lookAhead.getRow() , _lookAhead.getCol());
            }
        }
    }
    _message.print(DBUG, "PARSER: End of Term()\n");
    return type;
}
Exemple #19
0
Real LC::CalcCavityDist (size_t i, const std::string &name, const PropertySet &opts) {
    Factor Bi;
    Real maxdiff = 0;

    if( props.verbose >= 2 )
        cerr << "Initing cavity " << var(i) << "(" << delta(i).size() << " vars, " << delta(i).nrStates() << " states)" << endl;

    if( props.cavity == Properties::CavityType::UNIFORM )
        Bi = Factor(delta(i));
    else {
        InfAlg *cav = newInfAlg( name, *this, opts );
        cav->makeCavity( i );

        if( props.cavity == Properties::CavityType::FULL )
            Bi = calcMarginal( *cav, cav->fg().delta(i), props.reinit );
        else if( props.cavity == Properties::CavityType::PAIR ) {
            vector<Factor> pairbeliefs = calcPairBeliefs( *cav, cav->fg().delta(i), props.reinit, false );
            for( size_t ij = 0; ij < pairbeliefs.size(); ij++ )
                Bi *= pairbeliefs[ij];
        } else if( props.cavity == Properties::CavityType::PAIR2 ) {
            vector<Factor> pairbeliefs = calcPairBeliefs( *cav, cav->fg().delta(i), props.reinit, true );
            for( size_t ij = 0; ij < pairbeliefs.size(); ij++ )
                Bi *= pairbeliefs[ij];
        }
        maxdiff = cav->maxDiff();
        delete cav;
    }
    Bi.normalize();
    _cavitydists[i] = Bi;

    return maxdiff;
}
Exemple #20
0
bool Parser::TPrime()
{
	bool div = false;
	if ("*" == lex) {
		L.getTokLex(tok,lex);
	} else if ("/" == lex) {
		div = true;
		L.getTokLex(tok,lex);
	} else {
//		std::cout << "TPrime => null\n";
		return true;
	}
	
	if (!Factor()) return false;
	
	if (!TPrime()) return false;

	if (div) {
		assembly.push_back(icode(a_line, "DIV"));
		++a_line;
	} else {
		assembly.push_back(icode(a_line, "MUL"));
		++a_line;
	}

//	if (div) {
//		std::cout << "TPrime => / Factor TPrime\n";
//	} else {
//		std::cout << "TPrime => * Factor TPrime\n";
//	}
	return true;
}
Exemple #21
0
void FactorGraph::makeCavity( size_t i, bool backup ) {
  // fills all Factors that include var(i) with ones
  std::map<size_t,Factor> newFacs;
  bforeach( const dai::Neighbor &I, nbV(i) ) // for all neighboring factors I of i
    newFacs[I] = Factor(factor(I).nodes());
  setFactors( newFacs, backup );
}
Exemple #22
0
/*b*/
static double ap_carr_b(int i,int n,double S,double K,double T,double r,double divid,double sigma,double s[10])
{
  int j,k,l;
  double S1,S2,S3;
  double d=ap_carr_D(divid,T,n);
  double epsilon=ap_carr_epsilon(r,divid,sigma,T,n);
  double gamma_carr=ap_carr_gamma(r,divid,sigma);
  double delta=ap_carr_delta(T,n);
  double R1=ap_carr_R(r,T,n);
  double q1=ap_carr_q(r,divid,sigma,T,n);
  double p1=ap_carr_p(r,divid,sigma,T,n);
  double q_1=ap_carr_qhat(r,divid,sigma,T,n);
  double p_1=ap_carr_phat(r,divid,sigma,T,n);
  
  S1=0.;
  for(j=1;j<=n-i+1;j++)
    {
      S2=0.;
      for(k=0;k<=j-1;k++)
	{
	  S3=0.;
	  for(l=0;l<=j-k-1;l++)
	    {
	      S3+=Combi(j-1+l,j-1)*(pow_int(q1*R1,j)*pow_int(p1,k+l)*K*r-pow_int(q_1*d,j)*pow_int(p_1,k+l)*s[n-j+1]*divid)*delta;
							
							
	    }
	  S2+=(pow_int(2*epsilon*log(S/s[n-j+1]),k)/Factor(k))*S3;
	}
      S1+=pow(S/s[n-j+1],gamma_carr-epsilon)*S2;
			
    }
  
  return S1;
}
Exemple #23
0
vector<Factor> Factor::readUai10(std::istream& is) {
  size_t nvar, ncliques, csize, v, nval;
  char* st; st = new char[20];
  is >> st;
 
  if ( strcasecmp(st,"MARKOV") ) 
    throw std::runtime_error("Only UAI-2010 Markov-format files are supported currently");

  is >> nvar;
  vector<size_t> dims(nvar);
  for (size_t i=0;i<nvar;i++) { is>>dims[i]; if (dims[i] == 0) dims[i]=1; }
  
  is >> ncliques;
  std::vector<mex::vector<Var> > cliques(ncliques);
  std::vector<VarSet > sets(ncliques);
  for (size_t i=0;i<ncliques;i++) {
    is >> csize;
    cliques[i].reserve(csize);
    for (size_t j=0;j<csize;j++) { 
      is>>v; Var V(v,dims[v]);
      cliques[i].push_back(V); 
      sets[i] |= V;
    }   
  }
  
  //vector<vector<double> > tables(ncliques);
  vector<Factor> tables(ncliques);
  for (size_t i=0;i<ncliques;i++) {
    is >> nval;
    assert(nval == sets[i].nrStates());
    tables[i] = Factor(sets[i],0.0);        // preallocate memory and convert from given order, bigEndian
		if (nval==1) { is>>tables[i][0]; continue; }  // special case for constant factor
    permuteIndex pi( cliques[i], true); pi=pi.inverse();   // to our order
    for (size_t j=0;j<nval;j++) is>>tables[i][pi.convert(j)];
  }
Exemple #24
0
      int
      Factor (double a2, double a1, double a0, double roots[2][2], const double& EPS)
      {
        double d;
        if (fabs (a2) <= EPS)
        {
          return Factor (a1, a0, roots, EPS);
        }

        d = a1 * a1 - 4 * a0 * a2;
        a1 /= (2 * a2);
        if (d < 0)
        {
          d = sqrt (-d) / (2 * a2);
          roots[0][0] = roots[1][0] = -a1;
          roots[0][1] = -d;
          roots[1][1] = d;
        }
        else
        {
          d = sqrt (d) / (2 * a2);
          roots[0][1] = roots[1][1] = 0;
          roots[0][0] = -a1 - d;
          roots[1][0] = -a1 + d;
        }
        return 2;
      }
// <math_signed_factor> ::= [-] <math_factor>
void SignedFactor(CPU *cpu, Files file){
    const bool negate = Peek('-', file);
    if(negate) Match('-', file);
    Factor(cpu, file);
    if(negate)
        cpu->Negate();
}
void MF::construct() {
    // create beliefs
    _beliefs.clear();
    _beliefs.reserve( nrVars() );
    for( size_t i = 0; i < nrVars(); ++i )
        _beliefs.push_back( Factor( var(i) ) );
}
Exemple #27
0
void
BayesBall::constructGraph (FactorGraph* fg) const
{
  const FacNodes& facNodes = fg_.facNodes();
  for (size_t i = 0; i < facNodes.size(); i++) {
    const BBNode* n = dag_.getNode (
        facNodes[i]->factor().argument (0));
    if (n->isMarkedAbove()) {
      fg->addFactor (facNodes[i]->factor());
    } else if (n->hasEvidence() && n->isVisited()) {
      VarIds varIds = { facNodes[i]->factor().argument (0) };
      Ranges ranges = { facNodes[i]->factor().range (0) };
      Params params (ranges[0], LogAware::noEvidence());
      params[n->getEvidence()] = LogAware::withEvidence();
      fg->addFactor (Factor (varIds, ranges, params));
    }
  }
  const VarNodes& varNodes = fg_.varNodes();
  for (size_t i = 0; i < varNodes.size(); i++) {
    if (varNodes[i]->hasEvidence()) {
      VarNode* vn = fg->getVarNode (varNodes[i]->varId());
      if (vn) {
        vn->setEvidence (varNodes[i]->getEvidence());
      }
    }
  }
}
Exemple #28
0
//   FFT implementation
void CFFT::Perform(complex * const Data, const unsigned int N,
                   const bool Inverse /* = false */) {
    const double pi = Inverse ? 3.14159265358979323846 : -3.14159265358979323846;
    //   Iteration through dyads, quadruples, octads and so on...
    for (unsigned int Step = 1; Step < N; Step <<= 1) {
        //   Jump to the next entry of the same transform factor
        const unsigned int Jump = Step << 1;
        //   Angle increment
        const double delta = pi / double(Step);
        //   Auxiliary sin(delta / 2)
        const double Sine = sin(delta * .5);
        //   Multiplier for trigonometric recurrence
        const complex Multiplier(-2. * Sine * Sine, sin(delta));
        //   Start value for transform factor, fi = 0
        complex Factor(1.);
        //   Iteration through groups of different transform factor
        for (unsigned int Group = 0; Group < Step; ++Group) {
            //   Iteration within group
            for (unsigned int Pair = Group; Pair < N; Pair += Jump) {
                //   Match position
                const unsigned int Match = Pair + Step;
                //   Second term of two-point transform
                const complex Product(Factor * Data[Match]);
                //   Transform for fi + pi
                Data[Match] = Data[Pair] - Product;
                //   Transform for fi
                Data[Pair] += Product;
            }
            //   Successive transform factor via trigonometric recurrence
            Factor = Multiplier * Factor + Factor;
        }
    }
}
Exemple #29
0
FactorGraph*
CFactorGraph::getGroundFactorGraph (void) const
{
  FactorGraph* fg = new FactorGraph();
  for (unsigned i = 0; i < varClusters_.size(); i++) {
    VarNode* var = varClusters_[i]->getGroundVarNodes()[0];
    VarNode* newVar = new VarNode (var);
    varClusters_[i]->setRepresentativeVariable (newVar);
    fg->addVarNode (newVar);
  }

  for (unsigned i = 0; i < facClusters_.size(); i++) {
    const VarClusters& myVarClusters = facClusters_[i]->getVarClusters();
   Vars myGroundVars;
    myGroundVars.reserve (myVarClusters.size());
    for (unsigned j = 0; j < myVarClusters.size(); j++) {
      VarNode* v = myVarClusters[j]->getRepresentativeVariable();
      myGroundVars.push_back (v);
    }
    FacNode* fn = new FacNode (Factor (myGroundVars,
        facClusters_[i]->getGroundFactors()[0]->factor().params()));
    facClusters_[i]->setRepresentativeFactor (fn);
    fg->addFacNode (fn);
    for (unsigned j = 0; j < myGroundVars.size(); j++) {
      fg->addEdge (static_cast<VarNode*> (myGroundVars[j]), fn);
    }
  }
  return fg;
}
Exemple #30
0
/*Calleuro_n*/
static double Call_euro_n(double S, double K, double T, double r, double divid, double sigma,int n)
{
  double d=ap_carr_D(divid,T,n);
  double epsilon=ap_carr_epsilon(r,divid,sigma,T,n);
  double gamma_carr=ap_carr_gamma(r,divid,sigma);
  double R1=ap_carr_R(r,T,n);
  double q1=ap_carr_q(r,divid,sigma,T,n);
  double p1=ap_carr_p(r,divid,sigma,T,n);
  double q_1=ap_carr_qhat(r,divid,sigma,T,n);
  double p_1=ap_carr_phat(r,divid,sigma,T,n);
  double S1,S2;
  int k,l;

  if (S>K)
    {
      return S*pow_int(d,n)-K*pow_int(R1,n)+Put_euro_n(S,K,T,r,divid,sigma,n);
    } else {
    S1=0;
    for (k=0;k<=n-1;k++)
      {
	S2=0;
	for(l=0;l<=n-k-1;l++)
	  {
	    S2+=Combi(n-1+l,n-1)*(K*pow_int(d,n)*pow_int(q_1,k+l)*pow_int(p_1,n)-K*pow_int(R1,n)*pow_int(q1,k+l)*pow_int(p1,n));
	  }
	S1+=(pow_int(2*epsilon*log(K/S),k)/Factor(k))*S2;
      }
    return pow(S/K,gamma_carr+epsilon)*S1;
  }
}