source: src/vector.cpp@ 04ef48

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 04ef48 was ce3d2b, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Added a "forward declaration" to the gsl_vector struct to avoid inclusion of the GSL-Headers in too many files

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