ITC Research Computing Support Colloquia Fall, 2004

Mathematics on the Desktop


Presented by Kathy Gerber

of the

ITC Research Computing Support Group

(Kathy Gerber, Ed Hall, Katherine Holcomb, Tim F. Jost Tolson)


E-Mail:  Res-Consult@Virginia.EDU

http://www.itc.virginia.edu/researchers

Telephone: 243-8800


The Maple worksheet from this talk, as well as notes from previous talks will be available on

ITCWeb at
http://www.itc.virginia.edu/research/talks/

Functions of a Mathematical Desktop

Teaching Support

The comprehensive desktop environment viewed as a teachining tool

Strengths:
   -  Interactive, easy to use, with extensive built in and on-line help

   -  Nice interface with output in standard mathematical notation

   -  Within a single document the user can

        -- perform computations
        -- manipulate mathematical expressions

        -- describe the problem-solving process

   -  Easy to program
   -  Integration of algebraic, numerical and graphical facilities

   -  Extensive library of functions including packages in areas such as

      precalculus, calculus, linear algebra, polynomials, etc.


Weakness:

   -  For large numerical calculations, environments such as Maple, Mathematica are not as fast as Matlab, R or compiled languages.

      But they are better as a tool for teaching and developing numerical algorithms.

Numerical Calculations

> nextprime(1007898743453453465767945830458254303);

1007898743453453465767945830458254451

> evalf(Pi,100);

3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068

   -  Not truly comprehensive.  

  

Maple Help

Basic HowTo

Help Introduction

Examples

Math Dictionary

Dictionary

Publishing Documents

Word Processing and Typesetting - Using Export

HTML:  Use Export from the File Menu.  When Sections are expanded, one page with internal links is created.  When Sections are collapsed, a separate html page is created for each Section and linked back to the main page.

RTF:   can be converted to Word.

LATEX:  When creating dvi files in the Windows environment from exported *.tex documents, the *.sty files from the ..\Maple 8\etc directory (in Windows) or the ../maple8/etc directory (in unix) must be available either by modifying the PATH, or copying them into the appropriate directory.  In Windows, MikTeX's latex and dvips commands are useful.  If desired, the resulting ps file can be converted to pdf with Adobe Distiller.

RedHat users may need to install the rpm for dvips.  Use a current version of dvips.  For RedHat 8.0 this is
tetex-dvips-1.0.7-57.1.i386.rpm.   A vulnerability in earlier version may allow local or remote attackers who have print access to carefully craft a print job that would allow them to execute arbitrary code as the user 'lp'.

Latex command

Latex snippets are easily generated with the latex command in Maple.

> Int(1/(x^2+1), x) = int(1/(x^2+1), x);

Int(1/(x^2+1), x) = arctan(x)

> latex(Int(1/(x^2+1), x) = int(1/(x^2+1), x));

\int \! \left( {x}^{2}+1 \right) ^{-1}{dx}=\arctan \left( x \right)

>

MAPLE TEXT:   can be opened by Maple

PLAIN TEXT:  can also be opened by Maple showing execution statements only

Proof and Verfication

"Many proofs in Discrete Math are really algorithms in disguise." - Doron Zeilberger

An Example

Rene - A Maple Package for Stating and Proving Theorems in Geometry

http://www.math.rutgers.edu/~zeilberg/tokhniot/RENE

Interfacing with Other Programs

Code Generation

Code Generation

External Calling

External Calling

Random Objects

Random Tools

Examples

The CurveFitting Package

The CurveFitting contains functions to fit various types of curves to given data points.  

Introduction to the CurveFitting Package

> restart;

The following command allows you to use the short form of the function names in the CurveFitting package.  Note that the PolynomialInterpolation , RationalInterpolation , Spline , and ThieleInterpolation functions replace the obsolete functions interp, ratinterp, spline, and thiele, respectively.

> with(CurveFitting);

[BSpline, BSplineCurve, Interactive, LeastSquares, PolynomialInterpolation, RationalInterpolation, Spline, ThieleInterpolation]

A feature of the CurveFitting package is that the routines allow you to specify the data points in two ways.  The points can be provided as two lists, the first containing the independent values and the second containing the dependent values.  The following command computes a polynomial that interpolates the points {(0,1), (1,3), (2,-1), (3,2)}.

> PolynomialInterpolation([0,1,2,3], [1,3,-1,2], v);

13/6*v^3-19/2*v^2+28/3*v+1

The points can also be provided as a list of lists.

> PolynomialInterpolation([[0,1],[1,3],[2,-1],[3,2]], v);

