LABORATORY 3: Solving the Quadratic Equation

advertisement
COP 4331
OO Processes for Software Development
Lab3 Requirements
For a
Vector Application
© Dr. David A. Workman
School Electrical Engineering and Computer Science
University of Central Florida
Computer Science Department
Orlando, Florida
May 21, 2003
Last Revised: February 24, 2007
Table of Contents
Lab3: Obstacle Avoidance using Vector Algebra. .......................................................................................................... 1
Submission Requirements................................................................................................................................................... 1
The Vector Abstraction and Class Specification.............................................................................................................. 2
Special Vectors ..................................................................................................................................................................... 2
Vector Operations ............................................................................................................................................................... 3
Properties of Vector Operations ........................................................................................................................................ 3
Relationships between Points and Lines ........................................................................................................................... 4
Point-to-Line Solution ......................................................................................................................................................... 5
Line Intersection Problem .................................................................................................................................................. 6
Analysis of Obstacle Avoidance ......................................................................................................................................... 7
Distance to an Obstructing Object .................................................................................................................................... 8
Simple Obstacle Avoidance ................................................................................................................................................ 9
A General Object Oriented Design.................................................................................................................................. 11
Software Requirements..................................................................................................................................................... 14
List of Figures
Figure 1.
Figure 2.
Figure 3.
Figure 4.
Figure 5.
Figure 6.
Figure 7.
Definition of a Vector, V. ................................................................................................................................... 2
Equation of a Line.............................................................................................................................................. 4
Distance from P to L. ......................................................................................................................................... 5
Obstructing Object, Z. ....................................................................................................................................... 7
Impact Geometry. .............................................................................................................................................. 8
Possible Paths to Avoid Obstacle, Z ................................................................................................................. 9
Object Oriented Architecture for the Vector Applications ........................................................................ 11
List of Tables
Table 1. Operations on Vectors......................................................................................................................................... 3
Page i
Lab3: Obstacle Avoidance using Vector Algebra.
Objectives:
To introduce features of C++ key to developing large software systems.
To exploit reusable abstractions and components in constructing software.
To develop potentially reusable components for the term simulation project.
To introduce software specification concepts using UML.
C++ Features:
(1)
(2)
(3)
(4)
(5)
Exception classes and exception handling.
File IO using fstream and its subclasses ifstream and ofstream.
Overloaded extraction (>>) and insertion( << ) operators as friend functions.
Namespaces for organizing and sharing reusable components or packages.
Math and Template libraries.
Submission Requirements
All labs associated with this project shall include, as a minimum, the following deliverables:
all source files necessary to successfully compile, link and execute the delivered program
using g++ on Unix (Olympus); all input and output data files used to test the program prior
to delivery; a Readme file giving your name (or team members), submission date, Lab
number, and any comments about the submission that will help in fairly evaluating your
work.
These files shall be submitted electronically via email in the form of a (.zip) file with a prefix
having the form: Lab <number> - <last name> - <month><day>. For example, the file name
for Dr. Workman submitting Lab 2 on May 21 would be: Lab3-Workman-May21.zip.
Any resubmission of the same Lab shall be submitted using the same file format – only the
date portion would need to change. If you have more than one submission of a given Lab on
the same day, then only the latest one will be evaluated for a grade.
Page 1 of 16
The Vector Abstraction and Class Specification
AAvector
vectorinin2-space
2-spaceisisaapair
pair(a,
(a,b)b)
denoting
respectively
the
X
and
denoting respectively the X andYY
coordinates
coordinatesofofpoint
pointdenoting
denotingthe
the
head
of
a
vector
with
tail
at
(0,
head of a vector with tail at (0,0)0)
Y
r  a 2  b2
sin())
aa=rrcos(
bb== rr sin(
cos() )
  Sin 1 (b / r )  Cos 1 (a / r )
- 2    2
b
(a, b)
head point
r

V
(0, 0)
tail point
a
X
Figure 1. Definition of a Vector, V.
As illustrated in Figure 1, there are two common representations of vectors in 2-space, Cartesian
and Polar. In Cartesian form, the XY-coordinates of the Head are used to uniquely define a vector.
In Polar coordinates, the reference angle () relative to the positive X-axis, and its length ( r)
uniquely define a vector. In the discussion to follow, (X,Y) will implicitly denote the Cartesian
form, while Polar(r, ) will denote the equivalent Polar form.
Special Vectors
Many data abstractions define special constants or basis elements. For our vector abstraction we
define:
Zero
= (0.0 , 0.0) = Polar (0.0 , 0.0) = the null vector (head at origin)
Unit-X = (1.0, 0.0) = Polar (1.0 , 0.0) = the unit vector along the X-axis
Unit-Y = (0.0, 1.0) = Polar (1.0 , ) = the unit vector along the Y-axis
Page 2 of 16
Vector Operations
Given vectors, V1 = (x1, y1) = Polar(r1, 1) and V2 = (x2, y2) = Polar(r2, 2), amd a scalar real value,
c, we define the following operations on V1 and V2:
Operation
Unitize
Magnitude
Table 1. Operations on Vectors
Expression
Definition
Unit(V1)
(x1/r1, y1/r1) = Polar(1.0, 1)
|V1|
r1 = x 2  y 2
1
Angle

Sum
Difference
Dot Product
Cross Product
Scalar Product
Rotation
V1 + V2
V1 - V2
V1  V2
V1  V2
cV1 = V1c
α @ V1
Negation
- V1
1
y 
1 = Tan 1  1  , where x1  0
 x1 
 
1 = sign ( y1 )  , if x1 = 0 and y1  0
2
(x1  x 2 , y1  y 2 )
(x1  x 2 , y1  y 2 )
x1 x 2  y1 y 2  |V1 ||V2 |cos(2  1 )
x1 y 2  y1 x 2  |V1 ||V2 |sin(2  1 )
( cx1, cy1)
Polar( r1, (1+α) mod 2), where α ≥  is the rotation
angle in radians. (See Cartesian formulation below).
( -x1, -y2) = Polar(r1, π+1) = Polar(r1, 1 - )
Properties of Vector Operations
(1) Dot product is commutativ e : A  B = B  A
(2) Dot product is associativ e : A  ( B  C ) = (A  B)  C
(3) Cross product is NOT commutativ e : A  B = - (B  A)
(4) Cross product is NOT associativ e ( Cross product yields a scalar val ue)
(5) Scalar product associates with both Dot and Cross product :
c  (A  B) = (c  A)  B = A  (c  B)
c  (A  B) = (c  A)  B = A  (c  B)
(6) Dot, Cross, and Scalar product distribute over + and - :
A  ( B + C ) = ( A  B ) + (A  C )
A  ( B + C ) = (A  B ) + ( A  C )
c  ( A + B) = c  A + c  B
(7) Let A be a Cartesian vector and  be an angle measured counterclo ckwise in radians, 0    2 . Then
Cos( )  Sin ( )  A.x 
B RA  
    is the Cartesian vector obtained by rotating A through angle  .
 Sin ( ) Cos( )   A. y 
Page 3 of 16
Relationships between Points and Lines
Figure 2 illustrates the equation for a line expressed in terms of two vectors, A and U; A defines a
point on the line (anchor point) and U is a unit vector that defines the positive direction of the line.
Two important geometric relationships can be computed quite easily using vector algebra: the
distance between a point and a line, and the point of intersection between two lines. The solutions
to these problems are described in Figures 3 and 4, respectively.
Y
Line Equation: L(α) = A + α·U
where A denotes a vector on the
line (anchor) and U denotes a
unit vector defining the positive
direction of the line. The line is
swept out as the scalar α varies
over all real values.
L(α)
α < 
A
U
L(α)
α ≥ 
X
Figure 2. Equation of a Line
Page 4 of 16
Point-to-Line Solution
The distance of a given point, P, from a line, L, is the length of a vector, V, perpendicular to L,
having its head at P and its tail on L at Q. See Figure 3.
Y
Line Equation: L(α) = A + α·U
A
P
U
V
Q
X
Figure 3. Distance from P to L.
V must satisfy the following equations:
[1] P = V + Q
[2] U  V = 0
[3] Q  A  c  U , for some scalar c.
We want to solve for the scalar c. Knowing the value of (c) enables us to compute Q from equation
[3] and then V from equation [1], since P,A, and U are given vectors. Thus we have:
[4] V  P  Q , from [1]
[5] P  Q  P  ( A  c  U )  ( P  A )  c  U , from [3]
[6] U  V  U  ( P  Q )  U  [( P  A )  c  U ]  U  ( P  A )  c  (U  U )  0, from [2],[4] and [5]
[7] But U  U  1, so we have c = U  ( P  A ), the desired solution.
[8] The distance between P and L then becomes |V|.
Page 5 of 16
Line Intersection Problem
Given two lines, L1() = A1 + ·U1 and L2() = A2 + ·U2, there are three cases to consider:
(a)
(b)
(c)
the lines are parallel and distinct (void intersection)
the lines are co-linear (the same) (the lines intersect at all their points)
the lines intersect at exactly one point.
Two lines are parallel or co-linear if and only if the Cross product of their direction vectors is zero
(U1  U2) = 0. Now, in addition, the two lines are co-linear if and only if their anchor points
(A1 and A2) lie on either line. This is equivalent to saying that the vector connecting these two
points is parallel to L1 (is actually co-linear with L1). Thus (A1 - A2)  U1 = 0. We may
summarize the three cases as follows:
(a)
(b)
(c)
(U1  U2) = 0 and (A1 - A2)  U1  0
(U1  U2) = 0 and (A1 - A2)  U1 = 0
(U1  U2)  0
//Parallel and distinct
// Co-linear
// Unique point of intersection
Now, assuming (c) holds there must be a unique value of the scalars and  for which L1() =
L2(). In other words, it must hold that
[9] A1    U1 = A2    U 2
To solve for  we take the Cross product of both sides of [9] with U1. This yields,
[10] ( A1    U1 )  U1 = ( A2    U 2 )  U1
Distributing both sides and simplifying we have,
[11] ( A1  U1 )    (U1  U1 ) = ( A2  U1 )    (U 2  U1 )
Now, assuming (c) holds and knowing that (U1  U1) = 0 we obtain,
[12] ( A1  U1 ) = ( A2  U1 )    (U 2  U1 ), and then
[13]
( A1  U1 )  ( A2  U1 ) ( A1  A2 )  U1


(U 2  U1 )
(U 2  U1 )
In an analogous fashion it follows that
( A  A1 )  U 2
[14] 2

(U1  U 2 )
Page 6 of 16
Analysis of Obstacle Avoidance
The problem is depicted in the Figure 4. A Rover object, R, is in motion traveling in a direction and
speed defined by velocity vector, V. This vector has been defined to create a future rendezvous
with some Target object or Rover position, T. At some point in time, R discovers that some fixed
and motionless object, Z, is obstructing its path. That is, if R continues in its current direction, it
will eventually collide with Z. R must alter its direction (and possibly speed) to avoid Z with the
least impact on the total distance it must travel to avoid the obstruction, Z.
Y
Target
Object (T)
Current path corridor
β
DT
DR
T
Obstructing
Object (Z)
Z
α
V
Moving
Rover (R)
R
X
Figure 4. Obstructing Object, Z.
All objects in the scenario are modeled by circles with radii Zrad and Rrad, respectively. We assume
the target, T, has the same radius as the Rover, since it represents a future position of the Rover.
The vector diagram satisfies the following relationships:
Z = T + DT = R + DR.
|DT| ≥ Zrad + Rrad =
|DR| ≥ Zrad + Rrad =
We assume no two objects are closer that  (center-to-center). Then Z is an obstructing object iff
V  DR
V  DT


 | sin(  ) | 
and
 | sin(  ) | 
| V |  | DR |
| DR |
| V |  | DT |
| DT |
Note that 0  |α|, |β| < π/2.
Page 7 of 16
Distance to an Obstructing Object
Implementing a solution strategy to avoid an obstructing object as depicted in Figure 4, may require
computing the distance the Rover must travel to actually make contact with the obstacle, Z. Figure
5 shows the geometry at the moment of impact.
Y
Target
Object (T)
β
Impact Pt
DT

DI
RI
T
Obstructing
Object (Z)
Z
DR
α
Moving
Rover (R)
R
X
Figure 5. Impact Geometry.
What we want to compute is the vector RI, the vector defining the distance traveled by the Rover
from its original position, R, to the impact point with Z. The vector DI is a vector from the center of
the Rover object at impact to the center of Z. This vector must be of length . The angle between
DI and DR is denoted by . The equations for computing these vectors are given below.
| D R |  | R I | cos( )  | D I | cos( )
| R I | sin(  )  | D I | sin(  )
 | D R | sin(  ) 
  
|
D
|
I


  Sin -1 
| DI |  
 | D | - | D I | cos( ) 

| R I |   R
cos( )


Page 8 of 16
Substituting  for DI in all the above equations we have:
 D - sin   
α
ψ  Sin 1  R

Δ


D   cos( )
RI  R
cos( )
Simple Obstacle Avoidance
One solution in the simplest cases involves computing the geometry of two possible paths around
the obstructing object Z. These paths are depicted in Figure 6. Each path has a turning point (P1
and P2) that is defined by the intersection of two lines, one defined by a clear path to the Target,
one defined by a clear path from the Waiter, each tangential to the obstructing object.
Y
B+
B-
β
-β
Turing Point (P 2)
Turing Point (P 1)
-α
α
AA+
T
Z
X
R
Figure 6. Possible Paths to Avoid Obstacle, Z
The alternative clear paths available to the Rover are characterized by a unit vector in a direction
obtained by rotating the vector DR by an angle ± α. Similarly, the alternative clear paths to the
Target are obtained by rotating the vector DT through an angle ± β. The two complete clear path
from R to T bypassing Z are:
Page 9 of 16
(a) traveling in direction A- to turning point P1 and then traveling in direction –B+ to the Target, T.
(b) traveling in direction A+ to turning point P2 and then traveling in direction –B- to the Target, T.
The desired path is the one for which |Pk – R| is a minimum, where k {1,2}. The formulas for
computing the above vectors and turning points are given below.
Now, since there may be many potential obstacles, the paths to the target at turning points P1 and P2
may also be obstructed by still other objects. So, at each turning point, or possibly even before, the
computation for identifying obstructing objects and computing the two possible paths around the
object must be repeated until, either a completely unobstructed path is found (with zero or more
turning points), or no such path exists. To implement this more general algorithm, you must build a
tree of turning points so that if one choice fails to provide an unobstructed path, you can return to
the most recent untried path and continue the search.
  
,

D
 R 
 Cos( ) Sin ( ) 
A-  
unit ( DR )
 Sin ( ) Cos( )
Cos( )  Sin ( )
A  
unit ( DR )
 Sin ( ) Cos( ) 
  
Cos(  )  Sin (  )
, B   
unit ( DT )

Sin
(

)
Cos
(

)
D


T


For turnin g point, P1 , we define :
 Cos(  ) Sin (  ) 
B  
unit ( DT )
 Sin (  ) Cos(  )
  Sin 1 
  Sin 1 
LA ( z)  R  z  A
LB ( z )  T  z  B 
The intersecti on of these two lines is P1  L A (c1 )  R  c1  A  , where c1 
(T  R)  B 
( A  B  )
For turnin g point, P2 , we define :
LA ( z)  R  z  A
LB ( z )  T  z  B 
(T  R)  B 
The intersecti on of these two lines is P2  L A (c 2 )  R  c 2  A , where c 2 
( A  B  )

Page 10 of 16
A General Object Oriented Design
In this section we present the generic design you will be implementing in C++. This section also
presents the general requirement and specifications necessary to understand and carry out the
implementation exercise.
AppErrors
IOMgmt
IOError
InMgr
VectorApp
OutMgr
vectorspace
problemspace
VectorError
ProblemError
ProblemMgr
Vector
Problem
Line
Line
Obstacle
Rover
Figure 7. Object Oriented Architecture for the Vector Applications
Page 11 of 16
VectorApp: This is the main unit. It defines the program entry point and encapsulates the highestlevel control object for the application. Its purpose is to acquire the resources needed for the
application. If and when these resources are acquired, it passes these resources to an instance of the
ProblemMgr. ProblemMgr encapsulates application control and coordinates all interactions
among solution objects at the highest level.
AppError: This is the root exception class. Every instance of this class contains two data
members that define the origin of an exception (in what method and class?) and a message string
that diagnoses the cause of the exception in the originating method. The values of these data
members can be obtained by methods: getMsg() and getOrigin(). As the exception travels up the
call chain, each exception handler ( catch block ) has an opportunity to append additional
information to the origin and message data members. After updating the exception content, the
handler re-throws the exception so that it may continue to propagate upward along the call chain to
some point where the exception can be properly dealt with, or terminate the program if the
exception propagates all the way to VectorApp. This is accomplished using the methods:
appendOrigin() and appendMsg(). If the exception is handled ( caught ) at the highest level of
control before the program terminates, the origin and message members of the exception can be
output to provide a trace of the call chain and a diagnosis at each method that handled (caught ) the
exception along this chain.
Package (Namespace) Descriptions
IOMgmt
Package IOMgmt provides reusable classes for identifying and opening (creating) an ASCII file
stream. The constructor of class OutMgr takes a prompt message string as a parameter and
interacts with the user in an attempt to associate an external ASCII file with an encapsulate instance
(fout) of std::ostream. If the association attempt is not successful, OutMgr raises (throws) an
instance of exception, IOError. In addition to dialog services for output streams, OutMgr
provides a number of methods for structuring and formatting output streams into lines – capabilities
that are beyond the services provided by std::iomanip and std::iostream.
Like OutMgr, the constructor of class InMgr takes a prompt message string as a parameter and
interacts with the user via the standard input (keyboard) and output (screen) objects. InMgr
attempts to associate an external ASCII file with an encapsulated instance of std::ifstream. If the
association attempt is not successful, InMgr raises (throws) an instance of exception, IOError. In
addition to dialog services for input streams, InMgr provides a number of methods for
manipulating streams using capabilities provided by std::iostream.
vectorspace
This package encapsulates a reusable abstraction for 2D vectors named Vector. It also contains an
exception class named VectorError. The set of operations supported by the Vector class were
presented at the beginning of this Lab. There are operations that support the view of a 2D vector in
Cartesian coordinates, or in Polar coordinates. There are also methods for extracting a Vector
from, or inserting the image of a Vector into an external ASCII file stream.
Page 12 of 16
problemspace
This package, together with VectorApp, encapsulates the abstractions that directly satisfy the
requirements of the given application. One could argue that Line should be placed in vectorspace,
and rightfully so, but we have chosen to keep it in problemspace because it was an abstraction
discovered or derived from the problem description. (The next 2D geometry application we
encounter that requires a Line abstraction should tell us that Line is a reusable and that should be
moved into vectorspace suitably renamed to geometry2D).
ProblemMgr is a control class that encapsulates the problem solution logic. It requires two
resources, an input file stream (fin) and an output file stream (fout). Using the Problem
abstraction, ProblemMgr parses the input file as a sequence of Problem instances delimited in
some fashion. ProblemMgr therefore “hides” the details about how the input file is structured with
respect to Problem instances. Problem hides the details about how a problem instance is
structured. Etc. ProblemMgr also hides the processing algorithm. For example, ProblemMgr
could parse all Problem instances and put them in an internal list. Once all Problem instances
have been created, it could process the list by solving and outputting each instance. This approach
appears to be unnecessarily complex (because of the list abstraction) and so we have chosen the
simpler approach of iterating over the steps of parsing one Problem instance, solving that instance,
and outputting the result until the input file stream is exhausted or an exception occurs.
The Problem class encapsulates an instance of our application problem, two lines and a point,
where lines and points are represented using instances of Vector. Once again, Problem
encapsulates the structure of a problem instance: each Line instance is labeled and appears on a
single line of the file, the point is labeled and appears on a separate line of the file, and finally, the
two line instances follow the instance of the point. Problem has two methods, an Extract()
method extracts an instance from an input file stream. The Solve() method solves the problem
instance and writes the result to an output file stream passed to it as a parameter.
The Line class encapsulates an instance of a 2D line and represents it as a pair of Vector objects.
The first Vector denotes an anchor point – a point that lies on the line. The second Vector defines
the positive orientation or direction of the line. All points on the Line instance can be computed by
the vector sum, anchor + c*direction, where c is some real scalar. The direction vector need not be
a unit vector. Like Problem, Line includes extraction and insertion methods for inputting and
outputting Line images. It includes methods for computing the intersection point of two Line
instances and a method for computing the distance of a given point (represented by a Vector) to a
given Line instance. The Intersection() method takes an instance of Line as a parameter and
computes whether or not this line intersects at a single point with the implied operand *this. It
throws an exception if the intersection point does not exist (parallel lines) or is not unique (co-linear
lines); otherwise, it returns an instance of Vector defining the unique intersection point. If this
method is called producing either of the other two possible results, then a ProblemError exception
is thrown indicating that the Lines were co-linear or parallel.. Finally, the DistanceTo() method
takes a Vector as a parameter and returns the distance of that Vector to the given Line instance.
Other classes can be included in problemspace as the application dictates; e.g Rover and
Obstacle.
Page 13 of 16
Software Requirements
Requirement 1. The developer shall use the OO+ software design and implementation as the
legacy baseline (starting point) for development.
Requirement 2. The developer shall redefine the Problem and ProblemMgr classes of the
OO+ design and shall add any new classes appropriate to satisfy all remaining requirements
of this project.
Requirement 3. A “Problem” instance shall consist of an initial Rover object (initial position
Vector, velocity Vector and radius) and the final Rover position Vector. In addition, the
“Problem” instance shall include one or more instances of Obstacle class.
Requirement 4. Rover and Obstacle objects shall be modeled as 2D circular geometric
shapes having a positive real radius. Obstacles need not have a uniform radius. The Rover
need not have a radius equal to that of any given Obstacle. Obstacles have a unique name
and a fixed position Vector and remain motionless through the application scenario.
Requirement 5. The distance between any pair of Obstacles in a Problem instance shall be
no less than the sum of their radii plus twice the diameter of the Rover object.
Requirement 6. The application program shall take as input an ASCII file with one or more
instances of the Problem class.
Requirement 7. For each input Problem instance, the application program shall compute and
output an obstacle-free path from the initial Rover position to its final destination position,
if such as path exists. If no such path exists or one cannot be found, the application shall
output the message, “Failure to find a solution path for this Problem.”
Requirement 8. If a solution path (see Requirement 6) is found, the application shall output
this path as a sequence of Vectors beginning with the initial position of the Rover and
ending with the target position of the Rover. Each intermediate Vector in the solution
sequence shall define a turning point determined to avoid an Obstacle. The turning points
shall be output along with name of the nearest Obstacle (the one to be avoided) in the order
the Rover visits them before arriving at the final destination.
Requirement 9. All class instances input or output by the application shall follow the OO IO
Data Format and Design Protocol presented in Lecture 10 notes.
Requirement 10. The application output shall be an ASCII file containing each Problem
instance input, followed by its solution output.
Requirement 11. Deliverables shall include the following:
1) Source code, Test Input files, Test Output files.
2) A spreadsheet similar to that used for Lab1 capturing your effort for various
development activities and the sizes of legacy classes modified along with the sizes of
classes newly developed.
3) A design document describing your software solution. Specifically, you should include
a UML Class Diagram showing the relationships between classes you modified and/or
added to the legacy design. Your design document shall also include a description of the
algorithm you used to compute the obstacle-free path – this shall be expresses as a UML
Activity diagram. You shall also indicate in what class(es) and/or method(s) this algorithm
was implemented.
Requirement 12. The project shall be due Monday, March 12.
Page 14 of 16
Download