New git HEAD version
[libdai.git] / src / matlab / dai_readfg.cpp
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * Copyright (c) 2006-2011, The libDAI authors. All rights reserved.
4 *
5 * Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
6 */
7
8
9 #include <iostream>
10 #include "mex.h"
11 #include <dai/matlab/matlab.h>
12 #include <dai/factorgraph.h>
13
14
15 using namespace std;
16 using namespace dai;
17
18
19 /* Input Arguments */
20
21 #define FILENAME_IN prhs[0]
22 #define NR_IN 1
23
24
25 /* Output Arguments */
26
27 #define PSI_OUT plhs[0]
28 #define NR_OUT 1
29
30
31 void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) {
32 char *filename;
33
34
35 // Check for proper number of arguments
36 if ((nrhs != NR_IN) || (nlhs != NR_OUT)) {
37 mexErrMsgTxt("Usage: [psi] = dai_readfg(filename);\n\n"
38 "\n"
39 "INPUT: filename = filename of a .fg file\n"
40 "\n"
41 "OUTPUT: psi = linear cell array containing the factors\n"
42 " (psi{i} is a structure with a Member field\n"
43 " and a P field, like a CPTAB).\n");
44 }
45
46 // Get input parameters
47 size_t buflen;
48 buflen = mxGetN( FILENAME_IN ) + 1;
49 filename = (char *)mxCalloc( buflen, sizeof(char) );
50 mxGetString( FILENAME_IN, filename, buflen );
51
52
53 // Read factorgraph
54 FactorGraph fg;
55 try {
56 fg.ReadFromFile( filename );
57 } catch( std::exception &e ) {
58 mexErrMsgTxt( e.what() );
59 }
60
61
62 // Save factors
63 vector<Factor> psi;
64 for( size_t I = 0; I < fg.nrFactors(); I++ )
65 psi.push_back(fg.factor(I));
66
67
68 // Hand over results to MATLAB
69 PSI_OUT = Factors2mx(psi);
70
71
72 return;
73 }