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

Last change on this file since 825 was 825, checked in by Peter, 16 years ago

removed minmax functions and moved shuffle into vector.*

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