source: src/LinearAlgebra/Vector.cpp@ a439e5

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 Candidate_v1.7.0 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 a439e5 was a439e5, checked in by Frederik Heber <heber@…>, 15 years ago

New functions vor class Vector and Matrix.

Matrix:

  • transpose() (returning copy and on itself)
  • zero() (initialize to zero)
  • transformToEigenbasis() (columns are eigenvectors, return value has eigenvalues)

Vector:

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