source: src/vector.cpp@ 4907a3

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 4907a3 was 9df5c6, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made the Vector::IsInParallelepiped() method take a matrix instead of a double*

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