source: src/LinearAlgebra/Vector.cpp@ 8bb05e

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

Added copyright note to each .cpp file and an extensive one to builder.cpp.

  • Property mode set to 100644
File size: 13.4 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
240/** Zeros all components of this vector.
241 */
242void Vector::Zero()
243{
[753f02]244 at(0)=at(1)=at(2)=0;
[6ac7ee]245};
246
247/** Zeros all components of this vector.
248 */
[776b64]249void Vector::One(const double one)
[6ac7ee]250{
[753f02]251 at(0)=at(1)=at(2)=one;
[6ac7ee]252};
253
[9c20aa]254/** Checks whether vector has all components zero.
255 * @return true - vector is zero, false - vector is not
256 */
[54a746]257bool Vector::IsZero() const
[9c20aa]258{
[d466f0]259 return (fabs(at(0))+fabs(at(1))+fabs(at(2)) < MYEPSILON);
[54a746]260};
261
262/** Checks whether vector has length of 1.
263 * @return true - vector is normalized, false - vector is not
264 */
265bool Vector::IsOne() const
266{
267 return (fabs(Norm() - 1.) < MYEPSILON);
[9c20aa]268};
269
[ef9df36]270/** Checks whether vector is normal to \a *normal.
271 * @return true - vector is normalized, false - vector is not
272 */
[273382]273bool Vector::IsNormalTo(const Vector &normal) const
[ef9df36]274{
275 if (ScalarProduct(normal) < MYEPSILON)
276 return true;
277 else
278 return false;
279};
280
[b998c3]281/** Checks whether vector is normal to \a *normal.
282 * @return true - vector is normalized, false - vector is not
283 */
[273382]284bool Vector::IsEqualTo(const Vector &a) const
[b998c3]285{
286 bool status = true;
287 for (int i=0;i<NDIM;i++) {
[d466f0]288 if (fabs(at(i) - a[i]) > MYEPSILON)
[b998c3]289 status = false;
290 }
291 return status;
292};
293
[6ac7ee]294/** Calculates the angle between this and another vector.
295 * \param *y array to second vector
296 * \return \f$\acos\bigl(frac{\langle x, y \rangle}{|x||y|}\bigr)\f$
297 */
[273382]298double Vector::Angle(const Vector &y) const
[6ac7ee]299{
[753f02]300 double norm1 = Norm(), norm2 = y.Norm();
[ef9df36]301 double angle = -1;
[d4d0dd]302 if ((fabs(norm1) > MYEPSILON) && (fabs(norm2) > MYEPSILON))
303 angle = this->ScalarProduct(y)/norm1/norm2;
[02da9e]304 // -1-MYEPSILON occured due to numerical imprecision, catch ...
[e138de]305 //Log() << Verbose(2) << "INFO: acos(-1) = " << acos(-1) << ", acos(-1+MYEPSILON) = " << acos(-1+MYEPSILON) << ", acos(-1-MYEPSILON) = " << acos(-1-MYEPSILON) << "." << endl;
[02da9e]306 if (angle < -1)
307 angle = -1;
308 if (angle > 1)
309 angle = 1;
[042f82]310 return acos(angle);
[6ac7ee]311};
312
[0a4f7f]313
314double& Vector::operator[](size_t i){
[753f02]315 ASSERT(i<=NDIM && i>=0,"Vector Index out of Range");
[ce3d2b]316 return *gsl_vector_ptr (content->content, i);
[0a4f7f]317}
318
319const double& Vector::operator[](size_t i) const{
[753f02]320 ASSERT(i<=NDIM && i>=0,"Vector Index out of Range");
[ce3d2b]321 return *gsl_vector_ptr (content->content, i);
[0a4f7f]322}
323
324double& Vector::at(size_t i){
325 return (*this)[i];
326}
327
328const double& Vector::at(size_t i) const{
329 return (*this)[i];
330}
331
[ce3d2b]332VectorContent* Vector::get(){
[0c7ed8]333 return content;
[0a4f7f]334}
[6ac7ee]335
[ef9df36]336/** Compares vector \a to vector \a b component-wise.
337 * \param a base vector
338 * \param b vector components to add
339 * \return a == b
340 */
[72e7fa]341bool Vector::operator==(const Vector& b) const
[ef9df36]342{
[1bd79e]343 return IsEqualTo(b);
[ef9df36]344};
345
[fa5a6a]346bool Vector::operator!=(const Vector& b) const
347{
348 return !IsEqualTo(b);
349}
350
[6ac7ee]351/** Sums vector \a to this lhs component-wise.
352 * \param a base vector
353 * \param b vector components to add
354 * \return lhs + a
355 */
[72e7fa]356const Vector& Vector::operator+=(const Vector& b)
[6ac7ee]357{
[273382]358 this->AddVector(b);
[72e7fa]359 return *this;
[6ac7ee]360};
[54a746]361
362/** Subtracts vector \a from this lhs component-wise.
363 * \param a base vector
364 * \param b vector components to add
365 * \return lhs - a
366 */
[72e7fa]367const Vector& Vector::operator-=(const Vector& b)
[54a746]368{
[273382]369 this->SubtractVector(b);
[72e7fa]370 return *this;
[54a746]371};
372
[6ac7ee]373/** factor each component of \a a times a double \a m.
374 * \param a base vector
375 * \param m factor
376 * \return lhs.x[i] * m
377 */
[b84d5d]378const Vector& operator*=(Vector& a, const double m)
[6ac7ee]379{
[042f82]380 a.Scale(m);
381 return a;
[6ac7ee]382};
383
[042f82]384/** Sums two vectors \a and \b component-wise.
[6ac7ee]385 * \param a first vector
386 * \param b second vector
387 * \return a + b
388 */
[72e7fa]389Vector const Vector::operator+(const Vector& b) const
[6ac7ee]390{
[72e7fa]391 Vector x = *this;
[273382]392 x.AddVector(b);
[b84d5d]393 return x;
[6ac7ee]394};
395
[54a746]396/** Subtracts vector \a from \b component-wise.
397 * \param a first vector
398 * \param b second vector
399 * \return a - b
400 */
[72e7fa]401Vector const Vector::operator-(const Vector& b) const
[54a746]402{
[72e7fa]403 Vector x = *this;
[273382]404 x.SubtractVector(b);
[b84d5d]405 return x;
[54a746]406};
407
[6ac7ee]408/** Factors given vector \a a times \a m.
409 * \param a vector
410 * \param m factor
[54a746]411 * \return m * a
[6ac7ee]412 */
[b84d5d]413Vector const operator*(const Vector& a, const double m)
[6ac7ee]414{
[b84d5d]415 Vector x(a);
416 x.Scale(m);
417 return x;
[6ac7ee]418};
419
[54a746]420/** Factors given vector \a a times \a m.
421 * \param m factor
422 * \param a vector
423 * \return m * a
424 */
[b84d5d]425Vector const operator*(const double m, const Vector& a )
[54a746]426{
[b84d5d]427 Vector x(a);
428 x.Scale(m);
429 return x;
[54a746]430};
431
[9c20aa]432ostream& operator<<(ostream& ost, const Vector& m)
[6ac7ee]433{
[042f82]434 ost << "(";
435 for (int i=0;i<NDIM;i++) {
[0a4f7f]436 ost << m[i];
[042f82]437 if (i != 2)
438 ost << ",";
439 }
440 ost << ")";
441 return ost;
[6ac7ee]442};
443
444
[1bd79e]445void Vector::ScaleAll(const double *factor)
[6ac7ee]446{
[042f82]447 for (int i=NDIM;i--;)
[d466f0]448 at(i) *= factor[i];
[6ac7ee]449};
450
[b5bf84]451void Vector::ScaleAll(const Vector &factor){
[ce3d2b]452 gsl_vector_mul(content->content, factor.content->content);
[b5bf84]453}
[6ac7ee]454
[1bd79e]455
[776b64]456void Vector::Scale(const double factor)
[6ac7ee]457{
[ce3d2b]458 gsl_vector_scale(content->content,factor);
[6ac7ee]459};
460
[45ef76]461std::pair<Vector,Vector> Vector::partition(const Vector &rhs) const{
462 double factor = ScalarProduct(rhs)/rhs.NormSquared();
463 Vector res= factor * rhs;
464 return make_pair(res,(*this)-res);
465}
466
467std::pair<pointset,Vector> Vector::partition(const pointset &points) const{
468 Vector helper = *this;
469 pointset res;
470 for(pointset::const_iterator iter=points.begin();iter!=points.end();++iter){
471 pair<Vector,Vector> currPart = helper.partition(*iter);
472 res.push_back(currPart.first);
473 helper = currPart.second;
474 }
475 return make_pair(res,helper);
476}
477
[6ac7ee]478/** Creates this vector as the b y *factors' components scaled linear combination of the given three.
479 * this vector = x1*factors[0] + x2* factors[1] + x3*factors[2]
480 * \param *x1 first vector
481 * \param *x2 second vector
482 * \param *x3 third vector
483 * \param *factors three-component vector with the factor for each given vector
484 */
[273382]485void Vector::LinearCombinationOfVectors(const Vector &x1, const Vector &x2, const Vector &x3, const double * const factors)
[6ac7ee]486{
[273382]487 (*this) = (factors[0]*x1) +
488 (factors[1]*x2) +
489 (factors[2]*x3);
[6ac7ee]490};
491
492/** Calculates orthonormal vector to one given vectors.
493 * Just subtracts the projection onto the given vector from this vector.
[ef9df36]494 * The removed part of the vector is Vector::Projection()
[6ac7ee]495 * \param *x1 vector
496 * \return true - success, false - vector is zero
497 */
[0a4f7f]498bool Vector::MakeNormalTo(const Vector &y1)
[6ac7ee]499{
[042f82]500 bool result = false;
[753f02]501 double factor = y1.ScalarProduct(*this)/y1.NormSquared();
[45ef76]502 Vector x1 = factor * y1;
[753f02]503 SubtractVector(x1);
[042f82]504 for (int i=NDIM;i--;)
[d466f0]505 result = result || (fabs(at(i)) > MYEPSILON);
[6ac7ee]506
[042f82]507 return result;
[6ac7ee]508};
509
510/** Creates this vector as one of the possible orthonormal ones to the given one.
511 * Just scan how many components of given *vector are unequal to zero and
512 * try to get the skp of both to be zero accordingly.
513 * \param *vector given vector
514 * \return true - success, false - failure (null vector given)
515 */
[273382]516bool Vector::GetOneNormalVector(const Vector &GivenVector)
[6ac7ee]517{
[042f82]518 int Components[NDIM]; // contains indices of non-zero components
519 int Last = 0; // count the number of non-zero entries in vector
520 int j; // loop variables
521 double norm;
522
523 for (j=NDIM;j--;)
524 Components[j] = -1;
[1829c4]525
526 // in two component-systems we need to find the one position that is zero
527 int zeroPos = -1;
[042f82]528 // find two components != 0
[1829c4]529 for (j=0;j<NDIM;j++){
[753f02]530 if (fabs(GivenVector[j]) > MYEPSILON)
[042f82]531 Components[Last++] = j;
[1829c4]532 else
533 // this our zero Position
534 zeroPos = j;
535 }
[042f82]536
537 switch(Last) {
538 case 3: // threecomponent system
[1829c4]539 // the position of the zero is arbitrary in three component systems
540 zeroPos = Components[2];
[042f82]541 case 2: // two component system
[753f02]542 norm = sqrt(1./(GivenVector[Components[1]]*GivenVector[Components[1]]) + 1./(GivenVector[Components[0]]*GivenVector[Components[0]]));
[1829c4]543 at(zeroPos) = 0.;
[042f82]544 // in skp both remaining parts shall become zero but with opposite sign and third is zero
[1829c4]545 at(Components[1]) = -1./GivenVector[Components[1]] / norm;
546 at(Components[0]) = 1./GivenVector[Components[0]] / norm;
[042f82]547 return true;
548 break;
549 case 1: // one component system
550 // set sole non-zero component to 0, and one of the other zero component pendants to 1
[1829c4]551 at((Components[0]+2)%NDIM) = 0.;
552 at((Components[0]+1)%NDIM) = 1.;
553 at(Components[0]) = 0.;
[042f82]554 return true;
555 break;
556 default:
557 return false;
558 }
[6ac7ee]559};
560
561/** Adds vector \a *y componentwise.
562 * \param *y vector
563 */
[273382]564void Vector::AddVector(const Vector &y)
[6ac7ee]565{
[ce3d2b]566 gsl_vector_add(content->content, y.content->content);
[6ac7ee]567}
568
569/** Adds vector \a *y componentwise.
570 * \param *y vector
571 */
[273382]572void Vector::SubtractVector(const Vector &y)
[6ac7ee]573{
[ce3d2b]574 gsl_vector_sub(content->content, y.content->content);
[ef9df36]575}
576
[005e18]577
578// some comonly used vectors
579const Vector zeroVec(0,0,0);
580const Vector e1(1,0,0);
581const Vector e2(0,1,0);
582const Vector e3(0,0,1);
Note: See TracBrowser for help on using the repository browser.