source: src/vector.cpp@ e1589e

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

New function Vector::NormSquared() and Angle checks whether Norm's are unequal to zero.

  • New function Vector::NormSquared() calculates norm squared
  • Vector::Angle() checks whether the norms of the vectors are not zero, otherwise returning M_PI
  • Property mode set to 100755
File size: 27.6 KB
Line 
1/** \file vector.cpp
2 *
3 * Function implementations for the class vector.
4 *
5 */
6
7#include "molecules.hpp"
8
9
10/************************************ Functions for class vector ************************************/
11
12/** Constructor of class vector.
13 */
14Vector::Vector() { x[0] = x[1] = x[2] = 0.; };
15
16/** Constructor of class vector.
17 */
18Vector::Vector(double x1, double x2, double x3) { x[0] = x1; x[1] = x2; x[2] = x3; };
19
20/** Desctructor of class vector.
21 */
22Vector::~Vector() {};
23
24/** Calculates square of distance between this and another vector.
25 * \param *y array to second vector
26 * \return \f$| x - y |^2\f$
27 */
28double Vector::DistanceSquared(const Vector *y) const
29{
30 double res = 0.;
31 for (int i=NDIM;i--;)
32 res += (x[i]-y->x[i])*(x[i]-y->x[i]);
33 return (res);
34};
35
36/** Calculates distance between this and another vector.
37 * \param *y array to second vector
38 * \return \f$| x - y |\f$
39 */
40double Vector::Distance(const Vector *y) const
41{
42 double res = 0.;
43 for (int i=NDIM;i--;)
44 res += (x[i]-y->x[i])*(x[i]-y->x[i]);
45 return (sqrt(res));
46};
47
48/** Calculates distance between this and another vector in a periodic cell.
49 * \param *y array to second vector
50 * \param *cell_size 6-dimensional array with (xx, xy, yy, xz, yz, zz) entries specifying the periodic cell
51 * \return \f$| x - y |\f$
52 */
53double Vector::PeriodicDistance(const Vector *y, const double *cell_size) const
54{
55 double res = Distance(y), tmp, matrix[NDIM*NDIM];
56 Vector Shiftedy, TranslationVector;
57 int N[NDIM];
58 matrix[0] = cell_size[0];
59 matrix[1] = cell_size[1];
60 matrix[2] = cell_size[3];
61 matrix[3] = cell_size[1];
62 matrix[4] = cell_size[2];
63 matrix[5] = cell_size[4];
64 matrix[6] = cell_size[3];
65 matrix[7] = cell_size[4];
66 matrix[8] = cell_size[5];
67 // in order to check the periodic distance, translate one of the vectors into each of the 27 neighbouring cells
68 for (N[0]=-1;N[0]<=1;N[0]++)
69 for (N[1]=-1;N[1]<=1;N[1]++)
70 for (N[2]=-1;N[2]<=1;N[2]++) {
71 // create the translation vector
72 TranslationVector.Zero();
73 for (int i=NDIM;i--;)
74 TranslationVector.x[i] = (double)N[i];
75 TranslationVector.MatrixMultiplication(matrix);
76 // add onto the original vector to compare with
77 Shiftedy.CopyVector(y);
78 Shiftedy.AddVector(&TranslationVector);
79 // get distance and compare with minimum so far
80 tmp = Distance(&Shiftedy);
81 if (tmp < res) res = tmp;
82 }
83 return (res);
84};
85
86/** Calculates distance between this and another vector in a periodic cell.
87 * \param *y array to second vector
88 * \param *cell_size 6-dimensional array with (xx, xy, yy, xz, yz, zz) entries specifying the periodic cell
89 * \return \f$| x - y |^2\f$
90 */
91double Vector::PeriodicDistanceSquared(const Vector *y, const double *cell_size) const
92{
93 double res = DistanceSquared(y), tmp, matrix[NDIM*NDIM];
94 Vector Shiftedy, TranslationVector;
95 int N[NDIM];
96 matrix[0] = cell_size[0];
97 matrix[1] = cell_size[1];
98 matrix[2] = cell_size[3];
99 matrix[3] = cell_size[1];
100 matrix[4] = cell_size[2];
101 matrix[5] = cell_size[4];
102 matrix[6] = cell_size[3];
103 matrix[7] = cell_size[4];
104 matrix[8] = cell_size[5];
105 // in order to check the periodic distance, translate one of the vectors into each of the 27 neighbouring cells
106 for (N[0]=-1;N[0]<=1;N[0]++)
107 for (N[1]=-1;N[1]<=1;N[1]++)
108 for (N[2]=-1;N[2]<=1;N[2]++) {
109 // create the translation vector
110 TranslationVector.Zero();
111 for (int i=NDIM;i--;)
112 TranslationVector.x[i] = (double)N[i];
113 TranslationVector.MatrixMultiplication(matrix);
114 // add onto the original vector to compare with
115 Shiftedy.CopyVector(y);
116 Shiftedy.AddVector(&TranslationVector);
117 // get distance and compare with minimum so far
118 tmp = DistanceSquared(&Shiftedy);
119 if (tmp < res) res = tmp;
120 }
121 return (res);
122};
123
124/** Keeps the vector in a periodic cell, defined by the symmetric \a *matrix.
125 * \param *out ofstream for debugging messages
126 * Tries to translate a vector into each adjacent neighbouring cell.
127 */
128void Vector::KeepPeriodic(ofstream *out, double *matrix)
129{
130// int N[NDIM];
131// bool flag = false;
132 //vector Shifted, TranslationVector;
133 Vector TestVector;
134// *out << Verbose(1) << "Begin of KeepPeriodic." << endl;
135// *out << Verbose(2) << "Vector is: ";
136// Output(out);
137// *out << endl;
138 TestVector.CopyVector(this);
139 TestVector.InverseMatrixMultiplication(matrix);
140 for(int i=NDIM;i--;) { // correct periodically
141 if (TestVector.x[i] < 0) { // get every coefficient into the interval [0,1)
142 TestVector.x[i] += ceil(TestVector.x[i]);
143 } else {
144 TestVector.x[i] -= floor(TestVector.x[i]);
145 }
146 }
147 TestVector.MatrixMultiplication(matrix);
148 CopyVector(&TestVector);
149// *out << Verbose(2) << "New corrected vector is: ";
150// Output(out);
151// *out << endl;
152// *out << Verbose(1) << "End of KeepPeriodic." << endl;
153};
154
155/** Calculates scalar product between this and another vector.
156 * \param *y array to second vector
157 * \return \f$\langle x, y \rangle\f$
158 */
159double Vector::ScalarProduct(const Vector *y) const
160{
161 double res = 0.;
162 for (int i=NDIM;i--;)
163 res += x[i]*y->x[i];
164 return (res);
165};
166
167
168/** Calculates VectorProduct between this and another vector.
169 * -# returns the Product in place of vector from which it was initiated
170 * -# ATTENTION: Only three dim.
171 * \param *y array to vector with which to calculate crossproduct
172 * \return \f$ x \times y \f&
173 */
174void Vector::VectorProduct(const Vector *y)
175{
176 Vector tmp;
177 tmp.x[0] = x[1]* (y->x[2]) - x[2]* (y->x[1]);
178 tmp.x[1] = x[2]* (y->x[0]) - x[0]* (y->x[2]);
179 tmp.x[2] = x[0]* (y->x[1]) - x[1]* (y->x[0]);
180 this->CopyVector(&tmp);
181
182};
183
184
185/** projects this vector onto plane defined by \a *y.
186 * \param *y normal vector of plane
187 * \return \f$\langle x, y \rangle\f$
188 */
189void Vector::ProjectOntoPlane(const Vector *y)
190{
191 Vector tmp;
192 tmp.CopyVector(y);
193 tmp.Normalize();
194 tmp.Scale(ScalarProduct(&tmp));
195 this->SubtractVector(&tmp);
196};
197
198/** Calculates the projection of a vector onto another \a *y.
199 * \param *y array to second vector
200 * \return \f$\langle x, y \rangle\f$
201 */
202double Vector::Projection(const Vector *y) const
203{
204 return (ScalarProduct(y));
205};
206
207/** Calculates norm of this vector.
208 * \return \f$|x|\f$
209 */
210double Vector::Norm() const
211{
212 double res = 0.;
213 for (int i=NDIM;i--;)
214 res += this->x[i]*this->x[i];
215 return (sqrt(res));
216};
217
218/** Calculates squared norm of this vector.
219 * \return \f$|x|^2\f$
220 */
221double Vector::NormSquared() const
222{
223 return (ScalarProduct(this));
224};
225
226/** Normalizes this vector.
227 */
228void Vector::Normalize()
229{
230 double res = 0.;
231 for (int i=NDIM;i--;)
232 res += this->x[i]*this->x[i];
233 if (fabs(res) > MYEPSILON)
234 res = 1./sqrt(res);
235 Scale(&res);
236};
237
238/** Zeros all components of this vector.
239 */
240void Vector::Zero()
241{
242 for (int i=NDIM;i--;)
243 this->x[i] = 0.;
244};
245
246/** Zeros all components of this vector.
247 */
248void Vector::One(double one)
249{
250 for (int i=NDIM;i--;)
251 this->x[i] = one;
252};
253
254/** Initialises all components of this vector.
255 */
256void Vector::Init(double x1, double x2, double x3)
257{
258 x[0] = x1;
259 x[1] = x2;
260 x[2] = x3;
261};
262
263/** Calculates the angle between this and another vector.
264 * \param *y array to second vector
265 * \return \f$\acos\bigl(frac{\langle x, y \rangle}{|x||y|}\bigr)\f$
266 */
267double Vector::Angle(const Vector *y) const
268{
269 double norm1 = Norm(), norm2 = y->Norm();
270 double angle = 1;
271 if ((fabs(norm1) > MYEPSILON) && (fabs(norm2) > MYEPSILON))
272 angle = this->ScalarProduct(y)/norm1/norm2;
273 // -1-MYEPSILON occured due to numerical imprecision, catch ...
274 //cout << Verbose(2) << "INFO: acos(-1) = " << acos(-1) << ", acos(-1+MYEPSILON) = " << acos(-1+MYEPSILON) << ", acos(-1-MYEPSILON) = " << acos(-1-MYEPSILON) << "." << endl;
275 if (angle < -1)
276 angle = -1;
277 if (angle > 1)
278 angle = 1;
279 return acos(angle);
280};
281
282/** Rotates the vector around the axis given by \a *axis by an angle of \a alpha.
283 * \param *axis rotation axis
284 * \param alpha rotation angle in radian
285 */
286void Vector::RotateVector(const Vector *axis, const double alpha)
287{
288 Vector a,y;
289 // normalise this vector with respect to axis
290 a.CopyVector(this);
291 a.Scale(Projection(axis));
292 SubtractVector(&a);
293 // construct normal vector
294 y.MakeNormalVector(axis,this);
295 y.Scale(Norm());
296 // scale normal vector by sine and this vector by cosine
297 y.Scale(sin(alpha));
298 Scale(cos(alpha));
299 // add scaled normal vector onto this vector
300 AddVector(&y);
301 // add part in axis direction
302 AddVector(&a);
303};
304
305/** Sums vector \a to this lhs component-wise.
306 * \param a base vector
307 * \param b vector components to add
308 * \return lhs + a
309 */
310Vector& operator+=(Vector& a, const Vector& b)
311{
312 a.AddVector(&b);
313 return a;
314};
315/** factor each component of \a a times a double \a m.
316 * \param a base vector
317 * \param m factor
318 * \return lhs.x[i] * m
319 */
320Vector& operator*=(Vector& a, const double m)
321{
322 a.Scale(m);
323 return a;
324};
325
326/** Sums two vectors \a and \b component-wise.
327 * \param a first vector
328 * \param b second vector
329 * \return a + b
330 */
331Vector& operator+(const Vector& a, const Vector& b)
332{
333 Vector *x = new Vector;
334 x->CopyVector(&a);
335 x->AddVector(&b);
336 return *x;
337};
338
339/** Factors given vector \a a times \a m.
340 * \param a vector
341 * \param m factor
342 * \return a + b
343 */
344Vector& operator*(const Vector& a, const double m)
345{
346 Vector *x = new Vector;
347 x->CopyVector(&a);
348 x->Scale(m);
349 return *x;
350};
351
352/** Prints a 3dim vector.
353 * prints no end of line.
354 * \param *out output stream
355 */
356bool Vector::Output(ofstream *out) const
357{
358 if (out != NULL) {
359 *out << "(";
360 for (int i=0;i<NDIM;i++) {
361 *out << x[i];
362 if (i != 2)
363 *out << ",";
364 }
365 *out << ")";
366 return true;
367 } else
368 return false;
369};
370
371ostream& operator<<(ostream& ost,Vector& m)
372{
373 ost << "(";
374 for (int i=0;i<NDIM;i++) {
375 ost << m.x[i];
376 if (i != 2)
377 ost << ",";
378 }
379 ost << ")";
380 return ost;
381};
382
383/** Scales each atom coordinate by an individual \a factor.
384 * \param *factor pointer to scaling factor
385 */
386void Vector::Scale(double **factor)
387{
388 for (int i=NDIM;i--;)
389 x[i] *= (*factor)[i];
390};
391
392void Vector::Scale(double *factor)
393{
394 for (int i=NDIM;i--;)
395 x[i] *= *factor;
396};
397
398void Vector::Scale(double factor)
399{
400 for (int i=NDIM;i--;)
401 x[i] *= factor;
402};
403
404/** Translate atom by given vector.
405 * \param trans[] translation vector.
406 */
407void Vector::Translate(const Vector *trans)
408{
409 for (int i=NDIM;i--;)
410 x[i] += trans->x[i];
411};
412
413/** Do a matrix multiplication.
414 * \param *matrix NDIM_NDIM array
415 */
416void Vector::MatrixMultiplication(double *M)
417{
418 Vector C;
419 // do the matrix multiplication
420 C.x[0] = M[0]*x[0]+M[3]*x[1]+M[6]*x[2];
421 C.x[1] = M[1]*x[0]+M[4]*x[1]+M[7]*x[2];
422 C.x[2] = M[2]*x[0]+M[5]*x[1]+M[8]*x[2];
423 // transfer the result into this
424 for (int i=NDIM;i--;)
425 x[i] = C.x[i];
426};
427
428/** Calculate the inverse of a 3x3 matrix.
429 * \param *matrix NDIM_NDIM array
430 */
431double * Vector::InverseMatrix(double *A)
432{
433 double *B = (double *) Malloc(sizeof(double)*NDIM*NDIM, "Vector::InverseMatrix: *B");
434 double detA = RDET3(A);
435 double detAReci;
436
437 for (int i=0;i<NDIM*NDIM;++i)
438 B[i] = 0.;
439 // calculate the inverse B
440 if (fabs(detA) > MYEPSILON) {; // RDET3(A) yields precisely zero if A irregular
441 detAReci = 1./detA;
442 B[0] = detAReci*RDET2(A[4],A[5],A[7],A[8]); // A_11
443 B[1] = -detAReci*RDET2(A[1],A[2],A[7],A[8]); // A_12
444 B[2] = detAReci*RDET2(A[1],A[2],A[4],A[5]); // A_13
445 B[3] = -detAReci*RDET2(A[3],A[5],A[6],A[8]); // A_21
446 B[4] = detAReci*RDET2(A[0],A[2],A[6],A[8]); // A_22
447 B[5] = -detAReci*RDET2(A[0],A[2],A[3],A[5]); // A_23
448 B[6] = detAReci*RDET2(A[3],A[4],A[6],A[7]); // A_31
449 B[7] = -detAReci*RDET2(A[0],A[1],A[6],A[7]); // A_32
450 B[8] = detAReci*RDET2(A[0],A[1],A[3],A[4]); // A_33
451 }
452 return B;
453};
454
455/** Do a matrix multiplication with \a *matrix' inverse.
456 * \param *matrix NDIM_NDIM array
457 */
458void Vector::InverseMatrixMultiplication(double *A)
459{
460 Vector C;
461 double B[NDIM*NDIM];
462 double detA = RDET3(A);
463 double detAReci;
464
465 // calculate the inverse B
466 if (fabs(detA) > MYEPSILON) {; // RDET3(A) yields precisely zero if A irregular
467 detAReci = 1./detA;
468 B[0] = detAReci*RDET2(A[4],A[5],A[7],A[8]); // A_11
469 B[1] = -detAReci*RDET2(A[1],A[2],A[7],A[8]); // A_12
470 B[2] = detAReci*RDET2(A[1],A[2],A[4],A[5]); // A_13
471 B[3] = -detAReci*RDET2(A[3],A[5],A[6],A[8]); // A_21
472 B[4] = detAReci*RDET2(A[0],A[2],A[6],A[8]); // A_22
473 B[5] = -detAReci*RDET2(A[0],A[2],A[3],A[5]); // A_23
474 B[6] = detAReci*RDET2(A[3],A[4],A[6],A[7]); // A_31
475 B[7] = -detAReci*RDET2(A[0],A[1],A[6],A[7]); // A_32
476 B[8] = detAReci*RDET2(A[0],A[1],A[3],A[4]); // A_33
477
478 // do the matrix multiplication
479 C.x[0] = B[0]*x[0]+B[3]*x[1]+B[6]*x[2];
480 C.x[1] = B[1]*x[0]+B[4]*x[1]+B[7]*x[2];
481 C.x[2] = B[2]*x[0]+B[5]*x[1]+B[8]*x[2];
482 // transfer the result into this
483 for (int i=NDIM;i--;)
484 x[i] = C.x[i];
485 } else {
486 cerr << "ERROR: inverse of matrix does not exists: det A = " << detA << "." << endl;
487 }
488};
489
490
491/** Creates this vector as the b y *factors' components scaled linear combination of the given three.
492 * this vector = x1*factors[0] + x2* factors[1] + x3*factors[2]
493 * \param *x1 first vector
494 * \param *x2 second vector
495 * \param *x3 third vector
496 * \param *factors three-component vector with the factor for each given vector
497 */
498void Vector::LinearCombinationOfVectors(const Vector *x1, const Vector *x2, const Vector *x3, double *factors)
499{
500 for(int i=NDIM;i--;)
501 x[i] = factors[0]*x1->x[i] + factors[1]*x2->x[i] + factors[2]*x3->x[i];
502};
503
504/** Mirrors atom against a given plane.
505 * \param n[] normal vector of mirror plane.
506 */
507void Vector::Mirror(const Vector *n)
508{
509 double projection;
510 projection = ScalarProduct(n)/n->ScalarProduct(n); // remove constancy from n (keep as logical one)
511 // withdraw projected vector twice from original one
512 cout << Verbose(1) << "Vector: ";
513 Output((ofstream *)&cout);
514 cout << "\t";
515 for (int i=NDIM;i--;)
516 x[i] -= 2.*projection*n->x[i];
517 cout << "Projected vector: ";
518 Output((ofstream *)&cout);
519 cout << endl;
520};
521
522/** Calculates normal vector for three given vectors (being three points in space).
523 * Makes this vector orthonormal to the three given points, making up a place in 3d space.
524 * \param *y1 first vector
525 * \param *y2 second vector
526 * \param *y3 third vector
527 * \return true - success, vectors are linear independent, false - failure due to linear dependency
528 */
529bool Vector::MakeNormalVector(const Vector *y1, const Vector *y2, const Vector *y3)
530{
531 Vector x1, x2;
532
533 x1.CopyVector(y1);
534 x1.SubtractVector(y2);
535 x2.CopyVector(y3);
536 x2.SubtractVector(y2);
537 if ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON) || (fabs(x1.Angle(&x2)) < MYEPSILON)) {
538 cout << Verbose(4) << "Given vectors are linear dependent." << endl;
539 return false;
540 }
541// cout << Verbose(4) << "relative, first plane coordinates:";
542// x1.Output((ofstream *)&cout);
543// cout << endl;
544// cout << Verbose(4) << "second plane coordinates:";
545// x2.Output((ofstream *)&cout);
546// cout << endl;
547
548 this->x[0] = (x1.x[1]*x2.x[2] - x1.x[2]*x2.x[1]);
549 this->x[1] = (x1.x[2]*x2.x[0] - x1.x[0]*x2.x[2]);
550 this->x[2] = (x1.x[0]*x2.x[1] - x1.x[1]*x2.x[0]);
551 Normalize();
552
553 return true;
554};
555
556
557/** Calculates orthonormal vector to two given vectors.
558 * Makes this vector orthonormal to two given vectors. This is very similar to the other
559 * vector::MakeNormalVector(), only there three points whereas here two difference
560 * vectors are given.
561 * \param *x1 first vector
562 * \param *x2 second vector
563 * \return true - success, vectors are linear independent, false - failure due to linear dependency
564 */
565bool Vector::MakeNormalVector(const Vector *y1, const Vector *y2)
566{
567 Vector x1,x2;
568 x1.CopyVector(y1);
569 x2.CopyVector(y2);
570 Zero();
571 if ((fabs(x1.Norm()) < MYEPSILON) || (fabs(x2.Norm()) < MYEPSILON) || (fabs(x1.Angle(&x2)) < MYEPSILON)) {
572 cout << Verbose(4) << "Given vectors are linear dependent." << endl;
573 return false;
574 }
575// cout << Verbose(4) << "relative, first plane coordinates:";
576// x1.Output((ofstream *)&cout);
577// cout << endl;
578// cout << Verbose(4) << "second plane coordinates:";
579// x2.Output((ofstream *)&cout);
580// cout << endl;
581
582 this->x[0] = (x1.x[1]*x2.x[2] - x1.x[2]*x2.x[1]);
583 this->x[1] = (x1.x[2]*x2.x[0] - x1.x[0]*x2.x[2]);
584 this->x[2] = (x1.x[0]*x2.x[1] - x1.x[1]*x2.x[0]);
585 Normalize();
586
587 return true;
588};
589
590/** Calculates orthonormal vector to one given vectors.
591 * Just subtracts the projection onto the given vector from this vector.
592 * \param *x1 vector
593 * \return true - success, false - vector is zero
594 */
595bool Vector::MakeNormalVector(const Vector *y1)
596{
597 bool result = false;
598 Vector x1;
599 x1.CopyVector(y1);
600 x1.Scale(x1.Projection(this));
601 SubtractVector(&x1);
602 for (int i=NDIM;i--;)
603 result = result || (fabs(x[i]) > MYEPSILON);
604
605 return result;
606};
607
608/** Creates this vector as one of the possible orthonormal ones to the given one.
609 * Just scan how many components of given *vector are unequal to zero and
610 * try to get the skp of both to be zero accordingly.
611 * \param *vector given vector
612 * \return true - success, false - failure (null vector given)
613 */
614bool Vector::GetOneNormalVector(const Vector *GivenVector)
615{
616 int Components[NDIM]; // contains indices of non-zero components
617 int Last = 0; // count the number of non-zero entries in vector
618 int j; // loop variables
619 double norm;
620
621 cout << Verbose(4);
622 GivenVector->Output((ofstream *)&cout);
623 cout << endl;
624 for (j=NDIM;j--;)
625 Components[j] = -1;
626 // find two components != 0
627 for (j=0;j<NDIM;j++)
628 if (fabs(GivenVector->x[j]) > MYEPSILON)
629 Components[Last++] = j;
630 cout << Verbose(4) << Last << " Components != 0: (" << Components[0] << "," << Components[1] << "," << Components[2] << ")" << endl;
631
632 switch(Last) {
633 case 3: // threecomponent system
634 case 2: // two component system
635 norm = sqrt(1./(GivenVector->x[Components[1]]*GivenVector->x[Components[1]]) + 1./(GivenVector->x[Components[0]]*GivenVector->x[Components[0]]));
636 x[Components[2]] = 0.;
637 // in skp both remaining parts shall become zero but with opposite sign and third is zero
638 x[Components[1]] = -1./GivenVector->x[Components[1]] / norm;
639 x[Components[0]] = 1./GivenVector->x[Components[0]] / norm;
640 return true;
641 break;
642 case 1: // one component system
643 // set sole non-zero component to 0, and one of the other zero component pendants to 1
644 x[(Components[0]+2)%NDIM] = 0.;
645 x[(Components[0]+1)%NDIM] = 1.;
646 x[Components[0]] = 0.;
647 return true;
648 break;
649 default:
650 return false;
651 }
652};
653
654/** Determines paramter needed to multiply this vector to obtain intersection point with plane defined by \a *A, \a *B and \a *C.
655 * \param *A first plane vector
656 * \param *B second plane vector
657 * \param *C third plane vector
658 * \return scaling parameter for this vector
659 */
660double Vector::CutsPlaneAt(Vector *A, Vector *B, Vector *C)
661{
662// cout << Verbose(3) << "For comparison: ";
663// cout << "A " << A->Projection(this) << "\t";
664// cout << "B " << B->Projection(this) << "\t";
665// cout << "C " << C->Projection(this) << "\t";
666// cout << endl;
667 return A->Projection(this);
668};
669
670/** Creates a new vector as the one with least square distance to a given set of \a vectors.
671 * \param *vectors set of vectors
672 * \param num number of vectors
673 * \return true if success, false if failed due to linear dependency
674 */
675bool Vector::LSQdistance(Vector **vectors, int num)
676{
677 int j;
678
679 for (j=0;j<num;j++) {
680 cout << Verbose(1) << j << "th atom's vector: ";
681 (vectors[j])->Output((ofstream *)&cout);
682 cout << endl;
683 }
684
685 int np = 3;
686 struct LSQ_params par;
687
688 const gsl_multimin_fminimizer_type *T =
689 gsl_multimin_fminimizer_nmsimplex;
690 gsl_multimin_fminimizer *s = NULL;
691 gsl_vector *ss, *y;
692 gsl_multimin_function minex_func;
693
694 size_t iter = 0, i;
695 int status;
696 double size;
697
698 /* Initial vertex size vector */
699 ss = gsl_vector_alloc (np);
700 y = gsl_vector_alloc (np);
701
702 /* Set all step sizes to 1 */
703 gsl_vector_set_all (ss, 1.0);
704
705 /* Starting point */
706 par.vectors = vectors;
707 par.num = num;
708
709 for (i=NDIM;i--;)
710 gsl_vector_set(y, i, (vectors[0]->x[i] - vectors[1]->x[i])/2.);
711
712 /* Initialize method and iterate */
713 minex_func.f = &LSQ;
714 minex_func.n = np;
715 minex_func.params = (void *)&par;
716
717 s = gsl_multimin_fminimizer_alloc (T, np);
718 gsl_multimin_fminimizer_set (s, &minex_func, y, ss);
719
720 do
721 {
722 iter++;
723 status = gsl_multimin_fminimizer_iterate(s);
724
725 if (status)
726 break;
727
728 size = gsl_multimin_fminimizer_size (s);
729 status = gsl_multimin_test_size (size, 1e-2);
730
731 if (status == GSL_SUCCESS)
732 {
733 printf ("converged to minimum at\n");
734 }
735
736 printf ("%5d ", (int)iter);
737 for (i = 0; i < (size_t)np; i++)
738 {
739 printf ("%10.3e ", gsl_vector_get (s->x, i));
740 }
741 printf ("f() = %7.3f size = %.3f\n", s->fval, size);
742 }
743 while (status == GSL_CONTINUE && iter < 100);
744
745 for (i=(size_t)np;i--;)
746 this->x[i] = gsl_vector_get(s->x, i);
747 gsl_vector_free(y);
748 gsl_vector_free(ss);
749 gsl_multimin_fminimizer_free (s);
750
751 return true;
752};
753
754/** Adds vector \a *y componentwise.
755 * \param *y vector
756 */
757void Vector::AddVector(const Vector *y)
758{
759 for (int i=NDIM;i--;)
760 this->x[i] += y->x[i];
761}
762
763/** Adds vector \a *y componentwise.
764 * \param *y vector
765 */
766void Vector::SubtractVector(const Vector *y)
767{
768 for (int i=NDIM;i--;)
769 this->x[i] -= y->x[i];
770}
771
772/** Copy vector \a *y componentwise.
773 * \param *y vector
774 */
775void Vector::CopyVector(const Vector *y)
776{
777 for (int i=NDIM;i--;)
778 this->x[i] = y->x[i];
779}
780
781
782/** Asks for position, checks for boundary.
783 * \param cell_size unitary size of cubic cell, coordinates must be within 0...cell_size
784 * \param check whether bounds shall be checked (true) or not (false)
785 */
786void Vector::AskPosition(double *cell_size, bool check)
787{
788 char coords[3] = {'x','y','z'};
789 int j = -1;
790 for (int i=0;i<3;i++) {
791 j += i+1;
792 do {
793 cout << Verbose(0) << coords[i] << "[0.." << cell_size[j] << "]: ";
794 cin >> x[i];
795 } while (((x[i] < 0) || (x[i] >= cell_size[j])) && (check));
796 }
797};
798
799/** Solves a vectorial system consisting of two orthogonal statements and a norm statement.
800 * This is linear system of equations to be solved, however of the three given (skp of this vector\
801 * with either of the three hast to be zero) only two are linear independent. The third equation
802 * is that the vector should be of magnitude 1 (orthonormal). This all leads to a case-based solution
803 * where very often it has to be checked whether a certain value is zero or not and thus forked into
804 * another case.
805 * \param *x1 first vector
806 * \param *x2 second vector
807 * \param *y third vector
808 * \param alpha first angle
809 * \param beta second angle
810 * \param c norm of final vector
811 * \return a vector with \f$\langle x1,x2 \rangle=A\f$, \f$\langle x1,y \rangle = B\f$ and with norm \a c.
812 * \bug this is not yet working properly
813 */
814bool Vector::SolveSystem(Vector *x1, Vector *x2, Vector *y, double alpha, double beta, double c)
815{
816 double D1,D2,D3,E1,E2,F1,F2,F3,p,q=0., A, B1, B2, C;
817 double ang; // angle on testing
818 double sign[3];
819 int i,j,k;
820 A = cos(alpha) * x1->Norm() * c;
821 B1 = cos(beta + M_PI/2.) * y->Norm() * c;
822 B2 = cos(beta) * x2->Norm() * c;
823 C = c * c;
824 cout << Verbose(2) << "A " << A << "\tB " << B1 << "\tC " << C << endl;
825 int flag = 0;
826 if (fabs(x1->x[0]) < MYEPSILON) { // check for zero components for the later flipping and back-flipping
827 if (fabs(x1->x[1]) > MYEPSILON) {
828 flag = 1;
829 } else if (fabs(x1->x[2]) > MYEPSILON) {
830 flag = 2;
831 } else {
832 return false;
833 }
834 }
835 switch (flag) {
836 default:
837 case 0:
838 break;
839 case 2:
840 flip(&x1->x[0],&x1->x[1]);
841 flip(&x2->x[0],&x2->x[1]);
842 flip(&y->x[0],&y->x[1]);
843 //flip(&x[0],&x[1]);
844 flip(&x1->x[1],&x1->x[2]);
845 flip(&x2->x[1],&x2->x[2]);
846 flip(&y->x[1],&y->x[2]);
847 //flip(&x[1],&x[2]);
848 case 1:
849 flip(&x1->x[0],&x1->x[1]);
850 flip(&x2->x[0],&x2->x[1]);
851 flip(&y->x[0],&y->x[1]);
852 //flip(&x[0],&x[1]);
853 flip(&x1->x[1],&x1->x[2]);
854 flip(&x2->x[1],&x2->x[2]);
855 flip(&y->x[1],&y->x[2]);
856 //flip(&x[1],&x[2]);
857 break;
858 }
859 // now comes the case system
860 D1 = -y->x[0]/x1->x[0]*x1->x[1]+y->x[1];
861 D2 = -y->x[0]/x1->x[0]*x1->x[2]+y->x[2];
862 D3 = y->x[0]/x1->x[0]*A-B1;
863 cout << Verbose(2) << "D1 " << D1 << "\tD2 " << D2 << "\tD3 " << D3 << "\n";
864 if (fabs(D1) < MYEPSILON) {
865 cout << Verbose(2) << "D1 == 0!\n";
866 if (fabs(D2) > MYEPSILON) {
867 cout << Verbose(3) << "D2 != 0!\n";
868 x[2] = -D3/D2;
869 E1 = A/x1->x[0] + x1->x[2]/x1->x[0]*D3/D2;
870 E2 = -x1->x[1]/x1->x[0];
871 cout << Verbose(3) << "E1 " << E1 << "\tE2 " << E2 << "\n";
872 F1 = E1*E1 + 1.;
873 F2 = -E1*E2;
874 F3 = E1*E1 + D3*D3/(D2*D2) - C;
875 cout << Verbose(3) << "F1 " << F1 << "\tF2 " << F2 << "\tF3 " << F3 << "\n";
876 if (fabs(F1) < MYEPSILON) {
877 cout << Verbose(4) << "F1 == 0!\n";
878 cout << Verbose(4) << "Gleichungssystem linear\n";
879 x[1] = F3/(2.*F2);
880 } else {
881 p = F2/F1;
882 q = p*p - F3/F1;
883 cout << Verbose(4) << "p " << p << "\tq " << q << endl;
884 if (q < 0) {
885 cout << Verbose(4) << "q < 0" << endl;
886 return false;
887 }
888 x[1] = p + sqrt(q);
889 }
890 x[0] = A/x1->x[0] - x1->x[1]/x1->x[0]*x[1] + x1->x[2]/x1->x[0]*x[2];
891 } else {
892 cout << Verbose(2) << "Gleichungssystem unterbestimmt\n";
893 return false;
894 }
895 } else {
896 E1 = A/x1->x[0]+x1->x[1]/x1->x[0]*D3/D1;
897 E2 = x1->x[1]/x1->x[0]*D2/D1 - x1->x[2];
898 cout << Verbose(2) << "E1 " << E1 << "\tE2 " << E2 << "\n";
899 F1 = E2*E2 + D2*D2/(D1*D1) + 1.;
900 F2 = -(E1*E2 + D2*D3/(D1*D1));
901 F3 = E1*E1 + D3*D3/(D1*D1) - C;
902 cout << Verbose(2) << "F1 " << F1 << "\tF2 " << F2 << "\tF3 " << F3 << "\n";
903 if (fabs(F1) < MYEPSILON) {
904 cout << Verbose(3) << "F1 == 0!\n";
905 cout << Verbose(3) << "Gleichungssystem linear\n";
906 x[2] = F3/(2.*F2);
907 } else {
908 p = F2/F1;
909 q = p*p - F3/F1;
910 cout << Verbose(3) << "p " << p << "\tq " << q << endl;
911 if (q < 0) {
912 cout << Verbose(3) << "q < 0" << endl;
913 return false;
914 }
915 x[2] = p + sqrt(q);
916 }
917 x[1] = (-D2 * x[2] - D3)/D1;
918 x[0] = A/x1->x[0] - x1->x[1]/x1->x[0]*x[1] + x1->x[2]/x1->x[0]*x[2];
919 }
920 switch (flag) { // back-flipping
921 default:
922 case 0:
923 break;
924 case 2:
925 flip(&x1->x[0],&x1->x[1]);
926 flip(&x2->x[0],&x2->x[1]);
927 flip(&y->x[0],&y->x[1]);
928 flip(&x[0],&x[1]);
929 flip(&x1->x[1],&x1->x[2]);
930 flip(&x2->x[1],&x2->x[2]);
931 flip(&y->x[1],&y->x[2]);
932 flip(&x[1],&x[2]);
933 case 1:
934 flip(&x1->x[0],&x1->x[1]);
935 flip(&x2->x[0],&x2->x[1]);
936 flip(&y->x[0],&y->x[1]);
937 //flip(&x[0],&x[1]);
938 flip(&x1->x[1],&x1->x[2]);
939 flip(&x2->x[1],&x2->x[2]);
940 flip(&y->x[1],&y->x[2]);
941 flip(&x[1],&x[2]);
942 break;
943 }
944 // one z component is only determined by its radius (without sign)
945 // thus check eight possible sign flips and determine by checking angle with second vector
946 for (i=0;i<8;i++) {
947 // set sign vector accordingly
948 for (j=2;j>=0;j--) {
949 k = (i & pot(2,j)) << j;
950 cout << Verbose(2) << "k " << k << "\tpot(2,j) " << pot(2,j) << endl;
951 sign[j] = (k == 0) ? 1. : -1.;
952 }
953 cout << Verbose(2) << i << ": sign matrix is " << sign[0] << "\t" << sign[1] << "\t" << sign[2] << "\n";
954 // apply sign matrix
955 for (j=NDIM;j--;)
956 x[j] *= sign[j];
957 // calculate angle and check
958 ang = x2->Angle (this);
959 cout << Verbose(1) << i << "th angle " << ang << "\tbeta " << cos(beta) << " :\t";
960 if (fabs(ang - cos(beta)) < MYEPSILON) {
961 break;
962 }
963 // unapply sign matrix (is its own inverse)
964 for (j=NDIM;j--;)
965 x[j] *= sign[j];
966 }
967 return true;
968};
Note: See TracBrowser for help on using the repository browser.