Cleanups of matlab, BP; small improvement of utils/fginfo
[libdai.git] / src / matlab / dai_readfg.cpp
1 /* Copyright (C) 2006-2008 Joris Mooij [joris dot mooij at tuebingen dot mpg dot de]
2 Radboud University Nijmegen, The Netherlands /
3 Max Planck Institute for Biological Cybernetics, Germany
4
5 This file is part of libDAI.
6
7 libDAI is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 libDAI is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with libDAI; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22
23 /*=================================================================*
24 * *
25 * This is a MEX-file for MATLAB. *
26 * *
27 * [psi] = dai_readfg(filename); *
28 * *
29 *=================================================================*/
30
31
32 #include <iostream>
33 #include "mex.h"
34 #include <dai/matlab/matlab.h>
35 #include <dai/factorgraph.h>
36
37
38 using namespace std;
39 using namespace dai;
40
41
42 /* Input Arguments */
43
44 #define FILENAME_IN prhs[0]
45 #define NR_IN 1
46
47
48 /* Output Arguments */
49
50 #define PSI_OUT plhs[0]
51 #define NR_OUT 1
52
53
54 void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] )
55 {
56 char *filename;
57
58
59 // Check for proper number of arguments
60 if ((nrhs != NR_IN) || (nlhs != NR_OUT)) {
61 mexErrMsgTxt("Usage: [psi] = dai_readfg(filename);\n\n"
62 "\n"
63 "INPUT: filename = filename of a .fg file\n"
64 "\n"
65 "OUTPUT: psi = linear cell array containing the factors\n"
66 " (psi{i} is a structure with a Member field\n"
67 " and a P field, like a CPTAB).\n");
68 }
69
70 // Get input parameters
71 size_t buflen;
72 buflen = mxGetN( FILENAME_IN ) + 1;
73 filename = (char *)mxCalloc( buflen, sizeof(char) );
74 mxGetString( FILENAME_IN, filename, buflen );
75
76
77 // Read factorgraph
78 FactorGraph fg;
79 try {
80 fg.ReadFromFile( filename );
81 } catch( std::exception &e ) {
82 mexErrMsgTxt( e.what() );
83 }
84
85
86 // Save factors
87 vector<Factor> psi;
88 for( size_t I = 0; I < fg.nrFactors(); I++ )
89 psi.push_back(fg.factor(I));
90
91
92 // Hand over results to MATLAB
93 PSI_OUT = Factors2mx(psi);
94
95
96 return;
97 }