source: src/vector.cpp@ 83c09a

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 83c09a was 5108e1, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Removed MatrixMultiplication() method from Vector class

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