Darwin  1.10(beta)
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
drwnIOUtils.h
Go to the documentation of this file.
1 /*****************************************************************************
2 ** DARWIN: A FRAMEWORK FOR MACHINE LEARNING RESEARCH AND DEVELOPMENT
3 ** Distributed under the terms of the BSD license (see the LICENSE file)
4 ** Copyright (c) 2007-2015, Stephen Gould
5 ** All rights reserved.
6 **
7 ******************************************************************************
8 ** FILENAME: drwnIOUtils.h
9 ** AUTHOR(S): Stephen Gould <stephen.gould@anu.edu.au>
10 **
11 *****************************************************************************/
12 
13 #pragma once
14 
21 #include <string>
22 #include <iostream>
23 #include <sstream>
24 #include <fstream>
25 
26 #include "Eigen/Core"
27 
28 using namespace std;
29 using namespace Eigen;
30 
31 // matrix i/o ---------------------------------------------------------------
32 
35 template <class EigenMatrix>
36 void drwnReadMatrix(EigenMatrix& m, istream& is, const char *filename = NULL)
37 {
38  for (int y = 0; y < m.rows(); y++) {
39  for (int x = 0; x < m.cols(); x++) {
40  is >> m(y, x);
41  DRWN_ASSERT_MSG(!is.fail(), "row/col " << y << "/" << x
42  << " of " << m.rows() << "/" << m.cols() << " ("
43  << (filename != NULL ? filename : "unknown file") << ")");
44  }
45  }
46 }
47 
49 template <class EigenMatrix>
50 void drwnReadMatrix(EigenMatrix& m, const char *filename)
51 {
52  DRWN_ASSERT(filename != NULL);
53  ifstream ifs(filename);
54  DRWN_ASSERT_MSG(!ifs.fail(), filename);
55  drwnReadMatrix(m, ifs, filename);
56  ifs.close();
57 }
58 
60 template <class EigenMatrix>
61 void drwnReadUnknownMatrix(EigenMatrix& m, const char *filename)
62 {
63  DRWN_ASSERT(filename != NULL);
64  const int nRows = drwnCountLines(filename);
65 
66  ifstream ifs(filename);
67  DRWN_ASSERT_MSG(!ifs.fail(), filename);
68 
69  const int nCols = drwnCountFields(&ifs);
70  m.resize(nRows, nCols);
71  drwnReadMatrix(m, ifs, filename);
72  ifs.close();
73 }
74 
int drwnCountLines(const char *filename)
counts the number of non-empty lines in a text file
Definition: drwnFileUtils.cpp:298
void drwnReadUnknownMatrix(EigenMatrix &m, const char *filename)
Read an Eigen::Matrix of unknown size from a text file.
Definition: drwnIOUtils.h:61
int drwnCountFields(ifstream *ifs, char delimiter= ' ', bool bSkipRepeated=true)
counts the number of fields per line (separated by a single character delimiter)
Definition: drwnFileUtils.cpp:214
void drwnReadMatrix(EigenMatrix &m, istream &is, const char *filename=NULL)
Read an Eigen::Matrix from an input stream (the filename argument is only used for reporting errors a...
Definition: drwnIOUtils.h:36