13/6*v^3-19/2*v^2+28/3*v+1

The ability to specify the data as a list of lists facilitates plotting the original data with the result.  Example plots are provided in the next section.  The following command allows you to use the short form of the function names in the plots package.

> with(plots):

Warning, the name changecoords has been redefined

Fitting a Curve Through a Set of Points

Below, we define a list of 8 points, then plot these points by using the plots[pointplot] function.  (Note that the short form of the function name is used below.)

> points1 := [[0,1],[1,2.5],[3,2.3],[4.2,5],[5,3.5],[5.8,4.2],[7,7],[8,10]]:
pntplot1 := pointplot(points1,symbol=BOX):

The next command uses the PolynomialInterpolation function to compute the unique polynomial that interpolates the data points.

> polycurve := PolynomialInterpolation(points1, v):

The plot command shown below generates a plot of the result. The plots[display] function displays both this plot and the previously computed plot of the data points.  It can be seen that the degree 7 polynomial passes through each of the 8 data points.

> polyplot := plot(polycurve,v=0..8):
display([pntplot1,polyplot]);

[Plot]

If n data points are supplied, then the interpolating polynomial has degree less than or equal to n-1.  One well-known problem with fitting an interpolating polynomial through a large set of data points is the undesirable oscillations produced by a high-degree polynomial.  In the plot above, the function value for v=2 is far from the value for v=1 or v=3.

A smoother curve can be obtained by using the Spline function.  This function returns a piecewise polynomial of default degree 3 that passes through the 8 data points.   The second derivative is set to zero at the endpoints, and this results in a "natural" spline.  The degree of the spline can be controlled by the degree option, described on the Spline help page.

> splcurve := Spline(points1, v);

