source: src/LinearAlgebra/Vector.cpp@ 6e5084

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 6e5084 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
Line 
1/** \file vector.cpp
2 *
3 * Function implementations for the class vector.
4 *
5 */
6
7#include "Helpers/MemDebug.hpp"
8
9#include "LinearAlgebra/Vector.hpp"
10#include "VectorContent.hpp"
11#include "Helpers/Verbose.hpp"
12#include "World.hpp"
13#include "Helpers/Assert.hpp"
14#include "Helpers/fast_functions.hpp"
15#include "Exceptions/MathException.hpp"
16
17#include <iostream>
18#include <gsl/gsl_blas.h>
19#include <gsl/gsl_vector.h>
20
21
22using namespace std;
23
24
25/************************************ Functions for class vector ************************************/
26
27/** Constructor of class vector.
28 */
29Vector::Vector()
30{
31 content = new VectorContent();
32};
33
34/**
35 * Copy constructor
36 */
37
38Vector::Vector(const Vector& src)
39{
40 content = new VectorContent();
41 gsl_vector_memcpy(content->content, src.content->content);
42}
43
44/** Constructor of class vector.
45 */
46Vector::Vector(const double x1, const double x2, const double x3)
47{
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);
52};
53
54Vector::Vector(VectorContent *_content) :
55 content(_content)
56{}
57
58/**
59 * Assignment operator
60 */
61Vector& Vector::operator=(const Vector& src){
62 // check for self assignment
63 if(&src!=this){
64 gsl_vector_memcpy(content->content, src.content->content);
65 }
66 return *this;
67}
68
69/** Desctructor of class vector.
70 */
71Vector::~Vector() {
72 delete content;
73};
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 */
79double Vector::DistanceSquared(const Vector &y) const
80{
81 double res = 0.;
82 for (int i=NDIM;i--;)
83 res += (at(i)-y[i])*(at(i)-y[i]);
84 return (res);
85};
86
87/** Calculates distance between this and another vector.
88 * \param *y array to second vector
89 * \return \f$| x - y |\f$
90 */
91double Vector::distance(const Vector &y) const
92{
93 return (sqrt(DistanceSquared(y)));
94};
95
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
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
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 */
126double Vector::ScalarProduct(const Vector &y) const
127{
128 double res = 0.;
129 gsl_blas_ddot(content->content, y.content->content, &res);
130 return (res);
131};
132
133
134/** Calculates VectorProduct between this and another vector.
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&
139 */
140void Vector::VectorProduct(const Vector &y)
141{
142 Vector tmp;
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];
145 (*this) = tmp;
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 */
153void Vector::ProjectOntoPlane(const Vector &y)
154{
155 Vector tmp;
156 tmp = y;
157 tmp.Normalize();
158 tmp.Scale(ScalarProduct(tmp));
159 *this -= tmp;
160};
161
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 */
169double Vector::DistanceToSpace(const Space &space) const
170{
171 return space.distance(*this);
172};
173
174/** Calculates the projection of a vector onto another \a *y.
175 * \param *y array to second vector
176 */
177void Vector::ProjectIt(const Vector &y)
178{
179 (*this) += (-ScalarProduct(y))*y;
180};
181
182/** Calculates the projection of a vector onto another \a *y.
183 * \param *y array to second vector
184 * \return Vector
185 */
186Vector Vector::Projection(const Vector &y) const
187{
188 Vector helper = y;
189 helper.Scale((ScalarProduct(y)/y.NormSquared()));
190
191 return helper;
192};
193
194/** Calculates norm of this vector.
195 * \return \f$|x|\f$
196 */
197double Vector::Norm() const
198{
199 return (sqrt(NormSquared()));
200};
201
202/** Calculates squared norm of this vector.
203 * \return \f$|x|^2\f$
204 */
205double Vector::NormSquared() const
206{
207 return (ScalarProduct(*this));
208};
209
210/** Normalizes this vector.
211 */
212void Vector::Normalize()
213{
214 double factor = Norm();
215 (*this) *= 1/factor;
216};
217
218/** Zeros all components of this vector.
219 */
220void Vector::Zero()
221{
222 at(0)=at(1)=at(2)=0;
223};
224
225/** Zeros all components of this vector.
226 */
227void Vector::One(const double one)
228{
229 at(0)=at(1)=at(2)=one;
230};
231
232/** Checks whether vector has all components zero.
233 * @return true - vector is zero, false - vector is not
234 */
235bool Vector::IsZero() const
236{
237 return (fabs(at(0))+fabs(at(1))+fabs(at(2)) < MYEPSILON);
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);
246};
247
248/** Checks whether vector is normal to \a *normal.
249 * @return true - vector is normalized, false - vector is not
250 */
251bool Vector::IsNormalTo(const Vector &normal) const
252{
253 if (ScalarProduct(normal) < MYEPSILON)
254 return true;
255 else
256 return false;
257};
258
259/** Checks whether vector is normal to \a *normal.
260 * @return true - vector is normalized, false - vector is not
261 */
262bool Vector::IsEqualTo(const Vector &a) const
263{
264 bool status = true;
265 for (int i=0;i<NDIM;i++) {
266 if (fabs(at(i) - a[i]) > MYEPSILON)
267 status = false;
268 }
269 return status;
270};
271
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 */
276double Vector::Angle(const Vector &y) const
277{
278 double norm1 = Norm(), norm2 = y.Norm();
279 double angle = -1;
280 if ((fabs(norm1) > MYEPSILON) && (fabs(norm2) > MYEPSILON))
281 angle = this->ScalarProduct(y)/norm1/norm2;
282 // -1-MYEPSILON occured due to numerical imprecision, catch ...
283 //Log() << Verbose(2) << "INFO: acos(-1) = " << acos(-1) << ", acos(-1+MYEPSILON) = " << acos(-1+MYEPSILON) << ", acos(-1-MYEPSILON) = " << acos(-1-MYEPSILON) << "." << endl;
284 if (angle < -1)
285 angle = -1;
286 if (angle > 1)
287 angle = 1;
288 return acos(angle);
289};
290
291
292double& Vector::operator[](size_t i){
293 ASSERT(i<=NDIM && i>=0,"Vector Index out of Range");
294 return *gsl_vector_ptr (content->content, i);
295}
296
297const double& Vector::operator[](size_t i) const{
298 ASSERT(i<=NDIM && i>=0,"Vector Index out of Range");
299 return *gsl_vector_ptr (content->content, i);
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
310VectorContent* Vector::get(){
311 return content;
312}
313
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 */
319bool Vector::operator==(const Vector& b) const
320{
321 return IsEqualTo(b);
322};
323
324bool Vector::operator!=(const Vector& b) const
325{
326 return !IsEqualTo(b);
327}
328
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 */
334const Vector& Vector::operator+=(const Vector& b)
335{
336 this->AddVector(b);
337 return *this;
338};
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 */
345const Vector& Vector::operator-=(const Vector& b)
346{
347 this->SubtractVector(b);
348 return *this;
349};
350
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 */
356const Vector& operator*=(Vector& a, const double m)
357{
358 a.Scale(m);
359 return a;
360};
361
362/** Sums two vectors \a and \b component-wise.
363 * \param a first vector
364 * \param b second vector
365 * \return a + b
366 */
367Vector const Vector::operator+(const Vector& b) const
368{
369 Vector x = *this;
370 x.AddVector(b);
371 return x;
372};
373
374/** Subtracts vector \a from \b component-wise.
375 * \param a first vector
376 * \param b second vector
377 * \return a - b
378 */
379Vector const Vector::operator-(const Vector& b) const
380{
381 Vector x = *this;
382 x.SubtractVector(b);
383 return x;
384};
385
386/** Factors given vector \a a times \a m.
387 * \param a vector
388 * \param m factor
389 * \return m * a
390 */
391Vector const operator*(const Vector& a, const double m)
392{
393 Vector x(a);
394 x.Scale(m);
395 return x;
396};
397
398/** Factors given vector \a a times \a m.
399 * \param m factor
400 * \param a vector
401 * \return m * a
402 */
403Vector const operator*(const double m, const Vector& a )
404{
405 Vector x(a);
406 x.Scale(m);
407 return x;
408};
409
410ostream& operator<<(ostream& ost, const Vector& m)
411{
412 ost << "(";
413 for (int i=0;i<NDIM;i++) {
414 ost << m[i];
415 if (i != 2)
416 ost << ",";
417 }
418 ost << ")";
419 return ost;
420};
421
422
423void Vector::ScaleAll(const double *factor)
424{
425 for (int i=NDIM;i--;)
426 at(i) *= factor[i];
427};
428
429void Vector::ScaleAll(const Vector &factor){
430 gsl_vector_mul(content->content, factor.content->content);
431}
432
433
434void Vector::Scale(const double factor)
435{
436 gsl_vector_scale(content->content,factor);
437};
438
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
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 */
463void Vector::LinearCombinationOfVectors(const Vector &x1, const Vector &x2, const Vector &x3, const double * const factors)
464{
465 (*this) = (factors[0]*x1) +
466 (factors[1]*x2) +
467 (factors[2]*x3);
468};
469
470/** Calculates orthonormal vector to one given vectors.
471 * Just subtracts the projection onto the given vector from this vector.
472 * The removed part of the vector is Vector::Projection()
473 * \param *x1 vector
474 * \return true - success, false - vector is zero
475 */
476bool Vector::MakeNormalTo(const Vector &y1)
477{
478 bool result = false;
479 double factor = y1.ScalarProduct(*this)/y1.NormSquared();
480 Vector x1 = factor * y1;
481 SubtractVector(x1);
482 for (int i=NDIM;i--;)
483 result = result || (fabs(at(i)) > MYEPSILON);
484
485 return result;
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 */
494bool Vector::GetOneNormalVector(const Vector &GivenVector)
495{
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;
503
504 // in two component-systems we need to find the one position that is zero
505 int zeroPos = -1;
506 // find two components != 0
507 for (j=0;j<NDIM;j++){
508 if (fabs(GivenVector[j]) > MYEPSILON)
509 Components[Last++] = j;
510 else
511 // this our zero Position
512 zeroPos = j;
513 }
514
515 switch(Last) {
516 case 3: // threecomponent system
517 // the position of the zero is arbitrary in three component systems
518 zeroPos = Components[2];
519 case 2: // two component system
520 norm = sqrt(1./(GivenVector[Components[1]]*GivenVector[Components[1]]) + 1./(GivenVector[Components[0]]*GivenVector[Components[0]]));
521 at(zeroPos) = 0.;
522 // in skp both remaining parts shall become zero but with opposite sign and third is zero
523 at(Components[1]) = -1./GivenVector[Components[1]] / norm;
524 at(Components[0]) = 1./GivenVector[Components[0]] / norm;
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
529 at((Components[0]+2)%NDIM) = 0.;
530 at((Components[0]+1)%NDIM) = 1.;
531 at(Components[0]) = 0.;
532 return true;
533 break;
534 default:
535 return false;
536 }
537};
538
539/** Adds vector \a *y componentwise.
540 * \param *y vector
541 */
542void Vector::AddVector(const Vector &y)
543{
544 gsl_vector_add(content->content, y.content->content);
545}
546
547/** Adds vector \a *y componentwise.
548 * \param *y vector
549 */
550void Vector::SubtractVector(const Vector &y)
551{
552 gsl_vector_sub(content->content, y.content->content);
553}
554
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.