source: trunk/yat/utility/Matrix.cc @ 1682

Last change on this file since 1682 was 1682, checked in by Peter, 15 years ago

prefer std::abs and re-use code

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 13.0 KB
Line 
1// $Id: Matrix.cc 1682 2008-12-29 21:27:32Z peter $
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  Copyright (C) 2007, 2008 Jari Häkkinen, Peter Johansson
8
9  This file is part of the yat library, http://dev.thep.lu.se/yat
10
11  The yat library is free software; you can redistribute it and/or
12  modify it under the terms of the GNU General Public License as
13  published by the Free Software Foundation; either version 3 of the
14  License, or (at your option) any later version.
15
16  The yat library is distributed in the hope that it will be useful,
17  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  General Public License for more details.
20
21  You should have received a copy of the GNU General Public License
22  along with yat. If not, see <http://www.gnu.org/licenses/>.
23*/
24
25#include "Matrix.h"
26#include "Vector.h"
27#include "VectorBase.h"
28#include "VectorConstView.h"
29#include "VectorView.h"
30#include "utility.h"
31
32#include <cassert>
33#include <cmath>
34#include <sstream>
35#include <vector>
36
37#include <gsl/gsl_blas.h>
38
39namespace theplu {
40namespace yat {
41namespace utility {
42
43
44  Matrix::Matrix(void)
45    : blas_result_(NULL), m_(NULL)
46  {
47  }
48
49
50  Matrix::Matrix(const size_t& r, const size_t& c, double init_value)
51    : blas_result_(NULL), m_(NULL)
52  {
53    resize(r,c,init_value);
54  }
55
56
57  Matrix::Matrix(const Matrix& o)
58    : blas_result_(NULL), m_(o.create_gsl_matrix_copy())
59  {
60  }
61
62
63  // Constructor that gets data from istream
64  Matrix::Matrix(std::istream& is, char sep) 
65    throw (utility::IO_error,std::exception)
66    : blas_result_(NULL)
67  {
68    if (!is.good())
69      throw utility::IO_error("Matrix: istream is not good");
70
71    // read the data file and store in stl vectors (dynamically
72    // expandable)
73    std::vector<std::vector<double> > data_matrix;
74    unsigned int nof_columns=0;
75    unsigned int nof_rows = 0;
76    std::string line;
77    while(getline(is, line, '\n')){
78      // Ignoring empty lines
79      if (!line.size()) {
80        continue;
81      }
82      nof_rows++;
83      data_matrix.resize(data_matrix.size()+1);
84      std::vector<double>& v=data_matrix.back();
85      std::string element;
86      std::stringstream ss(line);
87     
88      bool ok=true;
89      while(ok) {
90        if(sep=='\0')
91          ok=(ss>>element);
92        else
93          ok=getline(ss, element, sep);
94        if(!ok)
95          break;
96       
97        if (!element.size())
98          v.push_back(std::numeric_limits<double>::quiet_NaN());
99        else {
100          try {
101            v.push_back(convert<double>(element));
102          }
103          catch (std::runtime_error& e) {
104            std::stringstream ss(e.what());
105            ss << "\nMatrix.cc: " << element
106               << " is not accepted as a matrix element\n";
107            throw IO_error(ss.str());
108          }
109        }
110      }           
111      if(sep!='\0' && line[line.size()-1]==sep) // add NaN for final separator
112          v.push_back(std::numeric_limits<double>::quiet_NaN());
113      if (!nof_columns)
114        nof_columns=v.size();
115      else if (v.size()!=nof_columns) {
116        std::ostringstream s;
117        s << "Matrix::Matrix(std::istream&, char) data file error: "
118          << "line " << nof_rows << " has " << v.size()
119          << " columns; expected " << nof_columns << " columns.";
120        throw utility::IO_error(s.str());
121      }
122    }
123
124    // manipulate the state of the stream to be good
125    is.clear(std::ios::goodbit);
126   
127    // if stream was empty, create nothing
128    if (!nof_columns || !nof_rows)
129      return;
130
131    // convert the data to a gsl matrix
132    m_ = gsl_matrix_alloc ( nof_rows, nof_columns );
133    if (!m_)
134      throw utility::GSL_error("Matrix::Matrix failed to allocate memory");
135
136    // if gsl error handler disabled, out of bounds index will not
137    // abort the program.
138    for(size_t i=0;i<nof_rows;i++)
139      for(size_t j=0;j<nof_columns;j++)
140        gsl_matrix_set( m_, i, j, data_matrix[i][j] );
141  }
142
143
144  Matrix::~Matrix(void)
145  {
146    delete_allocated_memory();
147    if (blas_result_)
148      gsl_matrix_free(blas_result_);
149    blas_result_=NULL;
150  }
151
152
153  void Matrix::all(const double value)
154  {
155    assert(m_);
156    gsl_matrix_set_all(m_, value);
157  }
158
159
160  Matrix::iterator Matrix::begin(void)
161  {
162    return iterator(&(*this)(0,0), 1);
163  }
164
165
166  Matrix::const_iterator Matrix::begin(void) const
167  {
168    return const_iterator(&(*this)(0,0), 1);
169  }
170
171
172  Matrix::column_iterator Matrix::begin_column(size_t i)
173  {
174    return iterator(&(*this)(0,i), this->columns());
175  }
176
177
178  Matrix::const_column_iterator Matrix::begin_column(size_t i) const
179  {
180    return const_iterator(&(*this)(0,i), this->columns());
181  }
182
183
184  Matrix::row_iterator Matrix::begin_row(size_t i)
185  {
186    return iterator(&(*this)(i,0), 1);
187  }
188
189
190  Matrix::const_row_iterator Matrix::begin_row(size_t i) const
191  {
192    return const_iterator(&(*this)(i,0), 1);
193  }
194
195
196  VectorView Matrix::column_view(size_t col)
197  {
198    VectorView res(*this, col, false);
199    return res;
200  }
201
202
203  const VectorConstView Matrix::column_const_view(size_t col) const
204  {
205    return VectorConstView(*this, col, false);
206  }
207
208
209  size_t Matrix::columns(void) const
210  {
211    return (m_ ? m_->size2 : 0);
212  }
213
214
215  gsl_matrix* Matrix::create_gsl_matrix_copy(void) const
216  {
217    if (!m_)
218      return NULL;
219    gsl_matrix* m = gsl_matrix_alloc(rows(),columns());
220    if (!m)
221      throw utility::GSL_error("Matrix::create_gsl_matrix_copy failed to allocate memory");
222    if (gsl_matrix_memcpy(m,m_))
223      throw utility::GSL_error("Matrix::create_gsl_matrix_copy dimension mis-match");
224    return m;
225  }
226
227
228  void Matrix::delete_allocated_memory(void)
229  {
230    if (m_)
231      gsl_matrix_free(m_);
232    m_=NULL;
233  }
234
235
236  void Matrix::div(const Matrix& other)
237  {
238    assert(m_);
239    int status=gsl_matrix_div_elements(m_, other.gsl_matrix_p());
240    if (status)
241      throw utility::GSL_error(std::string("matrix::div_elements",status));
242  }
243
244
245  Matrix::iterator Matrix::end(void)
246  {
247    return iterator(&(*this)(0,0)+rows()*columns(), 1);
248  }
249
250
251  Matrix::const_iterator Matrix::end(void) const
252  {
253    return const_iterator(&(*this)(0,0)+rows()*columns(), 1);
254  }
255
256
257  Matrix::column_iterator Matrix::end_column(size_t i)
258  {
259    return column_iterator(&(*this)(0,i)+rows()*columns(), this->columns());
260  }
261
262
263  Matrix::const_column_iterator Matrix::end_column(size_t i) const
264  {
265    return const_column_iterator(&(*this)(0,i)+rows()*columns(),this->columns());
266  }
267
268
269  Matrix::row_iterator Matrix::end_row(size_t i)
270  {
271    return row_iterator(&(*this)(i,0)+columns(), 1);
272  }
273
274
275  Matrix::const_row_iterator Matrix::end_row(size_t i) const
276  {
277    return const_row_iterator(&(*this)(i,0)+columns(), 1);
278  }
279
280
281  bool Matrix::equal(const Matrix& other, const double d) const
282  {
283    if (this==&other)
284      return true;
285    if (columns()!=other.columns() || rows()!=other.rows())
286      return false;
287    for (size_t i=0; i<rows(); i++)
288      if (!row_const_view(i).equal(other.row_const_view(i), d))
289        return false;
290    return true;
291  }
292
293
294  const gsl_matrix* Matrix::gsl_matrix_p(void) const
295  {
296    return m_;
297  }
298
299
300  gsl_matrix* Matrix::gsl_matrix_p(void)
301  {
302    return m_;
303  }
304
305
306  void Matrix::mul(const Matrix& other)
307  {
308    assert(m_);
309    int status=gsl_matrix_mul_elements(m_, other.gsl_matrix_p());
310    if (status)
311      throw utility::GSL_error(std::string("Matrix::mul_elements",status));
312  }
313
314
315  void Matrix::resize(size_t r, size_t c, double init_value)
316  {
317    delete_allocated_memory();
318
319    assert( (r&&c) || (!r&&!c) );
320    if (r && c){
321      m_ = gsl_matrix_alloc(r,c);
322      if (!m_)
323        throw utility::GSL_error("Matrix::Matrix failed to allocate memory");
324      all(init_value);
325    }
326
327    // no need to delete blas_result_ if the number of rows fit, it
328    // may be useful later.
329    if (blas_result_ && (blas_result_->size1!=rows())) {
330      gsl_matrix_free(blas_result_);
331      blas_result_=NULL;
332    }
333  }
334
335
336  size_t Matrix::rows(void) const
337  {
338    return (m_ ? m_->size1 : 0);
339  }
340
341
342  const VectorConstView Matrix::row_const_view(size_t col) const
343  {
344    return VectorConstView(*this, col, true);
345  }
346
347
348  VectorView Matrix::row_view(size_t row)
349  {
350    VectorView res(*this, row, true);
351    return res;
352  }
353
354
355  void Matrix::swap_columns(const size_t i, const size_t j)
356  {
357    assert(m_);
358    int status=gsl_matrix_swap_columns(m_, i, j);
359    if (status)
360      throw utility::GSL_error(std::string("Matrix::swap_columns",status));
361  }
362
363
364  void Matrix::swap_rowcol(const size_t i, const size_t j)
365  {
366    assert(m_);
367    int status=gsl_matrix_swap_rowcol(m_, i, j);
368    if (status)
369      throw utility::GSL_error(std::string("Matrix::swap_rowcol",status));
370  }
371
372
373  void Matrix::swap_rows(const size_t i, const size_t j)
374  {
375    assert(m_);
376    int status=gsl_matrix_swap_rows(m_, i, j);
377    if (status)
378      throw utility::GSL_error(std::string("Matrix::swap_rows",status));
379  }
380
381
382  void Matrix::transpose(void)
383  {
384    assert(m_);
385    if (columns()==rows())
386      gsl_matrix_transpose(m_); // this never fails
387    else {
388      gsl_matrix* transposed = gsl_matrix_alloc(columns(),rows());
389      if (!transposed)
390        throw utility::GSL_error("Matrix::transpose failed to allocate memory");
391      // next line never fails if allocation above succeeded.
392      gsl_matrix_transpose_memcpy(transposed,m_);
393      gsl_matrix_free(m_);
394      m_ = transposed;
395      if (blas_result_) {
396        gsl_matrix_free(blas_result_);
397        blas_result_=NULL;
398      }
399    }
400  }
401
402
403  double& Matrix::operator()(size_t row, size_t column)
404  {
405    assert(m_);
406    assert(row<rows());
407    assert(column<columns());
408    double* d=gsl_matrix_ptr(m_, row, column);
409    if (!d)
410      throw utility::GSL_error("Matrix::operator()",GSL_EINVAL);
411    return *d;
412  }
413
414
415  const double& Matrix::operator()(size_t row, size_t column) const
416  {
417    assert(row<rows());
418    assert(column<columns());
419    const double* d=gsl_matrix_const_ptr(m_, row, column);
420    if (!d)
421      throw utility::GSL_error("Matrix::operator()",GSL_EINVAL);
422    return *d;
423  }
424
425
426  bool Matrix::operator==(const Matrix& other) const
427  {
428    return equal(other);
429  }
430
431
432  bool Matrix::operator!=(const Matrix& other) const
433  {
434    return !equal(other);
435  }
436
437
438  const Matrix& Matrix::operator=( const Matrix& other )
439  {
440    if (this!=&other) {
441      if (rows()!=other.rows() || columns()!=other.columns())
442        resize(other.rows(), other.columns());
443       
444      if (m_)
445        if (gsl_matrix_memcpy(m_, other.gsl_matrix_p())) {
446          std::string s="Matrix::operator=  assignment failed";
447          throw utility::GSL_error(s);
448        }
449    }
450    return *this;
451  }
452
453
454  const Matrix& Matrix::operator+=(const Matrix& other)
455  {
456    assert(m_);
457    int status=gsl_matrix_add(m_, other.m_);
458    if (status)
459      throw utility::GSL_error(std::string("Matrix::operator+=", status));
460    return *this;
461  }
462
463
464  const Matrix& Matrix::operator+=(const double d)
465  {
466    assert(m_);
467    gsl_matrix_add_constant(m_, d);
468    return *this;
469  }
470
471
472  const Matrix& Matrix::operator-=(const Matrix& other)
473  {
474    assert(m_);
475    int status=gsl_matrix_sub(m_, other.m_);
476    if (status)
477      throw utility::GSL_error(std::string("Matrix::operator-=", status));
478    return *this;
479  }
480
481
482  const Matrix& Matrix::operator-=(const double d)
483  {
484    assert(m_);
485    gsl_matrix_add_constant(m_, -d);
486    return *this;
487  }
488
489
490  const Matrix& Matrix::operator*=(const Matrix& other)
491  {
492    assert(m_);
493    if ( blas_result_ && ((blas_result_->size1!=rows()) ||
494                          (blas_result_->size2!=other.columns())) ) {
495      gsl_matrix_free(blas_result_);
496      blas_result_=NULL;
497    }
498    if (!blas_result_) {
499      blas_result_ = gsl_matrix_alloc(rows(),other.columns());
500      if (!blas_result_)
501        throw utility::GSL_error("Matrix::operator*= failed to allocate memory");
502    }
503    gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, m_, other.m_, 0.0, blas_result_);
504    gsl_matrix* tmp=m_;
505    m_ = blas_result_;
506    blas_result_=tmp;
507    return *this;
508  }
509
510
511  const Matrix& Matrix::operator*=(const double d)
512  {
513    assert(m_);
514    gsl_matrix_scale(m_, d);
515    return *this;
516  }
517
518
519  bool isnull(const Matrix& other)
520  {
521    return gsl_matrix_isnull(other.gsl_matrix_p());
522  }
523
524
525  double max(const Matrix& other)
526  {
527    return gsl_matrix_max(other.gsl_matrix_p());
528  }
529
530
531  double min(const Matrix& other)
532  {
533    return gsl_matrix_min(other.gsl_matrix_p());
534  }
535
536
537  void minmax_index(const Matrix& other,
538                    std::pair<size_t,size_t>& min, std::pair<size_t,size_t>& max)
539  {
540    gsl_matrix_minmax_index(other.gsl_matrix_p(), &min.first, &min.second,
541                            &max.first, &max.second);
542  }
543
544
545  bool nan(const Matrix& templat, Matrix& flag)
546  {
547    size_t rows=templat.rows();
548    size_t columns=templat.columns();
549    if (rows!=flag.rows() && columns!=flag.columns())
550      flag.resize(rows,columns,1.0);
551    else
552      flag.all(1.0);
553    bool nan=false;
554    for (size_t i=0; i<rows; i++)
555      for (size_t j=0; j<columns; j++) 
556        if (std::isnan(templat(i,j))) {
557          flag(i,j)=0;
558          nan=true;
559        }
560    return nan;
561  }
562
563
564  void swap(Matrix& a, Matrix& b)
565  {
566    assert(a.gsl_matrix_p()); assert(b.gsl_matrix_p());
567    int status=gsl_matrix_swap(a.gsl_matrix_p(), b.gsl_matrix_p());
568    if (status)
569      throw utility::GSL_error(std::string("swap(Matrix&,Matrix&)",status));
570  }
571
572
573  std::ostream& operator<<(std::ostream& s, const Matrix& m)
574  {
575    s.setf(std::ios::dec);
576    s.precision(12);
577    for(size_t i=0, j=0; i<m.rows(); i++)
578      for (j=0; j<m.columns(); j++) {
579        s << m(i,j);
580        if (j<m.columns()-1)
581          s << s.fill();
582        else if (i<m.rows()-1)
583          s << "\n";
584      }
585    return s;
586  }
587
588
589  Vector operator*(const Matrix& m, const VectorBase& v)
590  {
591    utility::Vector res(m.rows());
592    for (size_t i=0; i<res.size(); ++i)
593      res(i) = VectorConstView(m,i) * v;
594    return res;
595  }
596
597
598  Vector operator*(const VectorBase& v, const Matrix& m)
599  {
600    utility::Vector res(m.columns());
601    for (size_t i=0; i<res.size(); ++i)
602      res(i) = v * VectorConstView(m,i,false);
603    return res;
604  }
605
606}}} // of namespace utility, yat and thep
Note: See TracBrowser for help on using the repository browser.