splcurve := PIECEWISE([1.+2.04045418599999984*v-.540454185700000034*v^3, v < 1], [2.080908371+.419091629299999990*v-1.62136255679615826*(v-1)^2+.680908371300000037*(v-1)^3, v < 3], [-4.013625568+2.104...

The plot below shows that a smoother curve, without the unwanted oscillations, is produced.

> splplot := plot(splcurve,v=0..8):
display([pntplot1,splplot]);

[Plot]

Computing a Least Squares Fit

The LeastSquares function can be used to find a curve that best fits the data in a least-squares sense, that is, minimizes the sum of the squares of the differences between the estimated values and the actual data.  Unlike the curves described in the previous section, the least-squares curve may not necessarily pass through the given points.  The least-squares method is often used to fit models to experimental data.

The commands below show how the LeastSquares function is used to compute the best linear fit through the points defined at the beginning of the previous section.  In the resulting plot, it can be seen that the curve passes near but not necessarily through all the points.  

> lscurve := LeastSquares(points1,v);
lsplot := plot(lscurve,v=0..8):

display([pntplot1,lsplot]);

lscurve := .5284775465+.919769989047097502*v

[Plot]

In the previous example, the default curve used to fit the points is a linear polynomial av+b with parameters a and b.  The LeastSquares function allows you to provide a different type of curve and to specify the parameters to optimize.   In addition, weights associated with the data points can be defined.  See the LeastSquares help page for more details about these options.

The LeastSquares function requires that the model curve be linear in the parameters.  In some cases, a nonlinear model can be transformed to allow a least-squares fit.  For example, if you wish to use the model

w=a*exp(b*v),

you can take the logarithm of both sides of the equation and apply the transformation

{y=log(w), c=log(a)}

to obtain the model

y=c+b*v,

which is linear in the parameters c and b.

> newpoints1 := map(x->[x[1],evalf(log(x[2]))], points1);
newlscurve := LeastSquares(newpoints1,v);

newpoints1 := [[0, 0.], [1, .9162907319], [3, .8329091229], [4.2, 1.609437912], [5, 1.252762968], [5.8, 1.435084525], [7, 1.945910149], [8, 2.302585093]]

newlscurve := .2743867093+.238231965504746236*v

This result gives values for c and b.  The following commands show the resulting plot, after transforming back to the original model.

> a := exp(coeff(newlscurve,v,0));
b := coeff(newlscurve,v,1);

newlsplot := plot(a*exp(b*v),v=0..8):

display([pntplot1,newlsplot]);

a := 1.315723506

b := .238231965504746236

[Plot]

>

The Optimization Package

The Optimization package provides commands to find the minimum or maximum of various types of functions subject to various types of constraints.  This worksheet provides a few basic examples of each type of problem the package is capable of solving.  Further information can be found on the help pages for the package and each of the individual package members.

In this worksheet, we will be minimizing a function (referred to as the objective function) subject to a number of constraints.  Certain maximize examples are included as well.  In any of the examples, the maximize option can be added to the command to find the maximum instead of the minimum.  


Also note that in each case we are only finding a locally optimal value.  

Introduction to the Optimization Package

> restart;

The following command allows you to use the short form of the command names in the Optimization package.  

> with(Optimization); with(plots):

[ImportMPS, Interactive, LPSolve, LSSolve, Maximize, Minimize, NLPSolve, QPSolve]

Warning, the name changecoords has been redefined

The commands in the Optimization package allow you to specify the objective function and the constraints in several different ways.  This worksheet deals with the algebraic form of the objective function and constraints.  The other forms are Matrix form and procedure form where Matrix form is covered in a separate example worksheet.

In general, an optimization problem is of the form

The Optimization package handles several types of objective and constraint functions.  Each type of problem is a subtype of the next one.

Objective Function/Constraint/Command

Linear/Linear/LPSolve

Quadratic/Linear/QPSolve

Nonlinear(General)/Nonlinear(General)/NLPSolve


There is also a minimize command that will attempt to automatically select the best algorithm for a given problem.


In addition, there is a command,
LSSolve, which minimizes functions of the form

f(x) = (Sum(r[i](x)^2, i = 1 .. n))/2

Linear Programming Example 1

For a first example, we have a simplex two dimensional linear programming problem.

subject to

> obj := -2*x-y;

obj := -2*x-y

> cnsts := [y<=4*x+1/2,y<=-5*x+2,x>=0,y>=0];

cnsts := [y <= 4*x+1/2, y <= -5*x+2, 0 <= x, 0 <= y]

The plot below shows the feasible region in yellow, the contours of the objective function, and the optimal solution as a green circle.

> p1 := inequal(cnsts, x=-0.5..2, y=-0.5..2, optionsexcluded=(colour=white), optionsfeasible=(colour=yellow)):
p2 := contourplot(obj, x=-0.5..2, y=-0.5..2):

p3 := pointplot({[0.1666,1.166]}, symbolsize=13, colour=green):

display(p1, p2, p3);

[Plot]

The  command returns the optimal function values, as well as the point at which the optimal value occurs.

> LPSolve(obj, cnsts);

[-1.5000000000000, [y = 1.16666666666666674, x = .166666666666666658]]

Alternatively, we could use the first two constraints and the nonnegative option.

> LPSolve(obj, cnsts[1..2], assume=nonnegative);

[-1.5000000000000, [y = 1.16666666666666674, x = .166666666666666658]]

The first element of the solution is the minimum value that the objective function obtains, while satisfying the constraints.  The second element indicates a point where the minimum is reached.  This point is not necessarily unique.

Linear Programming example 2

We can also include equality constraint as the next example shows.  This example also demonstrates the maximize option.

> obj := 2*x+y+z;

obj := 2*x+y+z

> cnsts := [y<=4*x+1/2,y<=-5*x+2,z=-2/3*x-2/3*y+20/3];

cnsts := [y <= 4*x+1/2, y <= -5*x+2, z = -2/3*x-2/3*y+20/3]

> LPSolve(obj, cnsts, assume=nonnegative, maximize);

[7.2777777777778, [z = 5.77777777777780700, y = 1.16666666666666652, x = .166666666666666658]]

Quadratic Programming Example

For a first example of a quadratic program, we will use:

> obj := 4*x^2-y+x+5;

obj := 4*x^2-y+x+5

> cnsts := [x+y-7*x>=-11, 11/2*x+y<=0,x>=-4];

cnsts := [-11 <= -6*x+y, 11/2*x+y <= 0, -4 <= x]

The plot below shows the feasible region in yellow and the contours of the objective function.  The green circle indicates the optimal point.

> p1 := contourplot(obj, x=-4..4, y=-10..10, contours=30):
p2 := inequal(cnsts, x=-4..4, y=-10..10, optionsexcluded=(colour=white), optionsfeasible=(colour=yellow)):

p3 := pointplot({[-0.8125,4.486]}, symbolsize=13, colour=green):

display(p1,p2,p3);

[Plot]


The
QPSolve command returns the optimal function values, as well as the point at which the optimal value occurs.

> QPSolve(4*x^2-y+x+5, {x+y-7*x>=-11, 11/2*x+y<=0,x>=-10});

[2.3593750000000, [y = 4.46874999999999822, x = -.812499999999999889]]

Nonlinear Programming

The NLPSolve command allows us to solve problems of a fairly general nature.  As long as the derivative of the objective function and constraint function is continuous, we can use NLPSolve.

Our first basic example of nonlinear programming is a simple univariate minimization of a polynomial.

> p := 0.4126984123e-2*x^7-.1091666666*x^6+7.078095236*x+1.136388888*x^5-18.19500000*x^2-5.845833331*x^4+15.23138888*x^3+2;

p := 0.4126984123e-2*x^7-.1091666666*x^6+7.078095236*x+1.136388888*x^5-18.19500000*x^2-5.845833331*x^4+15.23138888*x^3+2

This plot shows the function and the minimum found by NLPSolve.

> p1 := plot(p, x=4.5..5.5):
p2 := pointplot({[4.8877,0.6883]}, symbolsize=13, colour=green):

display(p1, p2);

[Plot]

We can minimize this function in the range [0..6].

> NLPSolve(p, x=0..6);

[.683344558795397461, [x = 4.88774382231190784]]

We can also maximize the function.

> NLPSolve(p, x=0..6, maximize);  

[2.80062108007194865, [x = 2.97993880065539908]]


We can minimize more complex functions such as:

> f := x*erf(x)*cos(x);

f := x*erf(x)*cos(x)

> s := NLPSolve(f,x=1..20);

s := [-9.47729425947979288, [x = 9.52933438691188428]]

Below we plot the function f and the minimum point.  We can see that NLPSolve finds a local minimum, not necessarily a global one.

> p1 := plot(f,x=1..20): p2 := pointplot([[rhs(s[2][1]),s[1]]],color=green,symbolsize=14):
display(p1,p2);

[Plot]

We can also minimize multivariate functions such as

> f := 100*(y-x^2)^2+(1-x)^2;

f := 100*(y-x^2)^2+(1-x)^2

with

> NLPSolve(f, x=-10..10, y=-10..10, initialpoint=[x=-1.2, y=1]);

[0.179319068453110564e-15, [y = .99999997676418594, x = .99999998874486340]]

> plot3d(100*(y-x^2)^2+(1-x)^2,x=.95..1.05,y=.95..1.05);

[Plot]

[Ink]

Curve Fitting with Least Squares

> restart: with(Optimization):

We can use the least squares command to do curve fitting.  For example, if we have the following data points, (x[i], y[i] ):

> data := [[1,1.5],[2,3.5],[2.5,1.9],[3.1,4.5],[4.3,1.9],[4.7,2.4],[5.8,3],[6,5.7],[6.6,3.4],[6.7,0.5],[7.1,4],[7.4,1.7]]:

and we want to fit the data with a quintic polynomial.  Let our quintic be,

p(x) = a*x^5+b*x^4+c*x^3+d*x^2+e*x+f .

Now we need to find a, b, and c such that

(Sum((p(x[i])-y[i])^2, i = 1 .. 12))/2

is a minimum.

LSSolve takes as input a list of the residues p(x[i])-y[i] .

> p := a*x^5+b*x^4+c*x^3+d*x^2+e*x+f;

p := a*x^5+b*x^4+c*x^3+d*x^2+e*x+f

> residues := map((d) -> eval(p, x=d[1])-d[2], data);

residues := [a+b+c+d+e+f-1.5, 32*a+16*b+8*c+4*d+2*e+f-3.5, 97.65625*a+39.0625*b+15.625*c+6.25*d+2.5*e+f-1.9, 286.29151*a+92.3521*b+29.791*c+9.61*d+3.1*e+f-4.5, 1470.08443*a+341.8801*b+79.507*c+18.49*d...residues := [a+b+c+d+e+f-1.5, 32*a+16*b+8*c+4*d+2*e+f-3.5, 97.65625*a+39.0625*b+15.625*c+6.25*d+2.5*e+f-1.9, 286.29151*a+92.3521*b+29.791*c+9.61*d+3.1*e+f-4.5, 1470.08443*a+341.8801*b+79.507*c+18.49*d...residues := [a+b+c+d+e+f-1.5, 32*a+16*b+8*c+4*d+2*e+f-3.5, 97.65625*a+39.0625*b+15.625*c+6.25*d+2.5*e+f-1.9, 286.29151*a+92.3521*b+29.791*c+9.61*d+3.1*e+f-4.5, 1470.08443*a+341.8801*b+79.507*c+18.49*d...

Now we can call LSSolve with the residues.

> sol := LSSolve(residues);

sol := [9.79941650829796984, [c = 1.53722867786027217, d = -7.04487080570633939, b = -.148717633940657068, a = 0.506817808955171546e-2, e = 14.2425902266785958, f = -7.12139344171486677]]

Our polynomial becomes:

> poly := eval(p, sol[2]);

poly := 0.506817808955171546e-2*x^5-.148717633940657068*x^4+1.53722867786027217*x^3-7.04487080570633939*x^2+14.2425902266785958*x-7.12139344171486677


We can now plot the data and the curve

> with(plots):
p1 := pointplot(data):

p2 := plot(poly, x=0.9..8):

display(p1, p2);

Warning, the name changecoords has been redefined

[Plot]

>

Animation

Right click on the plot to bring up a list of options.  You may run the animation within Maple, or you may export as GIF to obtain an animated GIF file.

> restart:with(plots):x;  x:='x':
f:=x*sin(x): ft:=subs(x=t,f):f_1:=diff(ft,t): g:=f_1*(x-t)+ft;

p2:=plot(f,x=0..13,y=-13..13,color=blue,thickness=2,discont=true):

p1:=animate(g,x=0..13,t=0..13,frames=80,color=red):

display(p1,p2);

Warning, the name changecoords has been redefined

x

g := (sin(t)+t*cos(t))*(x-t)+t*sin(t)

[Plot]

>

Example - Legendre's Equation

> q := (1-x^2)*diff(y(x),x,x)-2*x*diff(y(x),x)+lambda*y(x)=0;

q := (1-x^2)*(diff(y(x), `$`(x, 2)))-2*x*(diff(y(x), x))+lambda*y(x) = 0

> q1 := selectremove(has,dsolve(q,y(x),output=basis), LegendreP):

> Y1 := q1[1][1];
Y2 := q1[2][1];

Y1 := LegendreP(1/2*(4*lambda+1)^(1/2)-1/2, x)

Y2 := LegendreQ(1/2*(4*lambda+1)^(1/2)-1/2, x)

> l := proc( n::nonnegint, x::name )
option remember;

if n=0

then 1

elif n=1 then x

else expand(

(n-1)/n*( x*l(n-1,x)-l(n-2,x) )

+ x*l(n-1,x) )

fi

end;


l := proc (n::nonnegint, x::name) option remember; if n = 0 then 1 elif n = 1 then x else expand((n-1)*(x*l(n-1, x)-l(n-2, x))/n+x*l(n-1, x)) end if end proc

> l0:=l(0,x);l1:=l(1,x);l2:=l(2,x);l3:=l(3,x);l4:=l(4,x);

l0 := 1

l1 := x

l2 := -1/2+3/2*x^2

l3 := -3/2*x+5/2*x^3

l4 := -15/4*x^2+35/8*x^4+3/8

> with(orthopoly);p0:=P(0,x);p1:=P(1,x);p2:=P(2,x);p3:=P(3,x);p4:=P(4,x);

[G, H, L, P, T, U]

p0 := 1

p1 := x

p2 := -1/2+3/2*x^2

p3 := -3/2*x+5/2*x^3

p4 := -15/4*x^2+35/8*x^4+3/8

> plot({p0,p1,p2,p3,p4},x=-1..1);
plot({l0,l1,l2,l3,l4},x=-1..1);

[Plot]

[Plot]

>

Builtin Tutors

> Student[Precalculus][LimitTutor]();

[Plot]

Builtin Assistants

> Student[LinearAlgebra][MatrixBuilder]();

Matrix([[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 3, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])

 Documentation and Getting Help

Tutorial online - http://www.mapleapps.com/categories/whatsnew/html/SCCCmapletutorial.shtml

ITC Research Computing Support page is a good starting point for help with Maple.

  http://www.itc.virginia.edu/research/maple.html

The manuals for Maple are available in the Research Computing Support Center, Wilson Hall, Room 244.  They are particularly helpful for programming procedures, modules and external programs.  Contact Research Computing Support for the MaplePrimes code.  Once registered online, you may download the full set of documentation in Maple in pdf format.

Upcoming Research Computing Colloquia

Upcoming Research Computing Colloquia

at the ITC Research Computing Support Center,
244 Wilson Hall from 3:30 PM to 4:45 PM


Wednesday, November 10: Optimization

Wednesday, November 17: Introduction to the MPI

Wednesday, December 1: Output Delivery System (ODS) in SAS 9.1


???????????????????????????????????

The notes from these talks and previous ones are available on-line at:
http://www.itc.virginia.edu/research/talks

> convert( 1.0, 'units', 'ft', 'm');

.3048000000

>