source: src/LinearAlgebra/Vector.cpp@ bbf1bd

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since bbf1bd was bbf1bd, checked in by Frederik Heber <heber@…>, 14 years ago

Extended VectorContent class.

  • VectorContent formerly has been just a structure to contain the gsl_vector due to forward declaration reasons.
  • now VectorContent is a true wrapper to gsl_vector, i.e. all functionality that is now specific to 3 dimensions has been shifted from GSLVector over to VectorContent.
  • VectorContentView is preserved to allow for VectorContent as a view on a row or column of a matrix.
  • changed and renamed unit test gslvectorunittest -> VectorContentUnitTest
  • GSLVector is not used anymore anywhere
  • one long-sough error was a missing assignment operator filled-in in a wrong manner by the compiler for VectorContent.

Note that:

  • gsl_vector is still used at many places
  • Property mode set to 100644
File size: 14.0 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/** \file vector.cpp
9 *
10 * Function implementations for the class vector.
11 *
12 */
13
14// include config.h
15#ifdef HAVE_CONFIG_H
16#include <config.h>
17#endif
18
19#include "Helpers/MemDebug.hpp"
20
21#include "LinearAlgebra/Vector.hpp"
22#include "VectorContent.hpp"
23#include "Helpers/Verbose.hpp"
24#include "World.hpp"
25#include "Helpers/Assert.hpp"
26#include "Helpers/fast_functions.hpp"
27#include "Exceptions/MathException.hpp"
28
29#include <iostream>
30#include <gsl/gsl_blas.h>
31#include <gsl/gsl_vector.h>
32
33
34using namespace std;
35
36
37/************************************ Functions for class vector ************************************/
38
39/** Constructor of class vector.
40 */
41Vector::Vector()
42{
43 content = new VectorContent((size_t) NDIM);
44};
45
46/** Copy constructor.
47 * \param &src source Vector reference
48 */
49Vector::Vector(const Vector& src)
50{
51 content = new VectorContent(*(src.content));
52}
53
54/** Constructor of class vector.
55 * \param x1 first component
56 * \param x2 second component
57 * \param x3 third component
58 */
59Vector::Vector(const double x1, const double x2, const double x3)
60{
61 content = new VectorContent((size_t) NDIM);
62 content->at(0) = x1;
63 content->at(1) = x2;
64 content->at(2) = x3;
65};
66
67/** Constructor of class vector.
68 * \param x[3] three values to initialize Vector with
69 */
70Vector::Vector(const double x[3])
71{
72 content = new VectorContent((size_t) NDIM);
73 for (size_t i = NDIM; i--; )
74 content->at(i) = x[i];
75};
76
77/** Copy constructor of class vector from VectorContent.
78 * \note This is destructive, i.e. we take over _content.
79 */
80Vector::Vector(VectorContent *&_content) :
81 content(_content)
82{
83 _content = NULL;
84}
85
86/** Copy constructor of class vector from VectorContent.
87 * \note This is non-destructive, i.e. _content is copied.
88 */
89Vector::Vector(VectorContent &_content)
90{
91 content = new VectorContent(_content);
92}
93
94/** Assignment operator.
95 * \param &src source vector to assign \a *this to
96 * \return reference to \a *this
97 */
98Vector& Vector::operator=(const Vector& src){
99 // check for self assignment
100 if(&src!=this){
101 *content = *(src.content);
102 }
103 return *this;
104}
105
106/** Desctructor of class vector.
107 * Vector::content is deleted.
108 */
109Vector::~Vector() {
110 delete content;
111};
112
113/** Calculates square of distance between this and another vector.
114 * \param *y array to second vector
115 * \return \f$| x - y |^2\f$
116 */
117double Vector::DistanceSquared(const Vector &y) const
118{
119 double res = 0.;
120 for (int i=NDIM;i--;)
121 res += (at(i)-y[i])*(at(i)-y[i]);
122 return (res);
123};
124
125/** Calculates distance between this and another vector.
126 * \param *y array to second vector
127 * \return \f$| x - y |\f$
128 */
129double Vector::distance(const Vector &y) const
130{
131 return (sqrt(DistanceSquared(y)));
132};
133
134size_t Vector::GreatestComponent() const
135{
136 int greatest = 0;
137 for (int i=1;i<NDIM;i++) {
138 if (at(i) > at(greatest))
139 greatest = i;
140 }
141 return greatest;
142}
143
144size_t Vector::SmallestComponent() const
145{
146 int smallest = 0;
147 for (int i=1;i<NDIM;i++) {
148 if (at(i) < at(smallest))
149 smallest = i;
150 }
151 return smallest;
152}
153
154
155Vector Vector::getClosestPoint(const Vector &point) const{
156 // the closest point to a single point space is always the single point itself
157 return *this;
158}
159
160/** Calculates scalar product between this and another vector.
161 * \param *y array to second vector
162 * \return \f$\langle x, y \rangle\f$
163 */
164double Vector::ScalarProduct(const Vector &y) const
165{
166 double res = 0.;
167 gsl_blas_ddot(content->content, y.content->content, &res);
168 return (res);
169};
170
171
172/** Calculates VectorProduct between this and another vector.
173 * -# returns the Product in place of vector from which it was initiated
174 * -# ATTENTION: Only three dim.
175 * \param *y array to vector with which to calculate crossproduct
176 * \return \f$ x \times y \f&
177 */
178void Vector::VectorProduct(const Vector &y)
179{
180 Vector tmp;
181 for(int i=NDIM;i--;)
182 tmp[i] = at((i+1)%NDIM)*y[(i+2)%NDIM] - at((i+2)%NDIM)*y[(i+1)%NDIM];
183 (*this) = tmp;
184};
185
186
187/** projects this vector onto plane defined by \a *y.
188 * \param *y normal vector of plane
189 * \return \f$\langle x, y \rangle\f$
190 */
191void Vector::ProjectOntoPlane(const Vector &y)
192{
193 Vector tmp;
194 tmp = y;
195 tmp.Normalize();
196 tmp.Scale(ScalarProduct(tmp));
197 *this -= tmp;
198};
199
200/** Calculates the minimum distance of this vector to the plane.
201 * \sa Vector::GetDistanceVectorToPlane()
202 * \param *out output stream for debugging
203 * \param *PlaneNormal normal of plane
204 * \param *PlaneOffset offset of plane
205 * \return distance to plane
206 */
207double Vector::DistanceToSpace(const Space &space) const
208{
209 return space.distance(*this);
210};
211
212/** Calculates the projection of a vector onto another \a *y.
213 * \param *y array to second vector
214 */
215void Vector::ProjectIt(const Vector &y)
216{
217 (*this) += (-ScalarProduct(y))*y;
218};
219
220/** Calculates the projection of a vector onto another \a *y.
221 * \param *y array to second vector
222 * \return Vector
223 */
224Vector Vector::Projection(const Vector &y) const
225{
226 Vector helper = y;
227 helper.Scale((ScalarProduct(y)/y.NormSquared()));
228
229 return helper;
230};
231
232/** Calculates norm of this vector.
233 * \return \f$|x|\f$
234 */
235double Vector::Norm() const
236{
237 return (sqrt(NormSquared()));
238};
239
240/** Calculates squared norm of this vector.
241 * \return \f$|x|^2\f$
242 */
243double Vector::NormSquared() const
244{
245 return (ScalarProduct(*this));
246};
247
248/** Normalizes this vector.
249 */
250void Vector::Normalize()
251{
252 double factor = Norm();
253 (*this) *= 1/factor;
254};
255
256Vector Vector::getNormalized() const{
257 Vector res= *this;
258 res.Normalize();
259 return res;
260}
261
262/** Zeros all components of this vector.
263 */
264void Vector::Zero()
265{
266 at(0)=at(1)=at(2)=0;
267};
268
269/** Zeros all components of this vector.
270 */
271void Vector::One(const double one)
272{
273 at(0)=at(1)=at(2)=one;
274};
275
276/** Checks whether vector has all components zero.
277 * @return true - vector is zero, false - vector is not
278 */
279bool Vector::IsZero() const
280{
281 return (fabs(at(0))+fabs(at(1))+fabs(at(2)) < MYEPSILON);
282};
283
284/** Checks whether vector has length of 1.
285 * @return true - vector is normalized, false - vector is not
286 */
287bool Vector::IsOne() const
288{
289 return (fabs(Norm() - 1.) < MYEPSILON);
290};
291
292/** Checks whether vector is normal to \a *normal.
293 * @return true - vector is normalized, false - vector is not
294 */
295bool Vector::IsNormalTo(const Vector &normal) const
296{
297 if (ScalarProduct(normal) < MYEPSILON)
298 return true;
299 else
300 return false;
301};
302
303/** Checks whether vector is normal to \a *normal.
304 * @return true - vector is normalized, false - vector is not
305 */
306bool Vector::IsEqualTo(const Vector &a) const
307{
308 bool status = true;
309 for (int i=0;i<NDIM;i++) {
310 if (fabs(at(i) - a[i]) > MYEPSILON)
311 status = false;
312 }
313 return status;
314};
315
316/** Calculates the angle between this and another vector.
317 * \param *y array to second vector
318 * \return \f$\acos\bigl(frac{\langle x, y \rangle}{|x||y|}\bigr)\f$
319 */
320double Vector::Angle(const Vector &y) const
321{
322 double norm1 = Norm(), norm2 = y.Norm();
323 double angle = -1;
324 if ((fabs(norm1) > MYEPSILON) && (fabs(norm2) > MYEPSILON))
325 angle = this->ScalarProduct(y)/norm1/norm2;
326 // -1-MYEPSILON occured due to numerical imprecision, catch ...
327 //Log() << Verbose(2) << "INFO: acos(-1) = " << acos(-1) << ", acos(-1+MYEPSILON) = " << acos(-1+MYEPSILON) << ", acos(-1-MYEPSILON) = " << acos(-1-MYEPSILON) << "." << endl;
328 if (angle < -1)
329 angle = -1;
330 if (angle > 1)
331 angle = 1;
332 return acos(angle);
333};
334
335
336double& Vector::operator[](size_t i){
337 ASSERT(i<=NDIM && i>=0,"Vector Index out of Range");
338 return *gsl_vector_ptr (content->content, i);
339}
340
341const double& Vector::operator[](size_t i) const{
342 ASSERT(i<=NDIM && i>=0,"Vector Index out of Range");
343 return *gsl_vector_ptr (content->content, i);
344}
345
346double& Vector::at(size_t i){
347 return (*this)[i];
348}
349
350const double& Vector::at(size_t i) const{
351 return (*this)[i];
352}
353
354VectorContent* Vector::get() const
355{
356 return content;
357}
358
359/** Compares vector \a to vector \a b component-wise.
360 * \param a base vector
361 * \param b vector components to add
362 * \return a == b
363 */
364bool Vector::operator==(const Vector& b) const
365{
366 return IsEqualTo(b);
367};
368
369bool Vector::operator!=(const Vector& b) const
370{
371 return !IsEqualTo(b);
372}
373
374/** Sums vector \a to this lhs component-wise.
375 * \param a base vector
376 * \param b vector components to add
377 * \return lhs + a
378 */
379const Vector& Vector::operator+=(const Vector& b)
380{
381 this->AddVector(b);
382 return *this;
383};
384
385/** Subtracts vector \a from this lhs component-wise.
386 * \param a base vector
387 * \param b vector components to add
388 * \return lhs - a
389 */
390const Vector& Vector::operator-=(const Vector& b)
391{
392 this->SubtractVector(b);
393 return *this;
394};
395
396/** factor each component of \a a times a double \a m.
397 * \param a base vector
398 * \param m factor
399 * \return lhs.x[i] * m
400 */
401const Vector& operator*=(Vector& a, const double m)
402{
403 a.Scale(m);
404 return a;
405};
406
407/** Sums two vectors \a and \b component-wise.
408 * \param a first vector
409 * \param b second vector
410 * \return a + b
411 */
412Vector const Vector::operator+(const Vector& b) const
413{
414 Vector x = *this;
415 x.AddVector(b);
416 return x;
417};
418
419/** Subtracts vector \a from \b component-wise.
420 * \param a first vector
421 * \param b second vector
422 * \return a - b
423 */
424Vector const Vector::operator-(const Vector& b) const
425{
426 Vector x = *this;
427 x.SubtractVector(b);
428 return x;
429};
430
431/** Factors given vector \a a times \a m.
432 * \param a vector
433 * \param m factor
434 * \return m * a
435 */
436Vector const operator*(const Vector& a, const double m)
437{
438 Vector x(a);
439 x.Scale(m);
440 return x;
441};
442
443/** Factors given vector \a a times \a m.
444 * \param m factor
445 * \param a vector
446 * \return m * a
447 */
448Vector const operator*(const double m, const Vector& a )
449{
450 Vector x(a);
451 x.Scale(m);
452 return x;
453};
454
455ostream& operator<<(ostream& ost, const Vector& m)
456{
457 ost << "(";
458 for (int i=0;i<NDIM;i++) {
459 ost << m[i];
460 if (i != 2)
461 ost << ",";
462 }
463 ost << ")";
464 return ost;
465};
466
467
468void Vector::ScaleAll(const double *factor)
469{
470 for (int i=NDIM;i--;)
471 at(i) *= factor[i];
472};
473
474void Vector::ScaleAll(const Vector &factor){
475 gsl_vector_mul(content->content, factor.content->content);
476}
477
478
479void Vector::Scale(const double factor)
480{
481 gsl_vector_scale(content->content,factor);
482};
483
484std::pair<Vector,Vector> Vector::partition(const Vector &rhs) const{
485 double factor = ScalarProduct(rhs)/rhs.NormSquared();
486 Vector res= factor * rhs;
487 return make_pair(res,(*this)-res);
488}
489
490std::pair<pointset,Vector> Vector::partition(const pointset &points) const{
491 Vector helper = *this;
492 pointset res;
493 for(pointset::const_iterator iter=points.begin();iter!=points.end();++iter){
494 pair<Vector,Vector> currPart = helper.partition(*iter);
495 res.push_back(currPart.first);
496 helper = currPart.second;
497 }
498 return make_pair(res,helper);
499}
500
501/** Creates this vector as the b y *factors' components scaled linear combination of the given three.
502 * this vector = x1*factors[0] + x2* factors[1] + x3*factors[2]
503 * \param *x1 first vector
504 * \param *x2 second vector
505 * \param *x3 third vector
506 * \param *factors three-component vector with the factor for each given vector
507 */
508void Vector::LinearCombinationOfVectors(const Vector &x1, const Vector &x2, const Vector &x3, const double * const factors)
509{
510 (*this) = (factors[0]*x1) +
511 (factors[1]*x2) +
512 (factors[2]*x3);
513};
514
515/** Calculates orthonormal vector to one given vectors.
516 * Just subtracts the projection onto the given vector from this vector.
517 * The removed part of the vector is Vector::Projection()
518 * \param *x1 vector
519 * \return true - success, false - vector is zero
520 */
521bool Vector::MakeNormalTo(const Vector &y1)
522{
523 bool result = false;
524 double factor = y1.ScalarProduct(*this)/y1.NormSquared();
525 Vector x1 = factor * y1;
526 SubtractVector(x1);
527 for (int i=NDIM;i--;)
528 result = result || (fabs(at(i)) > MYEPSILON);
529
530 return result;
531};
532
533/** Creates this vector as one of the possible orthonormal ones to the given one.
534 * Just scan how many components of given *vector are unequal to zero and
535 * try to get the skp of both to be zero accordingly.
536 * \param *vector given vector
537 * \return true - success, false - failure (null vector given)
538 */
539bool Vector::GetOneNormalVector(const Vector &GivenVector)
540{
541 int Components[NDIM]; // contains indices of non-zero components
542 int Last = 0; // count the number of non-zero entries in vector
543 int j; // loop variables
544 double norm;
545
546 for (j=NDIM;j--;)
547 Components[j] = -1;
548
549 // in two component-systems we need to find the one position that is zero
550 int zeroPos = -1;
551 // find two components != 0
552 for (j=0;j<NDIM;j++){
553 if (fabs(GivenVector[j]) > MYEPSILON)
554 Components[Last++] = j;
555 else
556 // this our zero Position
557 zeroPos = j;
558 }
559
560 switch(Last) {
561 case 3: // threecomponent system
562 // the position of the zero is arbitrary in three component systems
563 zeroPos = Components[2];
564 case 2: // two component system
565 norm = sqrt(1./(GivenVector[Components[1]]*GivenVector[Components[1]]) + 1./(GivenVector[Components[0]]*GivenVector[Components[0]]));
566 at(zeroPos) = 0.;
567 // in skp both remaining parts shall become zero but with opposite sign and third is zero
568 at(Components[1]) = -1./GivenVector[Components[1]] / norm;
569 at(Components[0]) = 1./GivenVector[Components[0]] / norm;
570 return true;
571 break;
572 case 1: // one component system
573 // set sole non-zero component to 0, and one of the other zero component pendants to 1
574 at((Components[0]+2)%NDIM) = 0.;
575 at((Components[0]+1)%NDIM) = 1.;
576 at(Components[0]) = 0.;
577 return true;
578 break;
579 default:
580 return false;
581 }
582};
583
584/** Adds vector \a *y componentwise.
585 * \param *y vector
586 */
587void Vector::AddVector(const Vector &y)
588{
589 gsl_vector_add(content->content, y.content->content);
590}
591
592/** Adds vector \a *y componentwise.
593 * \param *y vector
594 */
595void Vector::SubtractVector(const Vector &y)
596{
597 gsl_vector_sub(content->content, y.content->content);
598}
599
600
601// some comonly used vectors
602const Vector zeroVec(0,0,0);
603const Vector unitVec[NDIM]={Vector(1,0,0),Vector(0,1,0),Vector(0,0,1)};
Note: See TracBrowser for help on using the repository browser.