source: src/LinearAlgebra/Vector.cpp@ 06aedc

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 06aedc was 06aedc, checked in by Frederik Heber <heber@…>, 14 years ago

libMolecuilderLinearAlgebra is now a self-contained library fit for external use.

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