source: src/LinearAlgebra/Vector.cpp@ bf3817

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 bf3817 was bf3817, checked in by Frederik Heber <heber@…>, 15 years ago

Added ifdef HAVE_CONFIG and config.h include to each and every cpp file.

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