void BP::construct() { // create edge properties _edges.clear(); _edges.reserve( nrVars() ); _edge2lut.clear(); if( props.updates == Properties::UpdateType::SEQMAX ) _edge2lut.reserve( nrVars() ); for( size_t i = 0; i < nrVars(); ++i ) { _edges.push_back( vector<EdgeProp>() ); _edges[i].reserve( nbV(i).size() ); if( props.updates == Properties::UpdateType::SEQMAX ) { _edge2lut.push_back( vector<LutType::iterator>() ); _edge2lut[i].reserve( nbV(i).size() ); } foreach( const Neighbor &I, nbV(i) ) { EdgeProp newEP; newEP.message = Prob( var(i).states() ); newEP.newMessage = Prob( var(i).states() ); if( DAI_BP_FAST ) { newEP.index.reserve( factor(I).nrStates() ); for( IndexFor k( var(i), factor(I).vars() ); k.valid(); ++k ) newEP.index.push_back( k ); } newEP.residual = 0.0; _edges[i].push_back( newEP ); if( props.updates == Properties::UpdateType::SEQMAX ) _edge2lut[i].push_back( _lut.insert( make_pair( newEP.residual, make_pair( i, _edges[i].size() - 1 ))) ); } }
void CBP::construct() { // prepare datastructures for compression for (size_t i=0; i<nrVars(); i++) { _gndVarToSuperVar[i] = i; } for (size_t i=0; i<nrFactors(); i++) { _gndFacToSuperFac[i] = i; } // create edge properties _edges.clear(); _edges.reserve( nrVars() ); for( size_t i = 0; i < nrVars(); ++i ) { _edges.push_back( vector<EdgeProp>() ); _edges[i].reserve( nbV(i).size() ); foreach( const Neighbor &I, nbV(i) ) { EdgeProp newEP; size_t edgeCount = factor(I).counts()[I.dual].size(); newEP.message = vector<Prob>(edgeCount,Prob( var(i).states() )); newEP.newMessage = vector<Prob>(edgeCount,Prob( var(i).states() )); newEP.count = vector<int>(edgeCount); newEP.index = vector<ind_t>(edgeCount); newEP.nrPos = edgeCount; // simulate orginal varSet with possibly more variables, must ensure that the number of variables is equal to number of ground variables VarSet gndVarSet; size_t varCount = 0; foreach(const Neighbor &tmpVar, nbF(I)) { for(map<size_t, int>::const_iterator iter=factor(I).counts()[tmpVar.iter].begin(); iter!=factor(I).counts()[tmpVar.iter].end();iter++) { gndVarSet |= Var(varCount, var(tmpVar).states()); varCount++; } } varCount = 0; foreach(const Neighbor &tmpVar, nbF(I)) { size_t pos=0; for(map<size_t, int>::const_iterator iter=factor(I).counts()[tmpVar.iter].begin(); iter!=factor(I).counts()[tmpVar.iter].end();iter++,pos++) { if (tmpVar == i) { // assumes that counts are iterated in increases order of positions size_t sortedPos = factor(I).sigma()[(*iter).first]; newEP.count[pos] = (*iter).second; newEP.index[pos].reserve( factor(I).states() ); for( IndexFor k( Var(sortedPos, var(i).states()), gndVarSet ); k >= 0; ++k ) { newEP.index[pos].push_back( k ); } } varCount++; } } _edges[i].push_back( newEP ); }
void BcTest6(void) { enum { NUM_RECS = 2000, NUM_TRIALS = ONE_MILLION }; Bc t; VAR_LUMP(v, MAX_DATA); Key a[NUM_RECS]; u64 n = 0; u64 puts = 0; u64 deletes = 0; printf("%s\n", __FUNCTION__); init_twister(37); BcInit(&t, KEY_LEN); for (u64 j = 0; j < NUM_TRIALS; j++) { Key key; bool found; if (Prob(((NUM_RECS - n) * 100) / NUM_RECS)) { aver(n < NUM_RECS); key = IntKey(twister_urand(10000)); BcGet(&t, key.s, &found); if (!found) { a[n++] = key; RandLump(v); BcPut(&t, key.s, v); ++puts; } if (0 || Prob(2)) Audit("Put", &t, a, n, j); } else { aver(0 < n); u64 i = twister_urand(n); key = a[i]; BcGet(&t, key.s, &found); if (!found) { BcDump("not found", &t); fatal("didn't find %s %llu %llu", key.s, puts, deletes); } BcDelete(&t, key.s); BcGet(&t, key.s, &found); if (found) { BcDump("found", &t); fatal("found %llu", key); } a[i] = a[--n]; ++deletes; if (0 || Prob(2)) Audit("Delete", &t, a, n, j); } } BcDoAudit(&t); printf("\tputs=%llu deletes=%llu\n", puts, deletes); BcReport(__FUNCTION__, BcDoAudit(&t)); BcDump(__FUNCTION__, &t); BcFree(&t); }
double Prob(DdNode *node ) /* compute the probability of the expression rooted at node nodes is used to store nodes for which the probability has alread been computed so that it is not recomputed */ { int comp; int index; double res,resT,resF; double p; double * value_p; DdNode **key,*T,*F,*nodereg; double *rp; comp=Cudd_IsComplement(node); if (Cudd_IsConstant(node)) { if (comp) return 0.0; else return 1.0; } else { nodereg=Cudd_Regular(node); value_p=g_hash_table_lookup(nodes,&node); if (value_p!=NULL) { if (comp) return 1-*value_p; else return *value_p; } else { index=Cudd_NodeReadIndex(node); p=probs[index]; T = Cudd_T(node); F = Cudd_E(node); resT=Prob(T); resF=Prob(F); res=p*resT+(1-p)*resF; key=(DdNode **)malloc(sizeof(DdNode *)); *key=nodereg; rp=(double *)malloc(sizeof(double)); *rp=res; g_hash_table_insert(nodes, key, rp); if (comp) return 1-res; else return res; } } }
void BP_dual::regenerateBeliefs() { _beliefs.b1.clear(); _beliefs.b1.reserve(fg().nrVars()); _beliefs.Zb1.resize(fg().nrVars(), 1.0); _beliefs.b2.clear(); _beliefs.b2.reserve(fg().nrFactors()); _beliefs.Zb2.resize(fg().nrFactors(), 1.0); for( size_t i = 0; i < fg().nrVars(); i++ ) _beliefs.b1.push_back( Prob( fg().var(i).states() ) ); for( size_t I = 0; I < fg().nrFactors(); I++ ) _beliefs.b2.push_back( Prob( fg().factor(I).nrStates() ) ); }
void BP_dual::regenerateMessages() { size_t nv = fg().nrVars(); _msgs.Zn.resize(nv); _msgs.Zm.resize(nv); _msgs.m.resize(nv); _msgs.n.resize(nv); for( size_t i = 0; i < nv; i++ ) { size_t nvf = fg().nbV(i).size(); _msgs.Zn[i].resize(nvf, 1.0); _msgs.Zm[i].resize(nvf, 1.0); size_t states = fg().var(i).states(); _msgs.n[i].resize(nvf, Prob(states)); _msgs.m[i].resize(nvf, Prob(states)); } }
double Prob(DdNode *node, int comp_par) /* compute the probability of the expression rooted at node. table is used to store nodeB for which the probability has alread been computed so that it is not recomputed */ { int index, mVarIndex, comp, pos; variable v; double res; double p, pt, pf, BChild0, BChild1; double *value_p; DdNode *nodekey, *T, *F; comp = Cudd_IsComplement(node); comp = (comp && !comp_par) || (!comp && comp_par); if (Cudd_IsConstant(node)) { if (comp) return 0.0; else return 1.0; } else { nodekey = Cudd_Regular(node); value_p = get_value(table, nodekey); if (value_p != NULL) return *value_p; else { index = Cudd_NodeReadIndex(node); // Returns the index of the node. The // node pointer can be either regular or // complemented. // The index field holds the name of the variable that labels the node. // The index of a variable is a permanent attribute that reflects the // order of creation. p = probs_ex[ex][index]; T = Cudd_T(node); F = Cudd_E(node); pf = Prob(F, comp); pt = Prob(T, comp); BChild0 = pf * (1 - p); BChild1 = pt * p; mVarIndex = bVar2mVar_ex[ex][index]; v = vars_ex[ex][mVarIndex]; pos = index - v.firstBoolVar; res = BChild0 + BChild1; add_node(table, nodekey, res); return res; } } }
Prob readProb(uint32_t code, uint32_t totalProb) { uint64_t range = uint64_t(upper - lower) + 1; uint64_t unscaled = uint64_t(code - lower) + 1; unscaled = unscaled*totalProb; unscaled--; unscaled /= range; return Prob(unscaled); }
ParameterEstimation* CondProbEstimation::factory( const PropertySet &p ) { size_t target_dimension = p.getStringAs<size_t>("target_dim"); size_t total_dimension = p.getStringAs<size_t>("total_dim"); Real pseudo_count = 1; if( p.hasKey("pseudo_count") ) pseudo_count = p.getStringAs<Real>("pseudo_count"); return new CondProbEstimation( target_dimension, Prob( total_dimension, pseudo_count ) ); }
double ret_prob(extmanager MyManager, DdNode *bdd) { double prob; /* dividend is a global variable used by my_hash it is equal to an unsigned int with binary representation 11..1 */ prob = Prob(MyManager, bdd, Cudd_IsComplement(bdd)); return prob; }
double ret_probc(int node) { DdNode * node_in; double out; node_in=(DdNode *) node; nodes=g_hash_table_new(my_hash,my_equal); out=Prob(node_in); g_hash_table_foreach (nodes,dealloc,NULL); g_hash_table_destroy(nodes); return out; }
void BaTest6(void) { enum { NUM_RECS = 2000, NUM_TRIALS = ONE_MILLION }; Ba t; u64 a[NUM_RECS]; u64 n = 0; u64 puts = 0; u64 deletes = 0; printf("%s\n", __FUNCTION__); init_twister(17); BaInit(&t); for (u64 j = 0; j < NUM_TRIALS; j++) { u64 key; bool found; if (Prob(((NUM_RECS - n) * 100) / NUM_RECS)) { aver(n < NUM_RECS); key = twister_urand(10000); BaGet(&t, key, &found); if (!found) { a[n++] = key; BaPut(&t, key); ++puts; } if (0 || twister_urand(100) < 2) Audit("Put", &t, a, n, j); } else { aver(0 < n); u64 i = twister_urand(n); key = a[i]; BaGet(&t, key, &found); if (!found) { BaDump("not found", &t); fatal("didn't find %llu %llu %llu", key, puts, deletes); } BaDelete(&t, key); BaGet(&t, key, &found); if (found) { BaDump("found", &t); fatal("found %llu", key); } a[i] = a[--n]; ++deletes; if (0 || twister_urand(100) < 2) Audit("Delete", &t, a, n, j); } } BaDoAudit(&t); printf("\tputs=%llu deletes=%llu\n", puts, deletes); BaReportAudit(__FUNCTION__, BaDoAudit(&t)); BaDump(__FUNCTION__, &t); }
void BcTest8(void) { /* * Extensive test of all functions. Want to cover most code paths. * 1. Dynamically adjust number of records by a factor of 100. * 2. Randomly pick operations. * 3. Test iteration intermixed with other operations. */ enum { MAX_RECS = 100 * ONE_THOUSAND }; Bc t; u64 key; u64 keys[MAX_RECS]; u64 numKeys = 0; u64 numPuts = 0; u64 numDeletes = 0; VAR_LUMP(v, MAX_DATA); init_twister(37); BcInit(&t, KEY_LEN); RandLump(v); for (u64 i = 0; i < 10; i++) { u64 maxKeys = twister_urand(MAX_RECS); PRu(maxKeys); while (numKeys != maxKeys) { aver(numKeys <= MAX_RECS); if (numKeys < maxKeys && Prob(75)) { key = twister_random(); keys[numKeys++] = key; BcPut(&t, IntKey(key).s, v); ++numPuts; } else { if (numKeys) { u64 j = twister_urand(numKeys); key = keys[j]; keys[j] = keys[--numKeys]; BcDelete(&t, IntKey(key).s); ++numDeletes; } } } } aver(numPuts - numDeletes == numKeys); PRu(numPuts); PRu(numDeletes); PRu(numKeys); BcReport(__FUNCTION__, BcDoAudit(&t)); }
void ValidKMerGenerator<kK>::Next() { if (pos_ + kK > end_) { has_more_ = false; } else if (first || !is_nucl(seq_[pos_ + kK - 1])) { // in this case we have to look for new k-mer correct_probability_ = 1.0; uint32_t start_hypothesis = (uint32_t)pos_; uint32_t i = (uint32_t)pos_; for (; i < len_; ++i) { if (i == kK + start_hypothesis) { break; } if (qual_) correct_probability_ *= Prob(GetQual(i)); if (!is_nucl(seq_[i])) { start_hypothesis = i + 1; correct_probability_ = 1.0; } } if (i == kK + start_hypothesis) { kmer_ = Seq<kK>(seq_ + start_hypothesis, 0, kK, /* raw */ true); pos_ = start_hypothesis + 1; } else { has_more_ = false; } } else { // good case we can just shift our previous answer kmer_ = kmer_ << seq_[pos_ + kK - 1]; if (qual_) { correct_probability_ *= Prob(GetQual((uint32_t)pos_ + kK - 1)); correct_probability_ /= Prob(GetQual((uint32_t)pos_ - 1)); } ++pos_; } first = false; }
double ProbBool(extmanager MyManager, DdNode *node, int bits, int nBit,int posBVar,variable v, int comp) /* explores a group of binary variables making up the multivalued variable v */ { DdNode *T,*F; double p,res; double * probs; int index; probs=v.probabilities; if (nBit==0) { if (bits>=v.nVal) { return 0.0; } else { p=probs[bits]; res=p*Prob(MyManager,node,comp); return res; } } else { index=Cudd_NodeReadIndex(node); if (correctPosition(index,v,posBVar)) { T = Cudd_T(node); F = Cudd_E(node); bits=bits<<1; res=ProbBool(MyManager,T,bits+1,nBit-1,posBVar+1,v,comp); comp=(!comp && Cudd_IsComplement(F)) || (comp && !Cudd_IsComplement(F)); res=res+ ProbBool(MyManager,F,bits,nBit-1,posBVar+1,v,comp); return res; } else { bits=bits<<1; res=ProbBool(MyManager,node,bits+1,nBit-1,posBVar+1,v,comp); res=res+ ProbBool(MyManager,node,bits,nBit-1,posBVar+1,v,comp); return res; } } }
static YAP_Bool ret_prob(void) { YAP_Term arg1, arg2, out; DdNode *node; arg1 = YAP_ARG1; arg2 = YAP_ARG2; node = (DdNode *)YAP_IntOfTerm(arg1); if (!Cudd_IsConstant(node)) { table = init_table(boolVars_ex[ex]); out = YAP_MkFloatTerm(Prob(node, 0)); destroy_table(table, boolVars_ex[ex]); } else { if (node == Cudd_ReadOne(mgr_ex[ex])) out = YAP_MkFloatTerm(1.0); else out = YAP_MkFloatTerm(0.0); } return (YAP_Unify(out, arg2)); }
void testEucQuadratic(double *M, integer dim, double *X, double *Xopt) { // choose a random seed unsigned tt = (unsigned)time(NULL); std::cout << "tt:" << tt << std::endl; tt = 0; init_genrand(tt); // Obtain an initial iterate EucVariable EucX(dim, 1); if (X == nullptr) { EucX.RandInManifold(); } else { double *EucXptr = EucX.ObtainWriteEntireData(); for (integer i = 0; i < dim; i++) EucXptr[i] = X[i]; } // Define the manifold Euclidean Domain(dim); // Define the problem EucQuadratic Prob(M, dim); Prob.SetDomain(&Domain); // test RSD std::cout << "********************************Check all line search algorithm in RSD*****************************************" << std::endl; for (integer i = 0; i < LSALGOLENGTH; i++) { RSD *RSDsolver = new RSD(&Prob, &EucX); RSDsolver->LineSearch_LS = static_cast<LSAlgo> (i); RSDsolver->DEBUG = FINALRESULT; RSDsolver->CheckParams(); RSDsolver->Run(); delete RSDsolver; } // test RNewton std::cout << "********************************Check all line search algorithm in RNewton*************************************" << std::endl; for (integer i = 0; i < LSALGOLENGTH; i++) { RNewton *RNewtonsolver = new RNewton(&Prob, &EucX); RNewtonsolver->LineSearch_LS = static_cast<LSAlgo> (i); RNewtonsolver->DEBUG = FINALRESULT; RNewtonsolver->CheckParams(); RNewtonsolver->Run(); delete RNewtonsolver; } // test RCG std::cout << "********************************Check all Formulas in RCG*************************************" << std::endl; for (integer i = 0; i < RCGMETHODSLENGTH; i++) { RCG *RCGsolver = new RCG(&Prob, &EucX); RCGsolver->RCGmethod = static_cast<RCGmethods> (i); RCGsolver->LineSearch_LS = STRONGWOLFE; RCGsolver->LS_beta = 0.1; RCGsolver->DEBUG = FINALRESULT; RCGsolver->CheckParams(); RCGsolver->Run(); delete RCGsolver; } // test RBroydenFamily std::cout << "********************************Check all line search algorithm in RBroydenFamily*************************************" << std::endl; for (integer i = 0; i < LSALGOLENGTH; i++) { RBroydenFamily *RBroydenFamilysolver = new RBroydenFamily(&Prob, &EucX); RBroydenFamilysolver->LineSearch_LS = static_cast<LSAlgo> (i); RBroydenFamilysolver->DEBUG = FINALRESULT; RBroydenFamilysolver->CheckParams(); RBroydenFamilysolver->Run(); delete RBroydenFamilysolver; } // test RWRBFGS std::cout << "********************************Check all line search algorithm in RWRBFGS*************************************" << std::endl; for (integer i = 0; i < LSALGOLENGTH; i++) { RWRBFGS *RWRBFGSsolver = new RWRBFGS(&Prob, &EucX); RWRBFGSsolver->LineSearch_LS = static_cast<LSAlgo> (i); RWRBFGSsolver->DEBUG = FINALRESULT; RWRBFGSsolver->CheckParams(); RWRBFGSsolver->Run(); delete RWRBFGSsolver; } // test RBFGS std::cout << "********************************Check all line search algorithm in RBFGS*************************************" << std::endl; for (integer i = 0; i < LSALGOLENGTH; i++) { RBFGS *RBFGSsolver = new RBFGS(&Prob, &EucX); RBFGSsolver->LineSearch_LS = static_cast<LSAlgo> (i); RBFGSsolver->DEBUG = FINALRESULT; RBFGSsolver->CheckParams(); RBFGSsolver->Run(); delete RBFGSsolver; } // test LRBFGS std::cout << "********************************Check all line search algorithm in LRBFGS*************************************" << std::endl; for (integer i = 0; i < LSALGOLENGTH; i++) { LRBFGS *LRBFGSsolver = new LRBFGS(&Prob, &EucX); LRBFGSsolver->LineSearch_LS = static_cast<LSAlgo> (i); LRBFGSsolver->DEBUG = FINALRESULT; LRBFGSsolver->CheckParams(); LRBFGSsolver->Run(); delete LRBFGSsolver; } std::cout << "********************************Check RTRSD*************************************" << std::endl; RTRSD RTRSDsolver(&Prob, &EucX); std::cout << std::endl; RTRSDsolver.DEBUG = FINALRESULT; RTRSDsolver.CheckParams(); RTRSDsolver.Run(); std::cout << "********************************Check RTRNewton*************************************" << std::endl; RTRNewton RTRNewtonsolver(&Prob, &EucX); std::cout << std::endl; RTRNewtonsolver.DEBUG = FINALRESULT; RTRNewtonsolver.CheckParams(); RTRNewtonsolver.Run(); std::cout << "********************************Check RTRSR1*************************************" << std::endl; RTRSR1 RTRSR1solver(&Prob, &EucX); std::cout << std::endl; RTRSR1solver.DEBUG = FINALRESULT; RTRSR1solver.CheckParams(); RTRSR1solver.Run(); std::cout << "********************************Check LRTRSR1*************************************" << std::endl; LRTRSR1 LRTRSR1solver(&Prob, &EucX); std::cout << std::endl; LRTRSR1solver.DEBUG = FINALRESULT; LRTRSR1solver.CheckParams(); LRTRSR1solver.Run(); // Check gradient and Hessian Prob.CheckGradHessian(&EucX); const Variable *xopt = RTRNewtonsolver.GetXopt(); Prob.CheckGradHessian(xopt); if (Xopt != nullptr) { const double *xoptptr = xopt->ObtainReadData(); for (integer i = 0; i < dim; i++) Xopt[i] = xoptptr[i]; } };
Real MR::calcCavityCorrelations() { Real md = 0.0; for( size_t i = 0; i < nrVars(); i++ ) { vector<Factor> pairq; if( props.inits == Properties::InitType::EXACT ) { JTree jtcav(*this, PropertySet()("updates", string("HUGIN"))("verbose", (size_t)0) ); jtcav.makeCavity( i ); pairq = calcPairBeliefs( jtcav, delta(i), false, true ); } else if( props.inits == Properties::InitType::CLAMPING ) { BP bpcav(*this, PropertySet()("updates", string("SEQMAX"))("tol", (Real)1.0e-9)("maxiter", (size_t)10000)("verbose", (size_t)0)("logdomain", false)); bpcav.makeCavity( i ); pairq = calcPairBeliefs( bpcav, delta(i), false, true ); md = std::max( md, bpcav.maxDiff() ); } else if( props.inits == Properties::InitType::RESPPROP ) { BP bpcav(*this, PropertySet()("updates", string("SEQMAX"))("tol", (Real)1.0e-9)("maxiter", (size_t)10000)("verbose", (size_t)0)("logdomain", false)); bpcav.makeCavity( i ); bpcav.makeCavity( i ); bpcav.init(); bpcav.run(); BBP bbp( &bpcav, PropertySet()("verbose",(size_t)0)("tol",(Real)1.0e-9)("maxiter",(size_t)10000)("damping",(Real)0.0)("updates",string("SEQ_MAX")) ); bforeach( const Neighbor &j, G.nb(i) ) { // Create weights for magnetization of some spin Prob p( 2, 0.0 ); p.set( 0, -1.0 ); p.set( 1, 1.0 ); // BBP cost function would be the magnetization of spin j vector<Prob> b1_adj; b1_adj.reserve( nrVars() ); for( size_t l = 0; l < nrVars(); l++ ) if( l == j ) b1_adj.push_back( p ); else b1_adj.push_back( Prob( 2, 0.0 ) ); bbp.init_V( b1_adj ); // run BBP to estimate adjoints bbp.run(); bforeach( const Neighbor &k, G.nb(i) ) { if( k != j ) cors[i][j.iter][k.iter] = (bbp.adj_psi_V(k)[1] - bbp.adj_psi_V(k)[0]); else cors[i][j.iter][k.iter] = 0.0; } } } if( props.inits != Properties::InitType::RESPPROP ) { for( size_t jk = 0; jk < pairq.size(); jk++ ) { VarSet::const_iterator kit = pairq[jk].vars().begin(); size_t j = findVar( *(kit) ); size_t k = findVar( *(++kit) ); pairq[jk].normalize(); Real cor = (pairq[jk][3] - pairq[jk][2] - pairq[jk][1] + pairq[jk][0]) - (pairq[jk][3] + pairq[jk][2] - pairq[jk][1] - pairq[jk][0]) * (pairq[jk][3] - pairq[jk][2] + pairq[jk][1] - pairq[jk][0]); size_t _j = G.findNb(i,j); size_t _k = G.findNb(i,k); cors[i][_j][_k] = cor; cors[i][_k][_j] = cor; } } }
int main(void) { // choose a random seed unsigned tt = (unsigned)time(NULL); init_genrand(tt); // size of the Stiefel manifold integer n = 12, p = 8, m = 6, q = 2; // Generate the matrices in the Brockett problem. double *B1 = new double[n * n * 2 + p * 2 + m * m + q]; double *B2 = B1 + n * n; double *B3 = B2 + n * n; double *D1 = B3 + m * m; double *D2 = D1 + p; double *D3 = D2 + p; for (integer i = 0; i < n; i++) { for (integer j = i; j < n; j++) { B1[i + j * n] = genrand_gaussian(); B1[j + i * n] = B1[i + j * n]; B2[i + j * n] = genrand_gaussian(); B2[j + i * n] = B2[i + j * n]; } } for (integer i = 0; i < m; i++) { for (integer j = i; j < m; j++) { B3[i + j * m] = genrand_gaussian(); B3[j + i * m] = B3[i + j * m]; } } for (integer i = 0; i < p; i++) { D1[i] = static_cast<double> (i + 1); D2[i] = D1[i]; } for (integer i = 0; i < q; i++) { D3[i] = static_cast<double> (i + 1); } // number of manifolds in product of manifold integer numofmanis = 2; // two kinds of manifolds integer numofmani1 = 2; // the first one has two integer numofmani2 = 1; // the second one has one // Obtain an initial iterate StieVariable StieX1(n, p); StieVariable StieX2(m, q); ProductElement ProdX(numofmanis, &StieX1, numofmani1, &StieX2, numofmani2); ProdX.RandInManifold(); // Define the Stiefel manifold Stiefel mani1(n, p); Stiefel mani2(m, q); ProductManifold Domain(numofmanis, &mani1, numofmani1, &mani2, numofmani2); // Define the Brockett problem StieSumBrockett Prob(B1, D1, B2, D2, B3, D3, n, p, m, q); // Set the domain of the problem to be the Stiefel manifold Prob.SetDomain(&Domain); // output the parameters of the manifold of domain Domain.CheckParams(); //// test RSD //std::cout << "********************************Check all line search algorithm in RSD*****************************************" << std::endl; //for (integer i = 0; i < LSALGOLENGTH; i++) //{ // RSD *RSDsolver = new RSD(&Prob, &ProdX); // RSDsolver->LineSearch_LS = static_cast<LSAlgo> (i); // RSDsolver->DEBUG = FINALRESULT; // RSDsolver->CheckParams(); // RSDsolver->Run(); // delete RSDsolver; //} //// test RNewton //std::cout << "********************************Check all line search algorithm in RNewton*************************************" << std::endl; //for (integer i = 0; i < LSALGOLENGTH; i++) //{ // RNewton *RNewtonsolver = new RNewton(&Prob, &ProdX); // RNewtonsolver->LineSearch_LS = static_cast<LSAlgo> (i); // RNewtonsolver->DEBUG = FINALRESULT; // RNewtonsolver->CheckParams(); // RNewtonsolver->Run(); // delete RNewtonsolver; //} //// test RCG //std::cout << "********************************Check all Formulas in RCG*************************************" << std::endl; //for (integer i = 0; i < RCGMETHODSLENGTH; i++) //{ // RCG *RCGsolver = new RCG(&Prob, &ProdX); // RCGsolver->RCGmethod = static_cast<RCGmethods> (i); // RCGsolver->LineSearch_LS = STRONGWOLFE; // RCGsolver->LS_beta = 0.1; // RCGsolver->DEBUG = FINALRESULT; // RCGsolver->CheckParams(); // RCGsolver->Run(); // delete RCGsolver; //} //// test RBroydenFamily //std::cout << "********************************Check all line search algorithm in RBroydenFamily*************************************" << std::endl; //for (integer i = 0; i < LSALGOLENGTH; i++) //{ // RBroydenFamily *RBroydenFamilysolver = new RBroydenFamily(&Prob, &ProdX); // RBroydenFamilysolver->LineSearch_LS = static_cast<LSAlgo> (i); // RBroydenFamilysolver->DEBUG = FINALRESULT; // RBroydenFamilysolver->CheckParams(); // RBroydenFamilysolver->Run(); // delete RBroydenFamilysolver; //} //// test RWRBFGS //std::cout << "********************************Check all line search algorithm in RWRBFGS*************************************" << std::endl; //for (integer i = 0; i < LSALGOLENGTH; i++) //{ // RWRBFGS *RWRBFGSsolver = new RWRBFGS(&Prob, &ProdX); // RWRBFGSsolver->LineSearch_LS = static_cast<LSAlgo> (i); // RWRBFGSsolver->DEBUG = FINALRESULT; //ITERRESULT;// // RWRBFGSsolver->CheckParams(); // RWRBFGSsolver->Run(); // delete RWRBFGSsolver; //} //// test RBFGS //std::cout << "********************************Check all line search algorithm in RBFGS*************************************" << std::endl; //for (integer i = 0; i < LSALGOLENGTH; i++) //{ // RBFGS *RBFGSsolver = new RBFGS(&Prob, &ProdX); // RBFGSsolver->LineSearch_LS = static_cast<LSAlgo> (i); // RBFGSsolver->DEBUG = FINALRESULT; // RBFGSsolver->CheckParams(); // RBFGSsolver->Run(); // delete RBFGSsolver; //} //// test LRBFGS //std::cout << "********************************Check all line search algorithm in LRBFGS*************************************" << std::endl; //for (integer i = 0; i < 1; i++)//LSALGOLENGTH //{ // LRBFGS *LRBFGSsolver = new LRBFGS(&Prob, &ProdX); // LRBFGSsolver->LineSearch_LS = static_cast<LSAlgo> (i); // LRBFGSsolver->DEBUG = FINALRESULT; //ITERRESULT;// // LRBFGSsolver->CheckParams(); // LRBFGSsolver->Run(); // delete LRBFGSsolver; //} //// test RTRSD //std::cout << "********************************Check RTRSD*************************************" << std::endl; //RTRSD RTRSDsolver(&Prob, &ProdX); //RTRSDsolver.DEBUG = FINALRESULT; //RTRSDsolver.CheckParams(); //RTRSDsolver.Run(); // test RTRNewton std::cout << "********************************Check RTRNewton*************************************" << std::endl; RTRNewton RTRNewtonsolver(&Prob, &ProdX); RTRNewtonsolver.DEBUG = FINALRESULT; RTRNewtonsolver.CheckParams(); RTRNewtonsolver.Run(); //// test RTRSR1 //std::cout << "********************************Check RTRSR1*************************************" << std::endl; //RTRSR1 RTRSR1solver(&Prob, &ProdX); //RTRSR1solver.DEBUG = FINALRESULT; //RTRSR1solver.CheckParams(); //RTRSR1solver.Run(); //// test LRTRSR1 //std::cout << "********************************Check LRTRSR1*************************************" << std::endl; //LRTRSR1 LRTRSR1solver(&Prob, &ProdX); //LRTRSR1solver.DEBUG = FINALRESULT; //LRTRSR1solver.CheckParams(); //LRTRSR1solver.Run(); // Check gradient and Hessian Prob.CheckGradHessian(&ProdX); const Variable *xopt = RTRNewtonsolver.GetXopt(); Prob.CheckGradHessian(xopt); delete[] B1; return 0; }
static int compute_prob(void) /* this is the function that implements the compute_prob predicate used in pp.pl */ { YAP_Term out,arg1,arg2,arg3,arg4; array_t * variables,* expression, * bVar2mVar; DdNode * function, * add; DdManager * mgr; int nBVar,i,j,intBits,create_dot; FILE * file; DdNode * array[1]; char * onames[1]; char inames[1000][20]; char * names[1000]; GHashTable * nodes; /* hash table that associates nodes with their probability if already computed, it is defined in glib */ Cudd_ReorderingType order; arg1=YAP_ARG1; arg2=YAP_ARG2; arg3=YAP_ARG3; arg4=YAP_ARG4; mgr=Cudd_Init(0,0,CUDD_UNIQUE_SLOTS,CUDD_CACHE_SLOTS,0); variables=array_alloc(variable,0); bVar2mVar=array_alloc(int,0); create_dot=YAP_IntOfTerm(arg4); createVars(variables,arg1,mgr,bVar2mVar,create_dot,inames); //Cudd_PrintInfo(mgr,stderr); /* automatic variable reordering, default method CUDD_REORDER_SIFT used */ //printf("status %d\n",Cudd_ReorderingStatus(mgr,&order)); //printf("order %d\n",order); Cudd_AutodynEnable(mgr,CUDD_REORDER_SAME); /* Cudd_AutodynEnable(mgr, CUDD_REORDER_RANDOM_PIVOT); printf("status %d\n",Cudd_ReorderingStatus(mgr,&order)); printf("order %d\n",order); printf("%d",CUDD_REORDER_RANDOM_PIVOT); */ expression=array_alloc(array_t *,0); createExpression(expression,arg2); function=retFunction(mgr,expression,variables); /* the BDD build by retFunction is converted to an ADD (algebraic decision diagram) because it is easier to interpret and to print */ add=Cudd_BddToAdd(mgr,function); //Cudd_PrintInfo(mgr,stderr); if (create_dot) /* if specified by the user, a dot file for the BDD is written to cpl.dot */ { nBVar=array_n(bVar2mVar); for(i=0;i<nBVar;i++) names[i]=inames[i]; array[0]=add; onames[0]="Out"; file = open_file("cpl.dot", "w"); Cudd_DumpDot(mgr,1,array,names,onames,file); fclose(file); } nodes=g_hash_table_new(my_hash,my_equal); intBits=sizeof(unsigned int)*8; /* dividend is a global variable used by my_hash it is equal to an unsigned int with binary representation 11..1 */ dividend=1; for(j=1;j<intBits;j++) { dividend=(dividend<<1)+1; } out=YAP_MkFloatTerm(Prob(add,variables,bVar2mVar,nodes)); g_hash_table_foreach (nodes,dealloc,NULL); g_hash_table_destroy(nodes); Cudd_Quit(mgr); array_free(variables); array_free(bVar2mVar); array_free(expression); return(YAP_Unify(out,arg3)); }
static int compute_prob(void) /* this is the function that implements the compute_prob predicate used in pp.pl */ { YAP_Term out,arg1,arg2,arg3,arg4; variables vars; expr expression; DdNode * function; DdManager * mgr; int nBVar,i,intBits,create_dot; FILE * file; DdNode * array[1]; double prob; char * onames[1]; char inames[1000][20]; char * names[1000]; tablerow * nodes; arg1=YAP_ARG1; arg2=YAP_ARG2; arg3=YAP_ARG3; arg4=YAP_ARG4; mgr=Cudd_Init(0,0,CUDD_UNIQUE_SLOTS,CUDD_CACHE_SLOTS,0); create_dot=YAP_IntOfTerm(arg4); vars=createVars(arg1,mgr,create_dot,inames); //Cudd_PrintInfo(mgr,stderr); /* automatic variable reordering, default method CUDD_REORDER_SIFT used */ //printf("status %d\n",Cudd_ReorderingStatus(mgr,&order)); //printf("order %d\n",order); Cudd_AutodynEnable(mgr,CUDD_REORDER_SAME); /* Cudd_AutodynEnable(mgr, CUDD_REORDER_RANDOM_PIVOT); printf("status %d\n",Cudd_ReorderingStatus(mgr,&order)); printf("order %d\n",order); printf("%d",CUDD_REORDER_RANDOM_PIVOT); */ expression=createExpression(arg2); function=retFunction(mgr,expression,vars); /* the BDD build by retFunction is converted to an ADD (algebraic decision diagram) because it is easier to interpret and to print */ //add=Cudd_BddToAdd(mgr,function); //Cudd_PrintInfo(mgr,stderr); if (create_dot) /* if specified by the user, a dot file for the BDD is written to cpl.dot */ { nBVar=vars.nBVar; for(i=0; i<nBVar; i++) names[i]=inames[i]; array[0]=function; onames[0]="Out"; file = open_file("cpl.dot", "w"); Cudd_DumpDot(mgr,1,array,names,onames,file); fclose(file); } nodes=init_table(vars.nBVar); intBits=sizeof(unsigned int)*8; prob=Prob(function,vars,nodes); out=YAP_MkFloatTerm(prob); destroy_table(nodes,vars.nBVar); Cudd_Quit(mgr); for(i=0; i<vars.nVar; i++) { free(vars.varar[i].probabilities); free(vars.varar[i].booleanVars); } free(vars.varar); free(vars.bVar2mVar); for(i=0; i<expression.nTerms; i++) { free(expression.terms[i].factors); } free(expression.terms); return(YAP_Unify(out,arg3)); }