source: trunk/yat/utility/vector.h @ 966

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

fixing some doxygen warnings

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 17.0 KB
Line 
1#ifndef _theplu_yat_utility_vector_
2#define _theplu_yat_utility_vector_
3
4// $Id: vector.h 966 2007-10-11 17:01:01Z peter $
5
6/*
7  Copyright (C) 2003 Daniel Dalevi, Peter Johansson
8  Copyright (C) 2004 Jari Häkkinen, Peter Johansson
9  Copyright (C) 2005 Jari Häkkinen, Markus Ringnér, Peter Johansson
10  Copyright (C) 2006 Jari Häkkinen, Markus Ringnér
11  Copyright (C) 2007 Jari Häkkinen, Peter Johansson
12
13  This file is part of the yat library, http://trac.thep.lu.se/trac/yat
14
15  The yat library is free software; you can redistribute it and/or
16  modify it under the terms of the GNU General Public License as
17  published by the Free Software Foundation; either version 2 of the
18  License, or (at your option) any later version.
19
20  The yat library is distributed in the hope that it will be useful,
21  but WITHOUT ANY WARRANTY; without even the implied warranty of
22  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23  General Public License for more details.
24
25  You should have received a copy of the GNU General Public License
26  along with this program; if not, write to the Free Software
27  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
28  02111-1307, USA.
29*/
30
31#include "Exception.h"
32#include "Iterator.h"
33
34#include <iostream>
35#include <vector>
36#include <utility>
37
38#include <gsl/gsl_vector.h>
39#include <gsl/gsl_sort_vector.h>
40
41namespace theplu {
42namespace yat {
43namespace utility {
44
45  class matrix;
46
47  /**
48     @brief This is the yat interface to GSL vector.
49
50     For time being 'double' is the only type supported.
51
52     \par File streams:
53     Reading and writing vectors to file streams are of course
54     supported. These are implemented without using GSL functionality,
55     and thus binary read and write to streams are not supported.
56
57     \par Vector views:
58     GSL vector views are supported and these are disguised as
59     ordinary utility::vectors. A support function is added,
60     utility::vector::isview(), that can be used to check if a vector
61     object is a view. Note that view vectors do not own the
62     underlying data, and a view is not valid if the vector/matrix
63     owing the data is deallocated.
64
65     \par
66     Currently there is no restriction on how a vector is used when
67     the vector is a const view into another vector or matrix. To
68     avoid unexpected runtime errors, the programmer must declare
69     const view vectors as 'const' in order to get compile time
70     diagnostics about improper use of a const view vector object. If
71     'const' is not used and the const view vector is used erroneously
72     (such as on the left hand side in assignments), the compiler will
73     not catch the error and runtime error will occur. assert(3) is
74     used to catch the runtime error during development. Example on
75     bad and proper use of const view vectors:
76     @code
77  const vector vm(13,1.0);
78  vector v1(vm,2,4);       // bad code! not const!
79  v1(0)=-123;              // accepted by compiler, runtime abort will occur
80                           // or catched by assert depending on compiler flags
81  const vector v2(vm,2,4); // proper code
82  v2(0)=-123;              // not acceptable for the compiler
83     @endcode
84  */
85
86  class vector
87  {
88  public:
89
90    /// \brief vector::iterator
91    typedef Iterator<double&, vector> iterator;
92    /// \brief vector::const_iterator
93    typedef Iterator<const double, const vector> const_iterator;
94
95    /**
96       \brief The default constructor.
97    */
98    vector(void);
99
100    /**
101       \brief Allocates memory space for \a n elements, and sets all
102       elements to \a init_value.
103       
104       \throw GSL_error if memory allocation fails.
105    */
106    vector(size_t n, double init_value=0);
107
108    /**
109       \brief The copy constructor.
110
111       \note If the object to be copied is a vector view, the values
112       of the view will be copied, i.e. the view is not copied.
113
114       \throw A GSL_error is indirectly thrown if memory allocation
115       fails.
116    */
117    vector(const vector& other);
118
119    /**
120       \brief Vector view constructor.
121
122       Create a view of vector \a v, with starting index \a offset,
123       size \a n, and an optional \a stride.
124
125       A vector view can be used as any vector with the difference
126       that changes made to the view will also change the object that
127       is viewed. Also, using the copy constructor will create a new
128       vector object that is a copy of whatever is viewed. If a copy
129       of the view is needed then you should use this constructor to
130       obtain a copy.
131
132       \note If the object viewed by the view goes out of scope or is
133       deleted, the view becomes invalid and the result of further use
134       is undefined.
135
136       \throw GSL_error if a view cannot be set up.
137    */
138    vector(vector& v, size_t offset, size_t n, size_t stride=1);
139
140    /**
141       \brief Vector const view constructor.
142
143       Create a view of vector \a v, with starting index \a offset,
144       size \a n, and an optional \a stride.
145
146       A vector view can be used as any const vector. Using the copy
147       constructor will create a new vector object that is a copy of
148       whatever is viewed. If a copy of the view is needed then you
149       should use this constructor to obtain a copy.
150
151       \note If the object viewed by the view goes out of scope or is
152       deleted, the view becomes invalid and the result of further use
153       is undefined.
154
155       \throw GSL_error if a view cannot be set up.
156    */
157    vector(const vector& v, size_t offset, size_t n, size_t stride=1);
158
159    ///
160    /// Matrix row/column view constructor.
161    ///
162    /// Create a row/column vector view of matrix \a m, pointing at
163    /// row/column \a i. The parameter \a row is used to set whether
164    /// the view should be a row or column view. If \a row is set to
165    /// true, the view will be a row view (default behaviour), and,
166    /// naturally, a column view otherwise.
167    ///
168    /// A vector view can be used as any vector with the difference
169    /// that changes made to the view will also change the object that
170    /// is viewed. Also, using the copy constructor will create a new
171    /// vector object that is a copy of whatever is viewed. If a copy
172    /// of the view is needed then you should use the vector view
173    /// constructor to obtain a copy.
174    ///
175    /// @note If the object viewed by the view goes out of scope or is
176    /// deleted, the view becomes invalid and the result of further
177    /// use is undefined.
178    ///
179    vector(matrix& m, size_t i, bool row=true);
180
181    ///
182    /// Matrix row/column const view constructor.
183    ///
184    /// Create a row/column vector view of matrix \a m, pointing at
185    /// row/column \a i. The parameter \a row is used to set whether
186    /// the view should be a row or column view. If \a row is set to
187    /// true, the view will be a row view (default behaviour), and,
188    /// naturally, a column view otherwise.
189    ///
190    /// A const vector view can be used as any const vector. Using the
191    /// copy constructor will create a new vector object that is a
192    /// copy of whatever is viewed. If a copy of the view is needed
193    /// then you should use the vector view constructor to obtain a
194    /// copy.
195    ///
196    /// @note If the object viewed by the view goes out of scope or is
197    /// deleted, the view becomes invalid and the result of further
198    /// use is undefined.
199    ///
200    vector(const matrix& m, size_t i, bool row=true);
201
202    /**
203       \brief The istream constructor.
204
205       Either elements should be separated with white space characters
206       (default), or elements should be separated by the delimiter \a
207       sep. When delimiter \a sep is used empty elements are stored as
208       NaN's (except that empty lines are ignored). The end of input
209       to the vector is at end of file marker.
210
211       \throw GSL_error if memory allocation fails, IO_error if
212       unexpected input is found in the input stream.
213    */
214    explicit vector(std::istream &, char sep='\0')
215      throw(utility::IO_error, std::exception);
216
217    ///
218    /// The destructor.
219    ///
220    ~vector(void);
221
222    /**
223       \return mutable iterator to start of vector
224     */
225    iterator begin(void);
226
227    /**
228       \return read-only iterator to start of vector
229     */
230    const_iterator begin(void) const;
231
232    /**
233       \brief Make a copy of \a other.
234
235       This function will make a deep copy of \a other. Memory is
236       resized and view state is changed if needed.
237    */
238    const vector& clone(const vector& other);
239
240    /**
241       \brief This function performs element-wise division, \f$ this_i =
242       this_i/other_i \; \forall i \f$.
243
244       \throw GSL_error if dimensions mis-match.
245    */
246    void div(const vector& other);
247
248    /**
249       \return mutable iterator to end of vector
250     */
251    iterator end(void);
252
253    /**
254       \return read-only iterator to end of vector
255     */
256    const_iterator end(void) const;
257
258    /**
259       \brief Check whether vectors are equal within a user defined
260       precision, set by \a precision.
261
262       \return True if each element deviates less or equal than \a
263       d. If any vector contain a NaN, false is always returned.
264
265       \see operator== and operator!=
266    */
267    bool equal(const vector&, const double precision=0) const;
268
269    ///
270    /// @return A const pointer to the internal GSL vector,
271    ///
272    const gsl_vector* gsl_vector_p(void) const;
273
274    ///
275    /// @return A pointer to the internal GSL vector,
276    ///
277    gsl_vector* gsl_vector_p(void);
278
279    ///
280    /// Check if the vector object is a view (sub-vector) to another
281    /// vector.
282    ///
283    /// @return True if the object is a view, false othwerwise.
284    ///
285    bool isview(void) const;
286
287    /**
288       \brief This function performs element-wise multiplication, \f$
289       this_i = this_i * other_i \; \forall i \f$.
290
291       \throw GSL_error if dimensions mis-match.
292    */
293    void mul(const vector& other);
294
295    /**
296       @brief Resize vector
297       
298       All elements are set to @a init_value.
299
300       \note Underlying GSL vector is destroyed and a view into this
301       vector becomes invalid.
302    */
303    void resize(size_t, double init_value=0);
304
305    /**
306       \brief Reverse the order of elements in the vector.
307    */
308    void reverse(void);
309
310    ///
311    /// Set all elements to \a value.
312    ///
313    void all(const double& value);
314
315    ///
316    /// @return the number of elements in the vector.
317    ///
318    size_t size(void) const;
319
320    /**
321       \brief Exchange elements \a i and \a j.
322
323       \throw GSL_error if vector lengths differs.
324    */
325    void swap(size_t i, size_t j);
326
327    /**
328       \brief Element access operator.
329
330       \return Reference to element \a i.
331
332       \throw If GSL range checks are enabled in the underlying GSL
333       library a GSL_error exception is thrown if either index is out
334       of range.
335    */
336    double& operator()(size_t i);
337
338    /**
339       \brief Element access operator.
340
341       \return Const reference to element \a i.
342
343       \throw If GSL range checks are enabled in the underlying GSL
344       library a GSL_error exception is thrown if either index is out
345       of range.
346    */
347    const double& operator()(size_t i) const;
348
349    ///
350    /// Element access operator.
351    ///
352    /// @return Reference to element \a i.
353    ///
354    double& operator[](size_t i);
355
356    ///
357    /// Const element access operator.
358    ///
359    /// @return The value of element \a i.
360    ///
361    const double& operator[](size_t i) const;
362
363    /**
364       \brief Comparison operator. Takes linear time.
365
366       Checks are performed with exact matching, i.e., rounding off
367       effects may destroy comparison. Use the equal function for
368       comparing elements within a user defined precision.
369
370       \return True if all elements are equal otherwise false.
371
372       \see equal(const vector&, const double precision=0)
373    */
374    bool operator==(const vector&) const;
375
376    /**
377       \brief Comparison operator. Takes linear time.
378
379       Checks are performed with exact matching, i.e., rounding off
380       effects may destroy comparison. Use the equal function for
381       comparing elements within a user defined precision.
382
383       \return False if all elements are equal otherwise true.
384
385       \see equal(const vector&, const double precision=0)
386    */
387    bool operator!=(const vector&) const;
388
389    ///
390    /// @return The dot product.
391    ///
392    double operator*(const vector&) const;
393
394    /**
395       \brief The assignment operator.
396
397       Dimensions of the vectors must match. If the LHS vector is a
398       view, the underlying data will be changed.
399
400       \return A const reference to the resulting vector.
401
402       \see void set(const vector&).
403
404       \throw GSL_error if dimensions mis-match.
405    */
406    const vector& operator=(const vector&);
407
408    /**
409       \brief Addition and assign operator. Vector addition, \f$
410       this_i = this_i + other_i \; \forall i \f$.
411
412       \return A const reference to the resulting vector.
413
414       \throw GSL_error if dimensions mis-match.
415    */
416    const vector& operator+=(const vector&);
417
418    /**
419       \brief Add a constant to a vector, \f$ this_i = this_i + d \;
420       \forall i \f$.
421
422       \return A const reference to the resulting vector.
423    */
424    const vector& operator+=(double d);
425
426    /**
427       \brief Subtract and assign operator. Vector subtraction, \f$
428       this_i = this_i - other_i \; \forall i \f$.
429
430       \return A const reference to the resulting vector.
431
432       \throw GSL_error if dimensions mis-match.
433    */
434    const vector& operator-=(const vector&);
435
436    /**
437       \brief Subtract a constant to a vector, \f$ this_i = this_i - d
438       \; \forall i \f$.
439
440       \return A const reference to the resulting vector.
441    */
442    const vector& operator-=(double d);
443
444    /**
445       \brief Multiply with scalar and assign operator, \f$ this_i =
446       this_i * d \; \forall i \f$.
447
448       \return A const reference to the resulting vector.
449    */
450    const vector& operator*=(double d);
451
452
453  private:
454
455    /**
456       \brief Create a new copy of the internal GSL vector.
457
458       Necessary memory for the new GSL vector is allocated and the
459       caller is responsible for freeing the allocated memory.
460
461       \return A pointer to a copy of the internal GSL vector.
462
463       \throw GSL_error if memory cannot be allocated for the new
464       copy, or if dimensions mis-match.
465    */
466    gsl_vector* create_gsl_vector_copy(void) const;
467
468    /**
469       \brief Clear all dynamically allocated memory.
470
471       Internal utility function.
472    */
473    void delete_allocated_memory(void);
474
475    gsl_vector* v_;
476    gsl_vector_view* view_;
477    const gsl_vector_const_view* view_const_;
478    // proxy_v_ is used to access the proper underlying gsl_vector
479    // in all const member functions. It is not used by design for
480    // non-const vector functions and operators. This is to make sure
481    // that runtime errors occur if a const vector is used in an
482    // inappropriate manner such as on left hand side in assignment
483    // (remember, v_ is null for const vector views).
484    const gsl_vector* proxy_v_;
485  };
486
487  /**
488     \brief Check if all elements of the vector are zero.
489
490     \return True if all elements in the vector is zero, false
491     othwerwise.
492  */
493  bool isnull(const vector&);
494
495  /**
496     \brief Get the maximum value of the vector.
497
498     \return The maximum value of the vector.
499  */
500  double max(const vector&);
501
502  /**
503     \brief Locate the maximum value in the vector.
504
505     \return The index to the maximum value of the vector.
506
507     \note Lower index has precedence.
508  */
509  size_t max_index(const vector&);
510
511  /**
512     \brief Get the minimum value of the vector.
513
514     \return The minimum value of the vector.
515  */
516  double min(const vector&);
517
518  /**
519     \brief Locate the minimum value in the vector.
520
521     \return The index to the minimum value of the vector.
522
523     \note Lower index has precedence.
524  */
525  size_t min_index(const vector&);
526
527  /**
528     \brief Create a vector \a flag indicating NaN's in another vector
529     \a templat.
530
531     The \a flag vector is changed to contain 1's and 0's only. A 1
532     means that the corresponding element in the \a templat vector is
533     valid and a zero means that the corresponding element is a NaN.
534
535     \note Space for vector \a flag is reallocated to fit the size of
536     vector \a templat if sizes mismatch.
537
538     \return True if the \a templat vector contains at least one NaN.
539  */
540  bool nan(const vector& templat, vector& flag);
541
542  /**
543     \brief Transforms a vector to a basis vector.
544
545     All elements are set to zero except the \a i-th element which is
546     set to one.
547  */
548  void set_basis(vector&, size_t i);
549
550  /**
551     Randomly shuffles the elements in vector \a invec
552  */
553  void shuffle(vector& invec); 
554
555  /**
556     Sort the elements in the vector.
557  */
558  void sort(vector&);
559
560  /**
561     Create a vector \a sort_index containing the indeces of
562     elements in a another vector \a invec.  The elements of \a
563     sort_index give the index of the vector element which would
564     have been stored in that position if the vector had been sorted
565     in place. The first element of \a sort_index gives the index of the least
566     element in \a invec, and the last element of \a sort_index gives the index of the
567     greatest element in \a invec . The vector \a invec is not changed.
568
569  */
570  void sort_index(std::vector<size_t>& sort_index, const vector& invec);
571
572  /** Similar to sort_index but creates a vector with indices to the \a k
573  smallest elements in \a invec. 
574  */
575  void sort_smallest_index(std::vector<size_t>& sort_index, size_t k, const
576  vector& invec);
577
578  /** Similar to sort_index but creates a vector with indices to the \a k
579  largest elements in \a invec. 
580  */
581  void sort_largest_index(std::vector<size_t>& sort_index, size_t k, const
582  vector& invec);
583
584 
585
586  /**
587     \brief Calculate the sum of all vector elements.
588
589     \return The sum.
590  */
591  double sum(const vector&);
592
593  /**
594     \brief Swap vector elements by copying.
595
596     The two vectors must have the same length.
597
598     \throw GSL_error if vector lengths differs.
599  */
600  void swap(vector&, vector&);
601
602  /**
603     \brief The output operator for the vector class.
604  */
605  std::ostream& operator<<(std::ostream&, const vector&);
606
607}}} // of namespace utility, yat, and theplu
608
609#endif
Note: See TracBrowser for help on using the repository browser.