source: src/vector.cpp@ 205d9b

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 205d9b was b5bf84, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Added a method that allows to scale all components of one vector with all components of another vector.

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