Improved Gibbs and added FactorGraph::logScore( const std::vector<size_t>& statevec )
[libdai.git] / src / evidence.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) 2009 Charles Vaske [cvaske at soe dot ucsc dot edu]
8 * Copyright (C) 2009 University of California, Santa Cruz
9 */
10
11
12 #include <sstream>
13 #include <string>
14 #include <cstdlib>
15
16 #include <dai/util.h>
17 #include <dai/evidence.h>
18 #include <boost/lexical_cast.hpp>
19
20
21 namespace dai {
22
23
24 void Evidence::addEvidenceTabFile( std::istream &is, FactorGraph &fg ) {
25 std::map<std::string, Var> varMap;
26 for( std::vector<Var>::const_iterator v = fg.vars().begin(); v != fg.vars().end(); ++v ) {
27 std::stringstream s;
28 s << v->label();
29 varMap[s.str()] = *v;
30 }
31
32 addEvidenceTabFile( is, varMap );
33 }
34
35
36 void Evidence::addEvidenceTabFile( std::istream &is, std::map<std::string, Var> &varMap ) {
37 std::string line;
38 getline( is, line );
39 size_t line_number = 0;
40
41 // Parse header
42 std::vector<std::string> header_fields;
43 tokenizeString( line, header_fields );
44 std::vector<std::string>::const_iterator p_field = header_fields.begin();
45 if( p_field == header_fields.end() )
46 DAI_THROWE(INVALID_EVIDENCE_FILE,"Empty header line");
47
48 std::vector<Var> vars;
49 for( ; p_field != header_fields.end(); ++p_field ) {
50 std::map<std::string, Var>::iterator elem = varMap.find( *p_field );
51 if( elem == varMap.end() )
52 DAI_THROWE(INVALID_EVIDENCE_FILE,"Variable " + *p_field + " not known");
53 vars.push_back( elem->second );
54 }
55
56 getline(is,line);
57 if( is.fail() || line.size() > 0 )
58 DAI_THROWE(INVALID_EVIDENCE_FILE,"Expecting empty line");
59
60 // Read samples
61 while( getline(is, line) ) {
62 line_number++;
63
64 std::vector<std::string> fields;
65 tokenizeString( line, fields );
66 if( fields.size() != vars.size() )
67 DAI_THROWE(INVALID_EVIDENCE_FILE,"Invalid number of fields in line " + boost::lexical_cast<std::string>(line_number));
68
69 Observation sample;
70 for( size_t i = 0; i < vars.size(); ++i ) {
71 if( fields[i].size() > 0 ) { // skip if missing observation
72 if( fields[i].find_first_not_of("0123456789") != std::string::npos )
73 DAI_THROWE(INVALID_EVIDENCE_FILE,"Invalid state " + fields[i] + " in line " + boost::lexical_cast<std::string>(line_number));
74 size_t state = fromString<size_t>( fields[i].c_str() );
75 if( state >= vars[i].states() )
76 DAI_THROWE(INVALID_EVIDENCE_FILE,"State " + fields[i] + " too large in line " + boost::lexical_cast<std::string>(line_number));
77 sample[vars[i]] = state;
78 }
79 }
80 _samples.push_back( sample );
81 } // finished sample line
82 }
83
84
85 } // end of namespace dai