source: src/vector.cpp@ 08d9595

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 08d9595 was ce3d2b, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Added a "forward declaration" to the gsl_vector struct to avoid inclusion of the GSL-Headers in too many files

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