source: src/LinearAlgebra/Vector.cpp@ d5240d

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

MEMFIX: new function AddStaticEntitiestoIgnoreList() for putting static variables on ignore list.

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