source: trunk/yat/utility/vector.cc @ 789

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

Addresses #193. vector now works as outlined here. Added some
functionality. Added a clone function that facilitates resizing of
vectors. clone is needed since assignement operator functionality is
changed.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 11.5 KB
Line 
1// $Id: vector.cc 789 2007-03-10 20:07:13Z jari $
2
3/*
4  Copyright (C) 2003 Daniel Dalevi, Peter Johansson
5  Copyright (C) 2004 Jari Häkkinen, Peter Johansson
6  Copyright (C) 2005 Jari Häkkinen, Peter Johansson, Markus Ringnér
7  Copyright (C) 2006, 2007 Jari Häkkinen, Peter Johansson
8
9  This file is part of the yat library, http://lev.thep.lu.se/trac/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 2 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 this program; if not, write to the Free Software
23  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
24  02111-1307, USA.
25*/
26
27#include "vector.h"
28#include "matrix.h"
29#include "utility.h"
30
31#include <cassert>
32#include <cmath>
33#include <iostream>
34#include <sstream>
35#include <utility>
36#include <vector>
37
38namespace theplu {
39namespace yat {
40namespace utility {
41
42
43  vector::vector(void)
44    : v_(NULL), view_(NULL), view_const_(NULL), proxy_v_(NULL)
45  {
46  }
47
48
49  vector::vector(size_t n, double init_value)
50    : v_(gsl_vector_alloc(n)), view_(NULL), view_const_(NULL),
51      proxy_v_(v_)
52  {
53    if (!v_)
54      throw utility::GSL_error("vector::vector failed to allocate memory");
55
56    set_all(init_value);
57  }
58
59
60  vector::vector(const vector& other)
61    : v_(other.create_gsl_vector_copy()), view_(NULL),
62      view_const_(NULL), proxy_v_(v_)
63  {
64  }
65
66
67  vector::vector(vector& v, size_t offset, size_t n, size_t stride)
68    : view_const_(NULL)
69  {
70    view_ = new gsl_vector_view(gsl_vector_subvector_with_stride(v.v_,offset,
71                                                                 stride,n));
72    if (!view_)
73      throw utility::GSL_error("vector::vector failed to setup view");
74    proxy_v_ = v_ = &(view_->vector);
75  }
76
77
78  vector::vector(const vector& v, size_t offset, size_t n, size_t stride)
79    : v_(NULL), view_(NULL)
80  {
81    view_const_ = new gsl_vector_const_view(
82                   gsl_vector_const_subvector_with_stride(v.v_,offset,stride,n));
83    if (!view_const_)
84      throw utility::GSL_error("vector::vector failed to setup view");
85    proxy_v_ = &(view_const_->vector);
86  }
87
88
89  vector::vector(matrix& m, size_t i, bool row)
90    : view_const_(NULL)
91  {
92    view_=new gsl_vector_view(row ?
93                              gsl_matrix_row   (m.gsl_matrix_p(),i) :
94                              gsl_matrix_column(m.gsl_matrix_p(),i)  );
95    if (!view_)
96      throw utility::GSL_error("vector::vector failed to setup view");
97    proxy_v_ = v_ = &(view_->vector);
98  }
99
100
101  vector::vector(const matrix& m, size_t i, bool row)
102    : v_(NULL), view_(NULL)
103  {
104    view_const_ = new gsl_vector_const_view(row ?
105                                   gsl_matrix_const_row   (m.gsl_matrix_p(),i) :
106                                   gsl_matrix_const_column(m.gsl_matrix_p(),i) );
107    if (!view_const_)
108      throw utility::GSL_error("vector::vector failed to setup view");
109    proxy_v_ = &(view_const_->vector);
110  }
111
112
113  vector::vector(std::istream& is, char sep)
114    throw (utility::IO_error, std::exception)
115    : view_(NULL), view_const_(NULL)
116  {
117    // read the data file and store in stl vectors (dynamically
118    // expandable)
119    std::vector<std::vector<double> > data_matrix;
120    u_int nof_columns=0;
121    u_int nof_rows=0;
122    std::string line;
123    while(getline(is, line, '\n')) {
124      // Empty lines
125      if (!line.size())
126          continue;
127      nof_rows++;
128
129      std::vector<double> v;
130      std::string element;
131      std::stringstream ss(line);
132      bool ok=true;
133      while(ok) {
134        if(sep=='\0')
135          ok=(ss>>element);
136        else 
137          ok=getline(ss, element, sep);
138        if(!ok)
139          break;       
140
141        if(utility::is_double(element)) {
142          v.push_back(atof(element.c_str()));
143        }
144        else if (!element.size() || utility::is_nan(element)) {
145          v.push_back(std::numeric_limits<double>::quiet_NaN());
146        }
147        else {
148          std::stringstream ss("Warning: '");
149          ss << element << "' is not an integer.";
150          throw IO_error(ss.str());
151        }
152      } 
153      if(sep!='\0' && line[line.size()-1]==sep) // add NaN for final separator
154          v.push_back(std::numeric_limits<double>::quiet_NaN());
155      if (!nof_columns)
156        nof_columns=v.size();
157      else if (nof_rows && (nof_columns>1)) {
158        std::ostringstream s;
159        s << "vector::vector(std::istream&) data file error:\n"
160          << "    File has inconsistent number of rows (" << nof_rows
161          << ") and columns (" << nof_columns
162          << ").\n    Expected a row or a column vector.";
163        throw utility::IO_error(s.str());
164      }
165      else if (v.size()!=nof_columns) {
166        std::ostringstream s;
167        s << "vector::vector(std::istream&) data file error:\n"
168          << "    Line " << nof_rows << " has " << v.size()
169          << " columns; expected " << nof_columns << " column.";
170        throw utility::IO_error(s.str());
171      }
172      data_matrix.push_back(v);
173    }
174
175    // manipulate the state of the stream to be good
176    is.clear(std::ios::goodbit);
177    // convert the data to a gsl vector
178    proxy_v_ = v_ = gsl_vector_alloc(nof_rows*nof_columns);
179    if (!v_)
180      throw utility::GSL_error("vector::vector failed to allocate memory");
181    size_t n=0;
182    // if gsl error handler disabled, out of bounds index will not
183    // abort the program.
184    for (size_t i=0; i<nof_rows; i++)
185      for (size_t j=0; j<nof_columns; j++) 
186        gsl_vector_set( v_, n++, data_matrix[i][j] );
187  }
188
189
190  vector::~vector(void)
191  {
192    if (view_)
193      delete view_;
194    else if (view_const_)
195      delete view_const_;
196    else if (v_)
197      gsl_vector_free(v_);
198  }
199
200
201  gsl_vector* vector::create_gsl_vector_copy(void) const
202  {
203    gsl_vector* vec = gsl_vector_alloc(size());
204    if (!vec)
205      throw utility::GSL_error("vector::create_gsl_vector_copy failed to allocate memory");
206    if (gsl_vector_memcpy(vec, proxy_v_))
207      throw utility::GSL_error("vector::create_gsl_matrix_copy dimension mis-match");
208    return vec;
209  }
210
211
212  const vector& vector::clone(const vector& other)
213  {
214    if (this!=&other) {
215
216      if (view_)
217        delete view_;
218      else if (view_const_)
219        delete view_const_;
220      else if (v_)
221        gsl_vector_free(v_);
222
223      if (other.view_) {
224        view_ = new gsl_vector_view(*other.view_);
225        proxy_v_ = v_ = &(view_->vector);
226      }
227      else if (other.view_const_) {
228        view_const_ = new gsl_vector_const_view(*other.view_const_);
229        proxy_v_ = &(view_const_->vector);
230        v_=NULL;
231      }
232      else if (other.v_)
233        proxy_v_ = v_ = other.create_gsl_vector_copy();
234
235    }
236    return *this;
237  } 
238
239
240  void vector::div(const vector& other)
241  {
242    assert(v_);
243    int status=gsl_vector_div(v_,other.gsl_vector_p());
244    if (status)
245      throw utility::GSL_error(std::string("vector::div",status));
246  }
247
248
249  bool vector::equal(const vector& other, const double d) const
250  {
251    if (this==&other)
252      return true;
253    if (size()!=other.size())
254      return false;
255    // if gsl error handler disabled, out of bounds index will not
256    // abort the program.
257    for (size_t i=0; i<size(); ++i)
258      // The two last condition checks are needed for NaN detection
259      if (fabs( (*this)(i)-other(i) ) > d ||
260          (*this)(i)!=(*this)(i) || other(i)!=other(i))
261        return false;
262    return true;
263  }
264
265
266  const gsl_vector* vector::gsl_vector_p(void) const
267  {
268    return proxy_v_;
269  }
270
271
272  gsl_vector* vector::gsl_vector_p(void)
273  {
274    return v_;
275  }
276
277
278  bool vector::isview(void) const
279  {
280    return view_ || view_const_;
281  }
282
283
284  void vector::mul(const vector& other)
285  {
286    assert(v_);
287    int status=gsl_vector_mul(v_,other.gsl_vector_p());
288    if (status)
289      throw utility::GSL_error(std::string("vector::mul",status));
290  }
291
292
293  void vector::reverse(void)
294  {
295    assert(v_);
296    gsl_vector_reverse(v_);
297  }
298
299
300  void vector::set(const vector& vec)
301  {
302    assert(v_);
303    if (gsl_vector_memcpy(v_,vec.gsl_vector_p()))
304      throw utility::GSL_error("vector::set dimension mis-match");
305  }
306
307
308  void vector::set_all(const double& value)
309  {
310    assert(v_);
311    gsl_vector_set_all(v_,value);
312  }
313
314
315  size_t vector::size(void) const
316  {
317    if (!proxy_v_)
318      return 0;
319    return proxy_v_->size;
320  }
321
322
323  void vector::swap(size_t i, size_t j)
324  {
325    assert(v_);
326    int status=gsl_vector_swap_elements(v_, i, j);
327    if (status)
328      throw utility::GSL_error(std::string("vector::swap_elements",status));
329  }
330
331
332  double& vector::operator()(size_t i)
333  {
334    assert(v_);
335    double* d=gsl_vector_ptr(v_, i);
336    if (!d)
337      throw utility::GSL_error("vector::operator()",GSL_EINVAL);
338    return *d;
339  }
340
341
342  const double& vector::operator()(size_t i) const
343  {
344    const double* d=gsl_vector_const_ptr(proxy_v_, i);
345    if (!d)
346      throw utility::GSL_error("vector::operator()",GSL_EINVAL);
347    return *d;
348  }
349
350
351  double& vector::operator[](size_t i)
352  {
353    return this->operator()(i);
354  }
355
356
357  const double& vector::operator[](size_t i) const
358  {
359    return this->operator()(i);
360  }
361
362
363  bool vector::operator==(const vector& other) const
364  {
365    return equal(other);
366  }
367
368
369  bool vector::operator!=(const vector& other) const
370  {
371    return !equal(other);
372  }
373
374
375  double vector::operator*( const vector &other ) const
376  {
377    double res = 0.0;;
378    for ( size_t i = 0; i < size(); ++i ) 
379      res += other(i) * (*this)(i);
380    return res;
381  }
382
383
384  const vector& vector::operator=( const vector& other )
385  {
386    if( this != &other ) {
387      if (size()!=other.size())
388        throw utility::GSL_error("vector::operator= vector sizes differ");
389      for (size_t i=0; i<size(); ++i)
390        gsl_vector_set(v_, i, other(i));
391    }
392    return *this;
393  } 
394
395
396  const vector& vector::operator+=(const vector& other)
397  {
398    assert(v_);
399    int status=gsl_vector_add(v_, other.gsl_vector_p());
400    if (status)
401      throw utility::GSL_error(std::string("vector::add", status));
402    return *this;
403  }
404
405
406  const vector& vector::operator+=(double d)
407  {
408    assert(v_);
409    gsl_vector_add_constant(v_, d);
410    return *this;
411  }
412
413
414  const vector& vector::operator-=(const vector& other)
415  {
416    assert(v_);
417    int status=gsl_vector_sub(v_, other.gsl_vector_p());
418    if (status)
419      throw utility::GSL_error(std::string("vector::sub", status));
420    return *this;
421  }
422
423
424  const vector& vector::operator*=(const double d)
425  {
426    assert(v_);
427    gsl_vector_scale(v_, d);
428    return *this;
429  }
430
431
432  bool isnull(const vector& v)
433  {
434    return gsl_vector_isnull(v.gsl_vector_p());
435  }
436
437
438  double max(const vector& v)
439  {
440    return gsl_vector_max(v.gsl_vector_p());
441  }
442
443
444  size_t max_index(const vector& v)
445  {
446    return gsl_vector_max_index(v.gsl_vector_p());
447  }
448
449
450  double min(const vector& v)
451  {
452    return gsl_vector_min(v.gsl_vector_p());
453  }
454
455
456  size_t min_index(const vector& v)
457  {
458    return gsl_vector_min_index(v.gsl_vector_p());
459  }
460
461
462  std::pair<double,double> minmax(const vector& v)
463  {
464    std::pair<double,double> minmax;
465    gsl_vector_minmax(v.gsl_vector_p(), &minmax.first, &minmax.second);
466    return minmax;
467  }
468
469
470  std::pair<size_t,size_t> minmax_index(const vector& v)
471  {
472    std::pair<size_t,size_t> minmax;
473    gsl_vector_minmax_index(v.gsl_vector_p(), &minmax.first, &minmax.second);
474    return minmax;
475  }
476
477
478  void set_basis(vector& v, size_t i)
479  {
480    assert(v.gsl_vector_p());
481    gsl_vector_set_basis(v.gsl_vector_p(),i);
482  }
483
484
485  void sort(vector& v)
486  {
487    assert(v.gsl_vector_p());
488    gsl_sort_vector(v.gsl_vector_p());
489  }
490
491
492  double sum(const vector& v)
493  {
494    double sum = 0;
495    size_t vsize=v.size();
496    for (size_t i=0; i<vsize; ++i)
497      sum += v[i];
498    return sum;
499  }
500
501
502  void swap(vector& v, vector& w)
503  {
504    assert(v.gsl_vector_p()); assert(w.gsl_vector_p());
505    int status=gsl_vector_swap(v.gsl_vector_p(),w.gsl_vector_p());
506    if (status)
507      throw utility::GSL_error(std::string("swap(vector&,vector&)",status));
508  }
509
510
511  std::ostream& operator<<(std::ostream& s, const vector& a)
512  {
513    s.setf(std::ios::dec);
514    s.precision(12);
515    for (size_t j = 0; j < a.size(); ++j) {
516      s << a[j];
517      if ( (j+1)<a.size() )
518        s << s.fill();
519    }
520    return s;
521  }
522
523}}} // of namespace utility, yat, and thep
Note: See TracBrowser for help on using the repository browser.