source: src/LinearAlgebra/Vector.cpp@ f453d2

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 f453d2 was 6d5a10, checked in by Frederik Heber <heber@…>, 14 years ago

Added/Sorted some includes in LinearAlgebra and Exceptions.

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