source: trunk/yat/utility/matrix.cc @ 703

Last change on this file since 703 was 703, checked in by Jari Häkkinen, 16 years ago

Addresses #65 and #170.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 6.6 KB
Line 
1// $Id: matrix.cc 703 2006-12-18 00:47:44Z jari $
2
3/*
4  Copyright (C) 2003 Daniel Dalevi, Peter Johansson
5  Copyright (C) 2004 Jari Häkkinen, Peter Johansson
6  Copyright (C) 2005, 2006 Jari Häkkinen, Peter Johansson, Markus Ringnér
7
8  This file is part of the yat library, http://lev.thep.lu.se/trac/yat
9
10  The yat library is free software; you can redistribute it and/or
11  modify it under the terms of the GNU General Public License as
12  published by the Free Software Foundation; either version 2 of the
13  License, or (at your option) any later version.
14
15  The yat library is distributed in the hope that it will be useful,
16  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  General Public License for more details.
19
20  You should have received a copy of the GNU General Public License
21  along with this program; if not, write to the Free Software
22  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
23  02111-1307, USA.
24*/
25
26#include "matrix.h"
27#include "vector.h"
28#include "stl_utility.h"
29#include "utility.h"
30
31#include <cmath>
32#include <sstream>
33#include <vector>
34
35#include <gsl/gsl_blas.h>
36
37namespace theplu {
38namespace yat {
39namespace utility {
40
41
42  matrix::matrix(void)
43    : m_(NULL), view_(NULL)
44  {
45  }
46
47
48  matrix::matrix(const size_t& r, const size_t& c, double init_value)
49    : view_(NULL)
50  {
51    m_ = gsl_matrix_alloc(r,c);
52    set_all(init_value);
53  }
54
55
56  matrix::matrix(const matrix& o)
57    : view_(NULL)
58  {
59    m_ = o.create_gsl_matrix_copy();
60  }
61
62
63  matrix::matrix(matrix& m, size_t offset_row, size_t offset_column,
64                 size_t n_row, size_t n_column)
65  {
66    // Jari, exception handling needed here. Failure in setting up a
67    // proper gsl_matrix_view is communicated by NULL pointer in the
68    // view structure (cf. GSL manual). How about GSL error state?
69    view_ = new gsl_matrix_view(gsl_matrix_submatrix(m.m_,
70                                                     offset_row,offset_column,
71                                                     n_row,n_column));
72    m_ = &(view_->matrix);
73  }
74
75
76  // Constructor that gets data from istream
77  matrix::matrix(std::istream& is, char sep) 
78    throw (utility::IO_error,std::exception)
79    : view_(NULL)
80  {
81    // Markus to Jari, somewhere we should check that quiet_NaNs are supported
82    // std::numeric_limits<double>::has_quiet_NaN has to be true.
83    // Also in vector
84
85    // read the data file and store in stl vectors (dynamically
86    // expandable)
87    std::vector<std::vector<double> > data_matrix;
88    u_int nof_columns=0;
89    u_int nof_rows = 0;
90    std::string line;
91    while(getline(is, line, '\n')){
92      // Ignoring empty lines
93      if (!line.size()) {
94        continue;
95      }
96      nof_rows++;
97      std::vector<double> v;
98      std::string element;
99      std::stringstream ss(line);
100     
101      bool ok=true;
102      while(ok) {
103        if(sep=='\0')
104          ok=(ss>>element);
105        else
106          ok=getline(ss, element, sep);
107        if(!ok)
108          break;
109       
110        if(utility::is_double(element)) {
111          v.push_back(atof(element.c_str()));
112        }
113        else if (!element.size() || utility::is_nan(element)) {
114          v.push_back(std::numeric_limits<double>::quiet_NaN());
115        }
116        else {
117          // Jari, this should be communicated with as an exception.
118          std::cerr << "Warning: '" << element
119                    << "' is not accepted as a matrix element." << std::endl;
120        }
121      }           
122      if(sep!='\0' && line[line.size()-1]==sep) // add NaN for final separator
123          v.push_back(std::numeric_limits<double>::quiet_NaN());
124      if (!nof_columns)
125        nof_columns=v.size();
126      else if (v.size()!=nof_columns) {
127        std::ostringstream s;
128        s << "matrix::matrix(std::istream&, char) data file error: "
129          << "line " << nof_rows << " has " << v.size()
130          << " columns; expected " << nof_columns << " columns.";
131        throw utility::IO_error(s.str());
132      }
133      data_matrix.push_back(v);
134    }
135
136    // manipulate the state of the stream to be good
137    is.clear(std::ios::goodbit);
138    // convert the data to a gsl matrix
139    m_ = gsl_matrix_alloc ( nof_rows, nof_columns );
140    for(u_int i=0;i<nof_rows;i++)
141      for(u_int j=0;j<nof_columns;j++)
142        gsl_matrix_set( m_, i, j, data_matrix[i][j] );
143  }
144
145
146  matrix::~matrix(void)
147  {
148    if (view_)
149      delete view_;
150    else if (m_)
151      gsl_matrix_free(m_);
152    m_=NULL;
153  }
154
155
156
157  bool matrix::equal(const matrix& other, const double d) const
158  {
159    if (columns()!=other.columns() || rows()!=other.rows())
160      return false;
161    for (size_t i=0; i<rows(); i++)
162      for (size_t j=0; j<columns(); j++)
163        // The two last condition checks are needed for NaN detection
164        if (fabs( (*this)(i,j)-other(i,j) ) > d ||
165            (*this)(i,j)!=(*this)(i,j) || other(i,j)!=other(i,j))
166          return false;
167    return true;
168  }
169
170
171
172  gsl_matrix* matrix::create_gsl_matrix_copy(void) const
173  {
174    gsl_matrix* m = gsl_matrix_alloc(rows(),columns());
175    gsl_matrix_memcpy(m,m_);  // Jari, a GSL return value is ignored here
176    return m;
177  }
178
179
180
181  bool matrix::nan(matrix &m) const
182  {
183    m=matrix(rows(),columns(),1.0);
184    bool nan=false;
185    for (size_t i=0; i<rows(); i++)
186      for (size_t j=0; j<columns(); j++) 
187        if (std::isnan(operator()(i,j))) {
188          m(i,j)=0;
189          nan=true;
190        }
191    return nan;
192  }
193
194
195
196  // Jari, checkout GSL transpose support in GSL manual 8.4.9
197  void matrix::transpose(void)
198  {
199    if (columns()==rows())
200      gsl_matrix_transpose(m_);
201    else {
202      gsl_matrix* transposed = gsl_matrix_alloc(columns(),rows());
203      gsl_matrix_transpose_memcpy(transposed,m_);
204      gsl_matrix_free(m_);
205      m_=transposed;
206    }
207  }
208
209
210
211  const vector matrix::operator*(const vector&) const
212  {
213    std::cerr << "Not implemented:" << std::endl
214              << "   const vector matrix::operator*(const vector&) const"
215              << std::endl;
216    return vector(0);
217  }
218
219
220
221  const matrix& matrix::operator=( const matrix& other )
222  {
223    if ( this != &other ) {
224      if (view_)
225        delete view_;
226      else if (m_)
227        gsl_matrix_free(m_);
228      m_ = other.create_gsl_matrix_copy();
229    }
230    return *this;
231  }
232
233
234  const matrix& matrix::operator+=(const matrix& m)
235  {
236    add(m);
237    return *this;
238  }
239
240
241  const matrix& matrix::operator+=(const double d)
242  {
243    add_constant(d);
244    return *this;
245  }
246
247
248  const matrix& matrix::operator-=(const matrix& m)
249  {
250    sub(m);
251    return *this;
252  }
253
254
255  const matrix& matrix::operator*=(const matrix& other)
256  {
257    gsl_matrix* result = gsl_matrix_alloc(rows(),other.columns());
258    gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, m_, other.m_, 0.0, result);
259    gsl_matrix_free(m_);
260    m_=result;
261    return *this;
262  }
263
264
265  const matrix& matrix::operator*=(const double d)
266  {
267    scale(d);
268    return *this;
269  }
270
271
272  std::ostream& operator<<(std::ostream& s, const matrix& m)
273  {
274    s.setf(std::ios::dec);
275    s.precision(12);
276    for(size_t i=0, j=0; i<m.rows(); i++)
277      for (j=0; j<m.columns(); j++) {
278        s << m(i,j);
279        if (j<m.columns()-1)
280          s << s.fill();
281        else if (i<m.rows()-1)
282          s << "\n";
283      }
284    return s;
285  }
286
287
288}}} // of namespace utility, yat and thep
Note: See TracBrowser for help on using the repository browser.