Rk

13 downloads 0 Views 13MB Size Report
without first obtaining written permission from the editors. B. Madore, University of Toronto. The use of general descriptive names, trade names, trademarks,.
P U B L I C A T 1 O N

f

!

CO M P U T E R

ALGEBRR

~

FUN CTIO NALITY

~

A P P L I C A T I O N S

~

E O U C A T I O N

Rk- ~

- - ----- - -- - ---

-__

_..-. .

-

-- -- -- - - -

_

_ _ - ----- -

.~ ~

Aim and Scope A publication for the communication of applications among creators and users of Maple software in all areas of mathematics, engineering, and science. Subscription Information Beginning in 1996 MapleTech will be published three times per annum starling with Volume 3, numbers 1, 2, and 3. Annual institutional subscription rate (1996): US $46.00 plus $6.00 postage and handling charges. Individual subscription rate: US $34.00 plus $6.00 postage and handling. These prices are valid in North America only. (Canadian customers please add 7%GST. Birkhiiuser's GST registration number is 123394918.) Outside North America: Please place your order with your bookdealer or send directly to Birkhäuser Verlag, Journal Subscription Department, P.O. Box 133, CH-4010 Basel, Switzerland. Telephone: ++41 (0) 61 205 0799; Fax: ++ 41 (0) 61 2717666; Telex: 963475 birk ch, e-mail: [email protected]. All orders must be accompanied by payment, and if originating from the USA and Canada should be sent to: Birkhäuser Subscription Dept. 675 Massachusetts Ave. Cambridge, MA 02139 Toll Free 1-800-777-4643 Fax (201) 348-4505 Etnail:orders@birkhausercom Change of Address Allow six to eight weeks for all changes to become effective. All communications should include both the old and new address (with Postal Codes) and should he accompanied by a mailing label from a recent issue. Advertisements Correspondence concerning advertisements should be sent to: Mr. Bob Vrooman c/o Springer-Verlag, Inc. 175 Fifth Ave. New York, NY 10010, USA Telephone: (212) 460-1700 Office of Publication Birkhäuser 675 Massachusetts Ave. Cambridge, MA 02139 Telephone: (617) 876-2333 email: mapletech@birkhauseecom http://www.birkhauser.coin Copyright All articles published in this journal arc protected by copyright, which covers the exclusive rights to reproduce and distribute the article (e.g. as offprints), as well as all translation rights. No material published in this journal may be reproduced photographically or stored on microfilm, in an electronic database, video discs, etc. without first obtaining written permission from the editors. The use of general descriptive names, trade names, trademarks, etc. in this publication, even if not specifically identified, does not imply that these names are not protected by the relevant laws and regulations. While the information in this journal is believed to be true and accurate at the date of going to press, neither the authors, the editors, the Committee, nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Photocopies may be made for personal or in-house use beyond the limitations stipulated under section 107 or 108 of US Copyright Late, provided a fee is paid. The fee is $6.00 for each copy, regardless of the number of pages in the article. All fees should be paid to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, USA, stating the ISSN, the issue, and the first and last page of each article copied. The copyright owner's consent does not include copying for general distribution, promotion, new works, or resale. In these cases, specific written permission must first be obtained from the publisher.

Editor in Chief: Dr. Tony Scott Department of Chemistry & Statistics Ben Gurion University P.O. Box 653 Beer Sheva, Israel 84105 email: [email protected] Editor: Michael B. Monagan Department of Mathematics & Statistics Simon Fraser University Burnaby, B.C. V5A I G I Canada email: [email protected] Assistant Editor- Judi Borwein 7324 Braeside Drive Burnaby, B.C. V5A 1G1 Canada email: [email protected] '

'

"

IIVIyi`,',

Functionality M. Monagan, Simon Fraser University Applications W. C. Bauldry, Appalachian State University; D. Harper, Queen Mary & Westfield College, UK; A.B. Ogunye, The Dow Chemical Company, MI Education R. Lopez, Rose-Hulman Institute of Technology News and Reviews Blaire Madore, University of Toronto E



I

T



R

I

A

L

B



A

Ill•

S. Ail-Tahar, University of Oxford W.C. Bauldry, Appalachian State University M. Bronstein, ETH, Zurich B. Buchberger, RISC J. Carette, INRIA, Rocquencourt J.D. Child, Rollins College R.M. Corless, University of Western Ontario R. Fateman, University of California, Berkeley G. Fee, Simon Fraser University P. Flajolet, INRIA, Rocquencourt A. Granville, University of Georgia W. Koepf, Korad-Zuse-Zentrum, Berlin R.J. Lopez, Rose-Hulman Institute of Technology B. Madore, University of Toronto M.B. Monagan, Simon Fraser University A.B. Ogunye, The Dow Chemical Company, MI R.L. Peskin, Rutgers University K. Roach, University of Waterloo M. Rybowicz, University of Limoges B. Salvy, INRIA, Rocquencourt V. Strehl, University of Erlangen-Nurnberg

INEEMMM ADVANCING MATHEMATICS

Published with the support of Waterloo Maple, Inc. 450 Phillip St. Waterloo, Ontario, Canada N2L Wat SJL Phone: (519) 747-2373 FAX: (519) 747-5284 email: [email protected]

r

ät

E .II

9

y .

'

m

C O N T E N T S

; li ili

A Note from the Editors

Design of Cam Mechanisms Using Maple Ettore Pennestri and Vann! Falasca

Functionality

I4

i

Simple Engineering Mathematics with Maple

• ,` Weibull Probability Plot and Maximum Likelihood Estimation of its Parameters George A. Bohoris and Petros A. Kostagiolas

Robert M. Corless

Maple V Release 4: New Features for Engineers and Scientists

Chemical M; i1

Tom Lee

Et

L The Shooting Technique for the Solution of Two-Point Boundary Value Problems

MacroC and Macrofort: C and Fortran Code Generation Within Maple Patrick Capolsini and Claude Gomez

Douglas B. Meade, Bala S. Haran, and Ralph E. White

•,

Integrating MathEdge with Multimedia for Instruction in Engineering Jeffrey B. Layton and James H. Kane Electrical



It.

Syrup - A Symbolic Circuit Analyzer Joseph Riel

Symbolic Analysis of Multirate Systems Frank Heinle, Richard Reng, and Gerhard Runze tW Mechanical Computer Aided De

'lid

'? Modeling Flexible Robots with Maple Jean-Claude Piedboeuf

Automated Symbolic Analysis of Mechanical System Dynamics John McPhee and Carl Wells

Using Gröbner Bases in Kinematic Analysis of Mechanisms Oscar E. Ruiz S. and Placid M. Ferreira



The Basic Curves and Surfaces of Computer Aided Geometric Design Colm Mulcahy

AI

Process Control and Symbolic Computation: An Overview with Maple V Ayowale B. Ogunye

IN,,

Guidelines for Authors

A Note from the Editors Maple in Engineering — A Special Issue If one were to judge by the number of publications in which computer algebra plays a significant role one is forced to conclude that while the number of people using computer algebra continues to grow it seems that only a relatively modest number of computer users are using it in engineering applications. Yet, as we, the editors of this special issue, and the authors of the articles included here have found, Maple is an outstanding tool for many engineering computations. This special issue of Maple Tech brings together a number of contributions in various areas of engineering. Inside these pages can be found articles on topics in electrical engineering, mechanical engineering and chemical engineering. Several papers focus on various aspects of computer aided design. Some of the articles will be of interest to engineers of all kinds and, indeed, to workers in fields that may have nothing at all to do with engineering. Rob Corless provides our tutorial with a light hearted tour of some of the Maple functions that are of interest in engineering. We suggest that the future of general purpose engineering computing belongs to software systems that provide exceptional integration (pun intended) of several key functions. Those key functions are: symbolic mathematics, graphics, numerical computations, document creation, and an ability to link Maple with other software tools (e.g., spreadsheets, special purpose software, programming languages, numerical libraries, and data banks). Maple already excels at some of these functions and the very new Maple V Release 4, soon to be installed on a hard drive near you, provides significantly improved capabilities. The most obvious area of improvement is in document creation. Elsewhere in this issue Tom Lee writes about some of the mathematical features that will be of interest to engineers in this latest release of Maple. The editors would like to thank all those involved in the review process. Particular thanks to those of you that reviewed more than one of the papers submitted for this special issue (you know who you are). Thanks are due also to Rob Corless who wrote this issue's tutorial article in record time when he must have been exceptionally busy with other things; thanks Rob. Mike Monagan, Tony Scott, and Judi Borwein provided considerable assistance and we thank them as well.

Ross 'Taylor and Dave Pintur

Ross Taylor Professor of Chemical Engineering Department of Chemical Engineering Clarkson University Box 5705 Potsdam, New York 13699-5705, USA email:[email protected] Dr. David Pintur Application Development Manager Waterloo Maple Software 450 Phillip Street Waterloo, Ontario, Canada N2L. 5J2 email:[email protected]

Upcoming Maple'Teci_ Special Issues This issue is the second special issue of Maple Tech; the first, edited by Tony Scott and Mike Monagan, focussed on Maple in Science and was published in late 1994. Two more special issues are in the works. One, to be edited by Jon Borwein, will be entitled

Maple in the Mathematical Sciences. It is planned for early 1997 and the deadline for submissions is August 1, 1996. For further information, please contact the editor, Jon Borwein at jborwein@cecm. sfu. ca or Michael Monagan at monagan@cecm . s fu . ca. The other special issue is oriented to the biological sciences and chemistry and physics.

Maple in the Physical Sciences will be edited by James Herod of Georgia Tech and also published in 1997. The deadline for submissions is September 1, 1996. For further information, please contact the editor, James Herod at herod@math . gatech . edu or Michael Monagan at monagan@cecm. sfu. ca.

Simple Engineering Mathematics with Maple Robert M. Corless Though I work in an Applied Mathematics department, my Ph.D. is in Mechanical Engineering and my research area is Flow-Induced Vibration. Naturally, this means that I am assigned the job of teaching mathematics to engineering students, and this in an ideal world involves talking to the engineering faculty (I admit, usually over a beer in the pub) about just what it is that they want their students to know. What is surprising to my purer colleagues is that the engineers want more than we are currently teaching. Their research and their livelihood depends on very sophisticated mathematics — though they are quick to point out that that's not all there is to it. At any rate, my engineering colleagues want us to teach more mathematics (in fewer courses, without failing too many students, of course). What sort of mathematics? Well, the answer that comes back the most often is "algebra". "Great!" say my pure mathematics colleagues. "We can do rings, and fields, and prime ideal decompositions, and so on - - ." Well, that's not quite right. What my colleagues want is simpler than that: they want their students to be able to do (essentially) polynomial algebra. They should be able to add two rational functions; they should know how many roots a polynomial has; they should know what a rational function looks like, and to be able to do a partial fraction decomposition. They should be able to find polynomial roots, and to decide if a polynomial has all its roots in the left half plane (to decide if the system is stable, of course). This is necessary to understand basic control theory, for example. The answer just less popular than "polynomial algebra" is that of "formulating an integral". Not evaluating an integral, but formulating it. But before computer algebra systems like Maple came around, the students would get bogged down in evaluating an integral and never quite realize that that was the easy part. Of course there are yet more topics that engineering faculties want us to teach, and the claim here is that Maple can help us to do that; failing getting improvements into the math courses taught by your math departments, you might think about looking at what Maple can do to help you fill in the gaps left by those lazy "math types". In what follows we investigate some simple examples of how Maple can help you to solve basic mathematical problems, allowing you to concentrate on the formulation and analysis aspects, which are closer to the real engineering parts. For a more thorough introduction to Maple for scientific and engineering programmers, I can recommend the book [1].

2

Polynomials MANIPULATION We begin with some very simple manipulations. First of all, this is how we input the polynomial p = 3.x, 3 + 5x 2 — _ X+ 11 into Maple. Note the syntax is rather like that of C or Pascal. > p := 3*x"3 + 5*x"2 - 7/2*x + 11;

p:=3x 3 +5:x.2 — 2.r,+11 Notice that although the input is "keyboard style", the output looks as though we wrote it by hand. > q := 5*x"5 + 7*x -3;

q:=5x 5 +7.r,-3 If we multiply polynomials, the default is not to expand them out. > p* q;

3x3 +5x2 - 7 x+11 (5x5 +7.r.-3) 0

> expand(");

15x8+21x4+26x3+25x7— 72 x2 — +

175

2

32

.r,s

.r, +55.x,5-33

The terms appear in an apparently random order, but we can sort them if we like. > sort(");

15 x8 + 25x7 —

X

25

+ 55x5 + 21 x4 + 26x3 —

79 x2 2

+2 1 5 x-33 Rational functions are simple, just ratios of polynomials. > (x"3 + 3*x"2 + 3*x + 1)/(x"4-1);

x3 +3x2 +3x+1

X4 — I To eliminate any possible common factors, use normal. > normal(");

x 2 +2x+1 x3 — x 2 + .T, — I

Simple Engineering Mathematics with Maple

Convert to partial fractions form: > convert(", parfrac, x); 2 1 — x-1 X -1 .X, 2 +1

Multivariate polynomials are also easy. > p := randpoly([x,y,z], degree=3); p:= 79x+56z+49y2 z+63yz2 +57y3 -59.X,3 > q := randpoly([x,y,z], degree=3); q:=77+66x+54xy - 5xyz+99y2 z - 61y3 > expand(p*q); 6083 x + 4312 z — 395 x2 y z + 3878 .X, y z2 + 2646 y3 z x — 245y 3 z2 x + 3402y 2 z2 x —315y2 z3 x-285y4 xz+295.X,4 yz — 5841 x3 y2 z+ 11055 x y2 z— 3477y 6 — 3894 .x,4 + 3024 x y z + 5214 x2 + 4266 x 2 y — 1057 x y3 + 3696 z x + 5544 y2 z2 —3416 z y3 +1008 y4 z2 + 2654 y5 z + 6237y 3 z3 + 3078 y4 .X, —3186 x4 y + 3599x 3 y3 + 3773 y2 z + 4851 y z2 + 4389 y3 —4543 x3

Maple also has connections to the C programming language, and to the venerable Fortran. > readlib(C):

Remember, pq was the collected form of our polynomial. The following piece of C code will evaluate that polynomial, given values for .x, y, and z. > C(pq, optimized); tl = y*z; t3 = x*x; t4 = t3*t3; t6 = y*y; t7 = t6*y; t8 = t6*z; t14 = z*z; t16 = z*t7; t17 = t6*t14; t18 = y*t14; t19 = t6*t6; t21 = t14*z; t23 = 6083.0-245.0*t7*t14+11055.0\ *t8+2646.0*t16-1057.0*t7+3402.0*t17+ 3878.0*t18-285.0*t19*z+3696.0*z+3024.0*\ t1-315.0*t6*t21+3078.0*t19; t30 = (295.0*t1-3186.0*y-3894.0)*\ t4+(-4543.0+3599.0*t7-5841.0*t8)*t3*x+( 4266.0*y-395.0*t1+5214.0)*t3+t23*x+1008\ .0*t19*t14+4312.0*z+4851.0*t18+4389.0*t7 -3477.0*t19*t6+2654.0*t19*y*z+5544.0*t1\ 7-3416.0*t16+6237.0*t7*t21+3773.0*t8;

A very useful routine is collect: > pq

collect(", x);

pq := (295yz-3186y-3894)x4 + ( —4543 + 3599 y3 —5841 y2 z ) x3 + ( 4266 y — 395 y z + 5214 ) x2 +(6083 — 245 y3 z2 + 11055 y2 z + 2646 z y3 — 1057 y3 +3402 y2 z2 + 3878 y z2 — 285 y4 z

IZ®®TF'INDING Finding roots of polynomials is more interesting. > p := randpoly(x, degree--25);

P:=85x15 +49.X,15 +78x7 +17.X,0 +72x,5 - 99.X,18 > fsolve(", x, complex): > zeros := map( t->[Re(t), Im(t)], [ " ]);

+ 3696 z + 3024y z — 315 y2 z3 + 3078 y4) x+1008y4 z2 +4312z+4851yz2 + 4389 y3 —3477 ye + 2654 y5 z + 5544 y2 z2 —3416 z y3 +6237 y3 z3 + 3773 y2 z

Perhaps the most useful polynomial routine for me is factor. It is astonishing how many multivariate polynomials that occur in practice (in studying critical phenomena especially) have nontrivial factorizations.

zeros := [[ 0,0],[ 0,0 ],[0,0],[ 0,0 ],[0,0], [-1.027248146,—.2657568897], [ —1.027248146, .2657568897

1,

[—.7510945048,—.6847033981], [ —.7510945048,.6847033981 ], [—.3022422615,—.8304372728], [ —.3022422615,.8304372728], [.02935270011,—.84050599301, [ .02935270011, .8405059930 ],

> factor("); (-77-66x-54xy+5xyz-99y2 z+61y3 )( —79x — 56z — 49 y2 z — 63y z2 - 57 y 3 + 59X3

[.4987451955,—.78900082481, [ .4987451955, .7890008248

1,

[.9411336906,—.4206528640], [ .9411336906, .4206528640 ], [ 1.222706653, 0 ]]

3

Simple Engineering Mathematics with Maple

> plot(zeros, style=POINT, axes=BOXED);

0. S

Indeed, we see that two of the roots have positive real parts and the polynomial is unstable. However, sometimes the routine will be unable to decide for us, and will give us conditions on the values of c to determine things. > p := z -3 + z"2 + a*z + b;

0. 6

p:=z3 +z2 +az+b

0.4 0.2

> Hurwitz(p, z, 'sequen', 'g');

Ch

FAIL The word 'FAIL there means that the routine couldn't tell if it was always stable or always unstable. This means there are regions in parameter space which are ok. We now look at the 'partial quotients' provided by the algorithm. If these polynomials have positive coefficients, the polynomial is stable (and vice versa).

46

s

> sequen[l];

But we often do not have to find roots to decide on stability. We can, for example, use the Hurwitz criterion to decide for which parameter values the polynomial is "stable", i.e., has all its roots in the left half plane. We use a simple example here. > p := z"3 + c*z + 1; p:=z3 +cz+1 The question we wish to ask is "for which values of the real parameter c., if any, is the polynomial p stable?" We first load the Hurwitz package from the Maple share library. For the theory behind this code, see the book [3].

Z So that coefficient (1 times z) is positive. Let's look at the next one. > sequen[2]; Z

a — b

This says that a — b > 0. This is nontrivial. > sequen[3]; a

b —z > normal(");

(a — b)z

> with(share);

b

> readshare(Hurwitz, calculus);

Hurwitz > Hurwitz(p, z, 'sequen', 'g');

false The routine "Hurwitz" claims that no matter what c is, there will always be a root in the right half plane. Let us check this with a random value.

This says, since we know a — b > 0 from the previous condition, that if a > b > 0 then the polynomial will be stable, and not otherwise. Again, let us try some random values of a and b to see. > subs(a=3, b=2, p);

z3 +z2 +3z+2 > fsolve(", z, complex);

> subs(c=347, p);

Z3 + 347 z + 1

—.7152252384,—.1423873808 —1.6661475741, —.1423873808 +1.6661475741

> fsolve(", z, complex);

—.002881844311, .001440922156 — 18.62793618I, .001440922156 + 18.62793618 I

As predicted, all the real parts are negative. Now let's try some other values. > subs(a=-.3, b=-.2, p);

z3 + z2 — .3z — .2 > fsolve(", z,complex);

—1.107839097, —.3743781860,.4822172833

4

Simple Engineering Mathematics with Maple

One positive root—the polynomial is unstable. Now some strange values:

Often a little simplification is necessary to see that things are really the same. It's best to try to simplify things to zero:

> normal(lhs(") - rhs("));

> subs(a=837, b=837, p);

0

z3 + z2 + 837z + 837

There are also series and facilities for solving differential equations.

> fsolve(", z, complex); -1., -28.93095228 I, 28.930952281

> f;

Oh, of course: if a = b then the polynomial factors into

sin( .r, ) 3 co.-,(x ) — sin( .r, ) cos( x )3

(z2 + a)(z + 1). > subs(a=9.87,b=9.8703,p);

> series(f, x=Pi/2, 4); 4)

z 3 + z 2 + 9.87 z + 9.8703

— (x - 2Z)+ 8

2Z) 3 +0

(~: -

x - 2ff) 00

> fsolve(", z, complex);

> ODE := diff(y(x), x, x) + diff(y(x), x) -1.000027599,

- Y(x) = f;

>

.00001379937795 - 3.141660007 1, .00001379937795 + 3.1416600071

ODE :=

az Cax2

c7 Y(x )) +

äx Y(X )) — Y(x) _

sin( .r, )3 cos( x) — sin(.r, ) cos( x )3

', r ~ ~~ :M

Polynomials are by no means all that Maple can deal with. Let us look at some typical manipulations from calculus.

> f := sin(x)"3*cos(x) - sin(x)*cos(x)^3;

> combine(", trig);

) C2 2 Y(x)

Ca

a Y(X)) - Y(X) = - 1 sin(4.T) ) + ((9X 4

f :=sin( x )3 cos( x) — sin(x ) cos( x ) 3 > dsolve(", y(x) );

A useful thing to simplify trig expressions is y( x )

-- sin( 4x).

> Int( 1/(1 + exp(x)), x); 1

+

ex

dx.

In Maple, you have to add your own constant of integration — this is a deliberate decision, and useful pedagogically as well as in calculation (the main reason for this is that you get to choose your own constant name).

1

186050 + 744200 1

+ _CI e(1/2

Let's verify that by differentiation. > diff(", x);

x)

+ _C2 e ( — 1/2 (,~75-+1) x)

> evalc(");

17

3I cos(4x) + 1220 sin(4 x) y(x)

+ _CI

dx=-In(1+ex)+ In( ex)+C

(v75 -1)

A typical reaction of a mechanical engineering student to the sight of complex numbers is "Enough!" but they're not so bad. here, we can clean things up with the evalc command, which means "evaluate over the complex field", and this discovers that the imaginary part is zero.

> " = value(") + C; 1+ex

17

(305e( -41x) - 273e(41 x ) -1361e (41x) )

4

The above routine is very useful for robotics calculations, for example. Now consider an integral:

1

1

_

> combine(", trig); 1

e(1/2 x ~/5 -1/2 x) + _C2 e(` 1/2 x uT-1/2 x)

Now, let us check that calculation. One advantage of symbolic manipulation systems is that this can be done in many ways, and it is really a good idea to get in the habit. > subs( ", ODE):

1

1+e x

ex 1+ex +1

> normal(");

-

4

sin(4 x) = sin(x )3 cos( x) - sin( x ) cos( .r, )3

5

Simple Engineering Mathematics with Maple

> combine(", trig);

> Digits := 18;

Digits := 18

— 1 sin( 4 x) = — 1 sin(4x) 4 4

> evalf(Eigenvals(A, 'V'));

Linear Algebra

[.32879287721737482410-5 .000305898040151192748 .0114074916234198061 .208534218611013345 1.567050691098230831

> with(linalg); Warning: new definition for norm Warning: new definition for trace

[BlockDiagonal, GramSchrnidt., JordanBlock, Wronskian, add, addcol, addrow, adj, adjoint, angle, augment, backsub, band, basis, bezout, blockmatrix, ch.armat, charpoly, col, coldim, colspace, rolspan, companion, concat, cond, copyinto, crossprod, curl, definite, delcols, delrows, det, diag, diverge, dotprod, eigenvals, eigenvects, entermatrix, equal, exponential, extend,ffgausselim, fibonacci, frobenius, gausselim, gaussjord, genmatrix, grad, hadamard, hermite, hessian, hilbert, htranspose, ihermite, indexfunc, innerprod, intbasis, inverse, ismith, iszero, jacobian, Jordan, kernel, laplacian,leastsgrs,linsolve, matrix, minor, minpoly, mulcol, mulrow, multiply, norm, normalize, nullspace, orthog, permanent., pivot,, potential, randmatrix, randvector, rank, ratform, row, rowdim, rowspace, rowspan, rref , scalarmul, singularvals, smith., stack, submatrix, subvector, sumbasis, swapcol, .swaprow, sylvester, toeplitz, trace, transpose, vandermonde, vecpotent, vectdim, vector] Let us look at two problems; one numerical, one symbolic. Suppose we wish to find the eigenvalues of a matrix, numerically.

Let us verify that the matrix of eigenvectors really diagonalizes the matrix here. We clean up the results with fnormal, which sets roundoff noise to zero (after a calculation has been done). > evalm( V"(-1) &* A &* V): > map(fnormal,");

[.32879287721709981710-5 ,0,0,0,0] [0,.000305898040151191587,0,0,0] [0,0,.0114074916234198059,0,0] [0,0,0,.208534218611013335,0] [0,0,0,0,1.56705069109823081] Now let us look at something different. Suppose we wish to compute the Moore-Penrose inverse to a matrix. The Moore-Penrose inverse is a useful generalization of the ordinary inverse, and can be calculated numerically using the SVD. Here it is computed symbolically, which is occasionally useful. Here is our matrix: > A := matrix(3, 2, > Ha, 11, [a"2, 1] , [a"3, 1] ] ) ;

a 1 A:=

a2

1

a3 1 > alias(Eye = &*());

I, Eye

> A := hilbert(5);

1

A :=

6

1 2 1 3 1 4 1 5

1 2 1 3 1 4 1 5 1 6

1 3 1 4 1 5 1 6 1 7

1 4 1 5 1 6 1 7 1 8

1 5 1 6 1 7 1 8 1 9

The following "one-line program" is taken from Andres Heck's book [2], which I also recommend highly for scientific and engineering programmers. > Moore_Penrose := A -> map(limit, > evalm((transpose(A) &* A + t"2*Eye)-(-1) > &* transpose(A)), t=0): > Ap := Moore_Penrose(A);

Ap a +2 2 a(as-1)'

1

1

1

2 all+a+a2 )'

Simple Engineering Mathematics with Maple

1 2 a -I- 1 1 2 a(a3 -1) 1 a 1 1 1 2 a-1'2' 2 a-1J We can now verify the four Moore-Penrose conditions: > evalm( A &* Ap &* A - A);

0 0 0 0 0 0

[3] Norman Levinson and Raymond M. Redheffer, Complex Variables, Holden-Day, 1970 pp. 298-306.

Biography Robert Corless received his doctoral degree in mechanical engineering from the University of British Columbia. He is presently associate professor at the University of Western Ontario. His backround also includes computer science and applied mathematics, and his interests include computational aspects of dynamical systems, numerical solutions of ordinary differential equations, flow-induced vibration, and perturbations.

> evalm( Ap &* A &* Ap - Ap);

0 0 0 0 0 0 > evalm( transpose( A &* Ap) - A &* Ap);

0 0 0 0 0 0 0 0 0 > evalm( transpose( Ap &* A) - Ap &* A);

0 0 0 0

Concluding Remarks This 'whirlwind tour' was intended to give you some flavour of what using Maple in engineering could be like. Clearly there is a lot more to it than just what is presented here: three-dimensional plots, animations, numerical solution of differential equations, conversion of expressions (e.g., Jacobian matrices) to Fortran or C for numerical work, and many more. Please see the references for more details.

Acknowledgments I would like to thank Michael Monagan for suggesting this article, suggesting many of the details of its contents, and for actual help during its preparation.

References [ 1 ] Robert M. Corless, Essential Maple, Springer-Verlag, 1994. [2] Andr6 Heck, Introduction to Maple, Springer-Verlag, 1993.

7

Maple V Release 4: New Features for Engineers and Scientists Tom Lee* A New Standard Maple V Release 4, dubbed "The Power Edition", is a major enhancement of the Maple V system. With a completely redesigned user interface and new mathematical and programming features, users in engineering and science receive a substantially more productive and powerful computing environment. This article outlines the top new features that are useful for engineers and scientists.

Report Writing and Presentations A major objective in the design of the new user interface was to greatly increase the document processing capability of Maple V and to introduce features to support live presentations. These features allow users to document their work, create reports and present their findings to a live audience. The result is a solid balance between being able to quickly solve problems and to be able to transform the computations into a professional document. In terms of document processing, users now have access to:

• OLE 2 client support for the Windows version. You can embed pictures, sound, movies, and other OLE 2 compatible objects inside a worksheet.

Multiple Document Interface Another new feature of the user interface is the ability to work with more than one worksheet at a time. For organizing large problems, this is an essential feature. By default, all worksheets within a given Maple V session, share the same set of mathematical information. If a variable is assigned in one worksheet all others that are up in that session will also have that definition. This is called the "single server" mode. For operating systems that support advanced multitasking (e.g., Windows 95, Windows NT, OS/2 Warp, and UNIX), users can also work within a "multiple server" mode. In this mode, each worksheet in a given Maple V session is connected to its own mathematical engine and no information is shared. This is useful for users who wish to work with several problems at the same time without having to launch separate Maple V sessions which generally stresses system resources.

• comprehensive font control for all text

Piecewise Functions

• "style" control similar to that of general purpose wordprocessors

Piecewise functions are essential elements of engineering and scientific analysis. Release 4 provides comprehensive support for these functions. You can easily define a piecewise function and then plot, integrate, differentiate, etc. Consider, for example, a square wave defined in a piecewise form:

• formatting control such as justification • special predefined styles such as bullet lists • mathematical typesetting within text areas and sentences • interactive graphics within the worksheet rather than in a separate window To support the creation of live presentations and tutorials, the user interface features: • outlining: the ability to organize document in terms of collapsible sections • hyperlink facilities to interactive link worksheets and help files • executable typeset mathematics: the ability to view input commands in real mathematical notation. The executable mathematics can also be embedded inside a sentence within a text region. *Manager, Product Marketing, Waterloo Maple Inc.

> square_wave := piecewise( > x diff_eq := (diff(y(x),x,x,x) _ > y(x)*diff(y(x), x)-x);

diff-eg _ { 8 a3 y(x) = y(x)(

— y(x)) a .r.}

> init :_ ( (D@02) (y) (1) = 0, D(y) (1) = 0, > y(1) = 0); init := {D(y)(1) = 0, y(1) = 0, (D(2))(y)(1) = 0}

9

e V Release 4: New Features for Engineers and Scientists

Next, we invoke dsolve to create a procedure for the numerical solution of the above differential equation. An implicit method from the LSODE package is used for the solution. > answer := dsolve(diff_eq union init, y(x), > type_numeric, method=lsode[adamsfull]);

answer := proc(x-lsode) ... end The solution at x = 2.4 is given by > answer(2.4);

[x = 2.4, y(x) = —.6115094821082631, 0 y(..T) = —1.402016541283117, Ox 02 y(x) = —2.1930285218030701 äT2

Here we plot the numerical solution from x = 0 to 10. > plots[odeplot](answer, [x,y(x)], > 1..10, axes=BOXED);

> fortran(VonKarman);

real function VonKarman(yplus) real yplus real uplus if (0 .le. yplus .and. yplus .lt. 5) then uplus = yplus else if (5 .le. yplus .and. yplus .lt. 30) then uplus = 0.5E1*alog(uplus)-0.305E1 else uplus = 0.25E1*alog(uplus)+0.5E1 endif endif return end

The Fortran facility can also handle arrays although sums must be coded without using the sum command.

New Plotting Capabilities Maple V's ability to easily plot mathematical expressions is well-known. With the Power Edition, a new package with a wide range of plotting utility functions allows users to create a much richer variety of mathematical and even nonmathematical graphics. The new plotting capabilities provide users with the tools needed to create their own plot types more easily. For example, the following develops and displays a pie chart. > with(plottools): > ql := piesli.ce([0,0], 1, Pi/6..Pi/2, > color=red): > q2 := pieslice([0,01, 1, Pi/2..5*Pi/3, > color=yellow):

Improved Code Generation Maple has long had the ability to translate expressions into both of these two languages. Now Maple can translate complete procedures into working Fortran subroutines and C procedures. The velocity profile in turbulent flow in a pipe may be calculated using the following procedure > > > > > > > > > >

VonKarman := proc(yplus) local uplus; if yplus >= 0 and yplus < 5 uplus := yplus; elif yplus >= 5 and yplus < uplus 5.0 * ln(uplus) else uplus 2.5 * ln(uplus) fi; end:

which we convert to Fortran as follows

W

> q3 := pieslice([0,0], 1, Pi/6 .. -Pi/3, > color=green): > plots[display1([g1,g2,q31, > title='A Pie Chart with Maple V', > axes=NONE,scaling=CONSTRAINED);

®

then 30 then - 3.05; + 5.0;

Maple V Release 4: New Features for Engineers and Scientists

Integral Transforms with Pattern Matching

A Pie Chart with Maple V

Release 4 includes several new specialized plotting commands. The rootlocus command, for example, plots the complex roots of the equation 1+kf(s)=0

as k varies. Here f (s) is a quotient of two polynomials. In s3 11 . Thus we trace out the roots the example below f (s) = 9 of the cubic polynomial

The transform library has been rewritten for Release 4. The integral. transforms for continuous functions are grouped into the package inttrans that has been expanded to include the Fourier sine, cosine, and Hankel transforms. In addition, a powerful new function to append to the existing transform pairs has also been introduced. This is very useful in certain fields where transform pairs that are often not part of standard reference pairs are required. This facility also has the capability to perform pattern-matching so that an exact oneto-one match is not required. For example consider the inverse Laplace transform of the function 1+a f Access the integral transforms package. > with(inttrans): warning, new definition for hilbert

First, try computing the inverse transform of the function. Note that the function name and arguments are returned. The existing function does not know about this particular transform pair. > inv1ap1ace(1/(sgrt(s)+a),s,t);

invlaplace(~ + , s, t) a

.s+k(s3 -1)=0

as k varies between —5 and 5. Maple automatically joins up adjacent points where possible to aid in the interpretation of the graphic. Note, in color the different curves are more easily seen.

Use the addtable function to define a new transform pair. > addtable(invlaplace,l/(sgrt(s)+a), > 1/sgrt(Pi*t)-a*exp(a"2*t) > *erfc(a*sgrt(t)),s,t);

Try again. This time Maple V recognizes the function and returns the appropriate result.

> f := (s"3-1)/s: > plots(rootlocus]( f, s, -5..5 );

> inv1ap1ace(1/(sgrt(s)+a),s,t);

1 — a e(a' t) erfc(a v t-) 7 t

4a . This function is in essentially the same form as the previous one, however, several of the terms have been changed. Note that the pattern-matching facility can sort through the differences and identify the equivalent structure with the reference form. Try computing the inverse transform of

4

. __

~..._..

.

z

2

> invlaplace(2/((b+l)/2+sgrt(s/2)),*s,t);

-2

2 ~ —2e(1/z (a+1)' t) erfc( (b + 1) vf2- OF) b 2

-4 -6 -6

-4

-2

— 2 e(1/2 (b+1)' t) erfc( (b + 1) V/'2_ Vt-) 2

and Scientists

Maple V Release 4: New Features for

Share Library and PDEs

Command Line Versions

Release 4 provides new functions which solve many specific classes of PDEs (the pdesolve function). In addition, the Maple share library provides an additional function pdsolve to extend the range of solvable problems. The pdsolve command expresses the solution in terms of ODEs of the independent variables. For example, the following decomposes the one-dimensional heat equations in terms of two ODES in _ul(t) and _u2(x) where _C1 is an undetermined constant.

The substantially richer user-interface can stress system resources in modest machines. Typically a minimum of 8 MB of RAM is needed to perform any computation. Twelve MB or more is usually required to perform most computations comfortably. With the Power Edition, an alternate version of Maple is provided to help ease the demand on system resources. The Command Line version is a small application that accesses the full mathematical power of Maple but offers a simple, command-line user interface. UNIX users of Release 3 will recognize this version as the "TTY" version. Now it is available for most other platforms and ships with the complete Maple V package. This small application will comfortably run on a 4 M machine. It has many uses including,

> with(share): See ?share and ?share,contents for information about the share library > readshare(pdetools,analysis):

s running on older machines with limited RAM

> pde := diff(u(t,x),t) _ > a*diff(u(t,x),x,x);

+ performing very large computations on newer machines

2 pde, :_ ~ u(t, .T,) = 2 (

a

ll(t, :C))

r~x 2

Öt

®

running on laptops which generally have more modest system configurations

®

to be running at all times as a "Super Calculator" ac-

> pdsolve(");

(ii (t, T) _ _ul(t) _u2 (x)) &Where[{ ~a22 -u 2(x) = x

cl

cessory

_u2(x) ~_ ul t( ) _-11 _ci 1(t)l] a at

Special Functions Many more special functions are now known by Maple.These include the complete family of Bessel functions, the elliptic and inverse elliptic functions, the Jacobi amplitude, elliptic, and theta functions, Dawson's integral, and the Weirstrass family of functions. Additionally, the Bessel functions J (z), 1 (x), K (.r,), and Y, (x) and most of the new functions can be computed in the entire complex plane. For example > BesselJ(1,1.O+I); 6141603349 +.36502802881

2.054268496 — .078179477071

9 /3-

2 7r + 16 ;rx + O(~2)

® ability to break execution when a certain variable changes

Revised Help System

> diff(HankelH2(v,x),x);

12

a ability to interactively check any variable assignments ® ability to break execution a specified lines '

> series(AngerJ(1/3,x),x,2);

—HankelH2(v. +1, x)+

Many users in engineering and science use the Maple V system as a comprehensive programming language for developing custom mathematics-intensive applications. Programming large procedures has been made much easier with the addition of an interactive debugger. This new facility allows a programmer to interactively step through a procedure and to automatically trap certain conditions on variables. The debugger activated by calling the new stopat function with the name of the procedure as the argument. Afterwards, any calls to the procedure automatically enters the debugger. Some specific features include: e line-by-line stepping within a procedure

> JacobiSN(2+2.0*I,0.5);

3 v/3 —

Interactive Debugger

v HankelH2(v, ~ .T,

The Help facilities in Maple V have been completely revised for the Power Edition. For new users, the new help features, offer convenient paths to obtain the essential information to navigate through the extensive library and the substantially greater set of features in the user interface. The following is a brief summary of the new facilities:

Maple V Release 4: New Features for Engineers and Scientists

Balloon Help: brief descriptions of all interface buttons and menus are automatically displayed when the mouse cursor is placed over them ® Context-sensitive help: when the mouse cursor is placed over library functions, and other key words and characters, the Help menu automatically suggests a Help page

® Browser or table of contents: hyperlink-based categorization of all Help pages

Biography Dr. Tom Lee is the Manager of Product Marketing at Waterloo Maple Inc. He received his PhD in Mechanical Engineering and his MASc and BASc in Systems Design Engineering at the University of Waterloo. He has actively contributed to the application of computer algebra systems in engineering education, research, and practice for over 9 years including the publication of several papers on the topic. He has additional technical interests in computer aided design, engineering modeling and simulation, and control systems.

® Search by topic: a search facility based on a comprehensive set of predefined topics ®

Search by text: a complete search of the entire help database for certain words. This is one of the more powerful features. For example, if you wanted to know how to differentiate a function but did not know the actual command, this search facility will check for all appearances of the word differentiate in the database and order the findings in terms of the importance of the word to the help topic and provide a suggested list of help pages. At the top of the list, you would find the function diff.

The other major improvement is the format of the Help pages themselves. All Help pages are now worksheets: they are better structured and easier to read. Furthermore, any cross-references to related topics are now organized via hyperlinks. 1~>,

,m

As important as the functionality improvements are, the Power Edition also features new documentation to help users get the most out of the software. The new manuals are organized into four components: ® Installation guide: a quick summary for installing the system ® Learning guide: a comprehensive introduction to general problem-solving with Maple V ® Programming guide: a through treatment of the Maple programming language ® Maple V Handbook: a compact reference summarizing the Maple V library

Summary Maple V Release 4: The Power Edition is a major new release of Maple. The forgoing has been a brief summary of the many new powerful features that this release provides. For users in engineering and science, the Power Edition offers greater opportunities for engineers and scientists to fully exploit the mathematical power of the Maple system.

13

MacroC and Macrofort: C and Fortran Code Generation Within Maple Patrick Capolsini *and Claude Gomezt Motivation

> f := hornerform(f,x);

Computer algebra has become a very powerful and useful tool for engineers. however, many applications require largescale numerical in addition to symbolic computations. Typical examples arise in the control of mechanical systems where computer algebra is used for deriving the equation of motion and numerical computations must be used for solving the simulation and control problem (see the example given later and the example of the control of a bike in [4]). In Maple it is possible to perform floating-point numerical calculations with an arbitrary number of digits. This is very useful for ill-conditioned problems, but performance is poor. A number of Maple functions deal with standard numerical calculations but the running time of these functions is not as good as with compiled Fortran or C code. Moreover, the need to use existing C or Fortran programs arises often as well as the need to use them with code coming from computer algebra systems. For these reasons tools are needed to link computer algebra and numerical computations. One way to do this is for the computer algebra system to generate C or Fortan code. The MacroC and Macrofort packages offer users new tools in Maple to generate complete C and Fortran programs. These packages are described in this article and their use illustrated through two engineering applications.

What are MacroC and Macrofort for? Maple procedures called fortran and C already exist. They take a Maple expression as input and return the corresponding Fortran or C code. An optional argument (optimized) may be given so that common subexpressions are identified and an optimized code is produced. We have made benchmarks showing that big optimized Fortran programs run from 2 to 5 times faster. The example below illustrates the use of the C and f ortran functions. Supposeyou need to compute sin(.r,)l.r, for many values of (.r, < 2. One way to do it is to use a Taylor polynomial to approximate the function as follows.

f : 1+ ( 6 + 120 ~"a) TZ

> readlib(C): > fortran(f,optimized); t1 = x**2 t4 = 1+(-1.E0/6.E0+t1/120)*t1 > C(f,optimized); t1 = x*x; t4 = 1.0+(-1.0/6.0+t1/120)*t1;

If the user wants to get a complete subroutine to compute a function, the user has to translate the expression into the desired language using the C or fortran functions, write the developed code into a file, exit Maple and write the remaining code needed to complete the program. It would be nice if this tedious job could be automated, so that we may stay in Maple for the whole process. This is what MacroC and Macrofort can do. We show below how to generate a complete C program to compute the preceding function f using the MacroC package: > with(share):readshare(macroC,numerics): See ?share and ?share,contents for information about the share library > optimized:=true: autodeclare:=double: > func:=[functionm, double, horn, [[double, x]], > [[declareC, double, res], > [equalC, res, f], > > [returnC, res]]]: > genC(func); double horn(x) double x;

{ > with(numapprox,taylor,hornerform): > f := taylor(sin(x)/x,x);

X2+ f 16

120 r4+0(x5)

*French University of South Pacific, Tahiti, French Polynesia, [email protected] tINRIA-Rocquencourt, France, [email protected]

14

double res; res = f; return (res);

}

MacroC and Macrofort: C and Fortran Code Generation Within Maple

Description of the Packages MacroC and Macrofort have a very similar syntax so that users may use both with a minimum amount of work and time. The MacroC and Macrofort "languages" are made of two kinds of instructions: single instructions and macro instructions. Both have the same syntax: a Maple list whose first element is a keyword describing the statement to be generated. The other optional elements are the relevant arguments. Single instructions ordinarily describe a unique statement and macros describe a set (usually a block) of statements. Keywords are made from the Fortran or C instruction name (when it exists or something close when it does not exist) with, respectively, an f and a C at its end for a single statement or an m at its end for a macro statement. We shall not describe completely the syntax of all the single and macro instructions here. The reader may find all the desired details within the two technical reports ([2]) and ([3]) which may be downloaded, with the code itself, from Maple share library. Both packages are quite easy to use. First, to load the package you must load the share library as shown above for MacroC. For Macrofort, use the same way:

> func:=[[includeC,''], [functionm, double, foo, > > [[double, x]], > [[declareC, double, res], > [if_then_elsem, abs(x) > 0.2, > [equalC,res,f], > [equa1C,res,fh]]]]]: > genC(func);

The generated C function is: B include double foo(x) double x; double res; if((0.2 < fabs(x))) (

res = (1-cos(x))/x; else double tl; tl = x*x; res = (1/2+(-1/24+t1/720)*tl)*x; }

As you can see, the code is optimized and the corresponding declaration (double t1;) was made by the use of the flag autodeclare.

> with(share):

A SMALL EXAMPLE WITH MACROFORT

See ?share and ?share,contents for information about the share library

We want to evaluate the polynomial E o a;.r.' in horner form. We create a Fortran function to do it.

> readshare(macrofor,numerics);

> optimized:=true: > p:=[functionm,doubleprecision, > horner,[x,n,a], > [[declarem,doubleprecision, > [a(n),x]], > [equalf,horner,a[n]], > [dom,i,n-1,0,-1, [equalf,horner,a[i]+horner*x]]]]: >

MACROFORT : FORTRAN code. generator Version 1.2.4 (15 January 1992) We assume now that these packages are loaded in Maple and we show below two simple examples.

> genfor(p);

A SMALL EXAMPLE WITH MACROC We want to write a C function to compute the value of f (x) _ s (1— cos .r,)Ix accurate to 10_ for all x. The formula for f (x) is not accurate near x = 0 because of cancellation. f (.r,) can be computed accurately for small x from the Taylor series about .r, = 0. It is very easy to do it with MacroC.

The generated Fortran function is: c c

doubleprecision function horner(x,n,a) doubleprecision a(n),x horner = a(n) c

> with(numapprox,taylor,hornerform):

> optimized:=true: autodeclare:=double:

> fh:=hornerform(taylor(f,x,7),x); ~-

2 +

1000 c

do 1000, i=n-1,0,-1 horner = a(i)+horner*x continue end

> f:=(1-cos(x))/x:

_ 1

FUNCTION horner

1 1 \ 2 I x2 .r, 24 + 720 x

The loop has been generated without dealing with labels. As you can see, you can nearly do structured programming in Fortran with Macrofort. Now, we show two realistic problems solved by using the Macrofort and MacroC packages.

15

MacroC and Macrofort: C and Fortran Code Generation Within Maple

Generalized Newton Method Using Macrofort NEWTON ALGORITHM We want to solve a non-linear system with n, equations and n unknowns:

fl(XI,...,X.) = 0

fn(x1,...,:C n) = 0

with x l , ... , x real numbers. We use the matrix notation defining the vectors X and F(X), and the Jacobian matrix of the system F(X)—a n by n matrix—as: , X d;

) F,(X) der

X,

. fn(~l,

F ,(X) a_r

ixv.)

jac := linalg[jacobianl(llf,llx); # pg: MAPLE list describing the main # program pg:=[[declaref,'implicit doubleprecision', ['ia-h,o-z)']], (declaref,doubleprecision,[f[n], zj[n,n],x[nl]], (writem,output,[" eps (readm,input,('dl4.7'1,[eps]11; # while instruction linit:=[[dom,i,l,n, [[writem,output, [readm,input,('dl4.7'],[x[i]]jj]]; for ii from 1 to n do pushe([equalf,f[ii],llf[ii]],'linit') od; lwhile:=((matrixm,zj,jacl, (calif,resold,[zj,f,n]], [dom,i,l,n,[equalf,x[i],-f[i]+x[i]])]; for ii from 1 to n do pushe((equalf,f[ii),llf[ii]],'lwhile') od; pg:=[op(pg), ([whilem,znorm(f,n) >= eps,linit,lwhile,1000], [writem,output,['(2x,d14.7)'],[x]]]]; pg:=[programm, newton, pg];

% af; n 1\

ax;

The well-known algorithm of the Newton method is — in Pascal like syntax — : X := XO } where XO is an arbitrary vector } while NOR111(F(X)) > EPS do < solve the following linear system for Y > F'(X).Y = —F(X) X := A'+X end, Output X. The difficulty when encoding this algorithm in Fortran code is how to compute the jacobian matrix. Traditionally one would compute the derivatives by hand and copy them into the program. We would like to use Maple to generate the derivatives symbolically and have Maple write the program for us.

# fo: MAPLE list describing the subroutine computing # the quadratic norm of f fo:=[[declaref,doubleprecision,(f[m)]], [equalf,znorm,0.], [dom,i,1,n,[equalf,znorm,znorm+f(il**2]], (equalf,znorm,sgrt(znorm))j; fo:=[functionm,real,znorm,[f,ml,fo]; # FORTRAN code generation interface(quiet=true); writeto('newton.f'); init_genfor(); precision:=double; genfor(pg); genfor(fo); interface(quiet=false); writeto(terminal); end:

APPLICATION TO A STEEL DOLLING PROBLEM

The system we want to solve is described by the following equations: .ft (F, hz, 4') = hz — S —

MACROFORT PROGRAM

F -}- a2(1 — e°tF) at (

.fz(F,hz, : )=F—lkRj l \2

We give below a Maple function which generates a general Fortran program for solving a non-linear system using Macrofort. resold is a Fortran subroutine solving a linear system of equations.

(hNl — In h2l + 2 ]n( 1

# main program # Jacobian matrix

W41

% R.

] q J h arctan V17 — VVVV

2

+ l1

h2 R~~'t 1 h2 ~ 2 V R. ( 4 In (h2 ]zt l/

\ h2 ht //

R h2

.fa(F, hz, (D) = arctan ~

# GENERALIZED NEWTON ALGORITHM # LF: LIST OF EQUATIONS # LX: LIST OF UNKNOWNS gen_newton := proc(lf,lx) local f,ff,fo,ii,jac,jj,linit,llf,llx, lwhile,m,pg,x,zj; n:=nops(lf); if n nops(lx) then ERROR('number of equations different from number of unknowns'); fi 11x:=[x(ii]$ii=l..n7; llf:=eval(subs(zip((a,b)->a=b,lx,llx),lf));

h2 arctan ~—~£ 4 R

Tt

T2

a

k1hi + klh2

with ht — h2

ht — hz R

a + R~ hrv=hz and the following values of the parameters: a l = 610, 0,2 = 643, a3 = —.00247, l = 1250, k = .0014, R = 360, T1 = 12, T2 = 35, hl = 24 and S = 12. This set of equations is the simplified description of the behavior of a steel strip in a stand of a hot strip rolling mill.

=

h2

E=

MacroC and Macrofort: C and Fortran Code Generation Within Maple Macrofort code The Maple session which generates the corresponding Fortran code using the previously defined function is # STEEL ROLLING # solution by Newton method # numerical values of parameters data:=[a1=610,a2=648,a3=-.00247,1=1250,k=1.4*10-(-2), gr=360,tl=12,t2=35,hl=24,s=121: # equations expl:=h2-s-(f+a2*(1-exp(a3*f)))/al: exp2:= f-1*k*gr*(Pi*sgrt(h2/gr)*arctan(sgrt(r))/2-Pi*csi/4 -log(hn/h2)+log(hl/h2)/2)+gr*csi*tl/h2: exp3:= arctan(phi*sgrt(gr/h2))-sgrt(h2/gr)*(Pi*log(h2/hl)/4 +sgrt(gr/h2)*arctan(sgrt(r))-tl/k/1/hl+t2/k/1/h2)/2: r:=(hl-h2)/h2: csi:=sgrt((hl-h2)/gr): hn:=h2+gr*phi"2: # list of equations and unknowns lf:=eval(subs(data,[expl,exp2,exp3))); lx.=(f,h2,phi);

if (eps.le.znorm(f,3)) then if (nwhilel.le.maxwhilel) then NEW LOOP ITERATION nwhilel = nwhilel+l -

zj(2,1) = 1 zj(2,2) _ -0.4375000001D1*0.3141592653589793D1/sgrt(x(2)) +*sgrt(360.DO)*atan(sgrt(24-x(2))/sgrt(x(2))) -0.8750000001D1*0.3141 +592653589793D1*sgrt(x(2))*sgrt(360.D0)*(-1/ (sgrt(24-x(2)))/sgrt(x(+2))/2-sgrt(24-x(2))/ sgrt(x(2)**3)/2)/(1+(24-x(2))/x(2))-0.21875D1* +0.3141592653589793D1/sgrt(24-x(2))*sgrt(360.D0) +0.63D4*(1/x(2)-(x(+2)+360*x(3)**2)/x(2)**2)/(x(2) +360*x(3)**2)*x(2)+0.315D4/x(2)-6*sgrt(360.D0)/ sgrt(24-x(2))/x(2)-12*sgrt(360.D0)*sgrt(24-x(2))/ x(2)** +2 zj(1,3) = 0 call resold(zj,f,3) do 1002, i=1,3

x(i) _ -f(i)+x(i) 1002 c

continue f(1) = x(2)-3984.D0/305.D0-x(1)/610+324.D0/ 305.D0*exp(-0.2+47D-2*x(1))

# loading Macrofort with(share):readshare(macrofor,numerics): # reading and executing the Maple procedure # generating the Fortran code read gen__newton: gen_newton(lf,lx);

Generated Fortran code Parts of the Fortran program generated by Macrofort are shown below. c c

MAIN PROGRAM newton

program newton implicit doubleprecision (a-h,o-z) doubleprecision f(3),zj(3,3),x(3) write(6,2000) 2000 format('eps = ') read(5,2001) eps 2001 format(dl4.7) c c WHILE (eps 'Rt 1 2 (1-p)*R', > 'Rb 2 0 p*R',

> ' Rw 2 0 R',

fs,l

> '.end'): > syrup(exam, dc);

-

-

-

v1 = 5, v2 = 5 l+. p _ p2

27

Symbolic Circuit

The equation for v2 is clearly nonlinear; this can also be seen in figure 1 which shows the actual graph of v2 as well as the one that I hurriedly sketched during the interview. Fortunately, I was more careful with my other answers and got the job.

> denom(subs(",v1))-(1+s*tau)"3: > coeffs(collect(",$),$): > solve(("), {Rs,Cs,tau));

{C,=—C,T=0,R, =01,

R, =

> plot({5*p,subs(",v2)),p=0..1);

CT

8

=V CC,Cs=BC

{R,=-3vf3 C,Cs =8C,T=—~, CLc l The desired solution set is the second in the sequence, > sol

"[21;

sot:= R,=8v

C,T =~ CC,CS =BC} J

These equations may used to select component values for a snubber. Obtaining a similar result using numerical simulation would be tedious and require comparing the waveforms of multiple analyses while varying parameters Rs and Cs.

11

Figure 1: v2 vs p. The output of syrup can be readily processed by standard Maple commands to yield useful design equations; the next two examples illustrate the power of this combination. EXAMPLE 2e OPTIMIZING A SNUBBER A snubber—a resistor and a capacitor in series—is frequently used to dampen resonant oscillations between a parallel inductor and capacitor, see the following schematic and syrup listing. Given the parallel circuit elements L and C, we would like to choose values for the snubber so that the oscillations in the tank circuit are quickly damped, while at the same time the resonant frequency remains as high as possible. Use syrup to determine the characteristic expression.

0 > > > >

snubber ;= TEXT( 'Snubber Circuit', 'Is 0 1', 'L 1 0 ic=Io ,

Is

L

syrup performs a transient analysis by returning the differential equations, initial conditions, and state variables that describe the circuit. This output can be directly passed to Maple's dsolve procedure which solves differential equations. Suppose Consider the previous snubber example. we need to determine the energy dissipated in the resistor R, given the initial conditions i L (0) = Io and vc(0) = vcs (0) = 0. A straightforward method is to determine iRs (t) from the solution of the differential equations and then compute RS f ~ iR s dt. Use syrup to generate the differential equations. > degs := syrup(snubber,tran,'curr');

T 1 ¢

EXAMPLE 3e ENERGY DISSIPATION

RS

C

~2

degs :_ IVC., ( 0) = 0, VC (0) = 0, ir,(0) = Io, a

> 'C 1 0

T C, 1

> 'Rs 1 2', > 'Cs 2 0', > '.end'):

— _

— _

—_



> syrup(snubber, ac);

_

—VC. (t)+VC'(t)+iL(t)R,— I,R,

at 77` (t)

'

CR,

a

at vca(t) =

vC(t) —vc.9(t) a

at

CS R,

vc,(t)

iL(t)

L

fVC(t), VC, (t),iL(t)I

V2 — s3 LCC,R, + '5 2 V1

_

sLI, + sS22 LC+ sC,Rs + 1'

s(1+C,sR,)LI,

8 3 LCC,R, + s2 LC, + s2 LC + aC,R, + 1

The denominator of 7)1, a third order polynomial, is the characteristic expression of the network. To meet the design goal, this expression should have three equal roots; such a system is analogous to a critically damped second order system. Set the polynomial equal to (1 + sT)3 , equate coefficients, and solve for the snubber's element values.

28

The variable curr is assigned the set of equations expressing the current through each element in the circuit. > curr;

Is,iC = ZCs =

vcs (t) — vc(t) +I,R, — iL(t)R,

R,

VC (t) — yC., (t )

R,

i

Rs

=V

(t) —

VC. (t) 1

R,

1

Symbolic Circuit Analysis

Substitute the results of the previous example into the differential equations. > subs(sol, degs[l]): > simplify(");

{vc.,(0) = 0,ir,(0) = Io, VC, (0) = 0, a vc(t) ~% v"3-(vc(t) — c,, (t)) at'r (t) = L at ~~c~ (t) = 9 VIT at~~c(t) —

g

✓ (vcs(t) — vc(t)) + Is

LC

C

_'r(t) C

Solve these differential equations with dsolve. > assume(L>O,C>O): > dsol := dsolve(", degs[2], laplace):

dsol:_ fi r (t) =...,v~~(t,) =...,vr,(t,) _ ... } The result is too lengthy to display here. Substitute this solution and the values for RS and CS into the power dissipation in RS and integrate the expression from zero to infinity. > > > >

subs(curr, sol, dsol, Rs*iRs"2): P := simplify("): Energy = int(P, t=O..infinity): factor(");

1

Energy = 2L-(Io — I8 ) 2 This nice result could have been achieved without solving the differential equations; the method is not widely known.

Summary syrup has been a useful addition to this engineer's toolbox. It provides a quick and easy means to symbolically analyze many circuits, using a familar input notation. Source code for syrup and a worksheet illustrating its usage is available in the share library.

[1] Tony Scott, Michael Monagan, Richard Pavelle and Darren Redfern, Maple in Education—Part II, The Maple Technical Newsletter, Volume 1, Number 1, Birkhduser, (Spring 1994). [2] Walter Banzhaf, Computer-Aided Circuit Analysis Using SPICE, Prentice-Hall, New Jersey (1989). r

e

' +h - M;.; m

Joseph Riel, the author of syrup, is a power system engineer employed by AT&T Global Information Solutions, formerly NCR, since 1981. He has a B.S. in electrical engineering from the University of California at Irvine.

QTJ

Symbolic Analysis, of Multirate Systems Frank Meinte, Richard Reng, and Gerhard Runze Introduction Digital systems for the transmission [1] and processing of signals [2] have been playing a major role in modern telecommunications for a long time. In recent years a large number of new applications was found that consistently use all opportunities offered by modern digital technologies. Most of these applications no longer have an equivalent in the analog world. One class of digital systems that gained more and more importance in the last few years are multirate systems [3, 4] with different sampling rates. Some important applications of these systems are ® subband and transform coding of still images, video, audio signals, and speech,

have been implemented. Our analysis tool is by far not complete, but even in this early stage it already permits the analysis of almost all multirate structures used in communications applications. In this paper we are going to describe the fundamental building blocks and their implementation as well as the basic operations for connecting multirate systems.

Description of Multirate Systems Multirate systems are a special type of time varying systems. A linear time varying system can be described by an impulse response depending on both the time index k1 of excitation and the time index k2 of observation. The input-output relation is given by +oo

® efficient realization of very high speed digital systems, ® multiplexing and demultiplexing of digital signals in time or in frequency, e.g., for satellite communications, * sampling rate conversions, e.g., between CD music and studio quality music, ® fast implementation of the Discrete Wavelet Transform for image compression or the analysis of nonstationary signals, e.g. seismic data sets, ® (not necessarily linear) interpolation of intermediate points from sampled data. Since multirate systems are widely used today there have been some efforts to develop methods for the analysis and description of such systems [5, 6, 7]. The theoretical results are often not easy to handle. What is more, they are usually restricted to particular systems like M—channel filter banks with equal sampling rates at the input and at the output. However, in [8] a new consistent matrix description of arbitrary multirate systems, well suited for an automated symbolic analysis of these systems, was introduced. Based on this description a MAPLE tool for the analysis of multirate systems has been developed [9]. Since all linear multirate systems are composed of a few fundamental building blocks, those blocks have been realized as MAPLE procedures. Furthermore functions for connecting multirate systems and the analysis of the resulting composite systems "Telecommunications Institute, University of Erlangen-Nuremberg, Cauerstrasse 7, D-91058 Erlangen, Germany, [email protected]

30

y(k2)

h(k2,k1)?'(k1). k,=—oo

In case of multirate systems the impulse response has the shift property h(k2i kr ) = h(k2 — L2, ki — Li). Therefore it is +oo

y(k2 — L2) _ I: h(k2,kt)v(kr — Li).

(1)

kl =—oo

A shift of the input signal by L1 samples thus results in a shift of the output signal by L2 samples. EXAMPLE — DOWNSAMPLER

—I

V(kt )

~.- - Y(k2)

v(k1-1) - - ~

~_1 3

-~— ~

v(k1-2)~

®

—~ y(k21) ~

v(kl-3) k t =0 1 2 3

k2 =0 1 2 3

Figure 1: Impulse responses of a downsampler As an example let us consider a downsampler, one of the fundamental building blocks of multirate systems. It reduces the sampling rate of a digital signal by simply picking out samples with time index k2 L1 , k2 = I ... ,-1,0,1,...}. Here, we use a sampling rate reduction by a factor of 3, i.e. L1 = 3, L2 = 1. The shift property (1) then can be verified easily (fig. 1).

Symbolic Analysis of Multirate Systems

2- ~

2 ) Y(ze jL 2_1 Y(zej L2 )

POLYPHASE DESCRIPTION The shift property leads to an equivalent structure (fig. 2) of multirate systems [8], consisting of three main parts. In a

Y (m:L2 )(z)

1

=

L2

: 4; (Ls -1)

I

D

Delay

r,-:.~~ L2+ i

H(p:L2 xLi ) Z ( ) :

D A Downsam pler _

blucking

~ L2 Upsampler

~~:~~~~ ~

Unblocking

Figure 2: Equivalent representation of multirate systems first step blocks of L1 successive input samples are formed (blocking). Then these blocks are processed simultaneously by a time invariant linear system with L1 inputs and L2 outputs (block processing). The system can be described by the matrix H(p: F,z x L,) (z) of its partial transfer functions. The L2 output signals are recombined in a final step into a block of L2 successive output samples of the multirate system (unblocking). A specific multirate system obviously can be described completely by the blocking factors L1 and L2 and the matrix H(p: 112 x 111) (z). Usually the matrix is called polyphase matrix.

From the polyphase matrix the so-called modulation or alias component matrix H("2 " x L') (zo) can be derived. It is H(m:7,2 xI,1 )(

zo

i

where WM denotes the unitary M x 1111 DFT matrix and Dv, (z) = diag 11, z-1 z`( 'tir—i) } describes an array of delays [8]. Each multirate system can be described entirely by this matrix as well. The matrix gives the relations between modulated, i.e., frequency shifted versions of the input and the output signal: Y (m:L2)( zo1)

= H(m:L2x(,1 )(z~nP7e2)Tr(m:L7 )(

\ 2-o

Fundamental Building Blocks We are going to investigate synchronous multirate systems that consist of several fundamental building blocks (fig. 3) and parallel or serial connections of these blocks. All fundamental building blocks, their polyphase and modulation matrices and their realization in MAPLE will be explained in detail now.

Downsampler

v(k,)

~y(k 2 ) = V(L,k2)

1 L, L,,L2 =1

Upsampler

V(k,)°

v ,k j (k2 / L2) 2 = k,L2 y(k2)- 1 0 k2 x k,L2

~ 1 L2

_

1

L1

2) zo

L,=1,L2 Linear time invariant system

v(k)

y(k) _

h(k)

h(k - x)v(x) K=—W

L,=1,L2 =1 ,

Synchronous modulator 2nµk

v(k) °----®

y(k) = v(k)e-' 2nµk

-i ~ nn L,=M,L2 =M

V(zej =i) V(m:Ll)(z)

Here, zo is the ---domain variable referring to a sampling interval To . To is chosen such that all other sampling intervals are integer multiples thereof. For example T1 = (2 To, T2 = (',To and thus z1 = zo2 , z2 = zol with n. = god{L,, L2}, (r = Ll/n,f2 = L2 /n. As opposed to the polyphase matrix, the modulation matrix is highly redundant. It is determined completely by a properly chosen subset of only n of its elements [8]. For this reason we decided to implement our program package using modulation matrices for all internal calculations in M APLE, reducing computational load significantly in this way.

)=

L 22 ) L 1 W I 2 H L2 (z01 ) H (p:L2 x Ll )(1zo Pl e2 )D -'(z W

L2 )

Y(ze

~ Output

L2

V (ze~ 2L11 )

: V(ze~~il

Figure 3: Fundamental building blocks of multirate systems )~

Each multirate system is represented in MAPLE by a data

31

Symbolic Analysis of Multirate Systems

with the transfer function

structure

+oo ~` h( k)z —k

LPTV:=[L2,L1,MR,[Hl(z),H2(z),...,Hn(z)]]

with the blocking factors Ll and L2, a string MR describing the type of representation (for now only the modulation representation is implemented) and a list of n = gcd{L1, L21 irredundant transfer functions of the modulation matrix.

k= ~ L— oo

and the impulse response h(k) of the LTI system. The real ization in MAPLE is straightforward: > # H = transfer function of the LTI system > #

DOWNSAMPLER A downsampler by a factor of L1 with input signal v(ki) has an output signal y(k2) = v(Ll k 2). Obviously the output blocking factor is L2 = 1. From fig. 2 it can be seen that the polyphase matrix of the downsampler is

> LTI >

proc(H)

[1,1,MR,[H]];

> end: Hdöwn r ) (z) = [ 1 0 . . . 0 1 >

while the modulation matrix is given by H(m:lxt")(z) =

down

1

[ 1 1 ...

In multirate signal processing applications mainly filters with a finite impulse response (FIR) are used. Their output signal is given by N

1].

VI V Li

y(k) = E b,?) (k — v)

The modulation matrix of the downsampler is completely determined by gcd{Li ,11 = 1 of its elements. Therefore the downsampler is realized as follows:

V=0

resulting in the transfer function

>

E"-0 1N —vz A'

> DOWNS := proc(L1)

H(z)

=

[1,L1,MR,[1/sgrt(L1)]];

~

z

The calculation of the transfer function can be done with MAPLE using the following procedure:

> end:

ITPSAMPLER An upsampler by a factor of L2 increases the sampling rate of a digital signal by inserting L2 — 1 zeros between successive samples. Here, the input blocking factor is L1 = 1. Again the polyphase matrix of the system can be obtained from fig. 2. It is H(p:Laxl)(z) = [ 1 0 ... 0 ]T up while the modulation matrix is given by

> # b = filter coefficients b0 ... bN > # z = z-domain variable > FIR := proc(b,z) > local range,i; > > > >

# filter degree - 1 range := nops(b); sum(b[i+l]*z^(i),i=O..range-1)/\ z-(range-1);

> end: Hup:Laxl)(z) =

1[ 1 1

1 1T

L2

Functions for other frequently used LTI systems and digital algorithms can be added easily.

The upsampler is also characterized by one single transfer function. It is realized in MAPLE as > UPS := proc(L2) >

[L2,1,MR,[1/sgrt(L2)]];

The last fundamental building block we are going to describe is the synchronous modulator. The input signal of this system is multiplied with a periodic complex exponential and therefore the signal is shifted in frequency. We have

> end:

LINEAR TIME INVARIANT (LTI) SYSTEM Another important building block are linear time invariant systems (digital filters). By definition of time invariance we have Ll = L2 = 1. As a consequence, the polyphase matrix as well as the modulation matrix are given by H LTI xl)(z) — HI.TIlxl)

32

(z) = H(z)

y(k) = v(k)e —~ a

, µ E {0,1,...,AI/1 — 11

Y(z) = V(zejW).

Obviously, the blocking factors are identical here. It is L1 = L2 = 11. The polyphase matrix of this system is given by YIxM

H(mod

an,

) (z) = diag [1, e—i~,. .. , e

— ~ 2T~.(mr-]) M

Symbolic Analysis of Multirate Systems

The modulation matrix is simply the identity matrix rotated I.c columns to the right, e.g.,

H(m: L2 xL, ) (7) O

0 (M: 11r x,bl)

Hmod

(z) —

1

0 0

0

0

1

0 1

0 0 1 0 0 0

0

H (m: Lz xL, ) 1

for Al = 4 and It = 1. The realization in MAPLE is as follows:

H(m: L2 xL,) O

(Z) +

(Z)J

H~m: L2 :L,)(Z)

> MOD := proc(mindex) > # mindex = modulation index > MOD := proc(mindex) > local d,n,mi;

;:I H(Om: Leo xL„ ) ( Zo"zof io ) ~ HJ(,: L21 xLzo ) (ZOAzlf'2o )

> # convert modulation index > # into a rational number > mi convert(mindex,fraction); > n numer(mi); > d denom(mi); >

[d,d,MR,subsop(n+1=1,[O$d])];

Hm: L2i xL2o ) /_, n( zi~2o ) , H(m: L2o xLio )'(~~'2oeto 1 i 0 / i 0 0.

Figure 4: Parallel and serial connection of multirate systems (n = gcd{Lla, L20, Lei f, C„ = L„ ln)

> end:

The modulation index mindex= µAll has to be a rational number of course.

Connections ®f Multirate Systems As already mentioned it is possible to represent each synchronous mulfirate system as an interconnection of the above fundamental building elements (fig. 2). In most practical applications there are only parallel and serial connections between multirate systems. We therefore restrict to the analysis of these two types of connections (fig. 4) in the current version of the program. PARALLEL CONNECTION A parallel connection of N systems with modulation matrices H(m. L2 ' r') (z) has the modulation matrix ,v H(m: 7, 2,ri)(

\z/)



E Hvm:L2,.,Li~)(

It can be seen that these systems can only be connected if

L1 = L1, L 2„ = L2 holds for all their blocking factors. Frequently it will be necessary to expand some of the systems appropriately. We will deal with this topic later on. It should be mentioned that it is impossible to connect systems in parallel if the ratio L1 1L2 is not the same. The parallel connection can be done in MAPLE like this:

> >

# get first system mrsl := args[1];

# get blocking factors, assume # blocking factors to be identical L2 mrsl[1]; L1 := mrsl[2];

> > >

# get number of irredundant transfer # functions n := gcd(L2,L1);

> > > > > > > >

# accumulation for i from 2 to nargs do # next system mrs2 := args[i]; # add system mrsl :_ [L2,L1,MR,[seq(mrs2[4][i]+\ mrs1[4][i],i=l..n)]]; od;

> end: z ).

v_r

> SUM := proc() > local mrs2,mrsl,i,n,L1,L2;

> > > >

The parameter list of this procedure consists of the multirate data structures of the connected systems. Again we use the redundancy of the modulation representation and accumulate irredundant transfer functions only. SERIAL CONNECTION A serial connection of multirate systems means a multiplication of the respective modulation matrices. In contrast to the parallel connection some more requirements have to be fulfilled. For this reason we will only itemize these requirements here and give a simple example. For a serial connection of multirate systems we have the following conditions: + The output blocking factor of the first system and the input blocking factor of the next system must be the

33

Symbolic Analysis of Multirate

same. In terms of linear algebra the modulation matrices must have the correct format for a multiplication. Again, an expansion of the systems may be necessary. ®

The sampling intervals of all signals in the overall system must be integer multiples of a common sampling interval. We therefore have to find this common sampling interval and the corresponding z-domain variable for the whole cascade of systems. The realization in MAPLE simply requires a substitution of variables.

We implemented the serial connection of N systems as a procedure > Hmod:=MUL(HN,HN-1, ... ,H2,Hl);

where all variables are data structures of multirate systems Z1

Zo

t2

I 3 Z2

o

~(~o) z

3

2

z1 ~ ~0 9 ~2 — ~0

Figure 5: Example for a serial connection of multirate systems To illustrate the serial connection of systems let us consider a simple example (fig. 5). The modulation matrix of the composite system can be calculated by hand of course. Nevertheless, it is a painful job. After expanding the matrices appropriately, substituting the correct z-domain variable and multiplying the modified matrices we end up with I-I(m:2x3)l z ) =

2 ) H(ze~~) I v H(z) H(ze.— j :+ — ~ [ H(—z) H(ze'a ) H(ze i 3 ) ~ Compared with that the same calculation in MAPLE simply looks like this: > PrintLPTV(MUL(DOWNS(3),H(z),UPS(2)));

Our routine PrintLPTV ( ) calculates the modulation matrix from the internal representation and does the screen output. Unfortunately MAPLE designers seem to be of the opinion that ,F2v"3-/6 is the best representation of Furthermore complex numbers are always converted to a real and imaginary part. For this reason the result is not as pretty as it could be.

Expansion of Multirate Systems As we have mentioned above it is sometimes necessary to expand a multirate system and the corresponding matrices. The question is how this can be done without changing the system itself. First of all, it is important to expand both rows and columns by the same integer factor p. Since the modulation matrix is completely specified by n = gcd{L1i L2 I elements it is sufficient to consider only the first n elements in the first row of the matrix. This row relates the unmodulated output signal of the system to L1 modulated versions of the input signal. Obviously the output signal does not change if we use an input modulation vector with a p times smaller modulation step and insert zeros between the elements of the first row of the modulation matrix. This modified first row is sufficient to determine the whole expanded modulation matrix. In mathematical terms the new matrix is [S, 101 I-I(m:pL2xpT.I)(z) = P-1

H(m:L2x L1)

(zee p nflt2

—o where A 0 B = [akIB] denotes the Kronecker product. All elements of the matrix Ek i p are zero except element (k, l) which is 1. Again, we give our MAPLE implementation of this basic operation: > # mrs = multirate system > # N = expansion factor > ExpandLPTV := proc(mrs,N) local Hprotolist,Hexplist,n,k,L1,L2; > > > > >

# get L2 L1 n

blocking factors mrs[l]; mrs[2]; gcd(L2,L1);

> > >

# get list of irredundant # transfer functions Hprotolist := mrs[41;

> > > > >

# insert N-1 zeros into list Hexplist := [0$N*n]; for k to n do Hexplist:=subsop((k-1)*N+1=\ Hprotolist[k],Hexplist)

>

od;

> # expanded system >

34

pxp L''v,v

[L2*N,L1*N,MR,Hexplist];

°

Symbolic Analysis of Multirate Systems

I GO(z) HO(%1)

> end:

Example To illustrate the usage of our program package we will now show the automated analysis of a more realistic example (fig. 6). We are going to investigate a filter bank with three chapV(k)

G1(z) 111( °101)

3

H (z)

13 —'

°

1 2(q L ,) F '~3

_~

L i

G J.

Y(k)

~

+

3 G2( z ) H2( %1 ),

3 GO(z) HO(%2 ) -f

G1(z) H1(%2 )

3

+ 3 G2(z)H2(%2)

3

[3 GO(%ol) HO(z )

i

+—G1(%1)111(x) Analysis filter bank

3

Synthesis filter bank -I-

H°(z), GO(z): lowpass H1(z), G1(z): bandpass H2(z), G2(z): highpass

Coding, Transmission, Decoding

Figure 6: Example for a filter bank with 3 channels nels. It can be used for the subband coding and decoding of audio signals for example. The system consists of an analysis filter bank for the separation of three frequency bands and a synthesis filter bank for the recombination of the subband signals. In a real application the three frequency bands would be coded, transmitted, and decoded separately. Nevertheless, we will ignore this part of the system in our example. The MAPLE session for the analysis of the system is given below. First of all we calculate the modulation matrices of the three channels separately: > HLP:=MUL(GO(z),UPS(3),DOWNS(3),HO(z)):

> HBP:=MUL(G1(z),UPS(3),DOWNS(3),H1(z)):

> Hmod:=SUM(HLP,HBP,HHP):

We end up with the modulation matrix of the overall sys-

G2(%1) H2(z ),

+ 3 G1(%1 } 111(°Jol ) + 1

3 G2(°101)112(°701)

GO(%1)110(%2 )

3

1

G1( °10 1) Hl(°y 2 ) 3 1 + 3 G2(%1)112( °72 )~ +

GO(%2) HO(z ) [3 L +I GI( %2)H1(z)

+

3

G2(%2)H2(z),

3 GO( %2 ) HO(%1) + 3 G1( %2 ) H1( %1 ) +

tem:

> PrintLPTV(Hmod);

3

1 GO( (Xo1) HO(%1) 3

> HHP:=MUL(G2(z),UPS(3),DOWNS(3),H2(z)):

The filter bank is simply a parallel connection of its branches. The overall modulation matrix therefore is the sum of the respective modulation matrices:

1

3

1

3

G2(%2)112( °J 1), T

GO(%2) HO(%2 )

+ 1GI( %2)H1(%2)

~3 GO(z) HO(z) 1

+ 3 G1(z) H1(z)

1 +

3

G2(%2)H2(%2)~

1 1 %1:-- 2 z+ 2 Iz~

+ I G2(z) H2(z ),

%2:=—

1

2

z — I IzVr3_

35

Symbolic Analysis of Multirate Systems

Using our function TransFunc ( ) the relation between modulated versions of the input signal and the output signal

Biirequency plot of IHI in dB

is revealed:

> TransFunc(Hmod,V,Y); Y(z)=

+

GO(z)HO(z) 3 (1

3 G1(z)H1(z)

+3G2(z)H2(z) V(z)+ ~ 3 GO( z)HO(-2z+2lzf)

+3G1(z)Hll-2z+21z-A- 1 + 3 G2(z)H2I

V(z

-2 z+

2 1z~I I

C- 2 +2I~)/+\

3G0(z)HOI —2z— 2Izv73 -I +3G1(z)H11 —

2

z— 2lzf l

+3G2(z)H2I — 2z-21z ~) I VIz \ 2 2Iv~// Obviously, these results are not easy to handle. The cal-

culation by hand thus is extremely error-prone and time-consuming while the calculation with MAPLE only requires the input of a few commands. Furthermore, it is possible to visualize the results in a more vivid manner using the MAPLE graphics capabilities. We now substitute somewhat realistic filters for the transfer functions H„(z) and G„(z) and evaluate the resulting matrices at discrete frequencies. The modulation matrix then is plotted as a bifrequency transfer function depending- on the frequencies at the input and output of the filter bank (fig. 7). We developed FIR ( ) for the calculation of the filter transfer functions and P1otLPTV ( ) for the bifrequency plot. System designers are interested in keeping distortions low and therefore the cascade of analysis and synthesis filter bank should behave like a pure delay of the input signal ("perfect reconstruction"). In this case there would be only the main diagonal with a constant value of 0 dB in the bifrequency plot. In our example we use linear-phase filters of length N = 33 with a stop band attenuation of about 40 dB and a transition bandwidth of AQ = 0.121r. Furthermore we choose H„(z) = 3G„(z). Since these filters are not prop-

36

Figure 7: Bifrequency transfer function of the filter bank erly designed we have nonzero components on the other diagonals in the bifrequency plot as well. This effect is called aliasing in multirate signal processing. For example in audio applications these distortions are audible even at a very low level. That is why they should be avoided as far as possible. Our example is typical of a wide class of multirate signal processing applications, although most real systems are by far more complicated. Nevertheless, this example clearly shows that a calculation by hand is difficult and quite extensive even in very simple cases. As opposed to this, our analysis tool only requires the input of the system structure. The really hard part of the symbolic analysis then is done by MAPLE without further interference of the program user.

Concluding Remarks In this paper we introduced a new convenient tool for the automated analysis of multirate systems using the computer algebra program MAPLE. The program package is based on a new systematic matrix description of multirate systems that permits a very simple connection of those systems. It is therefore especially well suited for the automated analysis of arbitrary systems composed of multirate building blocks. This version of our program deals with hierarcoical connections of systems, i.e., it is not possible to implement feedback loops and recursive multirate structures. This is going to be one of the next extensions of our analysis tool. Another desirable extension is the investigation of stochastic processes. In complex digital systems we have noise-like distortions caused by noisy transmission channels, finite wordlength effects, and coding. Even realistic input signals such as speech and audio signals can only be described in terms of stochastic processes. For the analysis of all these interrelations, the calculation of correlation matrices

Symbolic Analysis of Multirate Systems

will be implemented. In this context, an enhanced version of our MAPLE tool would be very useful for the comparison of measurement results [I 1] and theoretical results based on simplifying assumptions. In conjunction with a systematic description of multirate systems, MAPLE is a powerful tool for the analysis of arbitrary multirate systems, In addition we develop a compiler for the automatic generation of MAPLE script files from a simple description of multirate systems. With this, we have a very easy to use program package for the analysis of multirate systems that does not require extensive programming. MAPLE SOURCE COKE All functions mentioned so far are part of our multirate analysis toolbox mrct . maple. The file pub/maple/mrct.maple can be obtained by anonymous ftp from ftp-nt.e-technik.uni-erlangen.de For further information see the README file.

Acknowledgements The authors thank Prof. Dr.-Ing. H.W. Schuessler for making this work possible and for his advice and helpful discussion in preparing this paper.

References [1] J. G. Proakis: Digital Communications, McGraw-Hill, New York, NY, 1989 [2] A. V. Oppenheim, R. W. Schafer: Digital Signal Processing, Prentice Hall, Englewood Cliffs, NJ, 1975 [3] R. E. Crochiere, L. R. Rabiner: Multirate Digital Signal Processing, Prentice Hall, Englewood Cliffs, NJ, 1983

[9] G. Runze: Symbolische Analyse von Multiratensystemen mit dem Computeralgebra-Programm Maple, Diploma thesis (in German), University of Erlangen, Erlangen, Germany, 1995 [10] R. G. Shenoy: Analysis of Multirate Components and Application to Multirate Filter Design, Proc. Int. Conf. on Acoustics, Speech and Signal Processing, pp. 111. 121-124, Adelaide, Australia, 1994 [11] F. A. Heinle, H. W. Schuessler: An Enhanced Method for Measuring the Performance of Multirate Systems, Proc, Int. Conf. on Digital Signal Processing, June 2628, 1995, Limassol, Cyprus, pp. 182-187

Frank Heinle received the diploma degree in electrical engineering from the University of Erlangen-Nuremberg, Germany, in 1994. He is currently pursuing a doctoral degree at the Telecommunications Institute of the University of Erlangen-Nuremberg. His interests include digital signal processing, multirate signal processing, and the analysis and measurement of implemented digital systems. Gerhard Runze is a student of electrical engineering at the University of Erlangen-Nuremberg. His diploma thesis is a major contribution to the MAPLE analysis tool. Runze is currently with the Telecommunications Institute of the University of Erlangen-Nuremberg. His interests include digital signal processing, computer graphics, and solar energy. Richard Reng received his diploma degree in electrical engineering from Munich University of Technology, Munich, Germany, in 1987. Since then he has been with the Telecommunications Institute of the University of ErlangenNuremberg. He is currently finishing his Ph.D. thesis on mulfirate signal processing. He is now with the Daimler-Benz Aerospace AG (DASA) in Ulm, Germany, working in the field of robust speech recognition.

[4] P. P. Vaidyanathan: Multirate Digital Filters, Filter Banks, Polyphase Networks, and Applications: A Tutorial, Proc. IEEE, Vol. 78, January 1990, pp. 56-93 [5] K. Nayebi, T. P. Barnwell, M. J. T. Smith: Time-domain Filter Bank Analysis: A New Design Theory, IEEE Trans. SP, Vol. 40 June 1992, pp. 1412-1429 [6] P. P. Vaidyanathan: Multirate Systems and Filter Banks, Prentice Hall, Englewood Cliffs, NJ, 1993 [7] M. Vetterli: A Theory of Multirate Filter Banks, IEEE Trans. ASSP, Vol. 35, March 1987, pp. 385-372 [8] R. L. Reng: Polyphase and Modulation Descriptions of Multirate Systems - A Systematic Approach, Proc. Int. Conf. on Digital Signal Processing, June 26-28, 1995, Limassol, Cyprus, pp. 212-217

37

Modeling Flexible Robots with Maple Jean-Claude Piedbmuf * Developing the equations of motion for flexible manipulators requires considerable effort, even for very simple systems. Obtaining a model free of error is even less obvious. This explains why programs generating the models of complex mechanical systems are so abundant and popular. In a 1989 survey, Schiehlen [1] recorded twenty of those programs. More recently the German Research Council has established a nationwide research project devoted to dynamics of multibody systems [2]. The goal was to develop a general purpose multibody system software package. Traditionally, models were generated numerically. In the last few years, there have been an increasing number of programs producing these models symbolically. These models are now more efficient from a computational point of view, which is important in real-time control and simulation. Moreover, the capability of having a symbolic model allows additional operations like linearization or optimization [3]. Symbolic modeling has also been applied to manipulators with flexible links. Different symbolic languages have been used: Macsyma[4, 51, Maple[6, 7, 8], Mathematica[9], and Reduce[10, 11]. Some authors create their own symbolic language, using for example, Pascal[12]. The complexity of the models varies, depending on which deformations (bending, torsion, elongation) are considered but all models of flexible links assume small deformations. The main difficulty in modeling a flexible link is the proper representation of the foreshortening [13, 141. This effect is included to some extent in the papers mentioned above, but only the references [13, 14] give a complete representation. This paper discusses some practical aspects of the symbolic development of the model of a flexible robot. Since a rigid robot is a simplified version of a flexible one, the material presented here is applicable also to rigid manipulators. A brief description of SYMOFROS (Symbolic Modeling of Flexible Robots and Simulation), a symbolic modeling package developed by the author, is given and illustrated with a simple example

Symbolic Modelingof Dynamic Systems ® Some Considerations Generating the equations of motion symbolically, playing with the various assumptions, or using and comparing different methods, is like a dream for dynamicists. However, *Department of Mechanical Engineering, Royal Military College of Canada, Kingston, Ontario, Canada, K7K 51-0. Tel: (613) 541-6000x6121, Fax: (613) 542-8612, e-mail:piedboeuf [email protected]. The SYMOFROS program was developed during a leave at the Canadian Space Agency, 6767 Route de 1' Aeroport, St-Hubert, Quebec, Canada, BY 8Y9.

39

symbolic software is not the panacea. Anyone dealing with symbolic computation has been frustrated by the difficulties of simplification and the huge amount of memory or computation time required. In principle, all dynamic methods should yield the same result if correct assumptions are made. Yet it is well known in robotics that the cost of different methods may differ considerably. While Lagrange's equations are easy to apply, they are also very costly in terms of the number of operations and memory size required. Other methods, like Newton-Euler or 3ourdain's principle (also known as Kane's equations) are more efficient. However, the memory required for generating closed form equations increases exponentially with the number of degrees of freedom. When dealing with flexible links, it is not uncommon to use tens of megabytes of memory. That problem is well known in robotics, and is the driving force behind the success of recursive methods. Recursive methods are applicable to symbolic modeling. To keep their efficiency, future substitutions of the variables must be prevented by saving and replacing them with temporary variables [8]. For example, suppose a double pendulum with o1(t) and 02 (t) , the angles with respect to the vertical of links one and two. The position of the endpoint is computed recursively as: > r1 := vector([L1*cos(01(t)), > L1*sin(01(t)),0]): > r2 := eva1m(r1+vector([L2*cos(01(t)), > L2*sin(02(t)),0]));

r2 := [LI cos(01 (t)) + L2 cos(02(t)), L1 sin(01 (t)) + L2 sin(02(t)),01 It is obvious that if other links are added, the complexity of the expressions grows quickly. The same solution which uses the procedure temp_var (given in the Appendix) for defining temporary variables, is: > > > > > >

r1 := vector([L1*cos(01(t)), L1*sin(01(t)),0]): r1 := temp_var(rl,true): r2 := eva1m(r1+vector([L2*cos(01?t)), L2*sin(02(t)),0])): r2 := temp_var(r2,true);

1'2 := [z-t3, z-t4, 0 ] The table of the temporary variables is: > print(Z_t); table([l = LI cos(01(t)), 2= L1 sin(01(t)), 3= z_tl + L2 cos(02(t)), 4= z-t2 + L2 sin(02(t))])

Modeling Flexible Robots with Maple

To prevent resubstitution of the temporary variables z_t into the equation, a capital Z_t is used to define the table of the temporary variables. The drawback of using temporary variables is that the equations are no longer in closed form. That complicates the proper linearization of the degrees of freedom related to the link's flexibility, as well as the linearization of the equations of motion around an operating point. In addition, the equations of motion have to be expressed directly in the following form: ( 1) M(q)4+9'(q,4,u) = fl with q a set of generalized coordinates and u the inputs. Some care must be exercised for the rules that define temporary variables. If temporary variables are defined for any expression, they will be redundant and numerous. On the other hand, if the rules are restrictive, there will be just a few temporary variables. Then the benefit of the recursive procedure is probably lost because the expressions will be too complex. Another difficulty is that, as usual in dynamics, the generalized coordinates are time dependent, q = q(t). While this does not cause a problem in languages like Macsyma, it creates difficulties with Maple. Indeed, Maple cannot differentiate with respect to a variable that depends on another variable. For example, assume: > f := sin(q(t)); Use di f f (f , q (t) ) to differentiate f with respect to q (t) results in an error. To obtain an answer, a substitution of q (t) by a dummy variable is required, prior to the differentiation. Then q (t ) has to be resubstituted in the re-

sult. For example, the following expressions give the correct answer: > f sin(q(t)); > df := subs(s=q(t), > diff(subs(q(t)=s,f),$));

All the functions relying on differentiation, like a Taylor series or the Jacobian evaluation, suffer from the same problem. A solution used by the author, is to rewrite these functions to have the required substitutions done in a way that is transparent to the user. For example, the following procedure lin (f , v, order) , is a modified mtaylor function for expansion around zero with variables in the list v having a time t ddpendency: lin := proc(f,v:list,order) # Inputs: f - an algebraic expression # v - a list of name # order - non-negative integer # The lin function computes a multi# variate Taylor series expansion of # the input expression f, with respect # to the variables v, to order n. # copyright Jean-Claude Piedboeuf 1995 local n, fl, f2, f3, i; readlib(mtaylor): n := nops(v);

f1 := subs([diff=Diff,seq(v[i] - _s.i,i=1..n)], eval(f)); f2 := subs([seq(Diff(_s.i,t) =_Ds.i,i=1..n)],eval(fl)); f3 := map(mtaylor,eval(f2), [seq(_s.i,i=1..n)1,order); RETURN (subs([Diff=diff,seq(_s.i = v[i],i=1..n), seq(_Ds.i=diff(v[i],t),i=l..n)], eval(f3))); end:

LINEARIZATION FOR FLEXIBLE COORDINATES In building the model, it is assumed that the generalized coordinates related to the flexible links and their first time derivatives are small (of first order). To have a model consistent with that assumption, all the second order terms of these generalized coordinates must be absent from the final equations of motion. The key to obtaining the right model is to linearize appropriately. Premature linearization results in a loss of important terms, while no linearization at all results in additional high order terms rendering the model improper. It is possible to linearize only the final equations of motion but this is costly in terms of computation because many useless terms will be calculated. The best approach is to adapt the linearization strategy to the modeling method used. For example, in Jourdain's principle, to obtain the Jacobian matrices exact to the first order, the linear and angular velocities should be developed to the second order, while all subsequent operations can be linearized to the first order. However, if the Jacobian matrices are developed recursively, then only the position and angular velocity of a beam section with respect to the beam's origin need to be developed up to the second order. This will generate the exact relative Jacobian matrices therefore, all other operations can be linearized to the first order. In Lagrange's equations, the kinetic and potential energy need to be exact to the second order. Hence, the absolute linear and angular velocities of each body must be exact to the second order. The elimination of second and higher order terms related to flexible generalized coordinates is easy when all the terms appear in the equations, as in closed-form. Languages like Maple provide tools for Taylor series expansion. When equations are defined in terms of temporary variables, as with recursive approaches, the linearization is more difficult. A solution is to separate the variables into zero, and first order parts and attach a flag to the first order part. For example, suppose that a vector r is defined as follows: > r:=vector([L*01(t) + phi_L*eta(t) > + 1/2*phi_L*eta(t)"2, 0,0]); The terms of order higher than two in eta (t) are first

eliminated. Then the zero and first order terms are separated, and a flag is attached to the first order part. The procedure

39

Modeling Flexible Robots with Maple

temp_var, used with an additional parameter, does exactly that: > r := temp_var(r,true,[eta(t)]);

r :_

[z_t1

-[- Or1 z-t 2i 0,01

with z_t [ 1 ] = L 01 (t) and z_t [ 2 ] = phi_L* eta (t) . Then, the subsequent linearizations are done using Or1 instead of the flexible generalized coordinates eta (t) .

Since the goal of symbolic modeling often is to produce code for simulation or real-time control, the efficiency of the equations is important. When a new temporary variable is created, there is no check to verify if a similar variable has been already defined. Therefore, it is useful to have a verification of the redundancy in the resulting equations to reduce the number of variables and then improve the efficiency. Moreover, in recursive approaches, many unneeded temporary variables are saved, since at the time they are saved, there is no way to know if they will be required in the final equations. When the equations of motion are obtained, it is important to look at all the expressions that should be written in the code, for example, the mass matrix .11/1 and the nonlinear vector g, to see which temporary variables appear. Then, starting from the end of the vector of temporary variables, all the unused terms are eliminated. This is easily done and can reduce the number of variables by more than half.

symbolic languages. However, the resulting programs are often oriented towards academic type problems, and the use of the generated C or Fortran code is not straightforward. Besides, a good model for simulation or real-time control is not simply the mass matrix and the nonlinear vector. It consists also of direct kinematics, Jacobian matrices for applying constraints, or of computing numerically the inverse kinematics, graphical output capabilities, linear model, etc. Figure 1 shows the general structure of SYMOFROS. This package can generate the symbolic model, write the C code model and simulate any system in serial chain. The bodies can be rigid or flexible, and the joints can have from zero to six degrees of freedom. For the flexible links, two bending and one torsional deformations are considered, and these deformations are assumed small. The model of a flexible link uses second order strain-displacement relationships, rendering the dynamic equations exact to the first order. SYMOFROS also offers options to control the assumptions and to decide how the model is generated. The complete theoretical development of the model is described in [13]. Penh aM File Naran #.md hhMklling Option, and Top i,lr al Oecmptinn

Linearization of the equations of motion around an operating point often is useful, but difficult to realize when the model is in a recursive form. This is because the generalized coordinates do not appear explicitly in the model, but appear as part of the temporary variables. Besides, a temporary variable z1,[n] depends not only on the generalized coordinates, but also on all the previous temporary variables: zt [n] = f (z t [lj, . .. , zt [n — 1], g, q) •

Swppe Ponc uns

MODELLING

Dalabaae

*.gen Frame, Body and Force Pammelers *.Par

Symbolic Model

Recursive Form

Options for Model *.~av

POINT

M A P La

SYMBOLIC

C CODE

GENERATO

Numerical Data

*.aal

Optimized C Code MATLAB Be

Matlabinterface

( 2)

C

mex

SIMUL.INK

COMPILER

Model in

~,mex

Then linearization of the model implies a recursive application of the chain rules differentiation. For example, the derivative of zt [n] with respect to q is: SimuleriunParememrs

azt[n]

nr -1 azt[n] azt [i]

dzt [n]

ag — u azt [2] aq + dq

IMULATION

l3) Simulation

Results

This section discusses the development of a program for symbolic modeling of manipulators with flexible links. The literature survey has emphasized the interest in dynamic modeling of flexible structures, and in applications of the

40

Figure 1: Overview of SYMOFROS Software The software is divided into two main parts: the model

~

Modeling Flexible Robots with Maple

generation and the numerical simulation. Any numerical package could be used for the simulation, but SYMOFROS includes an interface to generate Matlab mex-files and simulate using Simulink, a Matlab toolbox. Due to space limitation, only the general aspects of SYMOFROS are covered here. The interested reader can find a complete description in [15].

The model generation is in itself divided into two parts. The first part starts from a topological description of the system, and generates a symbolic model in recursive form. The second part takes that model and generates an optimized C code model using the numerical values provided. To generate a model of a given system, a user must first develop a simplified model, define the various bodies, assign the frames and obtain all the required data. The bodies can be rigid, flexible, or massless. There is one frame for each body in conformity with the model assumptions used in [13]. For a flexible body, some restrictions apply for the frame location. The required data consist of the frame, body, and force parameters. The frame parameters are the relative position vector and rotation matrix between each consecutive frames. The body parameters are the position vector of the mass center and the inertial properties. The force parameters are the external and the internal forces and torques between two consecutive bodies. The users must also choose the generalized coordinates which are divided as follows: qT — lq~ gs gf ~

with q,, the coordinates associated to rigid body motions, qe the coordinates associated with the motion due to the elastic joints, and q f the coordinates associated to the flexible links. The coordinates are divided in this way to easily isolate the contribution of the different system components. One can also assume small elastic motion and linearize in terms of

stituted. All the parameters that are unevaluated are passed automatically as parameters in the C code. A mechanism also enables the assignation of nominal values to the parameters. The different C functions generated by SYMOFROS are summarized in Table 1. All these functions are written in the same file to avoid a mismatch problem. Owing to the initialization function ini_syst, a model knows its own characteristics. Therefore, a generic simulation program can be built. For example, in Matlab, the same Simulink diagram is used to simulate an experimental three motors robots, or the seven motors space station manipulator. The C code generated by SYMOFROS is transparent for the user: i.e., the code is ready for compilation.

~:~~ 12A. As an example, the model of the experimental robot shown in Figure 2 is developed. This robot has three Harmonic Drive motors and two flexible links and the motion takes place in the vertical plane (gravity effect is taken into account). Figure 3 shows a simplified model using 8 bodies (the counterweight is combined with joint 1). Joint elasticity is assumed for the first motor while the two others are assumed to be rigid. Beams 1 and 2 are assumed flexible while all the other bodies are assumed rigid. The frames used to describe the system are also shown in Figure 3. SYMBOLIC MODEL As indicated in Figure 1, the inputs for the symbolic model part are divided into three files. The file * . mod is the "main" program and contains paths and problem name. For the robot under consideration, this file, named r3 e 1 f 2 , mod (r for rigid bodies, e for elastic joints, f for flexible bodies), is: # File r3elf2.mod: Paths and name # copyright J.-C. Piedboeuf, June 1995 restart; # Erase the memory # Definition of the paths to the various # programs required main path := 'd:/map/main/':

qe. For a flexible body, the number of modes considered for each deformation (v, w or (x) is required. With that number, the program will compute the relative position vector, the rotation matrix, as well as the position of the center of mass. The user must also provide the shape functions, that can be picked from an existing database or be user-defined. These functions can be piecewise defined, permitting spline, B-spline, or even finite element type functions. The body parameters for a flexible body are distributed ones; they are defined in terms of unit of length. The structural characteristics, rigidity and damping are also required.

For efficiency reasons, in the C code generation all the parameters that are provided with numerical values are sub-

ini_syst mod_nlin mod_lin sorties jacobiens repere repere_flex fct_forme

System initialization Nonlinear model Linear model Endpoint positions and velocities Endpoint Jacobians and their first time derivatives Homogeneous transforms for the equivalent rigid bodies Homogeneous transforms for the flexible links Shape functions and their first three space derivatives

Table 1: C Functions Generated Symbolically

41

Modeling Flexible Robots with

Counterweight

Motor 1

0, 1,2

+Joint 1

®' 3

-~i

ä

Beam 1

4

Payload 1

' t

Motor 2 6 ®7

Beam 2

Figure 2: A Robot with Three Motors and Two Flexible

7

Payload 2 e

Links Motor 3

# General purpose procedures symb_path := 'd:/map/flexi7/': # SYMOFROS procedures fct_forme—path := 'd:/map/flexi7/': # shape functions local_path:='d:/map/example2/': # Model name model := 'r3elf2'; # Call to the program that will generate # the symbolic model read cat(symb_path,'gen_mod.p');

The second file, * . gen contains the modeling options and the topological description. In the example, a recursive formulation with temporary variables is used. The recursive model is saved into a file and a linearization around an operating point is done. The system has three rigid coordinates, the motor angles, and one elastic coordinate, due to the elasticity in motor 1. To describe the flexible links second order strain-displacement relationships are used with two cubic 13Spline shape functions per link. The resulting r3 el f2 . gen file is: file r3elf2.gen: General parameters and topological description copyright J.-C. Piedboeuf, June 1995 Ecrit true; Use recursive formulation and temporary variables Name of the file to save the model '_r3elf2.m'; fic_modele_bin true; linearisation # Model linearization # TOPOLOGICAL DATA # Title to be written at the top of the C file Titre := Model of a planar robot with three motors,\n two flexible links and one elastic \n joint rotating in the vertical plane'; # The topological structure

# _________________________

42

Figure 3: Simplified Model

Body names Corps :['Motor 1','Joint 1','Beam 1', 'Payload 1','Joint 2','Beam 2', 'Payload 2','Joint 3']; Body types (r: rigid, f: flexible, # z: massless) [r,r,f,r,r,f,r,r]; Type_Corps # List of the generalized rigid # coordinates qr := [01(t), 02(t), 03(t)]:

# List of the generalized elastic # coordinates qe := [Okl(t)]: # List of the inputs liste entree := [Tml,Tm2,Tm3]; # DATA FOR THE FLEXIBLE LINKS Ordre := 2; # Order of the strain-displacement rel. # Number of modes retained to describe # the flexible links # For Body 3 nu[v,3] := 2: nu[w,3] := 0: nu[a,3] := 0: # For Body 6 nu[v,6] := 2: nu[w,6] := 0: nu[a,6] :=.P: # Files containing the shape functions 'phi_bsc2.dat'; fichier—phi[v,31 'phi_bsc2.dat'; fichier_phi[v,6]

The third file, * . par contains the interframe relationships, the body characteristics, the applied forces and some options. The interframe relationships consist of the relative position vector and rotation matrix between each two subsequent frames. Since bodies 3 and 6 are flexible, the relationships between frames 3 and 4, and 6 and 7 are complex. Therefore the user does not need to provide them the program will compute these relationships from the information about the flexible links (the order and the number of modes). The

Modeling Flexible Robots with Maple

body characteristics are the position of the center of mass and the inertial properties (mass and inertia matrix). It is also at this point that the reducer ratio and the rotor inertia are given (if different from 1). For flexible bodies, the information differs. The center of mass is not required (it will be computed by the program) and the body parameters are distributed ones. In addition, the length, the rigidities and the damping coefficient are required. The applied force part contains the gravity vector, the external forces on the frames, and the internal forces between two subsequent frames. It is in the relative forces that the motor, the damping and the elastic torques are defined. The options are the linearization list and the parameter list. The linearization list defined which coordinates are of first order. The parameter list contains all the undefined parameters. This list is passed to the C code generation to have an automatic declaration of the parameters in C. The actual file r3 e1 f 2 . par follows. In this file, _pr means "with respect to" and indicated with respect to which frame the vector is defined. _ds means "in" and indicates in terms of the unit vector of which frame, the model is described. # File r2elf2.par: # Parameters for the model # copyright J.-C. Piedboeuf, June 1995 # # # # #

FRAME INFORMATION, I.E., THE INTERBODY RELATIONSHIPS Relative position of the frames (F) (by default: vector(3,0)) F3 wrt to F2 r3-pr2_ds2 vector([r3x,0,0]): # F5 wrt to F4 r5-pr4_ds4 := vector([r5x,0,0]): # F6 wrt to F5 r6-pr5_ds5 := vector([r6x,0,0]): # F8 wrt to F7 r8-pr7_ds7 := vector([r8x,0,0]): # Position of the endpoint w.r.t. # the last frame re-pr8_ds8 := vector([rex,0,0]): # Rotation matrices between the frames # (by default: matrix(3,3,0)) # F1 wrt FO (rotation around z) RIO := Rz(Ol(t)): It F2 wrt F1 (rotation around z) R21 := Rz(Okl(t)): It F5 wrt F4 (rotation around z) R54 := Rz(O2(t)): # F8 wrt F7 (rotation around z) R87 := Rz(O3(t)): #k Rotation matrix of the endpoint frame # w.r.t. the last frame Re8 := eye(3): # Identity matrix 4 INFORMATION ABOUT THE BODIES # Position of the center of mass # (by default: vector(3,0)) # CoM body 2 wrt F2 rcm2-pr2_ds2:=vector([ejlx,0,0]): # CoM body 4 wrt F4 rcm4-pr4_ds4:=vector([eplx,0,0]): # CoM body 5 wrt F5 rcm5-pr5_ds5:=vector([ej2x,0,0]) # COM body 7 wrt F7 rcm7-pr7_ds7:=vector([ep2x,0,0]): # CoM body 8 wrt F8 rcm8-pr8_ds8:=vector([ej3x,0,0]):

# Inertial properties # Motor 1 # Inertia I_1[3,31 := J_r1: # Reducer ratio and rotor inertia Red[l] := r_1: Ir_1 := J_rl: # Joint 1 # Inertia in terms of body frame #instead of CoM frame Rep_MdI[2] = RdC: I_2[3,31 := J_jl: m2 := m-il: # Inertia and mass # Beam 1 # Distributed inertia and mass dI_3_ds3f[3,3] := Idmzl: dm3 := rhol: # Length, rigidity and damping Lcf3 := Ll: EIzc3 := EIzl: Kec3 := Ke1: # Payload 1 I_4[3,3] : = J_p 1 : m4 := m_pl : # Inertia and mass # Joint 2 I_5[3,3] J_j2: m5 := m_j2: # Inertia and mass # Reducer ratio and rotor inertia Red[5] := r_2: Ir_5 := J_r2: # Beam 2 # Distributed inertia and mass dI_6_ds6f[3,3] := Idmz2: dm6 := rho2: # Length, rigidity and damping Lcf6 := L2: EIzc6•:= EIz2: Kec6 := Ke2: # Payload 2 1-7[3,31 : = J_p2: m7 := m-p2 : # Inertia and mass # Joint 3 I_8[3,31 J_j3: m8 := m_j3: # Inertia and mass # Reducer ratio and rotor inertia Red(8] r_3: Ir_8 := J_r3: # WORKING FORCES AND TORQUES vg_ds0 :_ # Gravity vector in frame 0 vector([g,0,0]): # External forces # None # Internal forces # Motor 1 torque, damping (bl), # elastic (kl) Ml_pr0_ds0 := vector([O,O,Tml-bl* (diff(Ol(t),t)+diff(Okl(t),t))]): M2-pr1_dsl := vector([0,0,-kl* Okl(t)-bl*(diff(ol(t),t) +diff(Okl(t),t))]): # Motor 2 torque and damping M5_pr4_ds4 := vector([O,O,Tm2-b2*diff(O2(t),t)]): # Motor 3 torque and damping M8-pr7_ds7 := vector([O,O,Tm3-b3*diff(O3(t),t)]): OPTIONS List for the linearization of the nonlinear equation liste_lin :_ [op(dgf),op(gf),op(qe)]: List of the unevaluated parameters liste-param :_ [g,r3x,r5x,r6x,r8x,rex, ejlx,eplx,ej2x,ep2x,ej3x, r_l,J_rl,J_jl,m_jl, rhol,Idmzl,Ll,EIzl,Kel,J_pl,m_p1, J_j2,m_j2,r_2,J_r2, rho2,Idmz2,L2,EIz2,Ke2,J_p2,m_p2, J_j3,m_j3,r_3,J_r3,kl,bl,b2,b3]:

43

Modeling Flexible Robots with Maple

C MODEI, ®.ZENEiZATION Having obtained the symbolic model in recursive form, the C model can be generated. As indicated in Figure 1, only two additional files are required. The first one * . sav, gives the paths, the file names, the desired options and call the C code generator. The r3 el f2 . sav file corresponding to the example is: # File r3elf2.sav: Create C code # copyright J.-C. Piedboeuf, June 1995 restart; # Erase the memory # Definition of the paths to the various # programs required main_path 'd:/map/main/': symb_path 'd:/map/flexi7/': local-path :_ 'd:/map/example2/': # Initialization read cat(symb_path,'ini_say.p'); # SYMBOLIC MODEL fic_modele_j7in := '_r3elf2.m'; # SAVE THE MODEL Ecrit := true; # FILE TO SAVE THE MODEL fic_jnodele := 'r3elf2.c'; # METHOD TO GENERATE THE MODEL methode_recursive i= false; # NUMERIC OR SYMBOLIC MODEL evaluation_numerique := true; # DATA FILE FOR NUMERIC MODEL fic_donnee := 'r3elf2.dat'; # Generation of the C code read cat(symb_path,'savl.p');

The second file contains the numerical values of the parameters. All parameters that do not have a numerical value are declared in the C code and have a nominal value of zero. Parameters which have _nom added to their names are declared in C but their nominal values are determined from the data (for example, see the gravity parameter g). The data file r3elf2 . dat, corresponding to the example, is: File r3elf2.dat: Numerical data copyright J.-C. Piedboeuf, June 1995 Motor 1 # Rotor inertia (kg m"2) J_rl 8.66e-6: r_1 50: # Reducer ratio Joint 1 r3x := 3.65e-2: # distance between joint 1 and # beginning of link 1 (m) ejlx :_ -0.1029: # Position CM (m) m_j1 3.895: # Mass (kg) J_il 0.074: # Inertia (kg m"2) (including motor # and counter-weight around rotation # axis k2) bl := 0.2818: # viscous damping coeff. (N m s) kl := 2542: # joint elasticity (N m) Link 1 L1 := 0.521: # length (m) Idmzl := 1.0224e-6: # Distributed inertia (kg m"2/m) rhol 1.01936: # linear density (kg/m) EIzl 25.8017: # rigidity (N m"2) Kel 0.0001: # internal damping coeff. (s) Payload 1 r5x := 4.445e-2: # distance end link 1 to motor 2 (m)

M

3.56e-2: # position CM (m) eplx J_p1 : = 1 .2le-4 : # inertia at the CM - axis k (kg m"2) m-pl := 0.361: # mass (kg) # Motor 2 J_r2 1.99le-6: # Inertia rotor (kg m-2) r_2 50: # Reducer ratio # Joint 2 r6x := 6.7e-2: # distance between joint 2 and # beginning link 2 (m) ej2x 2.67e-2: # position CM (m) J_j2 1.29e-4: # inertia (kg m"2) # (including motor around CM - axis k) m_j2 := 0.192: # mass (kg) b2 := 0.0637: # viscous damping coeff. (N m s) # Link 2 L2 := 0.2731: # length (m) Idmz2 := 52.343e-9: # Distributed inertia (kg m-2/m) rho2 0.351917: # linear density (kg/m) EIz2 := 1.2769: # rigidity (N m"2) Ke2 0.0001; # internal damping coeff. (s) # Payload 2 r8x 3.4925e-2: # distance between end # link 2 to joint 3 (m) ep2x 2.6le-2: # position CM (m) J_p2 : = 2 .7le-5 : # inertia around CM (kg m"2) m_p2 := 0.161: # mass (kg) # Motor 3 J_r3 2.535e-7: # Inertia rotor (kg m"2) r_3 80: # Reducer ratio # Joint 3 ej3x 0: # position CM (m) J_j3 2.64e-5: # inertia including motor around CM m_j3 := 7.le-2: # mass (kg) b3 := 0.02: # viscous damping coeff. (N m s) # Extremity rex 0.051: # extremity w.r.t. the end of # flexible link (m) # gravity (left to be changed in C code) g_nom := 9.81:

The following file represents a sample of what is created by the C code generator. This file is ready for compilation and the simulation can be done directly using Simulink. /* Model of a planar robot with three motors, two flexible links and one elastic joint rotating in the vertical plane */ #include #include #include #include #define #define #define #define #define #define #define #define #define

"gen_mod.h"

NDDL 8 N_MEMBRURE NR_PHI 2 NC-PHI 4 DIM mates 36 DIM matH_f 8 N_PARAM 1 LN_NOM_PAR 1 N U 3

/* liste_param = (g) */ void mod_nlin (double *Mnl, double *gnl, double *X,\ double *U, double *param)

M

Flexible Robots with

double sl=O,s2=0; double *Tt_; double 9; g = param[0]; if ((Tt_ = malloc(sizeof(double) * 256)) == 0)( return;

Motor Min. vel. (rad/s) Stat. fric. (N/m) Dyn, fric. (N/m)

2

3

0.001 0.2 0.17

0.001 0.12 0.11

Table 2: Friction Parameters

O-01= Time

Indiallzepon

clock

}

1 0.001 0.49 0.42

Button 1

/* Number of operations 718*additions+955*multiplications+ 4*functions+1549*subscripts+ 328*assignments

Cominuous simulation of a feuh'onvnr~ ry~ c"mml with cmesi.m vnjahny

G~Pha Button 2

Tt_[0] = sin(X[1]); Tt_[5] = cos(X(1]); Mnl[0] = 0.22054853*Tt_[1]-0.1334509121*Tt_[2]\ Mnl(63] = 0.2676976849; Tt_[6] = cos(X[0]); Tt_(2551 _ -0.1230557010E1*Tt_[158]+... gnl[1] = Tt_[186]+Tt_[187]+Tt_(191]+Tt_[207]; gnl[7] _ Tt_[252]+Tt_(253]+Tt_(254]+Tt_[255]; free(Tt_); }

void ini_syst (double *dim_syst, double *dim _flex,\ double *val_nom, char *nom—par) dim_syst[0] = 8.0; dim _syst(8] = 1.0; dim_flex(0] = 2.0; dim _flex[11] = 6.0; strcpy(nom_par,"g"); val_nom[0] = 0.981E1;

Figure 4: Simulation of a Cartesian Trajectory with a Feedforward Control —0.1, 0.1 and 0 radian for motors 1, 2 and 3 respectively. The goal is to go to the point (x = 0.3 m, y = 0.3 m,) and from that point, trace a square with a side length of 0.6 m. The simulation diagram is shown in Figure 4. The control is a feedforward one based on the rigid model and using the joint information provided by the inverse kinematics. Friction compensation is added to the feedforward torques. A local PD control stabilizes the system on the trajectory and reduces the error. In this simulation, the control does not consider the flexibility. Therefore the endpoint error is important as shown in Figure 5.

} #include "dim mod.c" 0.

The C model generated is compiled with the Matlab interface to create a . mex file that can be used by Simulink. In fact, two models are generated, one for the control calculation and the other for the simulation. Here, the control model is simply the model of the equivalent rigid robot. It is easily obtained by assuming zero mode for each flexible link. In addition to the parameters described in the r3elf2 . dat file given above, a set of parameters (see Table 2) are used to describe the Coulomb friction in the motor reducers. All the parameter values given in the r3 el f2 . dat file and in Table 2 correspond to physical values measured on an experimental system that has been developed at Ecole Polytechnique de Montreal (Canada) [16]. The example used for the simulation is the following. The robot start from the position where the motor angles are

0_

Endooint Motion in x—v Plane: Cartesian Motion

Desired trajectory (_)

1

Simulated trajectory (--) 1

I

I

I -o.

I

I I

E x

i

I

-0. -o. ,

—1

Rtreemass:='intersect'(massset, Rtreeset);

Rt,reemass := { 1 } where 1 is the element number assigned to in. The corresponding R-cutset equation is:

The next step in mt3.ms is to eliminate cotree across variables that appear in the previous equations. For the pendulum, the T-circuit equations for the mass m, are generated in terms of accelerations. Substituting the terminal equations for h and r into these equations gives

> Rsubset:=submatrix(Rcutegns, > l..nops(Rtreemass), 1..1);

Rsubset, := [ TI — T3 -}- T5

which corresponds to equation (2), with the pin joint numbered 3 and the dependent torque numbered 5. Substituting the terminal equations for these various elements from Table

2 ß1(t)~ cos( 81(t))r2y

~(

—I

at

01(t)

sin (B1(t,)) r2y I

az

— 01( t )~ sin( 01( t, ) ) r2y ~~ atz

1,

L L

02 — JI (~tz 01(t)) -{- cos( B1(t,))r2yF2x

+sin(B1(t))r2yF2y1 which is the scalar form of equation (3). The next worksheet (mt2.ms) automatically generates the circuit equations for kinematic joints in the translational or rotational cotrees, projected onto their reaction space. The only cotree joint for the single pendulum is h in the R-graph, and its R-circuit equation in the Z direction is orthogonal to the XY plane containing the corresponding reaction forces. Thus, no constraint equations are generated by mtZms for the single pendulum. In mt3.ms, the force variables for rigid-arms are generated using the corresponding T-cutset equations. For the single pendulum, the scalar X components of the T-cutset equation for rigid-arm element 2 are > > > >

2

LHSx:= multiply(submatrix(TQ, startarm..endarm, 1..ncotree), submatrix(-Tthrux, ntree+l..ntree+ncotree, 1..1));

LHSx := [ Flx + F4a , with a similar expression resulting for the Y components. Substituting the terminal equations for mass 1 and the force element (weight) 4, the scalar components of F ,, corresponding to equation (4) are obtained: —m1

-it—, xl( t )~

( at 0 1(t) I

1 1

cos(01(t) ) r2y

J

which are the two scalar components of am appearing in the vectorial equation (5). The last step in mt3.ms is to substitute the expressions for rigid-arm forces and cotree across variables into the equations produced by nztl.ms and nztZms. Doing this for the pendulum example results in / z

~— JI j ~ 01( t )~ — cos( 81( t ) ) tz r2y m,1 (

a2

(

~t2 01(t,)) cos( B1(t.))r2y

z

—(

at

Bl(t)) sin( B1(t)) r2y~ +

sin( 01(t ) ) r2y (— m,1 (

02 01(t)~ atz ( +(at

sin( B1(t,))r2y

Bl(t)~

z Cos( 81(t))r2y~

— W4) J which simplifies to —J1

t )~ — W4 ~ —m,1 (äza Y1( t)

l z

~

+

(ätz

, B1(t)~ — r2y2 m,1

(ät2

01(t)~

— sin( B1( t) ) r2yW4 in agreement with the equation of motion (8). The Maple worksheet niN.ms assembles the equations from mt3.ms into a matrix form that facilitates a subsequent numerical solution. The projected circuit equations corresponding to equation (7) are differentiated twice with respect

W1I

Mechanical System Dynamics

to time (symbolically) to obtain: — ({$ }9{q})q{q} — 2{~}y+{q} — {f}tt

_ {r(q,4,t)1

(9)

where the subscripts q and t indicate partial derivatives with respect to { q } and t, respectively. These equations, and the projected cutset equations (6), are then assembled by mtl.ms into the alternative matrix form [~~~) {1)}q {4} _ {Q } {~}g [01 I { {a} } — { {r} }

vectors T3_8 are selected into the translational tree, as are the edges h14-18 representing the 5 pin joints. The slider joint elements -910_20 are selected into the rotational tree, which is completed by the selection of mass elements m,0, m il , and 17112. Note that the dependent torque drivers have been left out of the rotational graph, for clarity.

(lo)

which can be solved numerically using a combinats-)n of linear algebra routines and ODE integration algorithms.

Quick-Return Mechanism Shown in Figure 3 is a quick-return mechanism which transforms a uniform rotational speed of the crank BC into a translation of the slider at E to the left (the forward stroke), followed by a rapid return of the slider to the right. In this example, the crank is assumed to be driven by a time-varying torque T, while a resisting force F acts on the slider at E. This example has been chosen to demonstrate the applicability of the Maple procedures to a mechanism with multiple closed kinematic chains. Figure 4: Translational Graph of Quick-Return

11

Figure 3: Quick-Return Mechanism The translational and rotational linear graphs of the quick-return mechanism are shown in Figures 4 and 5, respectively; the individual bodies are drawn in dotted lines and the edges comprising the two trees are shown in bold. The ground-fixed position vectors R, —2 and body-fixed position

52

The only unknown variables resulting from this tree selection are 09, 811, and 812 , which constitute the generalized coordinates in which the equations of motion will automatically be formulated. Since the mechanism has only one degree of freedom, these 3 coordinates will be related by 2 algebraic constraint equations corresponding to the 2 slider joints left out of the translational tree. Thus, the total number of DAEs resulting from this tree selection is 5. To generate these DAES using the four Maple procedures, an input worksheet is created that contains symbolic parameters and a topological description of the system. From this information, the complete set of cutset and circuit equations are automatically generated for subsequent use by mtl.ins to mN.ms. Due to space considerations, only the relevant results from these four worksheets are presented here. Since the only tree elements that have non-zero motions associated with them are m,s, 7n11, and m12 in the rotational graph, the first worksheet mtl.ms generates the Rcutset equations for these three masses: > Rsubset:=submatrix(Rcutegns, > 1..nops(Rtreemass), 1..1);

Rsubset. :_ [T9+T10+T15-I-T16+T17+T23+T24

Mechanical System Dynamics

ht4

S;

h 95

where 13 to 18 are the lengths of the rigid-arm elements, s19 is the time-varying displacement of the corresponding slider joint, and Tapp represents the applied torque on the crank. As was noted in the pendulum example, the circuit equations corresponding to pin joints h14 to hla in the rotational cotree are orthogonal to their corresponding reaction space. However, such is not the case for the slider joints 310 and s20 in the translational cotree. As a result, the second worksheet mt2.ms generates the translational circuit equations for these two joints, projected in the direction of the corresponding reaction forces (i.e., normal to the axes of sliding). To begin, one T circuit equation is generated for each slider. The X components of these equations are stacked together to produce: > cotreesliderx:=multiply(submatrix(Tcir, > startslider..endslider, 1..edges), > -Tacrossx);

cotreesliderx := [d2x-d3x+d7.T-d8x+d16T-d17.z-d18.r,

Figure 5: Rotational Graph of Quick-Return

+ T29] [TII —T17+TI8+T22+T27+T28] [ T12 — T14 — T15 + T25 + T261 where T23 to T29 represent the dependent torques corresponding to the 6 rigid-arm elements and the slider element s10. After substitution of the terminal equations from Table 1, these R-cutset equations become:

a2 a2 [— J9 ( ßt2 09(t) — J10 ( ate Olo(t )) —sin(09(t))13F3x+cos(09(t))13F3y + sin( 09(t) ) 14 Fox — cos( 09( 0 ) 14 Foy

— s19 F191 — ill

with an analogous expression for the Y components of these two equations. To project these circuit equations normal to the slider axes defined by the user, the X and Y components of the unit vectors in these normal directions are generated: > N.(sliderset[i]).x:=-U.(sliderset[il)[2,11; > N.(sliderset[i]).y:=U.(sliderset(i])[1,1];

N19x := —sin( 09 ) N19y := cos(09) N20x := 0

N20y := —1 2

r

— d19x] [dIx — d2x + d3x — d4x — d5x + d6x — d14x + d]5x — d16x — d20x]

ate 011(t) J + Tapp

—sin(011(t))17F7xl +cos(011(t))17Fly +sin(811(t))18F8x—cos(011(t.))18F8y J / 2

[— J12 I ßt2 012(t)

+ cos( 012(t)) 15 F5x

l+sin(01\2(t))15F5y — cos(012(t) ) 16 F6x — sin( 012(t) ) 16 F6y]

The dot products of the T-circuit equations with the normal unit vectors are then taken, giving the set of two equations calledTeirslid,er:

Tcirslider l ,, := —sin(09) d2x + sin(09) d3x — sin( 09) d7r, + sin( 09) d8x — sin( 09) dl6x + sin( 09) d1 ix + sin( 09) d18x + sin( 09) d19x + cos( 09) d2y — cos( 09) day + cos( 09) d7y — cos( 09 ) d8y + cos( 09) dl6y — cos( 09) dl7y — cos( 09) d18y — cos( 09) dl9y

53

Mechanical System Dynamics

2'cirsl,ider 2 , 1 := —d1y + d2y — d3y + dlt y + d5y — d,6y + d14y — d15y + d16y + d20y Upon substitution of the corresponding terminal equations, the final form of the constraint equations (7) is obtained: > print(Tcirslider);

[sin( 09 ) cos( 011) 17

Note that the two constraint equations generated by tnt2.ms do not require the elimination of intermediate variables, since only the three generalized coordinates appear in these equations. Such is not the case for the R-cutset equations generated by mtl.ms, which must be further processed by the worksheet mtl.ms. This worksheet begins by generating the rigid-arm forces using the corresponding T-cutset equations, into which the terminal equations are substituted. The resulting X components of these 6 forces are

+ sin( 09) cos( 011) 18 — cos( 09) 12

— cos( 09) sin( 011) 17 — cos( 09) sin( 011) 18] [—l1 — 12 + sin( 09) 13 + sin( 09) l/r + cos( 012 ) 15 + cos( 012 ) 16]

[— MO ~atz x9(t)~ — m12 (~tz x12(t)~ —%1

— F19 sin( 09( t) ) + F21xopp z

Note that the T-circuit equations are also projected onto the slider axes themselves in order to obtain analytical expressions for the slider displacements s19 and 520.

]

Im.12 (atz x12(t)~ +%1 — F2lxapp~ [ %1 — F21 xapp ] z x12(t)~ — %1 + F21xapp~ [—m,12

~atz

[— m10

(Ytz

x10(t)~ — m11 ( 7 X11(t)~ t

+ F19 sin( 09( t) )] z sin( 99( t) )I ~tz x10( t)~ — F19 ( / a2 %1 := m13 1 atz x13(t, )~ [m10

with analogous expressions produced for the Y components. These scalar expressions are then substituted into the Rcutset equations Rsubset, in order to eliminate the rigid-arm U

U.L

U.4

U.ti

U.ö

1

1.2

Time (s)

Figure 6: Kinematic Response of Quick-Return At this point, the quick-return nature of the mechanism can be easily demonstrated by performing a kinematic analysis for a constant angular speed of the crank. To do this, the 2 constraint equations just obtained are supplemented by the driving equation: 011 = 0.4356 + 47rt

(11)

corresponding to a crank speed of 47r rad/s. The link lengths given in [3] were entered into these 3 nonlinear algebraic equations, which were solved numerically using MATLAB for 2 complete crank cycles. The X position of the slider at E (i.e., s20) is plotted versus time in Figure 5, which clearly shows the forward "working" stroke being followed by a relatively quick return stroke.

54

forces: > for i from 1 to rowdim(Rsubset) do > for j from 1 to nrigidarms do Rsubset[i,1]:=subs( > F.(rigidarmset[j]).x=LHSx[j,1], > > F.(rigidarmset[j]).y=LHSy[j,1], > Rsubset[i,1]); > od; > od;

In a similar manner, the across variables for masses in the T-cotree are eliminated by substituting the corresponding T-circuit equations into Rsubset. Finally, the R-circuit equations for masses m,10 and m13 in the R-cotree are generated and used to eliminate 010 and 013 from Rsubset. If the cotree velocities or accelerations are also present, then analytical derivatives of the R-circuit equations are used to eliminate these intermediate variables. The final output from w3.ms is a set of five DAEs of the form given by equations (6) and (7), expressed solely in terms of the three generalized coordinates and the unknown magnitudes F19 and F20 of the two slider

Mechanical System Dynamics

reaction forces. These DAEs have been checked and verified against a hand derivation of the same equations. The last worksheet mt4.ms assembles these DAEs into the matrix form given by equation (10) after using Maple's built-in differentiation functions to compute f r and the Jacobian matrix f D f 9. Although the complete set of equations is too lengthy to show here, some insight into the nature of these equations is obtained by examining the structure of the 5 by 5 coefficient matrix: ~9

Rsubset[l,1] Raubset[2, 11 Rsubset,[3, 1]

910 912 X 0 X

F19

F20

X X 0

X 0 X

X 0 X

0 X 0

Jacobian[l, l]

X

X

0

0

0

Ja.cobia,n.[2,1]

X

0

X

0

0

where X signifies an entry in that position. The coefficient matrix is symmetric, as expected, and almost half of the entries are zeroes. In spite of this, Maple has a difficult time computing an inverse to this matrix in an attempt to obtain a symbolic solution for the generalized accelerations and reaction forces. Thus, Maple-optimized Fortran expressions for the coefficient matrix and right-hand side column matrix, formed by stacking f Cif and f F J are exported to a file for subsequent solution by an appropriate numerical method. Before leaving this example, it is important to consider the fact that only 5 DAEs were generated for this relatively complex mechanism. In contrast, use of the popular set of absolute coordinates [3, 7] would result in 15 differential equations (3 coordinates for each of the 5 rigid bodies) and 14 algebraic equations of constraint (2 for each kinematic joint), for a total of 29 coupled DAEs. Even the more efficient set of joint coordinates [1] would result in 9 DAEs (5 joint variables related by 4 loop closure constraint equations), almost twice as many as that obtained above. Thus, the Maple implementation of our graph-theoretic formulation, combined with an intelligent tree selection scheme, automatically generates a relatively small system of equations for this example.

Conclusions A procedure that combines Maple and graph-theoretic methods to automatically generate the equations of motion for planar mechanical systems has been presented. As demonstrated by the two examples, the use of linear graph theory and a suitable tree selection scheme results in a reduction in the number of final DAEs, as compared to more traditional absolute or joint coordinate formulations. The Maple procedures are applicable to systems with a variety of common mechanical components, and containing both open and closed kinematic chains.

There are many advantages to using Maple to implement the graph-theoretic formulation. First of all, significant insight into the structure and nature of the governing DAEs is provided by their symbolic form. This is important for both pedagogical reasons and further development of the algorithms. The object-oriented nature of Maple corresponds well with the physical structure of a multibody system; this leads to procedures that are easier to understand (and modify) by a user, as well as a clear distinction between the linear topological equations and nonlinear terminal equations. The Maple code was relatively easy to develop as compared to a purely numerical implementation [3], especially when one considers the fact that expressions for the first and second derivatives of constraint equations have to be hard-coded into a numerical algorithm; by using Maple's built-in differentiation functions in our symbolic approach, the number of lines of code (and corresponding programming effort) was greatly reduced. Finally, numerical solutions can be generated more quickly [10] for the symbolic equations of motion than for their numerical counterparts, which usually involve many evaluations of multiplications involving 0 or 1. Currently, the authors are working to further increase the automation and range of application of these Maple procedures, as well as the amount of equation reduction that is performed. The latest version of the complete code is available upon request to either author.

Acknowledgments Financial support of this research by the Natural Sciences and Engineering Research Council of Canada is gratefully acknowledged, as is the skillful preparation of the figures in this paper by Mr. Layi Oshinowo.

[1] P. Capolsini, The Use of Maple for Multibody Systems Modeling and Simulation, Mathematical Computation with Maple V.• Ideas and Applications, Tom Lee, editor, Birkhäuser, Boston, pp. 109-117, (1993). [2] M. Fayet and F. Pfister, Analysis of Multibody Systems with Indirect Coordinates and Global Inertia Tensors, European Journal of Mechanics A/Solids, 13, no.3, pp. 431-457, (1994).

[3] E. J. Haug, Computer-Aided Kinematics and Dynamics of Mechanical Systems, Allyn and Bacon, (1989). [4] R. L. Huston, Y.S. Liu, and C. Liu, Use of Absolute Coordinates in Computational Multibody Dynamics, Computers and Structures, 52, no. 1, pp. 17-25, (1994). [5] H. E. Koenig, Y. Tokad, and H.K. Kesavan, Analysis of Discrete Physical Systems, McGraw-Hill, (1967).

55

Mechanical System Dynamics

[6] J. J. McPhee, On the Use of Linear Graph Theory in Multibody System Dynamics, Journal of Nonlinear Dynamics, vol.9, pp.73-90, (1996). [7] J. J. McPhee, Formulation of Multibody Dynamics Equations in Absolute or Relative Coordinates Using the Vector-Network Method, Machine Elements and Machine Dynamics, ASME DE-Vo1.71, pp. 361-368, (1994). [8] J. J. McPhee, Automatic Generation of Motion Equations for Planar Mechanical Sysstems Using the New Set of "Branch Coordinates", submitted to Mechanism and Machine Theory, (1995). [9] W. Schiehlen, editor, Multibody Systems Handbook, Springer-Verlag, (1990). [10] Various authors, Special Session on Symbolic Analysis, Proceedings of the Canadian Congress of Applied Mechanics, Victoria, B.C., pp. 940-949, (1995).

John McPhee obtained his Ph.D. in Mechanical Engineering from the University of Waterloo in 1990. After spending two years as a NATO/NSERC Postdoctoral Fellow at the University of Liege, Belgium, and Queen's University, Canada, he returned to Waterloo as an Assistant Professor in Systems Design Engineering. His teaching and research interests include linear graph theory, symbolic analysis, advanced dynamics, automated design, and applications in the fields of vehicle dynamics, flexible multibody systems, and mechatronics. He is currently a member of the Executive Council of the Canadian Committee for the Theory of Machines and Mechanisms. Cari Wells is an M.A.Sc. student in the Department of Systems Design Engineering at the University of Waterloo. Her research interests lie in the areas of graph-theoretic analysis of mechanical and bio-mechanical systems.

56

Using Gröbner Bases in Kinematic Analysis ®f Mechanisms ®scar E. Ruiz S. and Placid M. Ferreira* ITA .MIt .~_ , . ~ ~ ~ The Geometric Constraint Satisfaction or Scene Feasibility (GCS / SF) problem consists of a basic scenario containing geometric entities, whose context is used to propose constraining relations among still undefined entities. If the constraint specification is consistent, the answer to the problem is one of finitely or infinitely many solution scenarios satisfying the prescribed constraints. Otherwise, a diagnostic of inconsistency is expected. The mathematical approach, previously presented in other publications, describes the problem using a set of polynomial equations, with the common roots to this set of polynomials characterizing the solution space for such a problem. That work presents the use of Gr6bner basis techniques for assessing consistency and redundancy of the constraints. It also integrates subgroups of the Special Euclidean Group of Displacements SE(3) in the problem formulation to exploit the structure implied by geometric relations. In this article, the application of the discussed techniques to kinematic analysis of mechanisms is illustrated by an example. It is implemented using MAPLE's routines to manipulate polynomial ideals, and calculate their Gr6bner Bases. GCS / SF underlies a number of problems in CAM / CAM / CAPP areas, for example, fixturing, assembly planning, constraint-based design, tolerancing and dimensioning, kinematic analysis, etc. Therefore, it is evident that a strong theoretical and practical background satisfying geometric constraints is crucial in CAD / CAM / CAPP. Topology and Geometry are two interdependent aspects of GCS / SF although they have often been treated independently. Topology deals exclusively with the connectivity and nature of the spatial relations between entities. Geometry refers to the distances and directions that parameterize these relationships. Topologically, this work will address constraints which can be expressed as algebraic equalities [10]. Geometrically, it is restricted to zero curvature (points, straight lines and planes) proper subsets of E3 . LITERATURE SURVEY Solving GCS / SF implies the ability to: (i) instance entities (or produce configurations) which satisfy the given constraints, (ii) identify a redundant constraint, (iii) identify an inconsistent set of constraints, and (iv) determine the degrees of freedom between several entities. These requirements *Department of Mechanical and Industrial Engineering, University of Illinois, Urbana-Champaign,[email protected]

immediately preclude the application of purely numerical techniques. In current literature, GCS / SF has been approached from the areas of group theory (Nerve [51) and kinematics and mechanisms (Angeles [2]). Therefore, the terms (trivial) constraint, joint and group are used interchangeably in the discussion. Popplestone et al [1, 91 formalized GCS / SF in the form of equations of unknown positioning matrices. They also explored the application of finite groups in situations involving symmetries such as arrays, hexagonal pieces, mirror arrangements, etc. Based on Herve's formalization, Thomas, Torras and Celaya in [12] attempted the topological reduction of constraint networks. Limitations of this work are the topologyonly treatment, and the type of constraints (trivial) that it considers. Its contribution is the methodology proposed to state the (geometry and topology of) GCS / SF in terms of the SE(3) group. In [10], Ruiz & Ferreira formulated the GCS / SF problem as one of determining the solution space of a set of polynomials, using Gr6bner Bases to characterize the solution space using [7]. The method allowed for the integration of geometric and topological reasoning, and the efficient group theoretic formulation of Herve. This article illustrates how Algebraic Geometry ([3, 6, 7]) and Group Theory ([5, 12, 2]) can be applied to the specific area of Kinematic Analysis. For that purpose, section 2 presents a summary of the necessary background. Section 3 directly relates GCS / SF to Kinematic Analysis. Section 4 discusses the specific example of the Oldham mechanism. Section 5 briefly presents relevant conclusions, while Appendix A presents the MAPLE script used to analyze the Oldham coupling.

Background ALGEBRAIC GEOMETRY AND THE G,CS / SF PROBLEM The GCS / SF problem takes place in a world W, with a set of relations R. If a set of entities S = Iei, .., e„ } satisfies the constraints, it is said that S is feasible for W and R , and this fact is written as S = feasible(W,R). If the polynomial form of the problem is F = { f l , f2 i .., fn } with fi polynomials in variables xi , x 2 , ... ,.r, n , it is said that F = poly-f or (W, R). Since S is a solution for F, it is denoted as S = solution(F).

57

PPI

Using Gröbner Bases in Kinematic Analysis of Mechanisms For the purposes of this paper, the calculation of the Gröbner Basis of a set of polynomials F can be regarded as a black box procedure whose result, GB (F), an alternative set of polynomials, has several important properties. The properties allow us to draw the following propositions ([6, 7]): 1. S = solution(F) iff S = solution(GB(F)). In the context of GCS / SF, this implies that GB(F) and F describe the same scene, although GB(F) presents properties useful in the solution process. 2. 1 E GB(F) => S = solution(F) = b

This property implies that finding "1" or a constant polynomial in GB(F) implies the equation "0=1" leading to the fact that F has no solution. 3. F is Zero-dimensional iff F (and GB(F)) has a finite number of solutions. The zero-dimensionality of I can be assessed: A variable x is non-instanced if it does not appear as head(p) for any polynomial p E GB(F) (p = X d + t,ail(p), d E N). 4. Let a new constraint be represented by polynomial f. f is redundant to F (1 (E GB(F U {y.f — 11)) for a new variable y. It establishes that the satisfaction of the new constraint f is unavoidable when the initial set of constraints is satisfied. 5. GB(F) (based on a lexicographic order x r >- X2 >X3 ... >- x,) is a triangular set in the sense that GB (F) contains polynomials only in x r , some others only in Xi, X2, and so on, making the numerical solution a process similar to triangular elimination. The theoretical framework for the solution of GCS / SF can be summarized in the following procedure [10]: In the event of the addition of new constraints to the scene, they are converted into polynomial(s), tested for redundancy (Proposition 4), consistency (Proposition 2) and finiteness of number of solutions (Proposition 3). If the new constraint is redundant, it is ignored (Proposition 4). If the ideal has become zero-dimensional a triangular Gröbner Basis under a stated lexicographic order is extracted and solved (Proposition 5). Proposition 1 is the underlying basis of the procedure, since it establishes that the GB(F) faithfully represents F. The use of a group-theoretical approach to express GCS / SF is explored next. It will provide (i) a direct relation between degrees of freedom and variables, and (ii) a smaller formulation of the problem. GROUP-THEORETIC FORMULATION FOR THE GCS / SF PROBLEM This section examines the modeling of GCS / SF by using the canonical form of conjugation classes developed by Herve [5] and the application of his work by several authors

58

(refs [2, 10, 12]). The set of Euclidean displacements in 31), SE(3), is a (non commutative) group [8] with the composition operation (o). SE(3) presents subsets which are groups themselves, and which express certain common classes of displacements. They are called subgroups. For example, the subgroup of the rotations about a given axis a in the space, Ru, is a subset of SE(3), and a group itself. A list of the subgroups of SE(3) and their canonical representation [5], as well as their degrees of freedom is shown in Table 1 1 . For example, "rotations" are all transformations of the form

Ru(H) = B.R,B —i = B.twi:r,(B).B —r The displacement B E SE(3) represents the geometric part of a particular constraint, while the canonical part (Ru) contains the topological information. Using this methodology, the contact constraints appear in Table 2. For example, a P — ON — PL11% relation confines a point to be on a plane, therefore configuring a 5-dof constraint 2. These (matrix) equations produce the polynomial form of GCS / SF. GCSISF is stated as a series of constraints Ri relating Fir with Fi2 as shown in Figure 1 (corresponding to a two body system), where Fij is the ith feature of body Bj. The RiO constraints are as dictated by Tables 1 and 2. Body Br (in this case) contains two features, F11 and F21. B,, contains F12 and F22 . The goal is to find a final position of Br (assuming B2 stationary), such that Fri relates to F12 and F21 relates to F22 satisfying the invariance dictated by Rr (} and R2 ) respectively. The equations expressing the facts above are: B1.FIi .R1 O = B2-F12 ; B1•F'2i•R2O = B2-F22 (1) The above procedure can be generalized to larger systems. The solution and interpretation of Equation I follow the constraint management procedure discussed in the last section [10, 5, 10].

The GCS / SF Problem in Design and Analysis of Mechanisms GCS / SF and Kinematic Analysis of Mechanisms are related since kinematic joints are constraints on the relative position of entities. A solution for GCS / SF is a physically realizable configuration of kinematic links. Continuous regions of the solution space for GCS / SF directly map to the possible motion (degrees of freedom) of the mechanism. 1 I this table, twix(B) means a rotation about the X axis by 0. XTOY means a rotation by 900 about the Z axis. trans(x, y, z) indicates a general spatial translation. 2 Points are in the origin of their attached frame. Lines coincide with the X axis of their frame. Planes coincide with the Y-Z plane of their attached frame.

Using Gröbner Bases in Kinematic Analysis of Mechanisms

Table 1: Conjugation Classes and their Canonical Forms Dof I Symbol

Conjugation Class

I

Canonical Subgroup

1

R,,

Rotations about axis a

{twix(B)}

1

T.

Translations along axis u

{traceas (x, 0, 0)}

1

H,,, p

Screw movement along axis u, with pitch p

{trans(x, 0, 0).twix(px)}

2

Cu

Cylindrical movement along axis u

{trans(x, 0, 0).twix(B)}

2

Tp

Planar translation parallel to plane P

{trans((), y, z)}

3

Gp

planar sliding along plane P

{trans(O, y, z).t,7vix(B)}

3

So

Spherical rotation about center "o"

{twix(?P).XTOY.twix(o).XTOY.twix(B)I

3

T

3D translation

{trans(x, y, z)}

3

Y,,,p

Translating Screw axis v, pitch p

{trans(x, y, z).twix(px)}

4

X„

3D translation followed by rotation about v

{trans(x, y, z).twix(B)}

Table 2: Entity Relations in the Form of Kinematic Joints macro

joint chain

kinematic joints in chain

dof

P-ON-P P-ON-LN P-ON-PLN LN-ON-LN LN-ON-PLN PLN-ON-PLN

S T o So Tp o So C

spherical linear translation, spherical planar translation, spherical cylindrical planar translation, revolute planar translation, revolute

3

Tn o R o R,,, Tp o R

4 5 2 4 3

59

Using Gröbner Bases in Kinematic Analysis of Mechanisms

Body 2

Body 1, Position 1

R1( )=T(xl,yl,zl

). Rot(61,eI,yr1

)

z

F22

x

~

~

B2 R2O=T(x2,y2,z2).Rot( 92,~2,t12 )

Body 1, Position 2

Body 2

Figure 1: Two Body Example of Canonical Variable Modeling of the GCS/SF Problem

~

BO

F13

IO

R3

R2

~

B2 R4

~

~OF11

F12

\

F22

x

Y

O Q

m~

F23 F20 ~

13

,

.

L8-L11 L11

RI

\

bodynode originframe

feature frame Positioning arc

2

Y

F2l

~

B1 63

F10

- a,d 1.

gp

>

2

3 consVaint arc

® n

/ L7

L3+L1 L12

Figure 2: Piece Disassembly and Spatial Constraint Graph of Oldham Mechanism

The Spatial Constraint (SC) graph (see Figure 2), conveys the topological and geometrical information of GCS / SE It is suitable for the computer generation of the equations governing the scene and allows the identification of subproblems which help in GCS / SF by allowing the application of preprocessing techniques [11]. Conventions: Since entities are represented by frames, the terms entity and frame are equivalent. In the SC graph the nodes are entity frames (Bj and FZ j ). The are between two nodes represents the displacement that relate the corresponding entity frames. There are three types of nodes: nodes Bj which represent the origin frame of a body in the World Coordinate System, feature nodes Fij which represent the feature i in body Bj and body nodes include the origin frame of the body and its features. Conceptually, there are two types of arcs: positioning and constraint arcs. Positioning arcs represent known relative positions of features within bodies. They always join an entity Bi and one of its features Fji. Constraint arcs always connects two feature nodes, which may be joined by more than one are to admit more than one con-

• 1

straint between them. The constraint arcs are represented by with the degrees of freedom xj, B rrt ... sometimes being omitted. To simplify the notation, positioning arcs are named Fji, as the features themselves, and the body nodes are named as their origin frame, Bj.

Qxj, 8,,,,, ..),

The Oldham Coupling The Oldham coupling is shown in Figure 2. This mechanism is designed to connect two parallel, non-collinear axes, allowing the transmission of rotational movement [4]. Using'I canonical variables, the types of joints present in this methsnism are modeled in Table 3. The ground frame is called Bo, and supports the Oldham coupling through the features Fn and Fro which are the parallel, non-collinear axes. The two! central joints Rr and R2 are prismatic, with their grooves F and F22 being non-parallel. R3 and R4 represent the rotatory movements (input / output) that are to be transmitted by tbc coupling.

Using Gr6bner Bases in Kinematic Analysis of Mechanisms

Table 3: Joint List of the Oldham Coupling i Joint I Joint Type I Canonical Representation trans(T 1) Tu Rl Tu trans(x2) R2 twiX(03) Ru R3 twix(04 ) Ru R4

Modeling of Oldham Coupling with Canonical Variables Using the methodology developed in [10] and the SC graph (Figure 2), the kinematic relations may be expressed by the following matrix equations:

B1.F11.R1.F121 = B2 B2.F22.R2.F131 = B3 B3.F23.R3 .F201 = Bo Bo .Fio .R4 .F211 = Bl

(2)

In this case the graph of constraints contains only one loop and it can be expressed by the equation: Flo .R4 .F211.F11.R1.F121

(3)

= F2o .R3.F231.F13.R2 .F221 where 14 is the 4 x 4 identity matrix. This equation conveys the topological configuration of the coupling. In the Oldham coupling, the non-collinearity between axes F20 and Flo is expressed by L3 . The total length of the mechanism is determined by parameter L12 . According to Equation 3 and Table 3, the polynomials which express the kinematics of the mechanism are: — L12+L8 — L11+L7+L1+L3 = 0 804 S03 - C04 CO3 - 1= 0 —SB4 CB3 - C04 803 = 0 L3 804 CO3 + L3 C04 S03 - 804 12 + C04 T1 = 0 C04 S03 + SO4 CO3 = 0 SO4 803 — c04 CO3 — 1= 0 -L3,304 .503 + L3 C04 CO3 - C04 T2 - SO4 .T,1 = 0 803 + C03 2 - 1 = 0 2 2 S04 + C04 - I = 0

(4)

Under the specification presented, the analysis of the Oldham coupling should predict the transmission of noncollinear, rotatory movement. In a first approximation, however, the Gr6bner Basis of this set of polynomials happens to be GB = {1}. This implies a topological or geometrical inconsistency. A careful examination of Equations 4 reveals that in the first equation, L12 is not an independentparameter (see Figure 2). This equation indicates that L12 = Ls — Lil + L7 + Ll + L3

(5)

is a necessary condition for the mechanism to be realizable. This detection of geometrical inconsistencies in relation to the prescribed topology is an unexpected bonus of using algebraic geometry techniques for GCS / SF. Under the condition imposed by Equation 5, the first equation in (4) would become 0 = 0. The lexicographic Gr6bner Basis, calculated under the order T I >- T2 >- 803 ~- CO 3 >- s04 >- C04, is: xl + L3 904 = 0

22 + L3 C04 = 0

903 - 804 = 0

CO3 + C04 = 0 '9042 + c042 — 1 = 0.

(6)

This triangularized Gröbner Basis presents a free variable, C04 , responsible for the one-dimensionality of the polynomial ideal [3, 71. As expected, the prismatic joints RI and R2 (variables T1 and T2) are controlled by the separation between the two axes, L12. Variation 1. Cylindrical Joints in Central Connector A question arising from the previous section is whether other configurations different from the Oldham coupling would also transfer rotational movement between non-collinear axes (see Figure 3). One of such variations is achieved by replacing joints Rl and R2 , which originally are prismatic (Tu), by cylindrical ones (Cu = trans(T, 0, 0).twiT(0)). The translational dof T is essential to the functioning of the coupling. It would be expected that the rotational degree of freedom 0 be instanced. Using the cycle formulation from Equation 3, and the joint specification of Table 4, the kinematic equations can be formulated. Under the ordering .xl >- 80 1 >- cpl >- .T,2 >802 >- CO2 >- .S03 >- CO3 >- s04 >- C04 this equation set has the following lexicographic Gr6bner Basis: T 1 + L3 804 = 0

T 2 +L3 c04 =0

801 = 0

CBI — 1= 0

802 +1=0 CO2=0

^803 — SO4 = 0 CO3 + C04 = 0

804

(7)

a

+ C04

The variable C04i the angular input/output of the mechanism is effectively the degree of freedom left. All other variables appear as headO of some polynomial. As expected, the angular freedoms given to the central joints Rl and R2 do not affect the degrees of freedom of the whole coupling, since they are immediately instanced. Therefore, the joints act as prismatic rather than cylindrical ones.

61

Using Gr6bner Bases in Kinematic Analysis of Mechanisms

1-177

Original

Variation t

Variation 2

Variation 3

Figure 3: Variations of the Oldham Mechanism Table 4: Joint List of the Oldham Coupling. Variation 1 Joint ( Joint Type I Canonical Representation. trans(.r,1).twi.r,(01 ) Rl Cu t7,an.s(.r,2 ).te1)ir,(01 ) R2 Cu R3

Ru

t?ViX(03)

R4

Ru

twi..r,(04 )

Variation 2. Cylindrical Joints in Input / Output Links If R3 and R4 are strictly rotational joints Rit, L12 was found dependent on other dimensions. Therefore, by allowing axial movement in joints R3 and R4 (see Figure 3), the expected result should be that the L12 can be considered an independent parameter. The coupling should act as a transmitter of cylindrical movement along two non-collinear parallel axes. The constraint polynomials are built under the joint configuration of Table 5 and the matrix Equation 3. Their Gr6bner Basis under the ordering x, >- x2 >- x3 >- -903 >0O3 `r X4 ~- SO4 >- ('04 is

x 1 + L3 s84 = 0 x 3 +r4+L12 —L8 +L11—L7 —L1 —L3 =0 — 504 = 0

CO 3 + C64 = 0 804

+ c842 —

I

= 0

(~)

This Gr6bner Basis represents a two-dimensional ideal with two free variables; X4 and c4 . c4 is the rotational movement transmitted. x4 represents the translational degree of freedom. Variables X4 and X3 act as slack variables; they allow L12 :A Ls — L11 + L7 + L 1 + L 3 , in contrast with the original Oldham coupling in which such condition would render the mechanism unrealizable. Variation 3. Parallel Prismatic Joints in Central Link In this variation the topology of the Variant 2 (expressed in Table 5) is maintained while the geometry is modified in such a way that the solution space changes radically. The features F12 and F22, the grooves of the prismatic joints R1 and R2 , are made parallel. This modification (see Figure 3) would

62

xl +X2 + L 3 s04 = 0 983 = 0 SO4 — 1= 0 00 4 = 0

r83 + 804 = 0

f (9) lI

This triangular Gr6bner Basis indicates that all the angular variables are locked (instanced). The mechanism cannot j transmit rotatory movement, and x2, the translational variable, is the only degree of freedom left.

Conclusions

X2 + L3 C04 = 0

,5 03

preclude the whole joint for transmitting rotational movement through the non-aligned axis Flo and F20. Under the order x, ~- .T,2 >- S03 >- CO3 >- s0 4 >- cB4 the lexicographic Gr6bner Basis of this arrangement would be

It has been shown that the kinematics of mechanical link arrangements can be expressed in terms of GCS / SF. Therefore, the methods of solution for such a problem can be applied in order to analyze the characteristics of kinematic chains. By using the set of canonical variables, a direct map between the kinematic characteristics of the mechanism and the algebraic expression of the corresponding GCS / SF problem can be established. This direct map can be taken advantage of in inferring possible variations of the mechanism by elaborating about variations on the basis of the polynomial ideal.

Gr®bner Bases for Oldham Coupling

Ex.>ruple This section shows the basic calculation for the original Oldham Coupling. The three variations are obvious modifications. # File: oldham—basic.mapl # Bodies:0. Ground

Using Gröbner Bases in Kinematic Analysis of Mechanisms

Table 5: Joint List of the Oldham Coupling. Variation 2 Joint I Joint Type I Canonical Representation R, Rz R3 R1

# # #

Tit Tit Cu C'u,,

1. Rotatory Groove Left 2. Central Piece 3. Rotatory Groove Right

# Constraints as per Tables 1 and 2: # (Rl:Tu F11-F14) (R2:Tu F21-F14) # (R3:Ru F12-F15) (R4:Ru F22-F15)

First define twix () , trans () , xTOy, rotX_90, and I_4 in order to express Herve's constraints. > > > > > > > > > >

twix := proc(s,c) RETURN( array([[1,0,0,0],[O,c,-s,0], [0,s,c,0],[0,0,0,1]])) end: trans := proc(x,y,z) RETURN(array([[1,0,0,x],[0,1,0,y], [0,0,1,z],[0,0,0,1]])) end: xTOy:=array([[O,-1,0,0],[1,0,0,0], [0,0,1,0],[0,0,0,1]]);

> I_4:=array([[1,0,0,0],[0,1,0,0], > [0,0,1,0],[0,0,0,1]]);

trans(x 1 ) trans(x 2) t7, ans(.T,3).t7ViX(03 ) trans(x 4 ).twix(04 )

> #----------------------------------> > > > > > > >

finite symmetries. Their handling is out of our scope. > cycle:=evalm( > F10&*MirrorX&*C4&*inverse(F21)&*Fll&* > C1&*inverse(F12)&*F22&*rotX_90&*C2&* > inverse(F13) &* > F23&*MirrorX&*C3&*inverse(F20)-I_4

Now, separate the equations. > eqs := [ cycle[1,l],cycle[1,2],cycle[1,3], > cycle[1,4],cycle[2,1],cycle[2,2], > > cycle[2,3],cycle[2,4],cycle[3,1], cycle[3,2],cycle[3,3],cycle[3,4], > > s3-2+c3"2-1,s4- 2+c4"2-1

> > rotX_90 := twix(-1,0);

> oldham := proc() > with( grobner ); > with( linalg );

Here, the GEOMETRY is defined. > > > > .> > > > > > > > > > > > > >

# Dimensional Parameters: L12:= L8 - L11 + L7 + L1 + L3; F11:=array([[0,1,0,L1],[-1,O,O,L4], [0,0,1,L2],[0,0,0,1]]); F21:=array([[-1,0,0,-L3],[0,-1,0,L4], [0,0,1,L2],[0,0,0,1]]); F12:=array([[0,1,0,-L7],[-1,0,0,L5], [0,0,1,L6],[0,0,0,1]]); F22:=array([[0,0,1,0],[0,-1,O,L5], [1,0,0,L6],[0,0,0,1]]); F13:=array([[0,-1,0,L11],[0,0,-1,L9], [1,0,0,L10],[0,0,0,1]]); F23:=array([[1,0,0,L8],[0,0,-1,L9], [0,1,0,L10],[0,0,0,1]]); F20:=array([[-1,O,O,L12],[0,0,1,0], [0,1,0,L3],[0,0,0,1]]); F10:=array([[1,0,0,0],[0,1,0,0], [0,0,1,0],[0,0,0,1]]);

1;

> N := nops( eqs ); > vars [x_l, x_2, s3, c3, s4, c4 ];

> MirrorX:=array([[-1,0,0,0],[0,1,0,0], [01 0,-1,0],[0,0,0,1]]); >

Next, simulate the Oldham mechanism.

# B0, B1, B2, B3 are immaterial C2:Tu=F22-F13 # C1:Tu=F11-F12 C1 := evalm( trans( x_1 ,0 ,0 )); C2 := evalm( trans( x_2 ,0 ,0 )); # C3:Ru=F23-F20 # C4:Ru=F10-F21 C3 := evalm( twix( s3, c3 ) ); C4 := evalm( twix( s4, c4 ) ); Next, the cycle equation. MirrorX and rotX_90 are

Do the calculations and measure performance: > > > >

tl time(); GB gbasis( eqs, vars , plex ); t2 time(); time := t2-t1;

Display the results: > #----------------------------------> > > > > > > > > > > >

print('Equations: ); for eq in eqs do print( eq ); od; print(' ); print('Oldham example: ); print('num vars : nops( vars ) ); print('num eqs nops( eqs ) ); print('num eqs GB : , nops( GB ) x ); print('time GB: ' ,time ); print(' ); print('GBasis:'); for g_pol in GB do print(g_pol); od; end:

Biographies Placid M. Ferreira is currently Associate Professor of Mechanical and Industrial Engineering at the University of Illi-

63

Using Gr6bner Bases in Kinematic Analysis of Mechanisms nois at Urbana-Champaign. His research interests include large scale flexible automation, computer-aided design, manufacturing and process planning and applied geometric reasoning. Professor Ferreira received his BE degree in Mechanical Engineering from University of Bombay, 1980, his MTech from Indian Institute of Technology, Bombay 1982, and his PhD degree from Purdue University in 1987. He received the Presidential Young Investigator Award in 1991. Professor Ferreira can be reached at the Department of Mechanical and Industrial Engineering in University of Illinois, Urbana, IL 61801. e-mail: [email protected] www : http://marshall.me.uiuc.edu/Isfa.html Oscar E. Ruiz S. is a post-doctoral Research Associate of Mechanical and Industrial Engineering at the University of Illinois at Urbana-Champaign. His research interests include computer-aided design, manufacturing and process planning, computer graphics and computational geometry. Oscar E. Ruiz S. received a B.S. in Mechanical Engineering and a B.S. in Computer Science from Universidad de los Andes, Santa Fe de Bogotä, Colombia, in 1983 and 1987, respectively. He earned his M.Sc. and Ph.D. degrees from University of Illinois at Urbana-Champaign in 1991 and 1995, respectively. Dr. Ruiz can be reached at the Department of Mechanical and Industrial Engineering in University of Illinois, Urbana, IL 61801. e-mail: [email protected] www : http://marshall.me.uiuc.edu/lsfa.html

References [1] A. Ambler and R. Popplestone. Inferring the Positions of Bodies from Specified Spatial Relationships. Artificial Intelligence, 6:157-174, 1975. [2] Jorge Angeles. Rational Kinematics. Springer-Verlag, New York, 1988. [3] B. Buchberger. Applications of grobner basis in nonlinear computational geometry. In: D. Kapur and J. Mundy, editors, Geometric Reasoning, pages 413446. MIT Press, 1989. [4] V. M. Faires. Design of Machine Elements. MacMillan Company, Toronto, Canada, 1965. [5] J. Herve. Analyse Structurelle des Mechanisms par Groupe des Deplacements. Mechanism and Machine Theory, 13:437-450, 1978.

64

[6] Christoph M. Hoffmann. Geometric and Solid Modeling. Morgan-Kaufmann Publishers Co., San Mateo, California, 1989. [7] D. Kapur and Y. Lakshman. Elimination Methods: An Introduction. In: B. Donald, D. Kapur, and J. Mundy, editors, Symbolic and Numerical Computation forArtificial Intelligence, pages 45-88. Academic Press, London, 1992. [8] W. Ledermann. Introduction to Group Theory. Barnes and Noble, New York, 1973. [9] R. Popplestone, Y. Liu, and R. Weiss. A Group Theoretic Approach to Assembly Planning. Artificial Intelligence Magazine, Spring, 1990. [10] O. Ruiz and P. Ferreira. Algebraic geometry and group theory in geometric constraint satisfaction. In: International Symposium on Symbolic and Algebraic Computation, St Catherine's College, University of Oxford, UK, July 1994. [11 ] O. Ruiz and P. Ferreira. Geometric reasoning in the analysis of assemblies and mechanisms. In: ASME Symposium on Computer Integrated Concurrent Design, Boston, U.S.A., September, 18-20 1995. [12] Federico Thomas. Graphs of Kinematic Constraints. In: L. Homem de Mello and S. Lee, editors, Computer Aided Mechanical Assembly Planning, pages 81-109. Kluwer Academic Publishers, Boston, 1991.

The Basic Curves and Surfaces of Computer Aided Geometric Design Calm Mulcahy $ Intr®ducti®n Computer Aided Geometric Design (CAGD) plays a major role in the design of cars, airplanes, and submarines, as well as in many modern manufacturing processes. The mathematics behind CAGD is also indispensable in computer graphics. We demonstrate the use of Maple V Release 3 as an educational tool in the construction, plotting and manipulation of the basic curves and surfaces of CAGD. This can be done using a bare minimum of Maple, hence anybody who knows a little linear algebra and multivariate calculus can be introduced to this important material. Maple's numerical and symbolic capabilities take the drudgery out of computing with the formulae, as well as providing immediate visual access to the resulting shapes. Topics which can easily be explored in this way include: polynomial and parametric interpolation, least squares and Bezier curves, Hermite and natural cubic splines, tensor product surfaces, lofting and Coons surfaces, B-splines, B-spline curves and surfaces, interpolation with B-spline curves, least squares B-spline methods, and NURBS (nonuniform rational B-splines). We provide examples of many of these constructions to give the general flavor of the subject. We concentrate on planar curves - the extension to space curves is routine. The emphasis throughout is on (piecewise) polynomial methods, and their rational counterparts. There are essential aspects of CAGD, which can also be investigated with the help of Maple, and which we will not have time to touch on, such as recipes for drawing the curves and surfaces, important and illuminating connections with projective geometry, numerical analysis considerations, advanced spline algorithms, and differential geometry. See [1, 2, 3, 4] for further information.

> xx:=[1, 3, 4, 5, 6, 8, 9]: > yy:=[32, 34, 36, 34, 39, 40, 371: > f:=interp(xx,yy,x); 767 379 ; 41657 ~ 84127 3

f = 20160

.r.

320

393091 Xz

+ 1440

r

+ 2880"

48097 1639 120

x

960 .1

+ 7

While we get no hint as to how the answer was arrived at, the mathematics involved is elementary and well known (see [3, Chapter 6] or [4, p. 57]). Let's look at this interpolant, along with the data points. For politeness sake we plot from 0 to 10. > > > > > >

pts:=i->(xx[j],yy[j]): n:=6: points:=[seq(pts(j),j=1..n+1)]: POINTS:=plot(points, style=point, symbol=circle, axes=boxed): INTERP0L:=p1ot(f,x=0..10): with(plots): display((POINTS,INTERPOL));

quo]

Right away, we see that although polynomial interpolants do the job they are assigned, they do strange things outside of the range of data points. They certainly cannot be trusted for extrapolation purposes! Plotting from 0.8 to 9.2 instead yields:

The central idea of interpolation is to find a polynomial -which goes through prescribed data points (xi, y;), 0 < i < n. Maple's interp command uses Newton interpolation to find the unique y = f (x) of degree less than or equal to n-one less than the number of points-which does the job. We try this for the seven data points (1, 32), (3, 34), (4, 36), (5, 34), (6, 39), (8, 40), and (9, 37): $Department Of Mathematics, Spelman College, PO Box 373, 350 Spelman Lane, Atlanta, GA 30314, USA; email: [email protected]; URL: http://www.auc.edu/- colm x

N

PW

Computer Aided Geometric Design

This highlights another undesirable aspect of our approach so far: the inevitable wiggling of high degree polynomials within the range of interest. In addition, the x coordinates need to be distinct. For an orientation free approach, we could start with distinct to , t1 , ... , t,,,, and obtain a parametric curve (f (t), g(t) ) such that (f (t i ), g(ti)) = (xi, yi) for all i, by taking f (t) and g(t) to be the unique polynomials of degree less than or equal to n. such that f (t i ) = .xi and g(ti) = y= for all i. For fixed (.x,T , yi ), different ti's result in different curves, some of them relatively wiggle-free [4, pp. 201-2].

Instead of insisting on interpolation, we could settle for some sort of approximation to our data. We might ask for a "best fit" polynomial of lower degree. If we seek a cubic, in the case of seven points, then unless we are lucky, we are not going to get an exact fit. The method of least squares is one popular technique used in such circumstances — it can be explored using Maple's leas tsquare command. Bezier curves provide another alternative. We start with points Po, P1, ... , P — note the switch to vector notation here — and end up with a parametric curve which is polynomial of degree less than or equal to n in each slot. The Bezier curve associated with control points Po , Pr , , P,1 is defined for 0 < t < 1 by

(

B(t)

""l t'(1- t)n-'P=

i=o

i

The functions attached to the points here are known as the Bernstein basis functions. Cubic Bezier curves use four control points, and the basis functions (1—t,) 3 3(1—t,) 2t, 3(1—t)t 2, t 3. These curves have many applications, sometimes in the equivalent Hermite formulation, specified in terms of just two control points with specified tangent vectors there [3, pp. 911. Large curves can be built up by stringing many such segments together, with tangent continuity at the joins [3, pp. Chapter 8]). These cubic curves are also the basis of font design in PostScript [3,p. 130]). Consequently, every page in this journal is bursting at the seams with Bezier curves! Let's look at the Bezier curve determined by our original data points, utilizing the binomial command. We replot the points over an extended range, making some labeling adjustments on account of the vector origins of pts and the desired form of the points Pi's. We take the linear combination of control points with the help of evalm. n:=6: P:= i-> [pts(i+1)]: POINTSE:=plot(points,x=O..10,y=31..41, style=point,symbol=circle,axes=boxed): brn:= (i,n,t) -> binomial(n,i) * t"i * (1-t)^(n-i):

,To,

> bez:= t -> evalm > (sum('brn(i,n,t)*P(i)', > BEZ:=plot([ bez[1], bez[2], t=o..1 ]): > display({POINTSE,BEZ));

The resulting picture illustrates some standard properties of Bezier curves. For instance, Bezier curves always lie within the convex hull of their control points, since on [0, 1] the Bernstein basis functions are clearly non-negative and sum to 1. Maple can verify the latter claim symbolically — even if we switch from n to the unspecified nn: simplify(sum('brn(i,nn,t)','i'=O..nn));

As the picture suggests, generally only the first and last control points are interpolated. The intermediate control points influence the curve's shape in a different way, acting more like magnets. There are various ways to adjust the influence of the control points. One could repeat some points, i.e., list them more than once, but increasing the number of points also increases the degree of the resulting curve. Another restriction inherent to the Bezier approach is the fact that the curves change totally as soon as one control point is moved. Let's broaden our horizons, and not restrict ourselves to polynomials. Given points Po , P1 ,... , P,,,, and corresponding "weights" wo , w1 , ... , w,,, the associated rational Bezier curve is defined on [0, 1] by R(t) _ z~ri

( () Z ( 1 t ) t ( f)n1~22VPi

It is an easy matter to modify the definition of be above to accommodate the weights and the new denominator.

Computer Aided Geometric Design

Elementary Surface Patches

The above plot shows the rational curve determined by our seven data points, taking 1113i and ws to be 5, and the other wi's to be 1. Note the curve's newfound affection for the fourth and sixth points. If the weights are all equal then the rational Bezier curve reduces to the ordinary Bezier curve, since the denominator simplifies to the common weight. Hence only select control points can be "emphasized." Readers who are curious about the effects of zero or negative weights can experiment for themselves at this point. An important application of rational quadratic Bezier curves is to the construction of (bits of) conic sections — including circles, ellipses and hyperbolas — without resorting to trigonometric or hyperbolic functions [3, pp. 244-5] [4, pp. 155-3]. In our brief tour of Bezier curves, we got more than a glimpse of things to come. From now on all curves will be of the form C(t) = E o fi(t)Pi, for control points Pi, and basis functions fi(t,). The interpolation functions considered earlier can also be realized in this way where the fi(t,) are the well known Lagrange functions [3, Chapter 6]. In the polynomial Bezier case, the fi(t)'s are the Bernstein basis functions. It will often happen that Ei o fi(t) = 1 as well, at least on some parameter interval, which ties in with the convex hull property mentioned above when the basis functions are also non-negative. As further evidence that Bezier curves are never too far away, we note that any continuous curve C(t) on the interval [0,1] can be approximated to an arbitrary degree of precision by a Bezier curve. This is the content of modern treatments of the celebrated Weierstraß Approximation Theorem: for fixed C and n let BC n(t)

_ L,

( Z lt2 (1 - t)n- C(n), i=0 \ //

We can use the interpolation and Bezier constructions already discussed to come up with two broad classes of surface patches, so-called tensor product surfaces and lofting surfaces. By a surface patch we mean a function of two parameters u, v, plotted over some rectangle in the u, v plane, taking values in three space. Surfaces of the type z = f (.r,, y) can be realized this way, as S (u, v) = [u, v, (f, u, r,')]. First we consider a tensor product surface patch built up from cubic Beziers. We start with a grid of sixteen control points Pi,j (0 < i, j < 3), and then consider the Bernstein j i 3-j used functions j!(33! (1—u) 3-i, and j,(33!_ M (1—v) in the definitions of the cubic Bezier curves controlled by Po,o, Pi,o, P2,o, P3,a, and P0,0, P0,1, Po,2, Po,3, respectively. We use the set of all possible products of these one variable functions as a basis for our surface: for u, z; E [0, 11, define S (u, v) to be 3

u i (1 —u) 3-'vi (1 — v)3-ipt,j. E (3) (I3) =,j=o This surface interpolates the corner points Po,o, Po,3,P3,0, and P3,3 —its precise shape may be varied by altering these and the other control points. One way to get control points is to sample a surface, say z = sin( 4y34o Xz ), on a regular 4 x 4 grid. We construct and save the mesh these points determine, to aid in visualizing them later. > P:=(x,y)->[x,y,sin((4*y"3-3*x"2)/40)]: > GRID:=p1ot3d(P(x,y), x=0..1, y=0..1, > grid=[4,4], axes=box, color=black, style=wireframe, thickness=2): >

We compute and plot the surface, using advance hindsight to chose a suitable viewing angle. > sur:= eva1m(sum(sum( 1 brn(i,3,u) > *brn(j,3,v)*P(i,j)','j'=0..3), > 'i'=0..3)): > SUR:=plot3d((sur[1],sur[2],sur[311, > u=0..1, v=0..1, shading=none): > display({GRID,SUR},orientation=[-140,60]);

o.; 0.1

o.. o.: -0 -0 -0

then the sequence {Bc,n (t)}nGN converges uniformly to C(t,) on [0,1] (see, e.g., [5, pp. 169-172]).

67

Computer Aided Geometric Design

A simpler example of a tensor product surface patch is the bilinear surface patch, which also turns out to be the easiest example of our second class of surface patches. We start with linear Leziers, i.e., straight lines, connecting four points Qo,o, Q1,o, wQ1,1, Qo,1 (in that order), yielding 1311(u, v) = (1 - u)(1 - v)Qo,o + (1 - u)vQo,1 +u(1 - v)Q1,o + u.vQ1,1 for u, v E [0, 1]. This is the simplest surface joining four points. It is a ruled surface, and interpolates the lines which connect the given points. If we take Qo,o = (0, 0, 0), Q1,o = (2, 0, 3), Q1,1 = (0, 2, 3), and Qo , 1 = (0, 4, 0) we get:

We can string a hammock between the curves C,,,o and C,,,1 by lofting in the v direction with Loft, (u, v) = (1 - v)C,,,o + vC,,,1, for u, ,v E [0, 11. This linearly interpolates between corresponding points on each curve.

2' z1. o.!

z1

We can also loft in the a direction with Loft„(u,v) = (1 - u) Co ,, + uC1,.,,

Now suppose we have four curves connecting the points: say C,,,o and Cu ,1 Joining Qo,o to Q1, o and Qo,1 to Q1,1 respectively, and Co and C1,~ joining Q1 o to Q1,1 and Qo,o to Q o , o respectively, where each parameter is in the interval [0, 1]. These determine a frame, and now we seek a surface patch which has these as its boundary. Isere is such a frame, drawn using spacecurve and display:

2 1 o.

The Coons surface construction gives a surface patch which interpolates all four of the space curves. Its parametric equation is given by: z1

Coons(u, v) = Loft u(u, v) + Loft v (u, v) - Bil(u, v) M

for u, v E [0, 1]. Our curves yield:

Here Co,, is the Lezier curve (1 - v)2 Qo,o +2(1 - v) v(4, 4, 0) +v2 Qo,1; C l ,, is a quarter of the intersection of the cylinder x4 + Y4 = 24 with the plane z = 3, i.e., C1,,, _ (2 cos 4 ( 2"),2sin 4 (2"),3);Cu,o=(1-u)2 Qo,o+2(1u) u(2,0,0) + U2 Q1,o, and Cu,1 = (1 - u) 2 Qo,l + 2(1 u)u(0,2,0) + u 2 Q1,1. The parametrization of C1, ß, provoked us to set numpoints equal to 270 for that spacecurve plot.

2 z1. 0.

Computer Aided Geometric

That this patch does indeed interpolate the four ingredient curves can be verified by hand - or we can let Maple do the work for us. For instance, with Bil, Loft-u and Loft -v defined as above, and Coons := evalm (Lo f t_u + Loft-v - Bil), then evalf (subs (v=0, eval (Coons))) does indeed yield (6(1 - u)z ) + 4u(1 - u) -(- 2u2 , 0,311, 2) = Cu,o. (We can alleviate the clutter of curves at the top of the Loff u and Coons plots, by re-parametrizing the curve C1,,, so as to spread out more evenly the points obtained by uniformly sampling v E [0, 1]. One possibility is to replace each v in the definition of C1,, by (arctan(Sv - 4) +arcta,n(4))/ (2 arctan(4)). ) Designer surfaces for engineering purposes may be obtained by stitching together lofting, Coons, and Bezier patches - or the more general B-spline surfaces or NURBS patches discussed later - subject to stringent matching conditions across the joins.

> m:=7: > T:=array(O..m, [0,0,0,0,1,1,1,1]): > w:=(i,j,t)-> > if T[i+j-l]=T[i] then 0 > else (t-T[i])/(T[i+j-1]-T[i]) fi:

We start the ball rolling by defining step functions S(a, b, t,) on intervals of the form [a, b) with the help of

Maple's Heaviside command. > > > > > >

S:=(a,b,t)->Heaviside(t-a)-Heaviside(t-b) B:=(i,j,t)-> if j=1 then S(T[i],T[i+1],t) else w(i,j,t)*B(i,j-1,t) + (1-w(i+1,j,t))*B(i+1,j-1,t) fi: (Note: S(a, b, t,) is 1 on [a, b) if a < b, and 0 everywhere

if a = b. We are being sloppy here and ignoring possible problems at the right most knot value). Maple is primed and ready to compute the B-splines: let's examine the cubics, i.e., the Bi,,, (t.)'s. There should be 7 4 -l- 1 = 4 of them: > k:=4: curves:= (seq(B(i,k,t),i=0..(m-k)): > plot(curves, t=O..t.m, axes=boxed);

B-splines B-splines are a class of functions made up of pieces of polynomials, joined together in some fashion. We start by choosing an in + 1-tuple T = [to, ti , ... , t ,] of non-decreasing real numbers, which is called the knot vector. We then define the B-splines Bij of order j recursively, as follows. Set Bi i (t) =

1

:gym

on [ti, ti+1)

0 elsewhere

for 0 < i < m, - 1 (with B,,,-i , 1 (t) = 1 on [t,,,_i , t,,,]), and for any j < in, we define Bij (t) = zoij(t)Bij-r(t) + (1 - wi+1.j(t))Bi+1,j-1(t)

for 0 < i < m - j, where the wi j are given by (c-t i )

2Ui~j(t) _

(fit+J-t - ~, i)

0

if ti+j-1 ti otherwise.

Given T and k _< m, we thus get m - k + 1 piecewise polynomials Bi k(t) of degree at most k - 1. The pieces which constitute each function join up at the knots, where they exhibit varying degrees of smoothness. _ Order one B-splines Bi,1 (t) are step functions, order two B-splines Bi,2 (t) are zig-zag linears, order three B-splines Bi,3 (t) are piecewise quadratics, and so on. It is difficult for the average reader to find much comfort or inspiration in the above formulae the first time around. We need examples and pictures-and fortunately Maple comes to the rescue. Our first example turns out to be an old friend. We force Maple to start counting the array elements at index 0 to facilitate the standard notation for the definition of the B-splines.

Here we have four polynomials (no pieces) defined on [0, 1). They are in fact the Bernstein functions (1- t)3, 3(1t)2 t, 3(1 - t)t.2 , t3, from earlier. This can be verified by not suppressing the output of the curves definition above, and ignoring the clutter due to the Heaviside functions. For our second example, we use the new knot vector [0, 1, 1, 3, 4, 4, 5, 6, 6, 6, 9] of length 11, and again plot the resulting B-splines. Changing m and T above, and re-executing the code yields seven piecewise cubic functions on the interval [0, 9]. In principle each comes in six pieces, switching 4t t = 1, 3, 4, 5, and 6: The multiplicity of a given knot (i.e., how often it is repeated in the knotvector) tells us a lot about the way the pieces of the B-splines join up there: at a knot of multiplicity P, each Bi k is at least k - ( - 1 times continuously differentiable [4, p. 174]), [3, p. 169]). If k - C - 1 = -1, this is to be interpreted as a potential discontinuity.

69

~

0

Aided Geometric Design

If T = [0, 0, 0, 0,1,1,1,1] and k = 4, we see that C(t) is just a cubic Bezier curve; indeed any Bezier curve can be realized in a similar way. Let's look at a cubic B-spline curve based on the knot vector [0, 1, 1, 3, 4, 4, 5, 6, 6, 6, 9] from before. Since we'll need in. — k + 1 = 10 — 4 -►-1 = 7 control points, we use our seven data points again. > bsp:=evalm(sum('B(i,k,t)*[P.i]', 'i'=0..(m-k) )): > > BSP1:=p1ot([ bsp[1], bsp[2], t = T[k-1]..T[m-k+1] ]): > > disp1ay((POINTS,BSP1));

Thus, the spike in the seventh function B6 , 4 in the last plot is not totally unexpected. At that point, t = 6, the B-splines are only guaranteed to be 4 — 3 — 1 times continuously differentiable, i.e., continuous but not necessarily differentiable. Similar considerations apply at t = 1 and at

Y 3

t=4.

The seven B-spline functions are visibly non-negative on [0, 9], and a plot of their sum suggests that they sum to 1 on the subinterval [3, 61. (These are key properties which will soon prompt us to define B-spline curves.) We can take advantage of Maple's symbolic prowess to verify that they sum to 1 here if we utilize the assume facility to restrict attention to those t between 3 and 6: > assume(t>3,t simplify(sum('B(i,k,t)','i'=0..(m-k)):

This should work under the assumption that 3 < t < 6 (or at least 3 < t, < 6 in view of the sloppiness commented on earlier) but Maple takes additional nudging to get that totally right. In general, the correct subinterval over which to sum the in — k + 1 B-splines is [tk-1, tm —k+11•

B®sp"-r~e Curves and Surfmces We have seen how Bernstein functions are special cases of Bsplines, and we already know how to build parametric curves from the Bernstein functions. It should therefore come as no surprise that general B-splines can be made to play a similar role.

Given a knot vector T = [to , tl. ... , t ,], and the corresponding in — k + 1 B-splines Bi , k (t) of order k, for some fixed k < in, then if we also have in, — k + 1 control points Po , P1 .. , P rn _k, we can put everything together to get a B-spline curve of degree k — 1 defined on [t k -1i t,,,—k+11: m-k+l

This picture raises further questions. Why is (9, 37) interpolated? How smooth is this piecewise cubic curve? Where, on the curve itself are the various segments joined up? How do the knots and the control points influence the shape of the curve? Could we change the knots so that (1, 32) doesn't get "left out in the cold"? Is there a way to actually interpolate all seven points with a piecewise cubic B-spline curve? These are important questions, and we take a look at some of them in the last section, An Educational Experience. Maple has built in spl ine and bspl ine libraries, containing very general routines, which even allow for symbolic knots. However, we do not explore them here, in keeping with our philosophy of using a minimal amount of Maple, while trying to understand how the mathematical pieces fit together. We finish this section by generalizing the tensor product bicubic Bezier surface patch definition from above,9to get Bspline surface patches. We start with knot vectors U = [uo , ul , ... , U m ", ], of possibly different lengths, and two Given a rectangular mesh of (m,,, — k„ -b curve orders k,,,, k,,. + 1) control points Pi j, we can then define 1) x (m„ — k S(u, v) =

m.- k u-Fl

m,,-k„+1

~

1:

i=0

}=o

Bi,k„ (u')B7,k„(V)Pi,i

C(t) = Y Bi,k(t)Pi. i=0

70

for (u,v) E [Uk,.—I,Um„—k„+1] X [vk„-1,vm„—k„+1]•

Computer Aided Geometric Design

When both knots vectors are [0, 0, 0, 0,1,1,1,1], and both orders are 4, we get a bicubic Bezier surface patch as seen before.

It should now be fairly obvious how to generate more exotic examples of surface patches using Maple.

We upped numpoints to 200, from the default 50, in an attempt to mask the annoying gap above (-1, 0). Our curve is composed of four quarter circles-each of which is a rational quadratic Bezier curve. One advantage of the NURBS approach is clear: we get the entire circle as a single curve.

An E ucati©nal Experience Non-uniform rational B-Splines (NURBS) refers to curve and surface generation using not-necessarily uniform (equally spaced) knots, in conjunction with the rational function approach already encountered in our study of Bezier curves. This leads to increased flexibility in design. We give one example: the representation of an entire circle as a rational quadratic B-spline curve. Our goal is to plot a rational B-spline curve: Em-k+ 1 iUiBi,k(t)Pi F1(t) _ ~ i=0

Ein0k +12IIiBi,k(t) given weights wi and control points Pi. We use the knot vector [0, 0, 0,1,1, 2, 2, 3, 3, 4, 4, 4] of length 12, set k = 3, and get the recursively defined B(i, k, t,)'s ready for action. For our control points we choose in - k + 1 = 11 - 3 + 1 = 9 points around the perimeter of a square centered at the origin, and plot these with a little room to spare. Note that PO and P8 are the same. For the weights, we attach 1 at the five(!) corners of the square, and sin(7r/4) _ elsewhere. PO:=(-1, 0): P1:=(-1,-1): P2:=( 0,-1): P3:=( 1,-1): P4:=( 1, 0): PS:=( 1, 1): P6:=( 0, 1): P7:=(-1, 1): P8:=(-1, 0): sq:=[P.(0..(m-)c)]: s:=1/sgrt(2): SQ:=plot(sq, style=point, symbol=circle, x=-1.25..1.25, y=-1.25..1.25, scaling=constrained, axes=boxed): ww:=array(0..8, [l,s,l,s,l,s,l,s,11): div:=sum('ww[i]*B(i,k,t)','i'=0..(m-k)): circa=evalm(sum( 'ww[i]*B(i,k,t) *[P.i]/div','i'=0..(m-k) )): CIRC:=plot([circ[1],circ[2], t=T[k-1]..T[m-k+1]],numpoints=200): display(fSQ,CIRC));

Our final explorations bring out some key properties of 13spline curves, as well as addressing questions such as "where are the knots on the curve?", "how do the knots influence the curve?" and "how do the control points influence the curve?" We look at a new, quadratic B-spline curve, and mark in the knots, so that we can see the. different polynomial segments which make up the curve. > m:=11: T:=array(O..m, [0,1,2,3,4,5,6,7,8,9,10,111): >

Execute the W : _ (i , j , t) ->, B : _ (i , j , t) -> code, and pick in, - k -I- 1 = 11 - 3 -)- 1 = 9 control points. > > > > > > >

PO:=(0,0): P1:=(0,2): P2-.=(3,0): P3:=(4,1): P4:=(8,0): P5:=(7,2): P6:=(8,3): P7:=(9,1): P8:=(10,4): k:=3: newpts:=[P.(0..(m-k))]: NEWPTS:=plot(newpts, style=point, x=-1..11, y=-1..5, symbol=circle, axes=boxed):

We plot on [t k -1, trn_k+1], in which there are (m, - k + 1) - (k - 1) + 1 = m - 2k, + 3 knots, i.e., the 3 knots from t z = 2 to t 9 = 9 inclusive. We evaluate the B-spline curve at these, and mark in the corresponding points. > > > > > > > > > > > >

edu:=evalm(sum('B(i,k,t)*[P.i]', 'i'=0..(m-k) ): EDU:=plot( [edu[1],edu[21, t=T[k-11..T[m-k+111 ): knotsx:=seq( eva1(subs(t=T[i];edu[1])), i=(k-1)..(m-k+1) ): knotsy:=seq( eva1(subs(t=T[i],edu[2])), i=(k-1)..(m-k+1) ): klist:=j->(knotsx[j],knotsy[jl): knots:=[seq(klist(j),j=i..(m-2*k+3))]: KNOTS:=plot(knots,style=point,symbol=box): display((NEWPTS,KNOTS,EDU));

a M KIM

71

Computer Aided Geometric Design

The curve appears to interpolate the midpoints of the lines joining consecutive control points, and these lines seem to be tangent to the curve there. These observations hold for any quadratic B-spline curve derived from a uniform knot vector, We now alter one of the control points, say P4, from (8,0) to (7, 0). What changes? We combine the new and the old plots using display.

here: when we alter one knot in a B-spline curve of order k, we change at most k - 1 segments of the curve on either side of that knot. Another thing worth noting here: the two knots which are closer together seem to be dragging the curve towards the control point (8, 0). If this is so, we can surely guess what happens when we change the knot vector to T = [0, 1, 2, 3, 4, 6, 6, 7,8,9, 10, 11].

Y

Evidently, altering one control point results in changes in three curve segments. In general, each control point on a B-spline curve of order k effects at most k segments of the curve: Pi influences only the segments between ti and t,+k [4, p. 176]. This important property of B-spline curves is known as "local control," and is one reason they are used so much in design: curve modifications can be made locally without changing other parts already deemed satisfactory. A complimentary fact is that each segment of such curves is controlled by at most k of the P;'s: the segment between tj and tj+l is completely determined by Pi _k+1, , Pj [4, p. 176). Next, we entertain the possibility of fiddling with the knots. Looking back at the original, before we altered a control point, we see that the knots t, = 5 and t = 6 correspond to points marked on the curve just before and just after it swings by the control point (8, 0), going from left to right. Now we change t;= 5 to 5.75, and see what happens.

The double knot at t, = 6 resulted in interpolation of one of the control points. Furthermore, the curve has k. - (- I = 3 - 2 - 1 = 0 continuous derivatives at this point, as the picture suggests. What effect would a triple knot have? First, let's have two knots sneak up on t, = 6 from different sides: try T = [0, 1, 2, 3, 4, 5.75, 6, 6.25, 8,9, 10, 11].

Y

The curve seems to be straining to interpolate two control points, with t, = 6 torn between the two points. What happens when we push all the way, and use T = T [0, 1, 2, 3, 4, 6, 6, 6, 8,9, 10, 111? Our final plot suggests that (8, 0) and (7, 2) are both interpolated - but if this is true, which point on the curve now corresponds to t = 6?

Only two curve segments on either side of the altered knot changed! Again, there is a general principle at work

72

Aided Geometric Design

road, Dr. Jeffrey Ehme for many helpful discussions, and the numerous seminar participants for their patience and perseverance while we grappled with these concepts together. This manuscript was made possible thanks to support from the W.K. Kellogg Foundation, through Spelman College's Center for Scientific Applications of Mathematics (CSAM). The referees made sensible suggestions which lead to significant strengthenings of this paper, for which the author is most grateful. P.S. Editor Ross Taylor provided much appreciated PostScript advice in the assembly process.

The picture is in fact wrong: in reality the curve jumps from just before (8, 0) to (7, 2), as t, reaches 6 from the left. It's hard to see at this scale, but (7, 2) is marked as a knot (square) and a control point (circle), whereas (8, 0) is only marked as a control point. There is actually a whopping big discontinuity here! Maple shouldn't have joined these two control points with a straight line, but then Maple's default way of plotting is to find a bunch of correct points and then join the dots, effectively assuming continuity. In spite of all the danger of believing the first computer generated picture we see, all is not lost: the truth of the matter is revealed upon changing the plot [ style J option to points. Maple makes a graceful recovery given half a chance.

Conclusion We have shown how Maple can be of assistance in exploring the principal geometric objects of study in CAGD, (Computer Aided Geometric Design). Concepts from just outside the standard undergraduate mathematics curriculum, together with a little Maple, go a long way in the construction of the shapes which are fundamental to many engineering design processes. We have only scratched the surface here, and we believe that there is a great deal of potential for further Maple exploration in this area.

Acknowledgments The author acknowledges the generous support of Boeing Computer Services, in the planning and running of an undergraduate seminar on CAGD for mathematics majors at Spelman College over the academic years 1993-5. It was in this forum that the bulk of the current materials was developed. In particular, Dr. Dave Ferguson of BCS was always happy to share his expertise at the drop of a hat. The author would like to thank his Spelman colleague Dr. Sylvia Bozeman for unwittingly starting him down this

References [1] Richard Bartels, John Beatty & Brian Barsky, An Introduction to Splines for Use in Computer Graphics and Geometric Modeling Morgan Kaufman (1987) [also published in France as Mathematiques et Cao, Volume 6, B-Splines and Mathematiques et Cao, Volume 7, Beta-Splines, Hermes (1988), translated by Pierre Bezier] [2] Carl de Boor, B(asic)-Spline Basics in Fundamental Developments Of Computer-Aided Geometric Modeling (Les Piegl, editor), Academic Press (1993) [3] Gerald Farin, Curves And Surfaces For CAGD (A Practical Guide), Academic Press, 3rd Edition (1993) [4] Josef Iloschek & Dieter Lasser, (Fundamentals of) Computer Aided Geometric Design, A.K. Peters (1993). [5] Robert G. Bartle, The Elements of Real Analysis, John Wiley & Sons, 2nd. Edition (1976).

Biographical Sketch Colm )Mulcahy earned his B.Sc. and M.Sc. degrees in Mathematics from University College Dublin, in Ireland. His Ph.D. thesis, written both east and west of there under the direction and guidance of Alex F.T.W. Rosenberg of Cornell University, concerned an abstract setting for the algebraic ret duced theory of higher level forms over fields. Recently his mathematical interests have broadened to include computational algebra (Groebner bases), general algebraic codology, CAGD, image processing, computer graphics, and wavelets. He likes Matlab and music, though not necessarily in that order. He actively encourages culinary minded readers to email him reliable, authentically Thai recipes for Massaman Curry.

73

Design of Cam Mechanisms Using Maple Ettore Pennestri, Vanni Fälasca * Intr®ducti®n Cams are widely used by mechanical engineers. They are simple and inexpensive devices which are able to deliver a specified motion to another element called the follower. The variety of cam topologies and their versatility are characteristic features of such mechanisms. Although more complicated topologies can be considered, in this paper our attention will be confined to the synthesis of a disk cam with translating flat follower (see Fig. 1). In particular, we will describe how Maple can assist a cam designer during all phases required to define and manufacture a cam profile. Theoretically the design process of a new cam mechanism could be divided into the following steps: ® Choice of the kinematic law of the follower (i.e., Definition of the displacement diagram); e Definition of the follower type (roller or flat); e Dynamic analysis. The program developed is able to perform all these steps. Moreover, it can integrate the results with the geometric information required when the cam is manufactured with a numerically controlled milling machine. The results obtained from the Maple program can be used by any CAD program (e.g., Autocad) in order to generate realistic drawings of the mechanisms. Such drawings, for example, can be interfaced with a rapid prototyping system for a quick manufacturing of the disk cam or for large series production. The main advantages of using a symbolic language such as Maple are the possibility of avoiding numerical errors due to the discontinuities of the follower motion, and flexibility of use. This paper is divided in three parts. The first part describes the main concepts for the kinematic synthesis of cam mechanisms. The second will briefly illustrate the model adopted for the dynamic analysis. The third will give a numerical example demonstrating the capabilities of our program.

KrnPmatic Synthesis Of Cams The definition of the profile geometry of a disk cam mechanism requires the following information: e a displacement diagram of the follower .vs. disk angular position; *Department of Mechanical Engineering, University of Rome Tor Ver gata, Italy E-mail:[email protected]

74

e the shape of the follower surface in contact with the cam; e the offset between the center of the cam and the translation axis of the follower. With regard to the first item there are different ways of approaching the problem. One can start from a given acceleration or jerk diagram of the follower and obtain the displacement diagram through graphical or numerical integration [1], or one may obtain it blending standard cam motions [2, 5]. We decided to adopt this second alternative because such motions have been extensively tested and can be defined analytically. DEFINITION OF THE DISPLACEMENT DIAGRAM The displacement diagram specifies the position of the follower versus disk angular position. Figure 2 shows an example of such a diagram, where are shown the three main motion phases: e Rise; e Dwell; e Return. Rise, dwell and return are divided into two different subphases whose boundaries are, respectively, determined by pr, /32, 71, 'Y2, al and a2 (see Fig. 2). At the present the displacement diagram portions that can be blended are: e Parabolic; ® harmonic; e Cycloidal. However, more types could be added. The analytical laws of such portions are predefined through the following Maple procedures > harmonicl_R:=proc(hl,betal,theta) > h1*(1-cos(Pi*(theta-gamma1)/ > (2*beta1))); > end; >

> harmonic2_R:=proc(h2,beta2,theta) > h1+h2*sin(Pi*(theta-beta1- gammal)/ > (2*beta2)); > end; >

> cycloidall_R:=proc(hl,betal,theta) > h1*((theta-gamma1)/ betal

Design of Cam Mechanisms Using Maple

> -(1/Pi)*sin(Pi*(theta-gammal)/betal)); > end; > cycloidal2_R:=proc(h2,beta2,theta) > hl+h2*((theta-betal-gammal)/beta2+(1/Pi) *sin(Pi*(theta-betal-gammal)/beta2)); > > end; > parabolicl_R:=proc(hl,betal,theta) (h1/(betal)2)*(theta-gammal)2; > > end; > > > >

parabolic2_R:=proc(h2,beta2,theta) hl+(2*h2/beta2)*(theta-betal-gammal) -(h2/(beta2)2)*((theta-betal-gammal)2); end;

> > > > >

harmonic3_RE:=proc(h3,alfal,theta) h4 +h3*(cos(Pi*(theta-(beta+gammal+gamma2))/ (2*alfal))); end;

> > > >

harmonic4_RE:=proc(h4,alfa2,theta) h4*(1-sin(Pi*(theta(beta+alfal+gammal+gamma2))/(2*alfa2))); end;

> > > > > >

cycloidal3_RE:=proc(h3,alfal,theta) h4+ h3*(1-((theta-beta-gammal-gamma2)/alfal) +sin((Pi*(theta-beta-gammal-gamma2)) /(Pi*alfal))), end,

> > > > > >

cycloidal4_RE:=proc(h4,alfa2,theta) h4*(1-((thetabeta-alfal-gammal-gamma2)/alfa2) -(1/Pi)*sin((Pi*(theta-beta-alfa1 -gammal-gamma2)) /alfa2)) ; end;

> parabolic3_RE:=proc(h3,alfal,theta) > (h3+h4)-(h3/(alfal)2)*((theta-gammal > -beta-gamma2)2); > end; > > > > > >

parabolic4_RE:=proc(h4,alfa2,theta) (h4)-(2*h4/alfa2)*(theta-gamma1 -beta-gamma2-alfal) +(h4/(alfa2)2)*((theta-gamma1 -beta-gamma2-alfal)2); end;

After the user specifies the types he or she wish to blend, together with the angles ß1, 02 , al and (12 and maximum lift H, the displacement diagram is assembled by the following

> > > > > > > > > > > > > > > > > > >

evalf(subs(theta=thetaf,S2)) elif(beta1+beta2+gamma1) > > > > > > >

htot:=proc(thetaf) local theta; if thetaf exp(-(t/eta)"beta): h:=t -> (beta/eta)*(t/eta)"(beta-1): H:=t -> (t/eta)"beta:

The various possible values of the two non-negative Weibull parameters, and their combinations, provide great flexibility and therefore extensive applicability to statistical studies as well as to the reliability/maintenance practice. For example, when 3 = 1 the Weibull is simplified to an Exponential distribution, and when p E [3, 41 it approximates to the Normal distribution [2]. The MAPLE code bellow plots the Weibull probability density function (pdf ) for .q = 1 and 13 = 1, 2, 3, and 4, as shown in Fig. 1. eta :=1: p:=seq(plot(f,0..2.5,0..1.6,color=COLOR ,rand()/10"12,rand()/10"12, rand()/10"12)), beta=l..4): plots[displayl([pl,labels=[time,pdfl); eta:='eta':beta:='beta'.

Another important attribute of the Weibull distribution is that it can serve as both a decreasing (,3 < 1) and increasing (13 > 1) hazard function model. The Weibull model enjoys wide applicability thanks to its resilience and its ability to provide a good fit for many different types of engineering survival data.

*School of Manufacturing and Mechanical Engineering, University of Birmingham, PO Box 363, Birmingham B 15 2TT, United Kingdom

79

,/: ibull Probability Plot and Maximum Likelihood Estimation of Its Parameters

> with(linalg):with(plots):Digits:=3: r.

Warning: new definition for norm Warning: new definition for trace

1. 1.

pdf 0. 0. 0. 0.

> > > > > > > >

ta:=vector([69,176,-195,208,215,233, 289, 300,384,390,-393,441,453,567,-617, -718,782 ,783,806,-1000,-1022]): N:=vectdim(ta): t:=map(proc(t) if type(t, negint) then 0 else t fi end,ta):

> > > > > > > > > > > > >

censorings:=pros() local e,i,j,k,countl,count2; e:=vector(N,0): for k from 1 to N do for i from k to N while t[i] O do countl:=i od: count2:=0; for j from countl+l to N while t[j]=0 do count2:=count2+1 od: e[countl]:=count2: k:=k+count2: od:RETURN(eval(e)); end:

> > > > > > >

risk:=proc(K) local i's; s:=0; if t[K]>O then s:=sum(e[i]+d[i] ,i=K..N) else s:=0 fi;RETURN(evalf(s)); end:

> > > >

e:=censorings(): d:=map(proc(t) if type(t, nonnegint) then 1 else 0 fi end,ta): n:=vector(N,risk):

> > > > > >

loadhazard:=proc(K) local v; v:=0; if t[K]>O then v:=evalf(d[K]/n[K]) else v:=0 fi;RETURN(v); end:

> > > > > >

loadcumulativehazard:=proc(K) local j,CH; CH:=O; if t[K]>O then CH:=sum(h[j] , j=1..K) ., else CH:=O fi;RETURN(evalf(CH)); end:

> > > > >

loadCHreliability:=proc(K) local R; if t[K]>O then R:=evalf(exp(-H[K])) else R:=O fi;RETURN(R); end:

r7 time

Figure 1: Weibull Probability Density Function for ß = 1, 2,3 and 4

Probability Plotting A probability plot is simply a cumulative distribution function (cdf) plotted on a graph with transformed axes such that the graph becomes a straight line. The transformation applied to the axes will depend on the type of distribution that is assumed to be characteristic of the data. The objective of PP is to obtain distribution parameter estimates using a simple, rapid and slightly approximate technique. However, the use of Cumulative Hazard (CH) analysis [1]-[2] has dominated the survival analysis studies in the engineering world, and therefore it is used for both the PP methodology and example presented in this paper. The CH procedure is applicable to all types of censored data and provides cdf estimates through the estimation of the hazard and cumulative hazard functions, hazard estimate h.(ij) = djlnj and cumulative hazard estimate h,(i,), respectively. Calculation of the cdf then is a direct application of the relationship between the cumulative hazard function and the cdf : F(t1.) = 1 —

AN EXAMPLE Let us assume that the following multiply censored data set, [3], is made available : Failures

69, 176, 208, 215, 233, 289, 300, 384, 390, 401, 452, 567, 782, 783, 806

Censorings

195, 393, 617, 718, 1000, 1022

i.e., ?fir = 21 lifetimes in total of which n f = 15 are failures and n, = 6 are censorings. For this sample, the CH estimates of the cdf have been calculated in Table 2. The latter has been reproduced from MAPLE using the following code :

UM

> h:=vector(N,loadhazard): > H:=vector(N,loadcumulativehazard):

Weibull

> Rch:=vector(N,loadCHreliability): > > > > >

loadEstimateOfC.D.F:=proc(K) local D; if t[K]>O then D:=evalf(1-Rch[K]) else D:=O fi;RETURN(D); end:

> CDF:=vector(N,loadEstimateOfC.D.F): > outestimates:=proc() > local i,j,count; > printf(' Event Failure S A M P L > E HAZ A R D Reliability C.D.F.'); > 1print(); > printf('Number Time Num. Time > Quantiles > Estimates Estimate Estimate ); > 1print O ; t(j) > printf(' i ta(i) j n d e > h(j) H(j) Rch(j) CDF(j) > 1print(); > printf('

Plot and Maximum Likelihood Estimation of Its Parameters

Rearranging the Weibull cdf (Tab. 1) we get: In { In l

1 } _ ,C~ ln t. — ,31n p. 1—F(t)jJJ

(2)

This represents a straight line of the form y = in.:z + c., with vertical ordinate y = — In In [1 — F(t)] , horizontal ordinate x = In t, slope in = ß and intercept on the Y axis r = ß In Thus, if the natural logarithm of the available lifetimes is plotted on the horizontal axis and y = — In In [1 — F(t)] on the vertical axis, then, if the data analyzed come from a Weibull distribution, the plotted points will approximately form a straight line. In that case, the shape parameter can be estimated from the slope of the regression line, and the scale parameter from the horizontal intercept c = A3 In rt. It would however greatly ease the calculations if there were available a form of graph paper where F(t) and t could be plotted directly, instead of having to transform each pair of observations into the logarithmic x and y values (Eq.2). This can be done as follows : F(lj) = 1 — e —eU where t. = e x

> > > > > > > >

1print();count:=0; for i from 1 to N do if ta[i]>O then count:=count+l; printf('%2g %7g %3g %5g %4g %2g %2g %8 g %6g %6g %10g',i,ta[i],count,t[i],n[i] ,d[i],e[i],h[i.],H[i],Rch[i],CDF[il); 1print();

> else > printf('%2g %7g ',i,ta[i]);lprint(); > fi; > od: > 1print(); > printf('

> _');lprint();

The Weibull graph paper consists simply of paper with the F(t) and t axes produced in this way, usually with the corresponding y and a axes omitted. This paper is commercially available (Chartwell, No 6572) [4] but a copy has been reproduced in Fig. 2 using MAPLE code: A formal curve fitting technique rather than "eyeballing" however is necessary to obtain accurate parameter estimates. This could be accomplished by using analytical methods of estimation such as maximum likelihood (ML).

Maximum Likelihood A considerable amount of work has been published on the non-graphical, i.e., analytical, estimation of densities. A Weibull—Graph

> printf('Table 1 Estimates of the > Reliability > y Function ');lprint(); > printf(' ); > > > > >

1print(); printf('* Note : Negative Lifetimes denote Censored Observations end:

> outestimates():

. ~ . `~. NM.I

Probability plots can be produced for many probability distributions by manipulation of the particular expression for F(t) .

Figure 2: Weibull Graph Paper

81

Weibull Probability Plot and Maximum Likelihood Estimation of Its Parameters

great share of that effort has been devoted to the Weibull distribution, especially to its two-parameter formulation which is studied in this paper. Of the analytical procedures available an accurate estimation technique is ML, although others like the least squares regression have occasionally drawn researchers' attention. Maximum-Likelihood Estimates (MLE) is reviewed in most of the major reliability textbooks, such as [5], [6], [7], and [8]. Important MLE work has also been published in papers ([9]). MAxIMuM LIKELIHOOD ESTIMATES Let us consider a general continuous distribution model under which a random set of the observed lifetimes ti have a time-dependent probability density function f (t : 0 1 i 02), where 01 and 02 are the model parameters which need to be estimated to fully define the distribution model used. Following the notation established in the previous sections, it is obvious that the cdf and reliability functions for this model are F(t, : 81 i 02) and R(t : 01 i 82) respectively. The likelihood function for such a set of censored lifetimes with n f failures and n, censorings is of the following form [8] : nI

n,

rl

L = ~ f (ti : 01,82 ) R(ti : 0 1) 82 ) i-1 i-1

(3)

Very often it is much easier to transform to the log -likelihood function : nj

n,

lnL =~ In f(ti : 01, 02 ) +

1n R(t,i : 81) 02 )

(4)

i=1

i=1

Since the estimates, theta estimate8l and theta estimate82 of the unknown parameters 01 and 02 maximise both the likelihood Eq. (3) and log-likelihood Eq. (4) functions, the MLE of each of the unknown parameters is obtained from the two following equations, involving the partial derivatives of either of these two functions : d1n L =0 for i = 1, 2 (5) 19 Bi

MLE f-,. theTwo-parameter Weibull istrnbuflon To simplify the complexity of the equations, let us temporarily replace 1/i7 in the functions described in Table 1 by A. According to the previous section then, the likelihood function for the two-parameter Weibull distribution can be transformed as follows : Table 1 L = lli J1 f (ti) ll2-1 R(ti)

A

L _ Ilnll ,ß(Ati)A—ie—()t,)o ~~`-1 P—(at,)ß

82

and after some algebra we obtain: nI

N

In L= n f 1n,C3-{-n f~3ln a-~-(,0-1) ~ In ti —ap ~ t.~ (6)

Estimates of the two Weibull parameters 13 and n can be now obtained by setting the partial derivatives of the above equation equal to zero. ti~

L9 In L

9

1 A

1, ] -~ `A =0~~-1 _ ~ _ ~r~, nI

1/p

An estimate of ri therefore can be obtained only after ,ß has been calculated. 91nL

,9,ß

= 0~ =>

1+~~

Int,

nI

_ ~E PT-- = O 1.p —

In the last equation the only unknown is 0. Due to its complexity however, the route Q cannot be calculated analytically. An appropriate convergence algorithm therefore would have to be employed to efficiently and speedily provide the root /3 of this particular function. Examples of such algorithms include the Van Wijngaarden-Dekker-Brent method [10], and MAPLE's FSOLVE routine used in this paper.

'T c PLE —fTlAximum LIKELIHOOD MATES Due to the notation adopted, the censoring lifetimes have been recorded as negative quantities. For the ML calculations however, the negative sign separating the failures from the censorings has to be removed. This, together with the complete MLE procedure in MAPLE V is detailed below. > > > > > > > > > > > >

tb:=convert(convert(convert(t,set) minus (0),1ist),vector):nf:= vectdim(tb): tc:=map(proc(t) abs(t) end,ta): fbeta:=1/beta+(sum(1n(tb[i]), i=1..nf)/nf) -(sum((tc[i]"beta)*ln(tc[i]), i=1..N)/sum( tc[i]"beta,i=1..N)):

Next, the number of digits used in the calculations is increased to the default.

Weibull Probability Plot and Maximum Likelihood Estimation of Its Parameters

> Digits:=10:

> >

BOLD,81,style=POINT, symbol=DIAMOND,xtickmarks=5,

> beta:=fsolve(fbeta=O,beta):

>

yticlunarks=5,color=red,

> eta:=evalf((sum(tc[i]"beta,i=1..N)/nf)

> >

labels=[Age_t,F_ ], view=[10..1000,1..1001):

> "(1/beta)): > > > > > > > > > > >

Ve:=matrix(2,21,[]):

> ap4:=loglogplot(Ve,style= > LINE,thickness=2, > color=navy, view=[10..1000,1..1001): >

vCDF:=transpose(convert(map(proc (t) t*100 end,CDF),matrix)): vt:=transpose(convert(t,matrix)): copyinto(vCDF,Ve,2,1): copyinto(vt,Ve,1,1):

> for i from -1 to 2 do > v[i]:=convert(vector(9,j-> evalf((j+1)*10^i)),set); > > od:i:='i': > Valuesofx:=convert(convert( > v[1] union v[2] minus (1000.), > list),vector):

> tp:=convert(sort(convert( > map(F*100,tb),list)),vector): > > tb:=convert(sort(convert(tb,list)), > vector): > tregression:=matrix(2,nf,[]): > > > >

for i from 1 to of do tregression[2,i]:=tp[i]; tregression[1,i7:=tb[i]; od: is='i':

> regressionline:=loglogplot( > tregression,style=LINE, > thickness=2,color=coral):

The Weibull Graph > Valuesofy:=convert(convert(v[-1] > union v[0] union v[1] ,list), vector): >

List of logarithmic plot structures Lines parallel to the x-axis : > devy:=0.001: > > for i from 1 to vectdim(Valuesofy) do > ap1[i]:=loglogplot([0.1, > Valuesofy[i],100, > Valuesofy[i]+devy,400, > Valuesofy[i]+devy,1000, > Valuesofy[i]],xtickmarks=17, ytickmarks=l,style=LINE, > > linestyle=3, > view=[10..1000,1..100]) > od: i:='i':

> display([ap3,seq(apl[i],i=1..27), > seq(ap2[j],j=1..17),ap4, > regressionline],insequence=false, > axes=BOXED,title=tl); > is='i':j:='j'. Weibull_Graph ••

_

,~~



~



,



,

~ ~ ~

1

Lines parallel to the y-axis : > devx:=0.01: > > for i from 1 to vectdim(Valuesofx) do > ap2[i]:=loglogplot([Valuesofx[i],1, > Valuesofx[i]+devx,10, > Valuesofx[i]+devx,50, > Valuesofx[i],100],xtickmarks=17, > ytickmarks=l,style=LINE, > linestyle=3, > view=[10..1000,1..1001): > od:i:='i': > t1:='Weibull_Graph':

• •



•• Age_t

••

••

•• z

Figure 3: Weibull Plot

In this paper the MLE calculations for the Weibull distribution were reviewed and the MAPLE V code for the estimation of the Weibull parameters and the reproduction of Weibull graph paper have been provided. The program's

> ap3:=loglogplot(Ve,axesfont=[COURIER,

83

Weibull Probability Plot and Maximum Likelihood Estimation of Its Parameters

complete graphical outcome for the example used in this paper, i.e., the scattergram of the plotted points plus the Weibull regression line obtained from the MAPLE V MLE procedure, is shown in Fig. 3.

References [1] W. Nelson: How to Analyze Data with Simple Plots, American Society for Quality Control, Milwaukee, (1979). [2] W. Nelson: Applied Life Data Analysis, John Wiley and Sons, New Fork (1982). [3] G. A. Bohoris: Comparison of the Cumulative-Hazard and Kaplan-Meier Estimators of the Survivor Function, IEEE Transactions on Reliability, 2, pp. 230-232, (1994). [4] B. Dodson: Weibull Analysis, ASQC Quality Press (1994). [5] N. R. Mann, R. E. Schafer, and N. D. Singpurwall: Methods for Statistical Analysis of Reliability and Life Data, John Wiley and Sons, New York, (1974). [6] L. J. Bain: Statistical Analysis of Reliability and LifeTesting Models-Theory and Methods, Marcel Dekker INC., New York, (1978). [7] J. F. Lawless: Statistical Models and Methods for Lifetime Data, John Wiley and Sons, New York (1982). [8] B. D. Bunday: Statistical Methods in Reliability Theory and Practice, Ellis Horwood, New York, (1991). [9] A. C. Cohen: Maximum Likelihood Estimation in the Weibull Distribution Based on Complete and on Censored Samples, Technometrics, 4, pp. 579-588, (1965). [10] W. H. Press, B. P. Flannery, S. A 'Teukolsky, and W. T. Vetterling: Numerical Recipes, The Art of Scientific Computing, Cambridge University Press, Cambridge (1986).

Biographies George A. Bohoris is a lecturer in Operational Research and Industrial Statistics in the School of Manufacturing & Mechanical Engineering, University of Birmingham (UK). He holds a B.Sc. in Mechanical Engineering, a M.Sc. in Quality and Reliability Engineering, a Ph.D. in Engineering Production, a Masters in Business Administration and a Diploma in Marketing. He is a chartered engineer and a member of the IEE, the OR Society, the ASQC, and the IQA.

84

Petros A. Kostagiolas is a research student in Operational Research in the School of Manufacturing & Mechanical Engineering, University of Birmingham (UK). He holds a B.Sc. in Applied Mathematics from the same university.

The Shooting Technique for the Solution of Two-Point Boundary Value Problems Douglas B. Meade, Bala S. Haran; and Ralph E. White' Introduction One of the strengths of Maple is its ability to provide a wide variety of information about differential equations. Explicit, implicit, parametric, series, Laplace transform, numerical, and graphical solutions can all be obtained via the dsolve command. Numerical solutions are of particular interest due to the fact that exact solutions do not exist, in closed form, for most engineering and scientific applications. The numerical solution methods available within dsolve are applicable only to initial value problems. Thus, at first glance, Maple appears to be very limited in its ability to analyze the multitude of two-point boundary value problems that occur frequently in engineering analysis. A commonly used numerical method for the solution of two-point boundary value problems is the shooting method. This well-known technique is an iterative algorithm which attempts to identify appropriate initial conditions for a related initial value problem (IVP) that provides the solution to the original boundary value problem (BVP). The first objective of this paper is to describe the shooting method and its Maple implementation shoot. Then, shoot is used to analyze three common two-point BVPs from chemical engineering: the Blasius solution for laminar boundary-layer flow past a flat plate, the reactivity behavior of porous catalyst particles subject to both internal mass concentration gradients and temperature gradients, and the steady-state flow near an infinite rotating disk.

A Maple Implementation of the Simple Shooting Method The basic idea of the shooting method for two-point boundary value problems is to reformulate the problem as a nonlinear parameter estimation problem. The new problem requires the solution of a related IVP with initial conditions chosen to approximate the boundary conditions at the other endpoint. If these boundary conditions are not satisfied to the desired *Department of Mathematics, University of South Carolina, Columbia, SC 29208, USA; E-mail: meade@math. sc. edu; WWW URL:

http://www.math.sc.edu/-meade/ ( Department of Chemical Engineering, University of South Carolina, Columbia, SC 29208, USA; E-mail: bala@sun. che. scar

olina.edu Department of Chemical Engineering, University of South Carolina, Columbia, SC 29208, USA; E-mail: rew@sun. che. scaro

lina.edu

accuracy, the process is repeated with a new set of initial conditions until the desired accuracy is achieved or an iteration limit is reached. To be more specific, consider the two-point BVP for a coupled system of n first-order ODES dy dt, = f (t, y(t)) yt ( a)

i = 1 2,... , 7n•1 j = 1, 2, . . . 7n2.

= a2,

yrn,+j (b) — ßj,

(1)

The vector y contains n, unknown functions of the independent variable t.. The unknown functions are ordered so that the first m l (0 < ml < n) components of y have first-kind boundary conditions at t = a (viz., (1)2). The remaining 7712 := n — m,l components of the solution have first-kind boundary conditions) specified at a second point, t. = b. (Note that if 7712 = 0, then (1) is an initial value problem.) The shooting method seeks to identify a vector of parameters s E Rrn2 so that the solution, denoted by y(t; s), to the initial value problem dy dt

y: (a; s)

= .f (t, y(t; •s)) = ai,

ym,+j(a;s) = sj,

i = 1, 2, . . . , m-i

j = 1,2,...

(2)

.m,2

agrees with the solution to (1). Note that (2) is simply (1) with the boundary conditions at t, = b replaced with unknown initial conditions at t = a. To determine the correct initial values, consider the "objective function" F with components Fj (S) := ym,+j (b; s)



Yj,

j = 1, 2, . . . 17712-

Then [1, p. 476], (1) is solvable if and only if there exists s E Rml so that F(s) = 0. The success of this process depends primarily on the iterative procedure used to construct a sequence of parameter vectors that converges to a zero of F. While any numerical' root-finding algorithm could be employed for this step, one step of the Newton-Raphson method is most commonly used. That is, given an initial guess s° E R' 2 , define a sequence of initial conditions {sk } by S k+l

,= sk — (VF(S

k)) 1F( sk )

IThe Maple procedure shoot supports nonlinear boundary conditions at t = b. In particular, (1)3 can be replaced with rj(y(b)) = 0, j = 1, 2, .., M2, where each rj is a differentiable function of n variables. The examples discussed in this paper all use rj (y(b)) := y,„, +.i (b) — /3j .

85

BVPs, Shooting Method, and Chemical Engineering

for all k: > 0. To implement this, note that the vector F(s') is directly available from the solution of (2), but the Jacobian matrix VF(s~) requires the values of ayas~, +° (b; sk ) for all i, j = 1, 2, • - • , M2. These values can be obtained by solving the n IVPs in (2) together with the nm2 sensitivity equations ([2 , p. 2261, [3, pp. 54-58]):

d (ayi )_ a f ay~ ~t asj — ay~ as,

i-1,2 ...~ n j = 1 ...~ m2

LorlinarBoundary-layer Flow Past a

with corresponding initial conditions ,9 y'

8s;

ay'"' +'

a3;

= 0,

_

Flat Plate

for all i = 1, • • , mi, j = 1, 2, •

b~~ •, for all i, j = 1,

subroutine COLSYS (available from Netlib). The numerical method used in this routine is collocation of B-splines at Gaussian points [5]. Finite difference methods can be easily implemented using MATLAB's fsolve command. The three examples discussed in this paper provide samples of how simple shooting, in particular shoot, can be applied to the analysis of boundary value problems that are encountered in chemical engineering.

m2

m2

The above algorithm is known as the simple, or single shooting method. While this method is effective for many problems, three specific problems should be mentioned [4]. Assume (1) has a unique solution. There is no guarantee that the initial value problem (2) has a solution on the interval [a, b] for all s E RM2 . Even if (2) does have a solution on [a, b], the problem may be stiff. In such a case the solution at t, = b may be so inaccurate as to make the results of the Newton-Raphson step meaningless. When the accuracy of the solution at t = b is known with sufficient accuracy, the local convergence of the Newton-Raphson step may prevent the iterations from converging to a solution of the original boundary value problem (1). This difficulty can be addressed by replacing the Newton-Raphson step with another iterative solver with improved convergence properties (e.g., modified Newton's method). The multiple, or parallel, shooting method addresses the other difficulties. As these problems are generally more pronounced as b - a increases, it seems appropriate to consider partitioning the interval into N subintervals. Then, using compatibility conditions between the subintervals, a well-posed IVP is obtained on each subinterval. The combination of Maple's facilities for symbolic manipulation and numerical solution of IVPs provide an excellent environment for the translation of the simple shooting method into the Maple programming language. The syntax for this procedure, called shoot, closely follows the syntax of dsolve. In particular, the data structures returned by shoot are identical to the ones returned by dsolve/numeric. Thus, all the techniques and tools for manipulating Maple's numerical solutions of differential equations, e.g., plots [odeplot], can be used to interpret the results from shoot. (The source code for shoot, including on-line help documentation, is available upon request from the first author.) Other numerical methods for the solution of two-point boundary value problems have also been developed on other platforms. One of the most well-known is the FORTRAN

Consider a fluid stream with velocity uo and kinematic viscosity v in which a thin plate is inserted parallel with the fluid flow. Determining the velocity of the fluid in the region close to the plate is the Blasius problem [6, p. 2331. Assuming the flow is steady, incompressible, and Newtonian, the plate is infinitely wide, and neglecting buoyancy, the equations of motion and continuity are: > restart; > alias( U=u(x,y), v=v(x,y) ): > PDE:= > ( U*diff(U,x)+V*diff(U,y) -nu*diff(U,y$2)=0, > diff(U,x)+diff(V,y)=0 }; >

PDE := { U

111

Cz\ äT

U + V I ~U1 \\\ J /// )

— v UY 2 U~ — °> V

U~ C~

+ (ay

) = 0~

where a and v are the x- and y-components of the fluid velocity. The boundary conditions consist of the "no-slip" conditions on the boundary of the plate: u(x, 0) = 7) (x, 0) = 0, and the free stream-merge condition lim u(x, y) = uo, for y- 00 all x > 0. A similarity transformation can be used to reduce this parabolic system of PDEs to a single ODE. This can be done by choosing the dimensionless similarity variable to be: > simsubs:=eta(x,y)=y*sgrt(u[0]/nu/x/2); 1 simsubs := rl( x, y ) = 2 y ~ FV U 01 The corresponding nondimensional stream function for the flow is: > stream:=psi(x,y) > =sgrt(2*nu*x*u[0])*f(eta(x,y));

stream := O(x,y)=~ vxuof(«x>y))

1

BVPs, Shooting Method, and Chemical Engineering

Thus, the velocities can be expressed as > Usubs:=U=diff(rhs(stream),y);

Usubs := U = V2 VT .r, uo

> ODE:= > simplify(subs(simsubs2,DDE),symbolic);

ODE := ~- Iu0 2

D(f)( 77(x,y)) G y ~r!(T , y)~

(D(2) (f)(q)f( 71)+D(3) (f)(q)) /T=0,0=0} .

> Vsubs:=V=-diff(rhs(stream),x); , Vsubs := V= - 1 ~f('7( ~' y ) ) v uo 2 vxu

v/2 v.r,uoD1(f)(q(x,y))

. ( x rl(T y) J Substituting the stream function representations of the velocities into the PDEs is tedious to complete by hand. )Fortunately, this is exactly one of Maple's strengths: > ODE:= > simplify(subs(Usubs,Vsubs,simsubs,PDE));

It is now easy to identify the Blasius equation f~ ..(77)

f C2 I

C2

,1_00

yVr2_F — uo

— uo y F

,)

vx,

v~

v. r,uoD(3) (f) C 2y

~ F _ V11 1X )

UO

X) ~wX2 F

f'

= 9'

f( 0) = 0

9'

= h,

9(0) = 0

h'

= - f h h(0) =,6

(4)

where a is the control parameter. The objective is to find Q so that the solution to (4) satisfies the boundary condition g(10) = 1. Since there is only one boundary condition at 9 = 10 we have m2 = 1 and s = 0. The sensitivity equations that are obtained from (4), together with their accompanying initial values, are:

0}

The trivial fulfillment of the continuity equation is evident in this result. However, the first equation is not so readily identified. To simplify this further, note that each argument to f, and its derivatives is simply g. To force this simplification, > simsubs2:= > solve(subs(eta(x,y)=eta,simsubs),(y));

simsubs2 :=

(3)

The "boundary condition" at 9 = oc presents a problem. However, a simple asymptotic analysis shows that solutions at ,q = 10 are safely in the far-field. The problem now takes the form of a third-order two-point boundary value problem for f on [0,10]. The reformulation as a first-order system is straightforward; let g := f' and h := f", then

f D(2)(f)

77 > 0.

The conversion of the boundary conditions can be done by inspection. The resulting conditions are f (0) = f'(0) = 0 and lim f'(77) = 1.

0=0,- 2uo2

ODE :=

+ f (rl)f"(rl) = 0,

Y =

9 uo V

fß(0) = 0

fp = 9ß> 9'p = hß

9ß(0) = 0

WO

hß (0) = 1

= - f A h, - f hß,

(5)

where, for example, fß(t; 0) := ap (t; ß). Now, assume that an approximate solution to (4) and (5) has been computed with s = sk, i.e. a = ~ k . Then, assuming 19(10; ßk ) - I is not sufficiently small, the next iteration will be made with

k ok+1 := ßk _ 9(10;,0 ) - 1 gß(10 ; ~ k ) While it is important to understand how shoot obtains its approximations, it is also a tremendous advantage to use Maple to both compute automatically and symbolically the sensitivity equations and iteratively solve the combined system of IVPs and take one step of the Newton-Raphson method until the boundary conditions are satisfied within a prescribed tolerance. Prior to preparing this problem for solution by shoot, it is necessary to load the definition of this procedure:

ME

BVPs, Shooting Method, and Chemical Engineering

less flow. The velocity reaches 99% of its bulk value when

> read shoot;

Now, define the dependent variables for the first-order system: > FNS:=( f(eta), g(eta), h(eta) ):

and the differential equations which they satisfy: > ODE:={ diff(f(eta),eta)=g(eta), > diff(g(eta),eta)=h(eta), > diff(h(eta),eta)=-f(eta)*h(eta) }:

The initial condition for f" is unknown, and the boundary condition at .q = 10 is the control for our iterations: > IC:=( f(0)=0, g(0)=0, h(0)=beta }: > BC:=g(10)=1:

We take the first shot with = 0, and iterate until the boundary condition is satisfied to six decimal places: > S:=shoot( ODE union IC, FNS, BC,beta=0, > bcerr=Float(5,-7) ):

This solution can be analyzed using any of the standard Maple tools for manipulating the numerical solution of a differential equation. A common place to begin is a plot of the solution, including labels to distinguish the different curves: > > > > > > > > > > > > >

with(plots): C:=odeplot( S, [ [eta,f(eta)], [eta,g(eta)], [eta,h(eta)] ],0..4): subs( [g='f ' , h='f " '], subs( [seq( op(O,lhs(F))=rhs(F(3.5)), F=subsop(1=NULL,S) )] ) ): L:=textplot( subs( eta=3.5,map(F->[eta,rhs(F)+1/10, lhs(F)],")),font=[TIMES,ITALIC,18], align=ABOVE ): display( (C,L), labels=['eta', '' ], title='Blasius solution for '. 'flat-plate boundary layer' ); Blasius solution for flat-plate boundary layer

2.!

f'(77) = 0.99: > fp:=subs( S, g(eta) ): > eta['99%']:=fsolve( 'fp(eta)'=0.99, > 'eta' );

rl.ssq" := 3.471887111 The corresponding boundary layer thickness is: > delta['99%']:=subs(eta=eta['99%'], combine(rhs(op(simsubs2))) ); > 699% := — 3.471887111 ~

V— v.-r, u°

As is now evident, the thickness of the boundary layer decreases with decreasing viscosity. The shear stress, r =µäy , is: > tau:=mu*simplify( > diff(subs(simsubs,rhs(Usubs)),y));

T:=



vruaD(2) (f) t 2 J~ vr to

ua ~/(vr)

J

`

Note that a large velocity gradient across the flow creates considerable shear stress in the boundary layer. The wall shear stress is: > tau [w]:= > subs( (D@@2)(f)(0)=subs(S,h(eta))(0), > subs( y=0, tau ) ); .2347998643 fr

v r u o uo

v .r, The analysis can be continued to obtain an understanding of parameters such as the displacement thickness and drag coefficient.

Porous Catalyst Prediction of the diffusion and reaction in a porous catalyst pellet is another important problem in chemical engineering. The reaction under consideration is A —> B which occurs inside the pellet. Mass balance and conservation of energy on the spherical pellet give

o.!

\r2 dr) — R(c,T) = 0 dT ) + (—OH R)R(c,T) = 0 ~ dr

eta

With increasing distance from the leading edge of the plate in the downstream direction the thickness S of the retarded boundary layer increases continuously as increasing quantities of fluid become affected. In the boundary layer the velocity of the fluid increases from zero at the wall (no slip) to its full value which corresponds to external friction-

88

r2 r~ är (

' (6 )

where c is the concentration of A, D, is the effective diffusivity, R(c,T) the reaction rate expression as a function of concentration c and temperature T, ke the effective thermal conductivity and —A H R the heat of the reaction. Due to radial symmetry about the center of the pellet dc

dr

0,

dT =0 d7,

at 7• = 0.

(7)

Y' BVPs, Shooting Method, and Chemical Engineering

On the surface of the pellet the quantities are at their bulk values: C = co,

at r = R.

T = To ,

(8)

For a simple first-order irreversible reaction R(c,T) = kocexp(— y ) RT ' the relationship between the reactant concentration and temperature at any point in the catalyst is given by [7]:

AT = T — T = —AH R De

The effectiveness factor, rl, for the reaction is the ratio of the average reaction rate with diffusion to the average reaction rate when the reaction rate is evaluated at the bulkstream (or boundary) values ([3, pp. 58-62], [8, p. 83]). Here is one way in which this quantity can be computed from the results returned by shoot: > eta:=3/phi"2*D(c)(1) > = subs(COEF,3/phi"2*dcdr1); 3 D( c)( 1) _ 100

dedrl

> dcdr1:=S1[2,11[2,31;

k

dcdrl := .03231087397210381

Introducing dimensionless variables

RTo , ß =

~

co(—OH R)De

c

7ß(l — y) ~ 1 + 0(1 — y)

Substituting these into (6) and the boundary conditions (7) and (8) leads to the two-point BVP ([7]) d~y

2 dy _ 2

dx~ + .r, dx

O = 1.077029132

k, Toy _ co +

the reaction rate can be expressed as R(y,T) = ko coy exp

> 'eta'=rhs(eta);

'yß(1 — y)

— ~ y ex p 1 +ß(1 — y»

As is well-known [8, pp. 87-881, for a given value of 0, the effectiveness factor can be multiple-valued. The other values can be obtained by starting the shooting method with different values of the control parameter: > Sh:= > shoot( subs(COEF,ODE) union IC, FNS, BC, alpha=1/2, value=array H 0,11) ); > > dcdr1:=Sh[2,1][2,3]: > 'eta' rhs(eta);

dy (0) = 0, dx

[[TY( ,t) z(x )]]

[[0,.1442192834000000,0] [1.,.999999999503557, .3250550528505473]]

y(1) = 1

where o:= R. D and x When expressed as a first-order system, this problem is easily solved by shoot for specific values of y, F~, and q. For example: > restart; > read shoot; > > > > > > > >

ODE:=( diff(y(x),x) = z(x), diff(z(x),x) = -2/x*z(x) + phi"2*y(x) *exp(gamma*beta*(1-y(x)) /(1+beta*(1-y(x))) ) }: FNS:=( y(x), z(x) }: IC:=( y(0)=a1pha, z(0)=0 }: BC:=y(1)=1:

> COEF:=[ gamma=30, beta=2/5, phi=3/10 ]: > S1:=shoot( subs(COEF,ODE) union IC, FNS, > BC, alpha=l, va1ue=array([0,1]) );

ri = 10.83516843 > SO:=shoot( subs(COEF,ODE) union IC, FNS, BC, > alpha=0, value=array([0,1]) ); > dcdr1:=S0[2,1l[2,31:

> ' eta -rhs ( eta) ; SO := [[XY(x)z(X)i]

[[0,.109667490400000010-',0] [1.,.999999998529494, 2.554522460710149]]

x

O = 85.15074869

Sl := [[xY(X)Z(X)]]

[[0,.9829180602000001,0] [1. 1.000000000280384, .03231087397210381]]

TO

BVPs, Shooting Method, and Chemical Engineering

The effectiveness factor has been computed for a wide range of values for ry, ,3, and 0. A sample of the results, for r = 30, are displayed in the following plot. The four datasets displayed in this plot correspond to Q = 0.4 (box — top curve), 0 = 0.2 (dotted line — second curve from top), 0 = 0.1 (solid line — second curve from bottom), and 3 = 0 (dashed line — bottom curve). The multiple values for the exothermic catalyst (13 = 0.4) were obtained using different initial guesses for the control parameter (a = 0, a = 0.5, and a = 1).

_—

pz + U ` W)"+ T W), + (vz )zz~ .

The boundary conditions are chosen (for all r > 0) to enforce no slippage at the interface with the disk: vr(r, 0) = vz(r, 0) = 0,

vo(r, 0) = rw, p(r, 0) = 0

(10)

and no non-axial viscous effect in the far-field: lim

Effectiveness Factor vs. Thiele Modulus, gamma=30 100 j

p

z —100

e

vr(r, z) = 0

ltm v0 (T, z) = 0

z —100

(11)

lim (vz )z (r, z) = 0.

z —100

10. 5

Similarity solutions to this equation were found by Kärmän [9], who noted that each of r , r , r , and p depends only on the distance from the disk, z. The system of PDEs reduces to a system of ODES with the introduction of z* = z v as the dimensionless independent variable for the dimensionless functions F, G, H, and P defined according

;

a eta

.__... ~ •

1.

••,.. ~...

0.5

r.MrI

to phi

vr =

ve = rwG(z*),

ni-z 2&ciUing Disk

I

rwF(z* ),

vz

Consider the steady fluid flow generated when the infinite plane z = 0, immersed in a Newtonian viscous fluid, rotates about the axis r = 0 with a constant angular velocity w. The viscous drag of the rotating surface creates a swirling flow toward the disk. The motion is characterized in terms of the pressure, p, and the three components of the velocity, yr ve vz, in cylindrical coordinates. The radial symmetry of this problem eliminates 0 as a independent variable. Thus, with p and v denoting the density and kinematic viscosity of the fluid and writing partial derivatives as subscripts, the equations of continuity and conservation of momentum reduce to

(12)

= wUH(z*),

P = pwvP(z*).

The substitution of (12) into (9), (10), and (11) can be completed in a manner analogous to that used in the Blasius problem. These steps are omitted here in the interest of space; the resulting BVP is

H' _ —2F F"

= F2 —G2 +PH

G" = 2FG + HG' P' _ —HH' + H" (13) F(0) = H(0) = P(0) = 0

[6]:

G(0) = 1

(rv r)r + W). 1'

lim F(z*) = lim G(z*) = 0.

=0

vr (vr )r + vz(vr

z"-100

)z — 1 (vB)2

r r

_ — ~pr + V(vr )rr + (Ur)r + (vr)zz T2 1 T J vr (2 JO )r + V z (vo )z +

1v rv 0

r

/ e~ J = U 1 (v0 )rr + T (7)0 )r + (vB )zz — T2 YJ r(v z)r + v z(vz)z

(9 )

z"'-100

Note that (13) can be solved as a two-point BVP for F, G, H. Once this solution is known, the pressure equation can be integrated to yield P = — z H 2 + H. In addition, note that any physically realistic solution must have F, G, P > 0 and H < 0 for all z* [6, p. 164]. Assuming the boundary condition at z* = oo can be applied at a finite distance from the disk, shoot can be used to obtain an approximate solution to this system. First, introduce the first derivatives of F and G as new dependent variables:

BVPs, Shooting Method, and Chemical Engineering

> restart; > read shoot; > with(plots):

Infinite Disk: alpha=0.51, beta=-0.62

> FNS:={ F(Z), G M , H(Z), Fp(Z), Gp(Z) ): 0.;

and reformulate the system as a first-order system of ODEs:

0. ,

> ODE:=(diff(H(Z),Z) = -2*F(Z), > diff(F(Z),Z) = Fp(Z), > diff(Fp(Z),Z) > = -G(Z)-2+F(Z)^2+Fp(Z)*H(Z), diff(G(Z),Z) = Gp(Z), > diff(Gp(Z),Z) > > = 2*F(Z)*G(Z)+H(Z)*Gp(Z)):

0. 0.:

with initial conditions: > IC:=( F(0)=0, G(0)=1, H(0)=0, FP(0)=alpha, Gp(0)=beta ): >

and boundary conditions (again, z* = 10 can be shown to be in the far-field): > BC:=( F(10)=0, G(10)=0 ):

Note that, as in the first example, the boundary condition at infinity has been moved to a finite position. The value z* = 10 is chosen as before on the basis that this is already in the far field. (In fact, truncating the computations at z* = 7 yields essentially the same solution.) Note also that since there are two boundary conditions at the second boundary point, there are two parameters to be determined in the shooting method (i.e., m2 = 2). This can be handled by shoot without modification: > infolevel[shoot]:=1: > S:=shoot( ODE union IC, FNS, BC, > [alpha=0.51, beta=-0.621 ): shoot:alpha = .51, beta = -.62 shoot:alpha=.5100033193, beta=-.6161487475 shoot:alpha=.5102117355, beta=-.6159070527 shoot:alpha=.5102135910, beta=-.6159096496

> P:=Z->-H(Z)"'2/2-2*F(Z): > > > > > > > > > > > >

C:=odeplot(S,[ [Z,F(Z)], [Z,G(Z)], [Z,H(Z)],[Z,-P(Z)] 1,0..10 ): subs( [seq( op(O,lhs(f))=rhs(f(3/4)), f=select(has,S,(F,G,H)) [op("),P=subs(", H"2+2*F)]: L:=textplot( subs(z=3/4, map(f->[z,rhs(f)+1/45,lhs(f)],")), font=[TIMES,ITALIC,181, align=ABOVE ): display( (C,L), labels=['z*' " ], title='Infinite Disk: ' .'alpha=0.51, beta=-0.62' );

This plot confirms that the solution satisfies the original boundary conditions at z* = co. (In fact, the solution obtained when the computational domain is truncated at .x* = 7.) Compare the solution in the preceding plot with the solution obtained when the starting values of the control parameters are a = 0.50 and 13 = —0.61 — each just 0.01 less than the first attempt: > S2:=shoot( ODE union IC, FNS, BC, > [alpha=0.5, beta=-0.611 ): shoot:alpha = .5, beta = shoot:alpha=.5181506133, shoot:alpha=.5178653168, shoot:alpha=.5019889119, shoot:alpha=.5040798081, shoot:alpha=.5042719718, shoot:alpha=.5042737786,

-.61 beta=-.5834922887 beta=-.5900697906 beta=-.5940268791 beta=-.5927957583 beta=-.5927086067 beta=-.5927079110

The different values of a and a suggest that the shooting method has returned a different solution. Is this also a solution to the problem? > > > > > > > > > > > > >

C:= odeplot(S2,[ [Z,F(Z)], [Z,G(Z)], [Z,H(Z)], [Z,-P(Z)l ], 0..12 ): subs( [seq( op(O,lhs(f))=rhs(f(3/4)), f=select(has,S2,{F,G,H)) [op("),P=subs(", H"2+2*F)]: L:=textplot( subs(z=3/4, map(f->[z,rhs(f)+1/45,lhs(f)],")), o font=[TIMES,ITALIC,18], align=ABOVE ): display( (C,L), labels=['z*' '' ], title='Infinite Disk: ' .'alpha=0.50, beta=-0.61' );

3

BVPs, Shooting Method, and Chemical Engineering

Infinite Disk: alpha=0.50, beta = -0.61

[2] Yonathan Bard, Nonlinear Parameter Estimation, Academic Press, 1974. [3] Mark E. Davis, Numerical Methods and Modeling for Chemical Engineers, John Wiley & Sons, Inc., 1984. [4] Uri M. Ascher, Robert M. M. Mattheij, and Robert D. Russell, Numerical Solution of Boundary Value Problems for Ordinary Differential Equations, SIAM, 1995.

-o

[5] U. Ascher, J. Christiansen and R. D. Russell, COL.SYS a collocation code for boundary value problems, Proc. Conf. for Codes for BVPs in ODEs, Houston, Texas, 1978. [6] Frank M. White, Viscous Fluid Flow, 1 st ed., McGrawHill, Inc., 1974.

Note that this solution does not satisfy the aforementioned sign constraints for F, G, H, and P for a physical solution to (13). Furthermore, while the boundary conditions at z' = 10 are satisfied, it is extremely unlikely that this solution will satisfy the boundary conditions at z* — oo. This is a spurious solution [6, p. 167]. Automating the detection of spurious solutions is extremely difficult. In some instances, this difficulty can be avoided by the use of one of the other solution techniques for boundary value problems mentioned previously.

Conclusion In this brief article we have introduced shoot, a Maple implementation of the simple shooting method for the numerical solution of two-point boundary value problems, and illustrated the application of shoot to assist with the analysis of three classic problems from chemical engineering. These examples demonstrate some of the potential that is available with Maple's combination of symbolic, numeric, and graphic computation.

Acknowledgment The authors would like to thank the referees for their useful comments. In addition, we would like to recognize our colleague, John Weidner, for his proofreading and suggestions. This project is a result of the interdisciplinary interactions supported by the Center for Electrochemical Engineering (URL: http : / /www-cee . the. sc . edu /), which has been funded by the State of South Carolina. In addition, the first author was partially supported by the National Science Foundation under grant DMS-9404488.

References [1] J. Stoer and R. Bulirsch, Introduction to Numerical Analysis Springer-Verlag, 1980.

92

[7] P. B. Wiesz and J. S. Hicks, The behaviour of porous catalyst particles in view of internal mass and heat diffusion effects, Chemical Engineering Science, 17, pp. 265-275, 1962. [8] Bruce A. Finlayson, Nonlinear Analysis in Chemical Engineering, McGraw-Hill, 1980. [9] T. von Kärmän, "Über laminare und turbulente Reibung," Z. Angew. Math. Mech., vol. 1, pp. 233-252, 1921.

Biographies Douglas B. Meade Douglas B. Meade received a Ph.D. in Mathematics from Carnegie Mellon University in 1989, then spent two years as a Research Assistant Professor in the Center of Applied Mathematics at Purdue University. Since 1991 he has been an Assistant Professor in the Department of Mathematics at the University of South Carolina. Research interests are presently directed towards numerical methods for PDEs, in particular, wave propagation on unbounded domains and nonlinear reaction-diffusion equations. Maple is used extensively in this research. Dr. Meade has also incorporated student usage of Maple into a variety of undergraduate and graduate courses. These efforts have been generously supported by the Office of the Provost, including funding (joint with Professor White) from the Lilly Endowment z Teaching Fellows Program. Bala S. Har°an Bala S. Haran received a Bachelors of Technology in Electrochemical Engineering from Central Electrochemical Research Institute, India in 1989. Since 1990 he has been a doctoral student in the Department of Chemical Engineering at the University of South Carolina. Research interests lie in the field of Electrochemical Engineering, in particular mathematical modeling of electro-kinetic processes, batteries and corrosion.

BVPs, Shooting Method, and Chemical Engineering

Ralph E. White Ralph E. White received his B.S. in Engineering from the University of South Carolina in 1971 and his M.S. and Ph.D. degrees from the University of California at Berkeley in 1973 and 1977, respectively. Dr. White joined the faculty at Texas A&M University (TAMU) in 1977 and was promoted to Associate Professor and Professor in 1981 and 1985, respectively. He served at TAMU as the Associate Head of the Department of Chemical Engineering from 1990-1992. Dr. White joined the faculty at the University of South Carolina in January 1993, and is now serving as the Chairman of the Department of Chemical Engineering and as a Westinghouse Distinguished Scientist. In addition, he is Director of the state authorized Center for Electrochemical Engineering in the Department of Chemical Engineering. Dr. White has also been active in research, having published over 130 refereed journal articles.

93

Process Control and Symbolic Computation: An Overview with Maple V Ay®wale B. Ogunyet Intr°oäu --Pon This paper will demonstrate advantages obtained in the design and analysis of linear control systems using symbolic computation. The representation of process control systems is by linear state space models or transfer functions models. As a result, the design and analysis of control systems using transfer function models entail the manipulation of polynomials for the computation of system time responses, Laplace and inverse Laplace transformations, Z and inverse Z transformations, frequency domain responses, stability analysis, controller tuning, solution of Diophantine equations, etc. In addition, the design of control systems represented by state space models involves the manipulation of matrices via the solution of matrix Lyapunov and Riccati equations, computation of eigenvalue-eigenvector decompositions, computation of system observability and controllability gramians, etc. The aforementioned calculations, except for trivial cases, are complex, lengthy, laborious and error prone. Furthermore, the solution of these problems in strict numerical computing environments, for example, Matlab (a matrix computing environment), results in a loss of the qualitative aspects of the design process. This happens because the emphasis is on the numerical manipulations being performed. Recently, there has been an interest in the application of symbolic computation to control design and analysis. Christensen (1994) describes the symbolic processor as a basic service in the computer aided control design process. Munro and Tsapekis (1994) discuss the use of Mathematica for computing Smith-Mcmillan forms and minimal balanced realizations. Polyakov et al. (1994) and Ohtani et al. (1994) describe the use of Mathematica packages for the design and analysis of nonlinear control systems. Ogunye and Penlidis (1995a, 1995b, 1996) discuss the use of MapleV to develop algorithms needed for the solution of state space design equations, computation of observability and controllability gramians, computation of minimal balanced realizations and the solution of matrix Lyapunov equations. Ogunye et al. (1995c) use MapleV to manipulate polynomial matrices in the rational functions field; algorithms for the solution of unilateral and bilateral Diophantine equations are developed. Jager (1995) describe a MapleV nonlinear controller package designed to help along with the analysis and design of nonlinear control systems. IComputing and Information Technology Laboratory, The Dow Chemical Company, Midland, Michigan, MI 48674, U.S.A, aogunye@dow.. corn

94

The first step in the analysis and design of a control system for a process is the development of a mathematical model. Process models enable us to study the transient and steady state behavior of our process units. These differential equation models are often nonlinear. Therefore, as a first step in linear control design, the nonlinear differential equations have to be linearized; consequently, we obtain a set of linear differential equations.

Consider the following nonlinear differential equation: dx(i ) dt,

= f[x(t), U(01

(1)

f(•, •) is a nonlinear function, x(t) and u(t) are the state and input vectors of dimensions P. x 1 and r x 1, respectively. A Taylor's series expansion of equation (1) about Ws = [x,, (t), uss(t)I results in a att

= f[xss (t), uss(t)] I ar[ äx~~~ af[ a(u~t~(t))

+

(t)7

k.. {x(t) — xAq (t)}

Iss{u(t) — ue8(t)}

(2)

= f[x,.(t), u._(t)], equation (2) becomes

Since

a(x(t)—Xea(t)) — afL(t),u(t)]

at

— +

ax(t) af[X(t),U(t)]

au(t)

{x(t) — X88 (t)} jss{u(t) — u88 (t)}

(3)

Define Ax(t) = {x(t) — xss(t)} and Du(t) = {u(t) — uss (t)} as perturbation variables. Then equation (3) becomes a linearized perturbation equation. Since the linearization is about a steady state operating point, the initial conditions for these linearized perturbation equations are all equal to zero. Procedure diffeqnlin performs the above mentioned computations for a single nonlinear differential equation. > > > > >

diffegnlin:=proc(degn,stvart,stvar, ststate,Ldegn) local nvar ,alstat, lijacob, Ll,stdstat, i; with(linalg,jacobian):

> > > > >

# # # # #

deqn: nonlinear differential eqn. stvart: List of state and input variables as a function of time stvar: List of state and input variables without time dependency

Process. Control and Symbolic Computation: An Overview with Maple V

> # ststate: List of steady state values > # of stvart > # Ldeqn: Linearized equation

> > > > > > > > > >

> L1:=rhs(deqn); > nvar:=nops(stvart); > alstat:=(op([seq(stvart[i]=stvar[i], > i=1..nvar)])); > stdstat:=(op([seq(stvar[i]= > ststate[i],i=1..nvar)])); > L1:=subs(alstat ,L1); > lijacob:=jacobian([L1],stvar); > lijacob:=subs(stdstat, > eval(lijacob)); > Ldeqn:=lhs(degn)=sum('lijacob[1,ii]* > stvart[ii]', 'ii'=1..nvar); > end:

rhsee:=rhs(ee): rhsee:=pw(coeff(rhsee,ca(t))=kappa, rhsee): rhsee:=pw(coeff(rhsee,T(t))=theta, rhsee): rhsee:=pw(coeff(rhsee,Ti(t))=phi, rhsee): rhsee:=pw(coeff(rhsee,Tc(t))=lambda, rhsee): see:=lhs(ee)=rhsee; see

etT(t) T(t)O+OTi(t)+Tc(t)A+ca(t)r.

Similarly, we carry out the linearization of equation (5) as follows: Consider the mathematical model of a continuous stirred tank reactor (CSTR) given by (Stephanopoulos, 1984; page 125): T(t) ät,T(t)=Ti(t)~

at

t)=

ca( t) — ko e(

a T t) ca( t) (5)

UAt(T(t) —Tc(t)) Pcp V

a

ca(t) =

cai(t) — ca(t) T

(_ — ko e ( ß T~ )) ca(t)

> diffegnlin(f2,[T(t),Ti(t),Tc(t),ca(t)], > [T,Ti,Tc,ca],[Ts,Tis,Tcs,cas],'ee'):ee;

8 q t _ — 1 + Jko E e( — RT,) cas _ UAt T t, öt () T Pcp V) ( ) R Ts 2 +

Ti( t) T

-I

U At, Tc(t) cV

T, )~ ca(t) ca(t) _ ~— — ko e( — ri

car( t, )

— koEe(— aT,) casT(t)

R Ts

P_ 8tT(t) = Ti(t,)~ T(t) +Jkoe~ aT(t)) ca( t)

at

öt

(4)

Equations (4 and 5) are linearized as follows:

P :=

> [ca,cai,T],[cas,cais,Ts],'dd'): dd;

+Jkoe( — aT ~ )ca(t)

_ UAt,(T(t,)—Tc(t)) P cp V cai( t)~

> diffegnlin(fl,[ca(t),cai(t),T(t)],

c

+Jkoe( —RT., ) ca( t)

P p

We make the notation in this linearized equation succinct by redefining the coefficients of T(t), Ti(t), Te(t) and ca(t) as B, 0, A and r,. This is done as follows:

In addition, we make the notation succinct by redefining the coefficients of ca(t), cai(t) and T(t) as a, /3 and y as follows: > > > > > > > > >

macro(pw=student[powsubs]): rhsdd:=rhs(dd): rhsdd:=pw(coeff(rhsdd,ca(t))=alpha, rhsdd): rhsdd:=pw(coeff(rhsdd,cai(t))=beta, rhsdd): rhsdd:=pw(coeff(rhsdd,T(t))=gamma, rhsdd): sdd:=lhs(dd)=rhsdd; sdd := at ca(t) = aca(t) +/3cai(t)+T(t) y

Note the ease with which we carry out this linearization process (symbolic differentiation) correctly. We can manipulate the resulting linear differential equations to obtain the inputoutput relationships (transfer functions) for this process (see Example 2).

Laplace-Domain Analysis The Maple command laplace performs Laplace transformations. It recognizes the Heaviside and Dirac delta functions. These functions allow the construction of any type of input forcing signals. Presented in the next sections are examples illustrating the uses of the Laplace transform.

95

Process Control and Symbolic Computation: An Overview with Maple V

TRANSFER FUNCTIONS The transfer function is the ratio of the Laplace transform of the output to the input signal. It is represented as follows: Y(8) G s_ Q(s) _ I~m r(s — gj) () u(s) P(s) II~ 1(s — pi)

(6)

where y(s) and u(s) are the Laplace transform of the output and input, respectively, while G(s) is the transfer function. Q(s) and P(s) are polynomials. For physically realizable systems, polynomial Q(s) will be of lower order than P(s). The roots of P(s) are the system poles while the roots of Q(s) are the process zeros.

We carry out the Laplace transform of equation (4) in a similar fashion: > lss:=laplace(see,t,$): > 1ss:=subs(T(0)=0,1ss);

Iss :=T(s)s=BT(s)+0Ti(s)+ATc(s) +r, Ca( s) Because we have two outputs, Ca(s) and T(s), and two equations, l ss and l dd, we can solve for the input-output relationships between the outputs and the inputs ( Cai(.$), Ti (s) and Tc(.$) ). We proceed as follows: > matxtrf:=solve({lss,ldd),{Ca(s),T(s))):

DI'NAMIC RESPONSE

> collect(matxtrf[1],[Ti(s),Tc(s), > Cai(s)]);

The dynamic response of a system to various input signals is investigated by computing the inverse Laplace transform of the product of the transfer function (G(s)) and the Laplace transform of the input signal (u(s)). From equation (6), we

T( s ) ~

_ (s~—cx¢)Ti(s) (sa—a.~)Tc(s) 0/01 %1

~

~iCai(s)n

have

%1 y(s) = G(s) u(s).

(7)

Taking the inverse Laplace transform of equation (7), we ob-

%1:=—s2 +8a+0s-0a+K'y > collect(matxtrf[2],[Ti(s),Tc(s), > Cai(s)]);

tain

Y(t) = C i{y(s)} = .C-1 {G(s) u(s)}.

(8)

Ca(s) = 0 7 Ti(s)

AyTc(s) (,(is—,OB)Cai(s)

%1 — %1

MWIMIT.-W

2

We present an illustration of the process of Laplace transforming a differential equation using the linearized equations obtained in Example 1. To obtain a compact structure for the resulting Laplace transformed variables, we proceed by forming aliases viz.: > alias(Ca(s)= laplace(ca(t),t,$),

%1

+,sa+Bs—Ba+~Y

We now have the transfer functions relating the process outputs to the process inputs. In this example, we have Laplace transformed a set of differential equations and solved the resulting equations for their input-output relationships. Example 3

> Cai(s)=laplace(cai(t),t,$), > T(s)=laplace(T(t),t,$), > Ti(s)=laplace(Ti(t),t,$), > Tc(s)=laplace(Tc(t),t,$));

1, Ca(s ),Cai(s),T(s),Ti(s),Tc(s) Equation (5) is Laplace transformed as follows: > ldd:=laplace(sdd,t,$);

ldd := Ca(s)s — ca(0 ) = a Ca(s) +

0 Cai(s) + yT(s)

The initial conditions for linearized equations are equal to zero. Therefore, we substitute the initial conditions for zero as follows: > 1dd:=subs(ca(0)=0,1dd);

The following example illustrates the process of computing a system response to an input signal by using the inverse Laplace transformation. Consider the following transfer function of a first order process with dead-time given as follows: G(s) _ K

exp( —Td s ) (T s + 1)

We determine the process output to an impulse, step and arbitrary input signal using the inverse Laplace transform. First, we define the input signals. The Dirac function enables the construction of the impulse signal as follows: > impulse:=Dirac(t);

impulse := Dirac(t) ldd, := Ca(s) s = a Ca(s) -)-,0 Cai(s) + yT(s)

(9)

V

Process Control and Symbolic Computation: An Overview with Maple V

Output Response

and its Laplace transform is > Impulse:=laplace(impulse,t,$);

1

Impulse := 1 We define the step signal using the Heaviside function as follows: > step:=Heaviside(t);

step : Heaviside(t )

Y(t)

> Step:=laplace(step,t,$); Step~= 1 .s

The transfer function model is given as: > Gs:=K*exp(-tau[d]*s)/(tau*s+1);

Gs :_

K e(—TB ~)

Time cross=Step response circle=Impulse response box=Arbitrary response

Ts+l

The dynamic response to the impulse signal is > impulsegs:=invlaplace(Gs*Impulse,s,t);

impulsegs :_

Figure 1: System Response for Example 2

K Heaviside (t. - Td ) e

T while the response to the step input is given by

Frequency Domain Analysis

> stepGs:=invlaplace(Gs*Step,s,t); stepGs := K Heaviside (t - Td)

i4l) + 1~

-e

The arbitrary input signal has a magnitude of 5 starting at time t = 5 and ending at time t = 10. We construct this signal as the difference between two delayed signals as follows: > Arbsigt:=Heaviside(t-5)> Heaviside(t-10);

Arbsigt, := Heaviside(t - 5) - Heaviside(t - 10 ) > Arbsig:=laplace(Arbsigt,t,$);

Arbsig :_

e (-ss) .S

-

e(-los)

Frequency response techniques are among the popular methods for the analysis and design of control systems. These techniques enable the study of the stability characteristics of a closed-loop system; they also enable the determination of the appropriate values of the adjustable parameters in a controller. When a linear process is subjected to a sinusoidal input (A sin ( w t ) ), its steady state response is also a sustained sinusoidal wave with the same frequency as that of the input signal, but with a different amplitude that either lags (falls behind) or leads (rises ahead) the input. The ratio of the output amplitude to the input amplitude is a function of the input frequency w and is given by the modulus of G(s) if we substitute s = I w :

,S

Ali. = modulus of G(I w) > ArbGs:=invlaplace(Gs*op(1,Arbsig),s,t) > +invlaplace(Gs*op(2,Arbsig),s,t); i—rT —5

ArbGs := KHeaviside (t - Td - 5)

-e(

- K Heaviside (t - Td - 10) -e

_

) + 1~ }1

(10)

while the output wave is shifted with respect to the input wave by an angle ¢ which is a function of the input frequency w given by

0

= argumentof G(Iw).

(11)

Consider the following transfer function: Figure 1 presents the output response of this process (K = 10, Td = 3, and T = 7) to the various input signals.

G(s) _

K {~ i (s - gz)} exp( -Td s)

rIi- i(s -pi) rl i'= 1 (4i (s)} exp( —Td s) = Ki ~~ 1P i(s)

(12)

97

Process Control and Symbolic Computation: An Overview with Maple V

Substituting s = I w into equation(12) we obtain

>

di(I w)} exp(—Td I w)

G(s) = K{~~I

(1~)

~i —1 pi (I w)

The modulus of G(I w) is given by

'

(14)

l li I Ii~i ( I w) (

I

while the phase angle of G(I w) is arg (G)

_

—TdW -I-

"

E sin-., i=1

~

— ~ sin —

rRe

IL

(Iw))1 ZIw) ~

~Re(pi(I w))1

(15)

The Bode diagram consists of a pair of plots showing: 1. How the amplitude ratio varies with frequency 2. How the phase angle varies with frequency With regard to the Bode plot, defined is a couple of important system parameters: Crossover frequency (w, j The frequency where the phase angle is equal to —180°. The amplitude ratio at LL),, is defined as Nl,o. Gain margin or ultimate gain (K,y) 1/•M,o Phase margin Let 0A R = I be the phase angle at the frequency where the amplitude ratio = 1. The phase margin is equal to 180 -I- ¢AR-I Ultimate period (P,,,) 2 ö Procedure ProcBode carries out the frequency domain computations for a transfer function model G(s). The frequency domain computations have harnessed Maple's ability to manipulate complex numbers.

98

> > > > > >

if nops (timedey) = 1 then nTrfGs:=nTrfGs/op(timedey); timedey:=subs(s=omega, op(op(timedey))); else timedey:=0

fi;

> > > > > > >

Procfac(nTrfGs,s,'fnTrfGs','dum'); ProcMabs(fnTrfGs,s,'MagNnt','AngNnt'); Procfac(dTrfGs,s,'fdTrfGs','dum'); ProcMabs(fdTrfGs,s,'MagDnt','AngDnt'); MagGs:=MagNnt/MagDnt: AngGs:=timedey+AngNnt-AngDnt; end:

> > > > > > > > > > > > >

# Procedure to compute magnitude and # phase angle of a complex number # Z(I)= Re(z) + I *Im(Z); # magtt:magnitude # argtt: phase angle procabs:=proc(tta,magtt,argtt) local tt; tt:=evalc(subs(s=I*omega,expand(tta))); magtt:=simplify(sqrt( coeff(tt,I,O)"2 +coeff(tt,I,1)"2)); argtt:=aresin(simplify(coeff(tt,I,1) /magtt)); end:

> > > > > > > > > > > > > > > >

# Compute the magnitude and phase # angle of a series of first order # transfer function models ProcMabs:=proc(fnTrfGs:list,s:name, MAG,ANG) local Nnt, PNnt, MagNnt, Gtrf, mag, ang, AngNnt,mtt,i; Nnt:=nops(op(2,fnTrfGs)); PNnt:=op(op(2,fnTrfGs)); MagNnt:=[fnTrfGs[1]]: AngNnt:=[]: for i from 1 to Nnt do if Nnt=1 then Gtrf:=PNnt[1];mtt:=PNnt[2]; else Gtrf:=PNnt[i][1]; mtt:=PNnt[i][2]

1

ODE ANALYSIS

> > > > > > > > > > > > > > > >

fi;

>

G _ K{ 112'~-- I'(di(Iw)I} j7

fi;

>

# Frequency Domain Analysis # TrfGs: Transfer function model # s: Transfer function indeterminate # MagGs: Amplitude ratio # AngGs: Phase angle ProcBode:=proc(TrfGs,s,MagGs,AngGs) local nTrfGs, dTrfGs,timedey,fnTrfGs,Nnt, PNnt,MagNnt,Gtrf,mtt,mag,ang,AngNnt,AngDnt, MagDnt,PDnt,i,Dnt; nTrfGs:=numer(TrfGs); dTrfGs:=denom(TrfGs); timedey:=(indets(nTrfGs,function)): if nops(timedey) = 1 then if not op(O,op(timedey))='exp' then ERROR ('Exponential Function Expected');

> > > > > > > >

fi; procabs(Gtrf,'mag' 'ang'); MagNnt:=[op(MagNnt),mag$mtt]; AngNnt:=[op(AngNnt),ang$mtt]; od; MAG:=convert(MagNnt,'*'); ANG:=convert(AngNnt,'+'); end:

>

> > > > > > > > > > > >

# Procedure to factor a polynomial # bpoly: input polynomial # fpoly: list of polynomial in factored # form; # rrpoly: factored polynomial Procfac:=proc(bpoly,s,fpoly,rrpoly) local rpoly,ij,bbpoly,lcpoly; readlib(factors); bbpoly:=expand(bpoly); lcpoly:=lcoeff(bbpoly,$); bbpoly:=bbpoly/lcpoly; rpoly:=[fsolve(bbpoly,s,complex)];

Process Control and Symbolic Computation: An Overview with Maple V

> if not nops(rpoly)=degree(bpoly,$) then > > ERROR('roots not solved for'); > fi: rpoly:=convert(rpoly,rational): > > rpoly:=product( (s-rpoly[ij]), > ij=1 .. nops(rpoly) ); rpoly:=rpoly*lcpoly; > > rrpoly:=rpoly; > fpoly:=factors(rpoly): > end:

=LM Presented is a representative example of designing closedloop control systems using the concepts of frequency response analysis. Figure (2) contains the block diagram of a closed-loop control system. The closed-loop response of the block diagram given in Figure (2) is

Figure 2: dock Diagram of Closed-Loop Control System procedure ProcBode as follows:

Y(s) = Gsp(S) Ysp(S) + Gload(S) dSP(s)

( 16)

where

> GsKc:=(8/10)/((3*s+l)*(30*s+1)*(10*s+1)); G Kc:= 5

GSP('s)

=

Gp(s)Gc(s) 1 -1Gp(s)Gc(s)

(17)

> ProcBode(GsKc,s,'MagGs','AngGs'): > 'MagGs':=MagGs;'AngGs':=AngGs;

Gd(s)

G load (S) =

(3s+1)(30s+1)(10s+1)

1 + GP(S)GC(S)

MagGs := 5

The transfer function of the Proportional-Integral-Derivative (PID) controller is

AngGs := —aresin 10 G, (s)= Kc ` 1+ 1 + Tds~ \

(19)

Ti S

— aresin 3

One of the established methods of determining the adjustable parameters in a PID controller is the Ziegler-Nichols tuning technique (Stephanopoulos, 1984). Table (1) contains the Ziegler-Nichols controller settings. Type of Control

Kc

Proportional (P)

2 — — zo

Proportional-Integral (PI)

K,

z.z

r;

1.2

Td



Proportional-Integral-Derivative ~ 2.0 8.0 (PID) Table 1: Ziegler-Nichols Controller Settings Consider the open-loop transfer function of a heat exchanger process (Smith and Corripio, 1985; page 319) given by:

1-I- 9 w 1-}- 900 w2

1+ 100 w w

1 + 100 wz

w _ +9 wz 1

aresin 30

w 1 + 900w2

The crossover frequency wco (rad/min) and ultimate period P u are determined as: > omega[co]:=fsolve(-Pi=AngGs,omega); > P[u]:= evalf(((2.*Pi)/omega[co])); w ca

:= .2185812841

P„ := 28.74530330

while the gain margin K u is > K[u]:=1/subs(omega=omega[co],MagGs);

K„ := 23.83333332

z

A proportional-integral-derivative controller using the Ziegler-Nichols settings is subsequently designed. The closed-loop system response to a step change in the set-point (y sp (s)) is also determined. These computations are carried out as follows: > Gc:=Kc*(l+ 1/(taaui*s) +(taud*s));

G(s) — Kc

8 10 (3 s + 1) (30 s + 1) (10 s + 1)

(20)

Gc := Kc { 1 +

\

1 + taud s)

taui s

The amplitude ratio and phase angle are computed using

SO]

Process Control and Symbolic Computation: An Overview with Maple V

> Gcsp:=(Gc*GsKc )/(1+(Gc*GsKc)): > Gcsp:=unapply(Gcsp,Kc,taui,taud): > PIDGcsp:= ((Gcsp(K[ul/1.7,P[ul/2.0,P[ul/8))): >

The process response to a step change in the set-point is plotted in Figure (3). > PIDresp:=evalf(evalc(invlaplace > (PIDGcsp*(1/s),s,t))):

In this example, we determined the analytic amplitude ratio and phase angle, numerically calculated the crossover frequency and gain margin, and computed the closed-loop system response.

State Space Analysis and Design

8 6 4

In this section, we illustrate the analysis and design of discrete-time control systems with concepts from: (1) poleplacement design, (2) solution of Riccati equations and (3) design of linear quadratic controllers.

0. 2 0 0 20 40 60 80 10012014016018

DISCRETE-T'IME SYSTEMS

C

Consider the discrete-time state space system described by: X [(k + 1)] = G X(k) + H U(k)

(21)

Y(k) — C X(k) + D u(k)

(22)

where G, H, C, D are matrices of dimensions n x n, n x r, in, x n., m x r, respectively, and Y, X and i1 are the output, state and input vectors of dimensions m x 1, n. x 1 and r x 1, respectively. The solution to equation (21) is given in Ogata (1987) as: X(k)

= Z -1 { [(zI — G)

-1]

[zX(0) + H U(z)]} (23)

The state transition matrix is Gk = .S-1 [(zI — G) -1 z]

(24)

Z denotes the z transform operator. The pulse transfer function matrix (matrix relating the output to the input of the process) is F(k)

=

S-1 [C (zI — G)-1 H + I)]

(25)

All the foregoing computations are carried out in procedure dtran. > > > > > > > >

dtran:=proc(GG,HH,CC,DD,XOO,UZ ,Gk,Xk,Yk,Fk) local G,H,C,D,XO,n1,ii,Gkz,Fkz,Xkz; with(linalg,inverse,coldim); readlib(ztrans); G:=map(convert,GG,rational); H:=map(convert,HH,rational); C:=map(convert,CC,rational);

Figure 3: System Response for Example 3

D:=map(convert,DD,rational); > XO:=map(convert,X00,rational); > n1:=coldim(G): > ii:=array(identity,l..n1,1..n1): > Gkz:=evalm((z*ii-G)"(-1)); > Gkz:=map(simplify,Gkz); > Gk:=map(invztrans,evalm(z*Gkz),z,k); > Xkz:=evalm(Gkz&*(z*XO+H*UZ)): > Xkz:=map(simplify,Xkz); > Xk :=map(invztrans,Xkz,z,k); > Yk:=evalm((C&*Xk)+(D*UZ)); > Fkz:=map(simplify,evalm( > (C&*Gkz&*H)+D)); > Fk:=map(invztrans,Fkz,z,k); > > end:

Example 5 To demonstrate the use of procedure dtran to compute the state transition (G k ) and pulse transfer function F(k) matrices, state matrix X(k) and output matrix Y(k), consider example 5-3 from Ogata (1987) with system matrices given as:

GG=

0

1

1 ,HH=

1 1 0 1

1,

1

—.16 —1 CC

0

1 DD=

0 0

1,

Process Control and Symbolic Computation: An Overview with Maple V

1

z

XO =

Ur = z —

—1

considered here is of dimension 1 x 1). Consider the nth order system modeled by

1

X [(k + 1)] = G X(k) + H U(k) > dtran(GG,HH,CC,DD,XO,Ur,'Gk','Xk', >

(26)

The control input is generated by the relationship

'Yk','Fk'):

> G[kl=eval(Gk);

U(k) = — K X(k)

(27)

K = [ K1 K2 . . . K,]

(2$)

where

Gk I

(- ) k + 4 3 54

3

(

) k

51

Substituting equation (27) into equation (26), we obtain X [(k + 1)] = {G — H K } X(k,)

3 ~ 54)k+3 ( 51)kl

[15 (

J4 ) k

—j1

l

5 1k

= ,

G f X(k,)

The desired closed-loop pole locations are chosen as

Z = A1, A2, ... An 3

~ 54)k 3 ( 51)k]

(

> X[k]=eval(Xk);

Xk =

25 31 54 13 25

_I)k

61 27

5

31

1

244

54 + 90 (5) > Y[k]=eval(Yk);

Ik =

25 27

62 45

25 31

54+90

( C

(

-4) k 5

-4

135 ( 5)k

-1) k + 61 (-4\ k 5 135 5J 1 k 244 (-4 k

5~

135

5~

> F[k]=eval(Fk);

Fk =

m 24 (k) — 12 ( 54)k J1)k ~k 3 k —3 54 51\



A(k) is the Kronecker delta function defined as follows:

0(k) _

1k=0 0 k;40

POLE - PLACEMENT DESIGN This controller design methodology results in the assignment of the poles of the closed-loop transfer function (zeros of the characteristic equation) to any desired locations. The poleplacement design procedure is presented (the control signal

(29)

(30)

Consequently, the closed-loop system characteristic equation is n zI — G—HK i z— A i) (31)

{

} = jI( t-1

In equation(31), there are n unknowns K1, ... , K,,, and n. known coefficients in the right-hand-side polynomial. Therefore, by equating coefficients, the unknown gains are solved for. The pole-placement controller design computations are carried out in ProcPole. Maple's ability to manipulate matrices and polynomials make these calculations possible; it also gives the calculations a "symbolic touch". > > > > > > > > > > > > > > >

>

# This procedure computes the gain # matrix K for a pole-placement # problem with a scalar input vector ProcPole:=proc(G;matrix(anything,square), H:matrix,despole:list,z,K) local n1, despoly,cofK,closedpoly,poleegn; with(linalg,rowdim,coldim,charpoly): n1:=rowdim(G); if nops (despole) nl then ERROR('Number of desired poles must equal system dimension'); else if not coldim(H)=1 then ERROR('Scalar Input vector neede,a H should be (n X 1)');

fi;

> fi; > despoly:=expand(product((z> despole['i']), 'i'=1..n1)); > > K:=array(1..1,1..n1): > cofK:=convert(evalm(K),set): > closedpoly:=charpoly(evalm(G-H&*K),z); > poleegn:={coeffs(collect( > closedpoly-despoly,z),z)); > assign(solve(poleegn,cofK)); > end:

101

Process Control and Symbolic Computation: An Overview with Maple V

Example 6 A pole-placement controller is designed for the system given in example 5. It is desired to place the closed-loop poles at z = 0.5 + 10.5 and z = 0.5 — 10.5 (Example 6-7; Ogata, 1987). The gain matrix K is designed using ProcPole as follows: > ProcPole(GG,HH,[.5+I*.5,.5-I*.5], > z,'GainK'):

Gainmat,rix = [ .34 —2.0 We verify that the closed-loop poles are at the desired locations by computing the eigenvalues of the closed-loop characteristic matrix G f (equation 29) as follows: > evalf(Eigenvals(evalm(GG-HH&*GainK))); [.500000 + .500000 I .500000 — .500000 I]

MUFF.W WOMSTM In this section, we present the design of linear controllers minimizing a quadratic objective function subject to the process model. This design methodology results in a linear, time-varying state feedback controller. However, we only discuss the steady-state solution. The steady-state linear quadratic (LQ) objective function is 00

JN =

T

[XT (k) Q X (k) + U (k) KU(k)1

(32)

k=0

where Q is a symmetric positive or positive semidefinite matrix and R is a symmetric positive definite matrix. The process model is given in equations (21 and 22). The steadystate linear quadratic control law (Ogata, 1987) is as follows: U(k) = — K X(k)

(33)

K=[R + HT P H]-1 HT PG

(34)

where

and P is the symmetric, positive definite solution to the following discrete-time Riccati equation: P= Q+ GT P G— C P FI K

(35)

The symmetric, positive definite solution P to the Riccati equation is computed in procedure riccat. The solution of the matrix Riccati equation is not a trivial computational issue. Fortunately, this is not the situation with Maple's ability to convert a matrix quadratic equation into a set of equations and unknowns. It is an effortless process to solve the resulting equations. In addition, the steady-state LQ control gain matrix K is determined in procedure PrDLQ.

102

# This procedure computes the LQ # gain matrix K. ProcDisLQ:=proc(G:matrix(anything, square), H:matrix,Q,R,LQK) with(linalg,transpose): riccat(G,H,Q,R,'P'); LQK:=evalm( ((R+(transpose(H)&*P&*H))"'(-1)) &*(transpose(H)&*P&*G)

> end:

> 'Gainmatrix'= eval(GainK);

E

> > > > > > > > >

> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >

# This procedure solves the discrete-time # Riccati equation. # P=Q+Gt*P*G-Gt*P*H*[R+(HtPH)^(-1)] *Ht*P*G riccat:=proc(G,H,Q,R,sRic ) local r1,mP,cmP,GtPH,HtPG,RHtPH,GtPG, RHH,Riceq,sRiceq,test,kkl,i,j,test, testl,soluRic, Ht,Gt,sRicl,sRic2; with(linalg,coldim,rowdim,inverse, definite): readlib(allvalues); r1:=rowdim(G): mP:=array(symmetric,l..r1,1..r1): cmP:=convert(evalm(mP),set); Ht:=transpose(H); Gt:=transpose(G); GtPH:= evalm(Gt&*mP&*H): HtPG:=transpose(GtPH): RHtPH:=evalm((R+(Ht&*mP&*H))^(-1)): GtPG:= evalm(Gt&*mP&*G): RHH:=evalm(GtPH&*RHtPH&*HtPG): Riceq:=map(numer,evalm(mP-Q-GtPG+RHH)): sRiceq:=convert(Riceq,set): soluRic:=solve(sRiceq,cmP): assign(soluRic): sRic:=evalm(mP); sRic:=map(allvalues,sRic,d); sRic1:=array(1..r1,1..r1); sRic2:=array(1..r1,1..r1); for i to rl do for j to r1 do if nops([sRic[i,j]]) > 1 then sRic1[i,j]:=sRic[i,j][1]; sRic2[i,j]:=sRic[i,j][2]; else sRic1[i,j]:=sRic[i,j] sRic2[i,j]:=sRic[i,j] fi; od; od; if definite(evalf (eval(sRicl)),'positive_def') then sRic:=evalm(sRic1) else if definite(evalf (eval(sRic2)),_'positive_def') then sRic:=evalm(sRic2) else ERROR('No positive definite solution'); fi; fi; end:

Example 7 An LQ controller is designed for the system in Example 5 with the following state and input constraining matrices 1 0

Q=

R= L 1, 0 1

> PrDLQ(GG,HH,Q,R,'lgg'): > 'LQgainmatrix'=eva1(1gg);

LQgain,m,atrix = [ —.1165582370 —.6981596932

[4] A.B. Ogunye and A. Penlidis, Advanced State Space Analysis Using Computer Algebra, in Proceedings of the American Control Conference, Seattle, Washington, Vol. 1, pp. 559-563, June, 1995a. [5] A.B. Ogunye and A. Penlidis, Computation of System Gramians and Balanced Realizations Using MapleV, Int. Journal of Systems Science, 26(4), pp. 899-926, 19956.

[6] A.B. Ogunye and A. Penlidis, State Space Computations Using MapleV, IEEE Control Systems, 16(1), 1996.

The closed-loop poles with this LQ controller is determined as follows: > evalf(Eigenvals(evalm(G-H&*lqg))); [—.1509201534 +.1437528097-T —.1509201534 —.14375280971]

In this paper, we have demonstrated how symbolic computation can aid the control design and analysis process. We have shown how Laplace transformations, Z transformations, frequency domain and state space computations are implemented as though hand calculations are being carried out. These calculations are involved, complex, tedious and error prone, even for simple examples. It has been shown that one can save time and effort, and hence tackle more realistic problems. The very process of programming with MapleV encourages appreciation of the important aspects of mathematical investigation, because there is a one to one correspondence between the symbolic code and the mathematical algorithms being implemented.

[1] A. Christensen, Symbolics in Control Design: Prospects and Research Issues, in Proceedings of the IEEE/IFAC Joint Symposium on Computer-Aided Control System Design, March, 1994, Tuscon, Arizona, pp. 103-108. [2] N. Munro and P. Tsapekis, Some Recent Results Using Symbolic Algebra, in Proceedings of the IEEE/IFAC Joint Symposium on Computer-Aided Control System Design, March, 1994, Tuscon, Arizona, pp. 109-116. [3] V. Polyakov, R. Ghanadan and G.L. Blankenship, Symbolic Numerical computational Tools for Nonlinear and Adaptive Control, in Proceedings of the IEEE/IFAC Joint Symposium on Computer-Aided Control System Design, Tuscon, Arizona, pp. 117-122, March, 1994.

[7] A.B. Ogunye, A. Penlidis and P.M. Reilly, Computer Algebraic Analysis and Design of Multivariable Control Systems Using Polynomial Matrices in the Rational Functions Field, submitted to Int. Journal of Systems Science , 1995c. [8] T. Ohtani, M. Fukuzawa and M. Masubuchi, A CAD System for Nonlinear control System Design Using Mathematica in Proceedings of the IEEE/IFAC Joint Symposium on Computer-Aided Control System Design, Tuscon, Arizona, pp. 197-204, March, 1994a. [9] B. de Jager, The Use of symbolic computation in Nonlinear control: Is It Viable?, IEEE Transactions on Automatic Control, 40(1), pp. 84— 89, 1995. [10] G. Stephanopoulos, Chemical Process Control: An Introduction to Theory and Practice, Prentice-Hall, 1984. [11] Ogata, K., Discrete-Time Control Systems, PrenticeHall, Inc., Englewood Cliffs, New Jersey, 1987. [12] Smith, C and A.B. Corropio, Principles and Practice of Automatic Process Control, Wiley, 1985. ~r " .: ~.~ 1 1= `,/ ~.~ ~ Ayowale B. Ogunye is at the Dow Chemical Company, Midland, Michigan, as Senior Research Engineer in the Computing and Information Technology Laboratory. He holds a B.Sc.(Hon.) degree from the University of Ife (Nigeria), MASc. and Ph.D. degrees from the University of Waterloo (Ontario, Canada), all in Chemical Engineering. His research interests include advanced control of chemical processes, multivariate statistical process control and application of computer algebra to engineering problems. Since the fall of 1994, he has been on the editorial board of the Maple Technical Journal (MapleTech). He is a member of the Canadian and Nigerian Societies of Chemical Engineers.

103

Guidelines for Authors Any user of Maple who has implemented an original, useful, elegant, or illustrative solution to a particular problem is invited to submit a description of the solution to the Maple Technical Newsletter (MapleTech). We especially encourage articles which have both technical merit and are accessible to the general user of Maple. Three categories of articles are published in MapleTech: (i) Articles on Maple functionality. (ü) Articles about the use of Maple in education. (iii) Articles on research applications of Maple. Articles in category (i) are usually provided by the Maple developers. Articles of category (ii) must be as accessible as possible. Applications in all areas (economics, engineering, environmental studies, etc.) are accepted. The intent and category of the article must be made clear by authors within their articles. All articles should be roughly 3 to 7 pages long, as they would appear in double-column format, a lOpt font, on 8.5 x 11 inch paper. The article must be submitted in the form of Unix compatible LE?TEX file in MTN format. It is important that any results obtained by Maple be reproducible by the general user. Within the article itself, Maple input must have the form: \begin{mapleinput} int( exp(-x-2), x=O..infinity ); \end{mapleinput} The corresponding Maple output should be a LKIpX equation of the form: \begin{maplelatex} {\frac {\sgrt {\pi }1{21} \] \end{maplelatex} To further ensure reproducibility of results, the author must use a standard and current version of Maple and not his or her own customized version. All articles developed in Maple worksheets should can be converted into UTEX using the "Export to PTEX" facility available as of Maple V Release 3. References, citations etc... should be included in MTN format. Guidelines and tools for preparing articles for the Maple Technical Newsletter, as well as BTEX style files and sample articles can be obtained via anonymous ftp from the

MTN directory of the share library. Articles must be written

according to the detailed instructions contained within the README file (this file explains MTN format). With submission of an article, a short one-paragraph biography from the author(s) including fields of interest, a short summary of the article and a test file containing the Maple input code contained within the submitted article, should be included. If the article is accepted, publication charges are at $25 per page for 25 reprints. For extra reprints, please contact BirkMuser, Boston (address and phone numbers supplied by front cover information). Any inquiries or submission should be directed to the editor Tony Scott at: Department of Chemistry Ben-Gurion University Beer Sheva, POB: 653, Israel 84105 FAX = 972-7-472943 Phone = 972-7-472156 email = [email protected]

AID d 21T&

: 1~ ei IO, M Mrel5 QF., rel „r. V Ie V

WATERLOO MAPLE INC.

Maple V Learning Guide 1996/269 PP., 74 ILLUS./SOFTCOVER/$24.00 ISBN 0-387-94536-9

Maple V Programming Guide

Solving Problems in Scientific Computing using Maple and MATLAB"'

1996/379 PP./SOFTCOVER/$34.00 ISBN 0-387-94537-7

1995/315 PP., 106 ILLUS./S0ETCOVER/$39.95 ISBN 3-540-58746-2

DARREN REDFERN, Practical Approach Corp.,

ROBERT M. CORLESS, University of Western Ontario,

Ontario, Canada

Canada

The Maple Handbook

Essential Maple

WATERLOO MAPLE INC.

_

a

,

——

1

i

Maple V Release 4

An Introduction for Scientific Programmers

1996/531 PP./SOFTCOVER/$29.00 ISBN 0-387-94538-5

1995/218 PP., 32 ILLUS./SOFTCOVER/$27:95 ISBN 0-387-94209-2

Second Edition ANDRE HECK, Expertise Center, Computer Algebra

ROBERT M. CORLESS, University of Western Ontario,

Netherlands, The Netherlands .

Scientific Computing with Maple 1996/APP. 300 PP., 60 ILLUS./HARDCOVER/$39.00 (T.)

ISBN 0-387-94535-0

ISBN 0-387-94210-6

DARREN REDFERN, Practical Approach Corp., Ontario, Canada and EDGAR CHANDLER, Paradise

Forthcoming... DARREN REDFERN, Practical Approach Corp.,

Valley Community College

Ontario, Canada

Maple ODE Lab Book

The Practical Approach Utilities for Maple Maple V Release 4

RONALD L. GREENE, University of New Orleans, LA

Classical Mechanics with Maple 1995/173 PP., 56 ILLUS./SOFTCOVER/$29.00/ISBN 0-387-94512-1

Maple and

MATL.sa

Symbolic Recipes

1996/APP. 699 PP., 1201LLUS./HARDCOVER/$44.95(1)

I ~►

Soluin9 Probl m In Scientific Computing

Canada

Introduction to Maple

1996/APP 150 PP./SOFTCOVER/$29.95 (1)/ISBN 0-387-94733-7

uwae

Second Expanded Edition WALTER GANDER, EFH Zorich, Switzerland and JIRI HfiEBICEK, University of Agriculture and Forestry, Brno, Czech Republic (Eds.)

1996/312 PP., 83 ILLUS./3.5" DISKETTE/SOFTCOVER/$69.00 SBN 0-387-14225-6

I

FROM THEORY To. PRACTICE. Maple

—The Power Edition

V

Maple V—The Power Edition is a complete mathematical problemsolving environment that maximizes your ability to solve engineering math problems in efficient new ways. Its impressive suite of mathematical and graphical functions lets you concentrate on analysis and design, not on mathematical manipulation. Over 100 Books are

Not Just a Black Box Maple V provides routines to solve equations analytically, manipulate matrices, visualize important phenomena, explore design parameters, and much more. Also, you won't be limited to the simple numbercrunching and back-solving techniques used by spreadsheets and other engineering mathematical software. Maple V lets you bring r mathematical concepts to practical analysis and design contexts in a fraction of the time it would take with traditional methods. A Complete Engineering Tool With a complete programming language, you can also develop applications that would have taken days with FORTRAN, in hours or even minutes. With advanced functions such as tensor manipulation, piecewise functions, and matrix decomposition, you can apply Maple V's powerful mathematical knowledge to any technical discipline.

"Maple V— The Power Edition is an outstanding tool for many engineering computations... including symbolic and numeric math, graphics

now available to help you realize the M power of Maple V.

Ins.t

Design and Analysis of a Band Pass Filter

Circuit Definition

Ross Taylor, Professor Clarkson University

w

F

Frequency Sensitivity to C3

+'W1~

B Circuit Equations

for Zl and Z2 =

°



Z