source: src/LinearAlgebra/Line.cpp@ 6e5084

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

New functions vor class Vector and Matrix.

Matrix:

  • transpose() (returning copy and on itself)
  • zero() (initialize to zero)
  • transformToEigenbasis() (columns are eigenvectors, return value has eigenvalues)

Vector:

  • Property mode set to 100644
File size: 6.9 KB
Line 
1/*
2 * Line.cpp
3 *
4 * Created on: Apr 30, 2010
5 * Author: crueger
6 */
7
8#include "Helpers/MemDebug.hpp"
9
10#include "LinearAlgebra/Line.hpp"
11
12#include <cmath>
13#include <iostream>
14
15#include "LinearAlgebra/Vector.hpp"
16#include "Helpers/Log.hpp"
17#include "Helpers/Verbose.hpp"
18#include "LinearAlgebra/gslmatrix.hpp"
19#include "Helpers/Info.hpp"
20#include "Exceptions/LinearDependenceException.hpp"
21#include "Exceptions/SkewException.hpp"
22#include "LinearAlgebra/Plane.hpp"
23
24using namespace std;
25
26Line::Line(const Vector &_origin, const Vector &_direction) :
27 direction(new Vector(_direction))
28{
29 direction->Normalize();
30 origin.reset(new Vector(_origin.partition(*direction).second));
31}
32
33Line::Line(const Line &src) :
34 origin(new Vector(*src.origin)),
35 direction(new Vector(*src.direction))
36{}
37
38Line::~Line()
39{}
40
41
42double Line::distance(const Vector &point) const{
43 // get any vector from line to point
44 Vector helper = point - *origin;
45 // partition this vector along direction
46 // the residue points from the line to the point
47 return helper.partition(*direction).second.Norm();
48}
49
50Vector Line::getClosestPoint(const Vector &point) const{
51 // get any vector from line to point
52 Vector helper = point - *origin;
53 // partition this vector along direction
54 // add only the part along the direction
55 return *origin + helper.partition(*direction).first;
56}
57
58Vector Line::getDirection() const{
59 return *direction;
60}
61
62Vector Line::getOrigin() const{
63 return *origin;
64}
65
66vector<Vector> Line::getPointsOnLine() const{
67 vector<Vector> res;
68 res.reserve(2);
69 res.push_back(*origin);
70 res.push_back(*origin+*direction);
71 return res;
72}
73
74/** Calculates the intersection of the two lines that are both on the same plane.
75 * This is taken from Weisstein, Eric W. "Line-Line Intersection." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/Line-LineIntersection.html
76 * \param *out output stream for debugging
77 * \param *Line1a first vector of first line
78 * \param *Line1b second vector of first line
79 * \param *Line2a first vector of second line
80 * \param *Line2b second vector of second line
81 * \return true - \a this will contain the intersection on return, false - lines are parallel
82 */
83Vector Line::getIntersection(const Line& otherLine) const{
84 Info FunctionInfo(__func__);
85
86 pointset line1Points = getPointsOnLine();
87
88 Vector Line1a = line1Points[0];
89 Vector Line1b = line1Points[1];
90
91 pointset line2Points = otherLine.getPointsOnLine();
92
93 Vector Line2a = line2Points[0];
94 Vector Line2b = line2Points[1];
95
96 Vector res;
97
98 auto_ptr<GSLMatrix> M = auto_ptr<GSLMatrix>(new GSLMatrix(4,4));
99
100 M->SetAll(1.);
101 for (int i=0;i<3;i++) {
102 M->Set(0, i, Line1a[i]);
103 M->Set(1, i, Line1b[i]);
104 M->Set(2, i, Line2a[i]);
105 M->Set(3, i, Line2b[i]);
106 }
107
108 //Log() << Verbose(1) << "Coefficent matrix is:" << endl;
109 //for (int i=0;i<4;i++) {
110 // for (int j=0;j<4;j++)
111 // cout << "\t" << M->Get(i,j);
112 // cout << endl;
113 //}
114 if (fabs(M->Determinant()) > MYEPSILON) {
115 Log() << Verbose(1) << "Determinant of coefficient matrix is NOT zero." << endl;
116 throw SkewException(__FILE__,__LINE__);
117 }
118
119 Log() << Verbose(1) << "INFO: Line1a = " << Line1a << ", Line1b = " << Line1b << ", Line2a = " << Line2a << ", Line2b = " << Line2b << "." << endl;
120
121
122 // constuct a,b,c
123 Vector a = Line1b - Line1a;
124 Vector b = Line2b - Line2a;
125 Vector c = Line2a - Line1a;
126 Vector d = Line2b - Line1b;
127 Log() << Verbose(1) << "INFO: a = " << a << ", b = " << b << ", c = " << c << "." << endl;
128 if ((a.NormSquared() < MYEPSILON) || (b.NormSquared() < MYEPSILON)) {
129 res.Zero();
130 Log() << Verbose(1) << "At least one of the lines is ill-defined, i.e. offset equals second vector." << endl;
131 throw LinearDependenceException(__FILE__,__LINE__);
132 }
133
134 // check for parallelity
135 Vector parallel;
136 double factor = 0.;
137 if (fabs(a.ScalarProduct(b)*a.ScalarProduct(b)/a.NormSquared()/b.NormSquared() - 1.) < MYEPSILON) {
138 parallel = Line1a - Line2a;
139 factor = parallel.ScalarProduct(a)/a.Norm();
140 if ((factor >= -MYEPSILON) && (factor - 1. < MYEPSILON)) {
141 res = Line2a;
142 Log() << Verbose(1) << "Lines conincide." << endl;
143 return res;
144 } else {
145 parallel = Line1a - Line2b;
146 factor = parallel.ScalarProduct(a)/a.Norm();
147 if ((factor >= -MYEPSILON) && (factor - 1. < MYEPSILON)) {
148 res = Line2b;
149 Log() << Verbose(1) << "Lines conincide." << endl;
150 return res;
151 }
152 }
153 Log() << Verbose(1) << "Lines are parallel." << endl;
154 res.Zero();
155 throw LinearDependenceException(__FILE__,__LINE__);
156 }
157
158 // obtain s
159 double s;
160 Vector temp1, temp2;
161 temp1 = c;
162 temp1.VectorProduct(b);
163 temp2 = a;
164 temp2.VectorProduct(b);
165 Log() << Verbose(1) << "INFO: temp1 = " << temp1 << ", temp2 = " << temp2 << "." << endl;
166 if (fabs(temp2.NormSquared()) > MYEPSILON)
167 s = temp1.ScalarProduct(temp2)/temp2.NormSquared();
168 else
169 s = 0.;
170 Log() << Verbose(1) << "Factor s is " << temp1.ScalarProduct(temp2) << "/" << temp2.NormSquared() << " = " << s << "." << endl;
171
172 // construct intersection
173 res = a;
174 res.Scale(s);
175 res += Line1a;
176 Log() << Verbose(1) << "Intersection is at " << res << "." << endl;
177
178 return res;
179}
180
181/** Rotates the vector by an angle of \a alpha around this line.
182 * \param rhs Vector to rotate
183 * \param alpha rotation angle in radian
184 */
185Vector Line::rotateVector(const Vector &rhs, double alpha) const{
186 Vector helper = rhs;
187
188 // translate the coordinate system so that the line goes through (0,0,0)
189 helper -= *origin;
190
191 // partition the vector into a part that gets rotated and a part that lies along the line
192 pair<Vector,Vector> parts = helper.partition(*direction);
193
194 // we just keep anything that is along the axis
195 Vector res = parts.first;
196
197 // the rest has to be rotated
198 Vector a = parts.second;
199 // we only have to do the rest, if we actually could partition the vector
200 if(!a.IsZero()){
201 // construct a vector that is orthogonal to a and direction and has length |a|
202 Vector y = a;
203 // direction is normalized, so the result has length |a|
204 y.VectorProduct(*direction);
205
206 res += cos(alpha) * a + sin(alpha) * y;
207 }
208
209 // translate the coordinate system back
210 res += *origin;
211 return res;
212}
213
214Plane Line::getOrthogonalPlane(const Vector &origin) const{
215 return Plane(getDirection(),origin);
216}
217
218std::vector<Vector> Line::getSphereIntersections() const{
219 std::vector<Vector> res;
220
221 // line is kept in normalized form, so we can skip a lot of calculations
222 double discriminant = 1-origin->NormSquared();
223 // we might have 2, 1 or 0 solutions, depending on discriminant
224 if(discriminant>=0){
225 if(discriminant==0){
226 res.push_back(*origin);
227 }
228 else{
229 Vector helper = sqrt(discriminant)*(*direction);
230 res.push_back(*origin+helper);
231 res.push_back(*origin-helper);
232 }
233 }
234 return res;
235}
236
237Line makeLineThrough(const Vector &x1, const Vector &x2){
238 if(x1==x2){
239 throw LinearDependenceException(__FILE__,__LINE__);
240 }
241 return Line(x1,x1-x2);
242}
Note: See TracBrowser for help on using the repository browser.