source: src/LinearAlgebra/Vector.cpp@ a01144

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 a01144 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
RevLine 
[bcf653]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
[6ac7ee]8/** \file vector.cpp
9 *
10 * Function implementations for the class vector.
11 *
12 */
13
[bf3817]14// include config.h
15#ifdef HAVE_CONFIG_H
16#include <config.h>
17#endif
18
[112b09]19#include "Helpers/MemDebug.hpp"
[edb93c]20
[57f243]21#include "LinearAlgebra/Vector.hpp"
[ce3d2b]22#include "VectorContent.hpp"
[952f38]23#include "Helpers/Verbose.hpp"
[b34306]24#include "World.hpp"
[0a4f7f]25#include "Helpers/Assert.hpp"
[753f02]26#include "Helpers/fast_functions.hpp"
[325390]27#include "Exceptions/MathException.hpp"
[6ac7ee]28
[1bd79e]29#include <iostream>
[923b6c]30#include <gsl/gsl_blas.h>
[a439e5]31#include <gsl/gsl_vector.h>
[923b6c]32
[1bd79e]33
34using namespace std;
[6ac7ee]35
[97498a]36
[6ac7ee]37/************************************ Functions for class vector ************************************/
38
39/** Constructor of class vector.
40 */
[753f02]41Vector::Vector()
42{
[ce3d2b]43 content = new VectorContent();
[753f02]44};
[6ac7ee]45
[753f02]46/**
47 * Copy constructor
[821907]48 */
[1bd79e]49
[753f02]50Vector::Vector(const Vector& src)
[821907]51{
[ce3d2b]52 content = new VectorContent();
53 gsl_vector_memcpy(content->content, src.content->content);
[1bd79e]54}
[821907]55
56/** Constructor of class vector.
57 */
[753f02]58Vector::Vector(const double x1, const double x2, const double x3)
[821907]59{
[ce3d2b]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);
[821907]64};
65
[d74077]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
[ce3d2b]76Vector::Vector(VectorContent *_content) :
[325390]77 content(_content)
78{}
79
[0a4f7f]80/**
81 * Assignment operator
[6ac7ee]82 */
[0a4f7f]83Vector& Vector::operator=(const Vector& src){
84 // check for self assignment
85 if(&src!=this){
[ce3d2b]86 gsl_vector_memcpy(content->content, src.content->content);
[0a4f7f]87 }
88 return *this;
89}
[6ac7ee]90
91/** Desctructor of class vector.
92 */
[d466f0]93Vector::~Vector() {
[ce3d2b]94 delete content;
[d466f0]95};
[6ac7ee]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 */
[273382]101double Vector::DistanceSquared(const Vector &y) const
[6ac7ee]102{
[042f82]103 double res = 0.;
104 for (int i=NDIM;i--;)
[d466f0]105 res += (at(i)-y[i])*(at(i)-y[i]);
[042f82]106 return (res);
[6ac7ee]107};
108
109/** Calculates distance between this and another vector.
110 * \param *y array to second vector
111 * \return \f$| x - y |\f$
112 */
[1513a74]113double Vector::distance(const Vector &y) const
[6ac7ee]114{
[273382]115 return (sqrt(DistanceSquared(y)));
[6ac7ee]116};
117
[a439e5]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
[1513a74]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
[6ac7ee]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 */
[273382]148double Vector::ScalarProduct(const Vector &y) const
[6ac7ee]149{
[042f82]150 double res = 0.;
[ce3d2b]151 gsl_blas_ddot(content->content, y.content->content, &res);
[042f82]152 return (res);
[6ac7ee]153};
154
155
156/** Calculates VectorProduct between this and another vector.
[042f82]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&
[6ac7ee]161 */
[273382]162void Vector::VectorProduct(const Vector &y)
[6ac7ee]163{
[042f82]164 Vector tmp;
[d466f0]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];
[753f02]167 (*this) = tmp;
[6ac7ee]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 */
[273382]175void Vector::ProjectOntoPlane(const Vector &y)
[6ac7ee]176{
[042f82]177 Vector tmp;
[753f02]178 tmp = y;
[042f82]179 tmp.Normalize();
[753f02]180 tmp.Scale(ScalarProduct(tmp));
181 *this -= tmp;
[2319ed]182};
183
[821907]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 */
[d4c9ae]191double Vector::DistanceToSpace(const Space &space) const
[821907]192{
[d4c9ae]193 return space.distance(*this);
[c4d4df]194};
195
[6ac7ee]196/** Calculates the projection of a vector onto another \a *y.
197 * \param *y array to second vector
198 */
[273382]199void Vector::ProjectIt(const Vector &y)
[6ac7ee]200{
[753f02]201 (*this) += (-ScalarProduct(y))*y;
[ef9df36]202};
203
204/** Calculates the projection of a vector onto another \a *y.
205 * \param *y array to second vector
206 * \return Vector
207 */
[273382]208Vector Vector::Projection(const Vector &y) const
[ef9df36]209{
[753f02]210 Vector helper = y;
211 helper.Scale((ScalarProduct(y)/y.NormSquared()));
[ef9df36]212
213 return helper;
[6ac7ee]214};
215
216/** Calculates norm of this vector.
217 * \return \f$|x|\f$
218 */
219double Vector::Norm() const
220{
[273382]221 return (sqrt(NormSquared()));
[6ac7ee]222};
223
[d4d0dd]224/** Calculates squared norm of this vector.
225 * \return \f$|x|^2\f$
226 */
227double Vector::NormSquared() const
228{
[273382]229 return (ScalarProduct(*this));
[d4d0dd]230};
231
[6ac7ee]232/** Normalizes this vector.
233 */
234void Vector::Normalize()
235{
[1bd79e]236 double factor = Norm();
237 (*this) *= 1/factor;
[6ac7ee]238};
239
[421a1f]240Vector Vector::getNormalized() const{
241 Vector res= *this;
242 res.Normalize();
243 return res;
244}
245
[6ac7ee]246/** Zeros all components of this vector.
247 */
248void Vector::Zero()
249{
[753f02]250 at(0)=at(1)=at(2)=0;
[6ac7ee]251};
252
253/** Zeros all components of this vector.
254 */
[776b64]255void Vector::One(const double one)
[6ac7ee]256{
[753f02]257 at(0)=at(1)=at(2)=one;
[6ac7ee]258};
259
[9c20aa]260/** Checks whether vector has all components zero.
261 * @return true - vector is zero, false - vector is not
262 */
[54a746]263bool Vector::IsZero() const
[9c20aa]264{
[d466f0]265 return (fabs(at(0))+fabs(at(1))+fabs(at(2)) < MYEPSILON);
[54a746]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);
[9c20aa]274};
275
[ef9df36]276/** Checks whether vector is normal to \a *normal.
277 * @return true - vector is normalized, false - vector is not
278 */
[273382]279bool Vector::IsNormalTo(const Vector &normal) const
[ef9df36]280{
281 if (ScalarProduct(normal) < MYEPSILON)
282 return true;
283 else
284 return false;
285};
286
[b998c3]287/** Checks whether vector is normal to \a *normal.
288 * @return true - vector is normalized, false - vector is not
289 */
[273382]290bool Vector::IsEqualTo(const Vector &a) const
[b998c3]291{
292 bool status = true;
293 for (int i=0;i<NDIM;i++) {
[d466f0]294 if (fabs(at(i) - a[i]) > MYEPSILON)
[b998c3]295 status = false;
296 }
297 return status;
298};
299
[6ac7ee]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 */
[273382]304double Vector::Angle(const Vector &y) const
[6ac7ee]305{
[753f02]306 double norm1 = Norm(), norm2 = y.Norm();
[ef9df36]307 double angle = -1;
[d4d0dd]308 if ((fabs(norm1) > MYEPSILON) && (fabs(norm2) > MYEPSILON))
309 angle = this->ScalarProduct(y)/norm1/norm2;
[02da9e]310 // -1-MYEPSILON occured due to numerical imprecision, catch ...
[e138de]311 //Log() << Verbose(2) << "INFO: acos(-1) = " << acos(-1) << ", acos(-1+MYEPSILON) = " << acos(-1+MYEPSILON) << ", acos(-1-MYEPSILON) = " << acos(-1-MYEPSILON) << "." << endl;
[02da9e]312 if (angle < -1)
313 angle = -1;
314 if (angle > 1)
315 angle = 1;
[042f82]316 return acos(angle);
[6ac7ee]317};
318
[0a4f7f]319
320double& Vector::operator[](size_t i){
[753f02]321 ASSERT(i<=NDIM && i>=0,"Vector Index out of Range");
[ce3d2b]322 return *gsl_vector_ptr (content->content, i);
[0a4f7f]323}
324
325const double& Vector::operator[](size_t i) const{
[753f02]326 ASSERT(i<=NDIM && i>=0,"Vector Index out of Range");
[ce3d2b]327 return *gsl_vector_ptr (content->content, i);
[0a4f7f]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
[ae21cbd]338VectorContent* Vector::get() const
339{
[0c7ed8]340 return content;
[0a4f7f]341}
[6ac7ee]342
[ef9df36]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 */
[72e7fa]348bool Vector::operator==(const Vector& b) const
[ef9df36]349{
[1bd79e]350 return IsEqualTo(b);
[ef9df36]351};
352
[fa5a6a]353bool Vector::operator!=(const Vector& b) const
354{
355 return !IsEqualTo(b);
356}
357
[6ac7ee]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 */
[72e7fa]363const Vector& Vector::operator+=(const Vector& b)
[6ac7ee]364{
[273382]365 this->AddVector(b);
[72e7fa]366 return *this;
[6ac7ee]367};
[54a746]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 */
[72e7fa]374const Vector& Vector::operator-=(const Vector& b)
[54a746]375{
[273382]376 this->SubtractVector(b);
[72e7fa]377 return *this;
[54a746]378};
379
[6ac7ee]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 */
[b84d5d]385const Vector& operator*=(Vector& a, const double m)
[6ac7ee]386{
[042f82]387 a.Scale(m);
388 return a;
[6ac7ee]389};
390
[042f82]391/** Sums two vectors \a and \b component-wise.
[6ac7ee]392 * \param a first vector
393 * \param b second vector
394 * \return a + b
395 */
[72e7fa]396Vector const Vector::operator+(const Vector& b) const
[6ac7ee]397{
[72e7fa]398 Vector x = *this;
[273382]399 x.AddVector(b);
[b84d5d]400 return x;
[6ac7ee]401};
402
[54a746]403/** Subtracts vector \a from \b component-wise.
404 * \param a first vector
405 * \param b second vector
406 * \return a - b
407 */
[72e7fa]408Vector const Vector::operator-(const Vector& b) const
[54a746]409{
[72e7fa]410 Vector x = *this;
[273382]411 x.SubtractVector(b);
[b84d5d]412 return x;
[54a746]413};
414
[6ac7ee]415/** Factors given vector \a a times \a m.
416 * \param a vector
417 * \param m factor
[54a746]418 * \return m * a
[6ac7ee]419 */
[b84d5d]420Vector const operator*(const Vector& a, const double m)
[6ac7ee]421{
[b84d5d]422 Vector x(a);
423 x.Scale(m);
424 return x;
[6ac7ee]425};
426
[54a746]427/** Factors given vector \a a times \a m.
428 * \param m factor
429 * \param a vector
430 * \return m * a
431 */
[b84d5d]432Vector const operator*(const double m, const Vector& a )
[54a746]433{
[b84d5d]434 Vector x(a);
435 x.Scale(m);
436 return x;
[54a746]437};
438
[9c20aa]439ostream& operator<<(ostream& ost, const Vector& m)
[6ac7ee]440{
[042f82]441 ost << "(";
442 for (int i=0;i<NDIM;i++) {
[0a4f7f]443 ost << m[i];
[042f82]444 if (i != 2)
445 ost << ",";
446 }
447 ost << ")";
448 return ost;
[6ac7ee]449};
450
451
[1bd79e]452void Vector::ScaleAll(const double *factor)
[6ac7ee]453{
[042f82]454 for (int i=NDIM;i--;)
[d466f0]455 at(i) *= factor[i];
[6ac7ee]456};
457
[b5bf84]458void Vector::ScaleAll(const Vector &factor){
[ce3d2b]459 gsl_vector_mul(content->content, factor.content->content);
[b5bf84]460}
[6ac7ee]461
[1bd79e]462
[776b64]463void Vector::Scale(const double factor)
[6ac7ee]464{
[ce3d2b]465 gsl_vector_scale(content->content,factor);
[6ac7ee]466};
467
[45ef76]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
[6ac7ee]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 */
[273382]492void Vector::LinearCombinationOfVectors(const Vector &x1, const Vector &x2, const Vector &x3, const double * const factors)
[6ac7ee]493{
[273382]494 (*this) = (factors[0]*x1) +
495 (factors[1]*x2) +
496 (factors[2]*x3);
[6ac7ee]497};
498
499/** Calculates orthonormal vector to one given vectors.
500 * Just subtracts the projection onto the given vector from this vector.
[ef9df36]501 * The removed part of the vector is Vector::Projection()
[6ac7ee]502 * \param *x1 vector
503 * \return true - success, false - vector is zero
504 */
[0a4f7f]505bool Vector::MakeNormalTo(const Vector &y1)
[6ac7ee]506{
[042f82]507 bool result = false;
[753f02]508 double factor = y1.ScalarProduct(*this)/y1.NormSquared();
[45ef76]509 Vector x1 = factor * y1;
[753f02]510 SubtractVector(x1);
[042f82]511 for (int i=NDIM;i--;)
[d466f0]512 result = result || (fabs(at(i)) > MYEPSILON);
[6ac7ee]513
[042f82]514 return result;
[6ac7ee]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 */
[273382]523bool Vector::GetOneNormalVector(const Vector &GivenVector)
[6ac7ee]524{
[042f82]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;
[1829c4]532
533 // in two component-systems we need to find the one position that is zero
534 int zeroPos = -1;
[042f82]535 // find two components != 0
[1829c4]536 for (j=0;j<NDIM;j++){
[753f02]537 if (fabs(GivenVector[j]) > MYEPSILON)
[042f82]538 Components[Last++] = j;
[1829c4]539 else
540 // this our zero Position
541 zeroPos = j;
542 }
[042f82]543
544 switch(Last) {
545 case 3: // threecomponent system
[1829c4]546 // the position of the zero is arbitrary in three component systems
547 zeroPos = Components[2];
[042f82]548 case 2: // two component system
[753f02]549 norm = sqrt(1./(GivenVector[Components[1]]*GivenVector[Components[1]]) + 1./(GivenVector[Components[0]]*GivenVector[Components[0]]));
[1829c4]550 at(zeroPos) = 0.;
[042f82]551 // in skp both remaining parts shall become zero but with opposite sign and third is zero
[1829c4]552 at(Components[1]) = -1./GivenVector[Components[1]] / norm;
553 at(Components[0]) = 1./GivenVector[Components[0]] / norm;
[042f82]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
[1829c4]558 at((Components[0]+2)%NDIM) = 0.;
559 at((Components[0]+1)%NDIM) = 1.;
560 at(Components[0]) = 0.;
[042f82]561 return true;
562 break;
563 default:
564 return false;
565 }
[6ac7ee]566};
567
568/** Adds vector \a *y componentwise.
569 * \param *y vector
570 */
[273382]571void Vector::AddVector(const Vector &y)
[6ac7ee]572{
[ce3d2b]573 gsl_vector_add(content->content, y.content->content);
[6ac7ee]574}
575
576/** Adds vector \a *y componentwise.
577 * \param *y vector
578 */
[273382]579void Vector::SubtractVector(const Vector &y)
[6ac7ee]580{
[ce3d2b]581 gsl_vector_sub(content->content, y.content->content);
[ef9df36]582}
583
[005e18]584
585// some comonly used vectors
586const Vector zeroVec(0,0,0);
[407782]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.