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