source: src/vector.cpp@ 986ed3

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 986ed3 was 4b94bb, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Moved Vector-Matrix operations to matrix class

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