source: src/vector.cpp@ d74077

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

Member variable Vector and element of class atom are now private.

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