Improved documentation of include/dai/evidence.h
[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
19
20 namespace dai {
21
22
23 void Evidence::addEvidenceTabFile( std::istream &is, FactorGraph &fg ) {
24 std::map<std::string, Var> varMap;
25 for( std::vector<Var>::const_iterator v = fg.vars().begin(); v != fg.vars().end(); ++v ) {
26 std::stringstream s;
27 s << v->label();
28 varMap[s.str()] = *v;
29 }
30
31 addEvidenceTabFile( is, varMap );
32 }
33
34
35 void Evidence::addEvidenceTabFile( std::istream &is, std::map<std::string, Var> &varMap ) {
36 std::string line;
37 getline( is, line );
38
39 // Parse header
40 std::vector<std::string> header_fields;
41 tokenizeString( line, header_fields );
42 std::vector<std::string>::const_iterator p_field = header_fields.begin();
43 if( p_field == header_fields.end() )
44 DAI_THROW(INVALID_EVIDENCE_FILE);
45
46 std::vector<Var> vars;
47 for( ; p_field != header_fields.end(); ++p_field ) {
48 std::map<std::string, Var>::iterator elem = varMap.find( *p_field );
49 if( elem == varMap.end() )
50 DAI_THROW(INVALID_EVIDENCE_FILE);
51 vars.push_back( elem->second );
52 }
53
54 // Read samples
55 while( getline(is, line) ) {
56 std::vector<std::string> fields;
57 tokenizeString( line, fields );
58 if( fields.size() != vars.size() )
59 DAI_THROW(INVALID_EVIDENCE_FILE);
60
61 Observation sampleData;
62 for( size_t i = 0; i < vars.size(); ++i ) {
63 if( fields[i].size() > 0 ) { // skip if missing observation
64 if( fields[i].find_first_not_of("0123456789") != std::string::npos )
65 DAI_THROW(INVALID_EVIDENCE_FILE);
66 size_t state = atoi( fields[i].c_str() );
67 if( state >= vars[i].states() )
68 DAI_THROW(INVALID_EVIDENCE_FILE);
69 sampleData[vars[i]] = state;
70 }
71 }
72 _samples.push_back( sampleData );
73 } // finished sample line
74 }
75
76
77 } // end of namespace dai