Exemple #1
0
void SharedParameters::collectSufficientStatistics( InfAlg &alg ) {
    for( std::map< FactorIndex, Permute >::iterator i = _perms.begin(); i != _perms.end(); ++i ) {
        Permute &perm = i->second;
        VarSet &vs = _varsets[i->first];

        Factor b = alg.belief(vs);
        Prob p( b.nrStates(), 0.0 );
        for( size_t entry = 0; entry < b.nrStates(); ++entry )
            p.set( entry, b[perm.convertLinearIndex(entry)] ); // apply inverse permutation
        _estimation->addSufficientStatistics( p );
    }
}
void BruteForceOptMatching::outputSingleFactorValues(
    const ConnectedFactorGraph& graph) {
    // output factor values
    for (int j = 0; j < graph.factors.size(); j++) {

        Factor fac = graph.factors[j];
        if (fac.vars().size() != 1)
            continue;
        cout << "singvals for var " << fac.vars().front().label() << " :\n";
        for (int k = 0; k < fac.nrStates(); k++) {
            cout << fac.get(k) << " ";
        }
        cout << "\n";
    }
}
Exemple #3
0
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) {
    // Check for proper number of arguments
    if( ((nrhs < NR_IN) || (nrhs > NR_IN + NR_IN_OPT)) || ((nlhs < NR_OUT) || (nlhs > NR_OUT + NR_OUT_OPT)) ) {
        mexErrMsgTxt("Usage: [logZ,q,qv,qf,qmap,margs] = dai_jtree(psi,varsets,opts)\n\n"
        "\n"
        "INPUT:  psi        = linear cell array containing the factors\n"
        "                     (psi{i} should be a structure with a Member field\n"
        "                     and a P field).\n"
        "        varsets    = linear cell array containing varsets for which marginals\n"
        "                     are requested.\n"
        "        opts       = string of options.\n"
        "\n"
        "OUTPUT: logZ       = logarithm of the partition sum.\n"
        "        q          = linear cell array containing all calculated marginals.\n"
        "        qv         = linear cell array containing all variable marginals.\n"
        "        qf         = linear cell array containing all factor marginals.\n"
        "        qmap       = linear array containing the MAP state.\n"
        "        margs      = linear cell array containing all requested marginals.\n");
    }

    // Get psi and construct factorgraph
    vector<Factor> factors = mx2Factors(PSI_IN, 0);
    FactorGraph fg(factors);

    // Get varsets
    vector<Permute> perms;
    vector<VarSet> varsets = mx2VarSets(VARSETS_IN,fg,0,perms);

    // Get options string
    char *opts;
    size_t buflen = mxGetN( OPTS_IN ) + 1;
    opts = (char *)mxCalloc( buflen, sizeof(char) );
    mxGetString( OPTS_IN, opts, buflen );
    // Convert to options object props
    stringstream ss;
    ss << opts;
    PropertySet props;
    ss >> props;

    // Construct InfAlg object, init and run
    JTree jt = JTree( fg, props );
    jt.init();
    jt.run();

    // Save logZ
	double logZ = NAN;
    logZ = jt.logZ();

    // Hand over results to MATLAB
    LOGZ_OUT = mxCreateDoubleMatrix(1,1,mxREAL);
    *(mxGetPr(LOGZ_OUT)) = logZ;

    Q_OUT = Factors2mx(jt.beliefs());

    if( nlhs >= 3 ) {
        vector<Factor> qv;
        qv.reserve( fg.nrVars() );
        for( size_t i = 0; i < fg.nrVars(); i++ )
            qv.push_back( jt.belief( fg.var(i) ) );
        QV_OUT = Factors2mx( qv );
    }

    if( nlhs >= 4 ) {
        vector<Factor> qf;
        qf.reserve( fg.nrFactors() );
        for( size_t I = 0; I < fg.nrFactors(); I++ )
            qf.push_back( jt.belief( fg.factor(I).vars() ) );
        QF_OUT = Factors2mx( qf );
    }

    if( nlhs >= 5 ) {
        std::vector<size_t> map_state;
        bool supported = true;
        try {
            map_state = jt.findMaximum();
        } catch( Exception &e ) {
            if( e.getCode() == Exception::NOT_IMPLEMENTED )
                supported = false;
            else
                throw;
        }
        if( supported ) {
            QMAP_OUT = mxCreateNumericMatrix(map_state.size(), 1, mxUINT32_CLASS, mxREAL);
            uint32_T* qmap_p = reinterpret_cast<uint32_T *>(mxGetPr(QMAP_OUT));
            for (size_t n = 0; n < map_state.size(); ++n)
                qmap_p[n] = map_state[n];
        } else {
            mexErrMsgTxt("Calculating a MAP state is not supported by this inference algorithm.");
        }
    }

    if( nlhs >= 6 ) {
        vector<Factor> margs;
        margs.reserve( varsets.size() );
        for( size_t s = 0; s < varsets.size(); s++ ) {
            Factor marg;
            jt.init();
            jt.run();
            marg = jt.calcMarginal( varsets[s] );

            // permute entries of marg
            Factor margperm = marg;
            for( size_t li = 0; li < marg.nrStates(); li++ )
                margperm.set( li, marg[perms[s].convertLinearIndex(li)] );
            margs.push_back( margperm );
        }
        MARGS_OUT = Factors2mx( margs );
    }

    return;
}
int main( int argc, char *argv[] ) {
    if ( argc != 3 ) {
        cout << "Usage: " << argv[0] << " <filename.fg> [map|pd]" << endl << endl;
        cout << "Reads factor graph <filename.fg> and runs" << endl;
        cout << "map: Junction tree MAP" << endl;
        cout << "pd : LBP and posterior decoding" << endl << endl;
        return 1;
    } else {
        // Redirect cerr to inf.log
        ofstream errlog("inf.log");
        //streambuf* orig_cerr = cerr.rdbuf();
        cerr.rdbuf(errlog.rdbuf());

        // Read FactorGraph from the file specified by the first command line argument
        FactorGraph fg;
        fg.ReadFromFile(argv[1]);

        // Set some constants
        size_t maxiter = 10000;
        Real   tol = 1e-9;
        size_t verb = 1;

        // Store the constants in a PropertySet object
        PropertySet opts;
        opts.set("maxiter",maxiter);  // Maximum number of iterations
        opts.set("tol",tol);          // Tolerance for convergence
        opts.set("verbose",verb);     // Verbosity (amount of output generated)

        if (strcmp(argv[2], "map") == 0) {
            // Construct another JTree (junction tree) object that is used to calculate
            // the joint configuration of variables that has maximum probability (MAP state)
            JTree jtmap( fg, opts("updates",string("HUGIN"))("inference",string("MAXPROD")) );
            // Initialize junction tree algorithm
            jtmap.init();
            // Run junction tree algorithm
            jtmap.run();
            // Calculate joint state of all variables that has maximum probability
            vector<size_t> jtmapstate = jtmap.findMaximum();

            /*
            // Report exact MAP variable marginals
            cout << "Exact MAP variable marginals:" << endl;
            for( size_t i = 0; i < fg.nrVars(); i++ )
                cout << jtmap.belief(fg.var(i)) << endl;
            */

            // Report exact MAP joint state
            cerr << "Exact MAP state (log score = " << fg.logScore( jtmapstate ) << "):" << endl;
            cout << fg.nrVars() << endl;
            for( size_t i = 0; i < jtmapstate.size(); i++ )
                cout << fg.var(i).label() << " " << jtmapstate[i] + 1 << endl; // +1 because in MATLAB assignments start at 1
        } else if (strcmp(argv[2], "pd") == 0) {

            // Construct a BP (belief propagation) object from the FactorGraph fg
            // using the parameters specified by opts and two additional properties,
            // specifying the type of updates the BP algorithm should perform and
            // whether they should be done in the real or in the logdomain
            BP bp(fg, opts("updates",string("SEQMAX"))("logdomain",true));
            // Initialize belief propagation algorithm
            bp.init();
            // Run belief propagation algorithm
            bp.run();

            // Report variable marginals for fg, calculated by the belief propagation algorithm
            cerr << "LBP posterior decoding (highest prob assignment in marginal):" << endl;
            cout << fg.nrVars() << endl;
            for( size_t i = 0; i < fg.nrVars(); i++ ) {// iterate over all variables in fg
                //cout << bp.belief(fg.var(i)) << endl; // display the belief of bp for that variable
                Factor marginal = bp.belief(fg.var(i));
                Real maxprob = marginal.max();
                for (size_t j = 0; j < marginal.nrStates(); j++) {
                    if (marginal[j] == maxprob) {
                        cout << fg.var(i).label() << " " << j + 1 << endl; // +1 because in MATLAB assignments start at 1
                    }
                }
            }
        } else {
            cerr << "Invalid inference algorithm specified." << endl;
            return 1;
        }
    }

    return 0;
}