Merge branch 'pletscher'
[libdai.git] / src / matlab / dai_readfg.cpp
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * libDAI is licensed under the terms of the GNU General Public License version
4 * 2, or (at your option) any later version. libDAI is distributed without any
5 * warranty. See the file COPYING for more details.
6 *
7 * Copyright (C) 2006-2009 Joris Mooij [joris dot mooij at libdai dot org]
8 * Copyright (C) 2006-2007 Radboud University Nijmegen, The Netherlands
9 */
10
11
12 #include <iostream>
13 #include "mex.h"
14 #include <dai/matlab/matlab.h>
15 #include <dai/factorgraph.h>
16
17
18 using namespace std;
19 using namespace dai;
20
21
22 /* Input Arguments */
23
24 #define FILENAME_IN prhs[0]
25 #define NR_IN 1
26
27
28 /* Output Arguments */
29
30 #define PSI_OUT plhs[0]
31 #define NR_OUT 1
32
33
34 void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) {
35 char *filename;
36
37
38 // Check for proper number of arguments
39 if ((nrhs != NR_IN) || (nlhs != NR_OUT)) {
40 mexErrMsgTxt("Usage: [psi] = dai_readfg(filename);\n\n"
41 "\n"
42 "INPUT: filename = filename of a .fg file\n"
43 "\n"
44 "OUTPUT: psi = linear cell array containing the factors\n"
45 " (psi{i} is a structure with a Member field\n"
46 " and a P field, like a CPTAB).\n");
47 }
48
49 // Get input parameters
50 size_t buflen;
51 buflen = mxGetN( FILENAME_IN ) + 1;
52 filename = (char *)mxCalloc( buflen, sizeof(char) );
53 mxGetString( FILENAME_IN, filename, buflen );
54
55
56 // Read factorgraph
57 FactorGraph fg;
58 try {
59 fg.ReadFromFile( filename );
60 } catch( std::exception &e ) {
61 mexErrMsgTxt( e.what() );
62 }
63
64
65 // Save factors
66 vector<Factor> psi;
67 for( size_t I = 0; I < fg.nrFactors(); I++ )
68 psi.push_back(fg.factor(I));
69
70
71 // Hand over results to MATLAB
72 PSI_OUT = Factors2mx(psi);
73
74
75 return;
76 }