mathPAD Special MuPAD issue -

71
mathPAD Special MuPAD issue: What' s New in MuPAD 1.2 The Language in Brief Evaluation Polynomials Domains Dornains and abelian Groups Axioms, Categories and Domains Graphical User Interfaces Graphics Debugging Data Structures and Memory Management Design and Implementation of the Kernel Structure of Libraries malhPAD is a publication of the mathPAD Group of the University of Paderborn

Transcript of mathPAD Special MuPAD issue -

Page 1: mathPAD Special MuPAD issue -

mathPAD

Special MuPAD issue:What' s New in MuPAD 1.2

The Language in Brief

Evaluation

Polynomials

Domains

Dornains and abelian Groups

Axioms, Categories and Domains

Graphical User Interfaces

Graphics

Debugging

Data Structures and Memory Management

Design and Implementation of the Kernel

Structure of Libraries

malhPAD is a publication of the mathPAD Group of the University of Paderborn•

Page 2: mathPAD Special MuPAD issue -

mathPADVo14/ No 1/ March 1994

Special MuPAD issue

Benno Fuchssteiner Editorial 2

Karsten Morisse What's New in MuPAD 1.2 4

Klaus Gottheil The Language in Brief 5

Klaus Gottheil Evaluation 12

Klaus Gottheil Polynomials 17

Holger Naundorf Domains 20

Holger Naundorf Domains and abelian Groups 23

Klaus Gottheil Axioms, Categories and Domains 24

Karsten Morisse The Graphical User Interfaces 30

Gerald Siek MuPAD for the Apple Macintosh 37

Thorsten Schulze The Graphics 39

Oliver Kluge Debugging 46

Karsten Morisse Data Structures and Memory 50Management

Andreas Kemper Design and Implementation of the 57Kernel

Klaus Gottheil The Structure of Libraries 64

MuPAD Factsheet 69

Editors: ISSN 0941 - 9187Benno Fuchssteiner V.i.S.d.P.: B. FuchssteinerKlaus Gottheil Pennisson of reprint is given as longUniversity of Paderborn as a voucher is sent to the editors.33095 Paderborn, Gennanye-mail:[email protected]@uni-paderborn.de

1

Page 3: mathPAD Special MuPAD issue -

mathPAD

Editorial

Benno Fuchssteiner

At the occasion of the CEBIT 1994 thepresent issue of the mathPAD journal isentirely devoted to the computer algebra sys­tem MuPAD, a development of theAUTOMATH Institute at the University ofPaderborn. On the foUowing pages some ofMuPAD's developers report in a leisurelystyle about the result of their work and theaims they have foUowed in the developmentof tbis system.

MuPAD is a parallel-processing, object orientedcomputer algebra system, of which sequentialversions are available as weIl. The sequentialMuPAD version is the topic of this mathPADissue. MuPAD is designed to solve simple asweIl as complex problems in Science, Engineer­ing and Mathematics. Special care has beentaken to provide state-of-the-art interfaces forutmost ease-of-use even for absolute beginnersin computer algebra. At present MuPAD isavailable on Unix Workstations, Macintosh, pe(under LINUX 0.99 p114) and Unix basedshared memory machines; ports to other plat­forms are coming.

The design of MuPAD was originally driven bythe desire to efficiently handle large data (up tothe Gigabyte range) generated by our algo­rithms for investigating the group theoreticalstructure of nonlinear systems. However,MuPAD outgrew this goal and was developedas a general purpose system and should be usedas such.

As other computer algebra systems, MuPADconsists of basic system functions which, forspeed and efficiency, were implemented in thekernel of the system. Further components are ahigh levellanguage, allowing the user comfort-·able programming (including parallel. con­structs on sequential machines) and theinterface modules.

2

The system functions include the necessaryarithmetic of arbitrary length. This arithmetic isrealized by incorporating the PARI1 system intoMuPAD.

A comfortable graphics module which allowsefficient computation and display of two­dimensional and three-dimensional plots is pro­vided with the system.

At present the MuPAD interfaces include adebugger, running either interactively withinthe system or as a more comfortable separatetool under X. We also provide an on-line hyper­text help system, which for Unix versions isbased on the HyTeX2 system allowing a hierar­chical search in the manual and its helpfiles; forthe Macintosh the hypertext system is our ownproduct. A filmtool, a compiler and a modulemanagement unit are under development.

MuPAD was developed as a service to the sei­entific community. As a consequence MuPAD,although copyrighted material, has a specialdistribution policy. It will be distributed to sei­entific and educational non-profit organizationsanywhere in the world free of charge, howevera license has to be acquired. At present 300 siteIicenses have been distributed worldwide andMuPAD is approximately running on 1100machines.

Many organizations have supported the devel­opment of MuPAD. We are indepted to theDeutsche Forschungsgemeinschaft, the Heinz­Nixdorf-Institut, the Mathematische Forsc­hungsinstitut Oberwolfach, and the Universityof Paderborn.

1. PARI, Copyright (c) by C. Batut, D.Bernardi, H. Cohen, and M. Olivier2. HyTeX,Copyright (c) by N. Köckler,University of Paderborn, Germany

Page 4: mathPAD Special MuPAD issue -

MuPAD is a joint effort of many people. Inaddition to the authors of this issue major con­tributors were Gudrun Oevel (Graphics),Andreas Sorgatz (Compiler and Module Man­agement development), Ralf Hillebrand (Pret­typrint and Linux port). Mrs. McIntosh­Schneider was of great help in preparing theEnglish manuscript.

We are grateful to our friend WaldemarWiwianka, MuPAD's project leader from thebeginning, who was tragically killed in an acci­dent in July 1993. MuPAD owes a great deal tohis enthusiastic work and the perspectives hehelped to develop.

In case you would like to obtain a copy ofMuPAD please send an e-mail to

[email protected]

A Reference Manual (in German) and a Tutorial(in English), which allows a guided tourthrough the systern.. are available fromBirkhäuser Publishing house in Basel.

3

Editorial

Page 5: mathPAD Special MuPAD issue -

mathPAD

What's New in MuPAD 1.2

Karsten Morisse

Since the release of MuPAD 1.1 a lot has hap­pened. Naturally aII errors that have beenpassed on to us (and those we have foundourselves) have been eliminated. However,we have invested more time in new and fur­ther developments. In tbis short article Iwould Iike to introduce the more importantinnovations.The user can now define new data types (so­called domains) at the user's level with the aidof a new type (DOM_DOMAIN). With this it ispossible to implement polymorphic algorithms:Instead of multiply implementing an algorithmfor the different instances of an algebraic struc­ture, a single generic implementation coupledwith the definition of special domain methods issufficient. Examples for working with domainscan be found in the article "Domains" in thisissue of the mathPAD journal. The quick han­dling of domains is enabled by them beingimplemented in the kernel, The library containsan experimental version of a category concept.A category represents a class of algebraic struc­tures. By using categories generic algorithmsfor these classes can be implemented.Many of the functions in the MuPAD kernel cannow be overloaded, so that, for example, bydefining a domain method -plus the normaloperator notation for addition can be used.

The kernel has an intrinsic data type (DOM_­

POLY) for the handling of polynomials. This is asparsely distributed representation. The workwith this data type is supported by more than 20functions. An overview of these functions iscontained in the article "Polynomials" in thismathPAD journal. On the library level routinesfor the recursive representation of polynomialsare also available. The library also containsexperimental versions of gcd and factorizingalgorithms for polynomials.

4

For the performance analysis of programs writ­ten in the MuPAD language a profiler isincluded. This gives information about the fre­quency and the duration of the programs called.

The graphic tool VCam has been completelyreworked. This concerns both the handling ofthe interfaces and the internally used structures.Objects can now be drawn in colour.

The use of the debugger has become more userfriendly. Breakpoints can now be combinedwith conditions so that, for instance, errors canbe searched for very quickly and specifically incomplex loops.

To avoid naming conflicts the library packagesare implemented with the aid of domains. Theyare only loaded on demand.

Many new functions have been implemented (aspecific list is contained in the on-line manual).The functionality of some functions has beenreworked. Whilst doing this we have madeevery effort to guarantee upward compatibility.

Page 6: mathPAD Special MuPAD issue -

The Language in Brief

Klaus Gottheil

In tbis passage the language will bedescribed - in about 6 pages. Naturally thisis very short, but the most important Ian­guage concepts should become clean Theevaluation of the language shall be describedin the article ''Evaluation''.

Comments are one of the most important lan­guage elements. In MuPAD they are enclosed in#, as in # cornment #.

Constants are numerical constants, the Booleanconstants TRUE and FALSE, and characterstrings. Numerical constants are integers, e.g.17.5, rational numbers, e.g. -17/3, tloating­POlOt numbers, e.g. 12. 3e-4, and complexnumbers, e.g. 2/5+4*I. (When giving expo­nents the user must use a small e.) Characterstrings are enclosed in 1', e.g.: "Otto".

~umericalvalues can have any number of dig­its. The precision of floating-point numbers canbe predefined with the system variable DIGITS.

Special Constants are I for the imaginary unit,E, PI and EULER for e, 1t and C respectively.The constant NIL is used to remove values fromidentifiers. .

Identifiers are formed of by an alphabeticalcharacter followed by any number of alphabeti­cal characters or digits, e.g. der iv or x_12.(The underline _ is an alphabetical character.)An identifier can have a value assigned to it byusing the assignment operator: =. At first anidentifier has no value assigned to it. An identi­fier is of no particular type and can be assignedany value.

Function caUs have the form procedure(pa­rameter) or procedure(). Here the parameter listis aseries of expressions separated by a ,. Pro­cedure names are frequently identifiers, e.g.reset(), sin(1} or append(1,x}. Proce-

5

dure names can also be given in the form ofexpressions. ()

Expression sequences are ordered series ofexpressions separated by the comma operator "e.g. 2 1 x , Y 1 3 /4.

Lists are expression sequences enclosed in [ ].The expressions are separated by I' e.g.[a 1 b , 3/7], [x] or [] (the empty list). The listentries can be accessed by [ ], for instance,1 [3] is the third element of list 1. By usingappend (1, 7) the value 7 can be attached to 1and the new list is retumed.

Sets are, like lists, expression sequences, whichare enclosed in { }, e.g. {a, 2.23 , Lisbet}or {}. A set contains no identical elements andis not ordered.

Tables are any number of equations with theform LndexevaLue, where index and valuecan be any expression. Tables are produced bythe function table, e.g. t: =table ( ). Thetable entries can be accessed by [ ], e.g. t [x] ,

t [7] or t [ z ] . (Here x, 7, z are the index val­ues of the respective entries.)

Arrays have any number of dimensions and areused for the storing of vectors, matrices, tensorsetc.. Arrays are produced by the functionarray, e.g. v: =array ( 1 .. 4) (vectorv [1] ...v [4]), In: =array (2 . . 6 , 3 .. 4)(matrix In [2 , 3] , In [2 , 4] ,... In [6,4]) ort : =array (1 .. 3 , 1 .. 3 , 1 .. 3) (a threedimensional array containing t [ 1 , 1 , 1] ,...t [ 3 , 3 , 3] ). Arrays cannot be appended. At firstthe array elements have no values.

Polynomials are represented by a data structure~hich is created by the function poly, formstance poly(x"3-2*x"2+x-1, [x]} orpoly(x*y"3+2*x-2, [x,y],IntMod(7}}.~dmissible coefficient rings are Expr (expres­sions), IntMod (n) (ring of residue classes

Page 7: mathPAD Special MuPAD issue -

mathPAD

modulo n) and Domains. More than 20 func­tions are available for working with polynomi­als.

Domains are used for the definition of new datatypes by the user. By the function domain, newdomains are generated, by domat tr or the ::operator the methods of a domain can beaccessed. Many system functi0Ili. can be over­loaded by domain methods. FOf instance bydefining a domain method "-plus", the usualoperator + can be used for addition of domainelements. Domains enable to implementation ofpolymorphic algorithms.

Expressions are data structures in MuPAD andnot calculation statements as in most other pro­gramming languages. Expressions are notalways directly evaluated. Evaluation isdependent on the context. During evaluation theidentifiers are substituted by values, functioncalls by their solutions and arithmetic expres­sions are simplified and sorted for easier com­parison.Identifiers are normally recursively substitutedas far as possible during the evaluation ofexpressions (so that in the expression no moreidentifiers with values are present). However,this does not apply to procedures. In proceduresthe identifiers are replaced by their values onlyonce. An expression consists of a simpleexpression or an operator and its operands. Asimple expression is a constant or an identifier,a function call, an expression sequence, a list, aset, a polynomial or a domain. Operators areoperators like +, * and s. The operands of anexpression are themselves any expression.Examples of expressions are a+3 *PI+sin (x)or [f ( i ) i =1 . . n] .Tables and arrays cannot be directly included inexpressions. There are only identifiers that haveentire tables or arrays as values, or indexedidentifiers, like t [3 ] , which have a single arrayor table element as value.A function call, with its actual parameters, isintemally understood as an operator with itsoperand. Conversely for every operator there isa system function which realizes the operator.An operator is executed by calling the relevantsystem function with the operands as theparameters.

6

Trees are defined by the recursive definitionabove. Every expression is a tree, operators andfunction calls are inner nodes, operands andparameters are children, simple expressions areleaves.

Arithmetical operators are +, -, *, /, divandmod. divand mod are integer division and inte­ger remainder respectively. 1/a mod b resultsin the modular inverse of a modulo b.

Rational operators are =, <>, -c, <=, >, and >=.

Logical operators are and, or and not.

Set operators are union, minus (difference)and intersect.

Special operators are the range operator .. ,the sequence operator $, the concatenationoperators . and @, and the domain attributeoperator : :.An range-expression has the form lower_limit. . upper_limit. The lower and upper limits areexpressions that result in integers. Such a rangerepresents the integers between the lower andupper limit.The simplest form of a sequence-expression isexpression $ quantity. Here an expressionsequence with a quantity of elements is defined,with each element equal to the expression. Theexpression a $ 3 results in the sequencea,a,a.With expression $ variable = range a expres­sion sequence with the element expression isdefined. Here, however, the running variable inthe expression is replaced with the respectivecurrent value from the range. The expressioni *PI $ i=O .. 3 results in the sequence 0, PI,2 *PI, 3*PI.A sequence of integers is defined by $ range.This consists of alt. integers between the lowerand upper limits of the range. The expression$2 .. 6 results in the sequence 2, 3, 4, 5, 6and $ - 2 .. - 2 in the number - 2. The expres­sion $1 .. 0 results in the empty series.The concatenation operator is used to concate­nate lists and character strings, and to definenew identifiers. [a, b] . [c, d] produces the list[a, b, c , d], "Can". "teen" produces thecharacter string "Canteen". The identifierforce_x is defined by force."_x". Natu-

Page 8: mathPAD Special MuPAD issue -

rally, when defining new identifiers the resultmust be a syntactically valid identifier.The @ operator is used for composition of func­tions. For example, (tan@exp) (x) returnstan (exp (x) ).

The : : operator is the short form of domattr,

D: : a is equivalent to domat t r (D, "a" ) .

The type of an expression is the domain towhich the expression belongs. With simpleexpressions this is identical to the expressiontype. Complex expressions have the typeDOM_EXPR. The type can be ascertained by thefunction domtype.

The expression type is the type of the corre­sponding object for simple expressions and foroperators the operator type. Expression typesare given by the function type. type texprireturns the type of expr, testtype texpr, type)results in TRUE when expr has the type type.The expressions type (a*b), type (x) ortype (a-sb-so ) result in 11_mul t" (product),DOM_IDENT (identifier) or "-plus" (sum). Theexpression test type (x , DOM_IDENT) resultsin TRUE.

The Operands of an expression can be deter­mined by the function op. op texpri results in asequence containing all the operands of theexpression e. op (expr, n) returns the nth oper­and of e. op texpr I 0) gives the operator of e. Ife= a-sb-s s i.n (3 *c) then op (e) is thesequence a,b I s in (c *3 ), op (e , 1) is a andop (e I 0) is -plus.

By using op, operands can also be ascertainedrecursively. If e is defined as above, thenop (e I [3 I 1]) results in the expression c *3,

op (e, [3, 1 , 2]) is 3 and op (e, [3 1 0]) issin.Furthermore, by using op, elements of complexdata structures, such as sets, lists and tables, canbe accessed. Thus, op ( [a I b , c] I 2) results inthe second element, b, of the list.

The number of operands in an expression canbe determined by the function nops. Theexpression nops (a+17+3*c) results in thevalue s (for the three operands a, 17 and 3 *c).

The substitution of partial expressions can becarried out with the functions subs, subsex

7

Language

and subsop. On calling subs texpr I oldenews ,the partial expression old in expression expr isreplaced by new. The partial expression oldmust be complete. It is not possible to replacesome operands of an operator singly and retainthe others. Therefore, in the expression e above3 * c can be replaced by d by using subs (e I

3 *c=d), but the partial expression a-sb cannotbe replaced by the function subs.

With subsex incomplete partial expressionscan be replaced, the call is the same as that forsubs. subsex (e 1 a+b=d) results in theexpression d-s s i.n (3 *c).

With subsop texpr I n=new) the nth operand ofexpr is replaced by new. subsop (e, 3=d)

results in the expression a+b+c. Internal partialexpressions can be specified by giving pathsinstead ofthe simple number n (see op).

Statements are expressions, assignments orconditional statements. Ouring interactiveinput, a statement must always be terminated by; or :, in order to be carried out. When : isused the result of the statement is not shown onthe screen.

Statement sequences are series of statementswhich are separated by ; or :. When : is usedthe result of the statement is not displayed onthe interactive level.

Assignments normally bind values to identifi­ers, as in a: =12+x. They have the form identi­fler : = expression. After assigning NIL, as ina: =NIL, an identifier has no value.An indexed identifier, such as I [2] (a list, tableor array element), an identifier generated by theconcatenation operator, such as x , 2, a domainattribute, such as D: : a, and a call of a function,such as f (2 ), or a combination of such con­structs can be placed on the left hand side of anassignment, instead of a simple identifier.The result of an assignment is normally theright hand side of an assignment. If the assign­ment is NIL then the result is the identifieritself. The result of a [3] : =12+x*O+4; is 16,

for b: = NIL the result is b.

An assignment of NIL to the system variablesresults in them being set back to their defaultvalues. Therefore, these identifiers always havea value.

Page 9: mathPAD Special MuPAD issue -

mathPAD

If-statements have the form

if condition thenstatement sequence

elif condition thenstatement sequence

elsestatement sequence

end_if

The conditions must be Boolean expressions. Ifthe first condition results in TRUE, then thestatements in the then-part are executed, if notthen the conditions in the el i f -part are exam­ined. If these result in TRUE, then the statementsin the elif-part are carried out. Any number ofel i f parts, whose conditions are examined oneafter the other, can follow. If none of the condi­tions result in TRUE, then the statements in theelse-part are executed. The elif- and else­parts may be omitted. Examples are i f x > y

then x else y end_if or if a mod 3 =o then a:= a+1j return(a) end_if.

For-loops have two possible fonns. In thefamiliar form a range of numbers is runthrough:

for identifier from beginning to ends tep step widtb do

statement sequenceend_while

The range beginning to end is run through withthe step width step width. In each run the indexvariable identifier is set to the current value andthe statement sequence is executed. for ifrom 2 to 8 step 2 do print(i)end_for results in the output of 2,4, 6 and 8.The step width may be omitted, in which casethe step width 1 is used. In for i from 1 to3 do a . i : = i end_for the assignmentsa1: =1, a2: =2 and a3: =3 are executed.The alternate form end downto beginning Canbe used instead of beginning to end. In thiscase the loop runs backwards and the index var­iable is reduced by the step width each time. Infor j from 4 downto 2 do t [j] : =t [ j -1 ] end_for the assignments t [4] : =t [3], t [3] : =t [2] and t [2] : =t [1] are exe­cuted in the given order.

8

In the second form ofthe for-loop alloperandsof an expression are run through:

for identifier in expression dostatement sequence

end_for

The operands of the expression are assigned,one after another, to the identifier and then theloop body is executed each time. In f or t ina+b+c do print (t) end_for the values fora, b and c are displayed one after the other.

While-Loops have the form

while condition dostatement sequence

end_while

Here, the statement sequence is executed aslong as the condition results in TRUE. The con­dition is evaluated before the statementsequence is executed.

Repeat-Loops have the form

repeatstatement sequence

until condition end_repeat

Here, the statement sequence is executed aslong as the condition results in FALSE. The con­dition is evaluated at the end of the statementsequence.A loop can be terminated by next or break.With next the execution of a statementsequence is terminated and the next run of theloop is started, with break the loop is termi­nated.

Case-statements have the form

case expressionof value 1 do statement sequence 1of value 2 do statement sequence 1

otherwise statement sequence nend_case

Here, the expression is compared with theexpressions value 1, value 2, etc. one after theother. If the expressions match, then all the fol­lowing statement sequences of the case-state­ment are executed. (Also the sequences of theremaining of- and otherwise-parts!) If theexpression does not match any of the of-parts,then only the statements ofthe otherwise-part

Page 10: mathPAD Special MuPAD issue -

are executed. The otherwise-part may beomitted.With the break eommand the user eanjump tothe end of a case-statement, the rest of thestatements in the case-statement are not exe­euted. With the next eommand the eomparisonofthe expression with the values ofthe of-partsis resumed: Like at the beginning of the case­statement, the eomparison of the expressionwith the values of the of-parts is resumed start­ing with the next-statement and the statementsare exeeuted after a matehing value is found.

Procedures have the form

proc tparametersilocal loeal variables i

opt ion options i

name name ,begin

statement sequeneeend-pr oc

The formal parameters are a (possibly empty)series of identifiers separated by a ,. The loealvariables are also a sequenee of identifiers sep­arated by a ,. Options are keywords separatedby a .: hold and remember are aeeepted. Thename ean be any expression and is used only foroutput, a proeedure ean not be ealled by usingits name. The declaration of the loeal variables,options and name may be omitted. If the specifi­eation of the name is missing, then by assigninga proeedure to an identifier, the identifier istaken as the proeedure's name. With

max:= proc(x,y)begin

if x > y then x else y end_ifend-pr oc

the procedure max is defined, it ealeulates themaxima of two numbers. With the assignmentf : =max, f is assigned the same procedure asmax. Procedures are data like expressions orlists.On ealling a proeedure, the formal parametersare assigned eopies of the actual parameters. (A"call by value" is exeeuted, a "call by refer­enee" does not exist.) Then the body ofthe pro­eedure is exeeuted. At the beginning loealvariables are unassigned.Afree variable in a proeedure (a variable that isneither a parameter nor a loeal variable) is auto-

9

Language

matieally a global variable. A proeedure can bedefined in the body of another proeedure. In thisease the loeal variables of the outer proeedureean be global variables of the inner one, as in

g:= proc(x)local y, f;

beginy:= Xi

f:= proc(x) begin x*y end prOCi

f (x)

end-proc

Here the inner proeedure f is a loeal variable ofthe outer proeedure g, y is a loeal variable of gand a global variable of f. g (x) evaluates (veryclumsily) to x"2.Dynamie seoping is used for the free variables,i.e, global variables are bound during run-time.(In a procedure, those global variables whiehwere last defined in one of the procedures ealledso far, are used.)Normally, a procedure returns the value of thelast exeeuted statement. A procedure ean alsobe left by using the function return. Theparameters of return are the return values ofthe procedure. The above mentioned proceduremax ean also be defined as folIows:

max:= proc(x,y)begin

if x > y then return(x) end_ifiy

end-pr oc

The return value of a proeedure ean be anexpression sequenee, with this a proeedure eanreturn several values at the same time.Options for procedures are, as already men­tioned, hold and remember. Normally, the eur­rent proeedure parameters are evaluated beforethe procedure is executed. This meehanism isprevented with the option hold. The optionremember eauses a procedure to "remember"the return values and if possible simply toreturn these values instead of executing the pro­eedure again. By this means especially reeur­sions ean be greatly aeeelerated at the eost ofusing more memory.

Environment variables are system variablesthat are automatieally reset to their former val­ues after a proeedure has been exeeuted. Thefollowing proeedure

Page 11: mathPAD Special MuPAD issue -

mathPAD

pi: = proc ()local DIGITS;

beginDIGITS:=200;float(PI)

end,J>roc

returns 1t to exactly 200 digits. After callingpi ( ), the system variable DIGITS still has thesame value as before the call, i.e. it was onlyaltered during the procedure pi. However, forthis the environment variable must be declaredas local!

Parallel statements are easy to handle in thedomain of micro-parallelism, and offer an opti­mal adaptation to the hardware in this domain.Micro-parallelism can be employed efficientlywhen communication time between the proc­esses involved is minimal. The system carriesout load balancing and process communicationautomatically. The user only has to mark theparallel executable tasks. The constructs ofmacro-parallelism make a means available forthe optimal use of the network topology. Loadbalancing and process communication are nolonger carried out automatically but have to bedone by the user.

Micro-parallelism is oriented on the model ofthe shared memory machine. With the availableconstructs processes are generated and depos­ited on a task stack. Idle processors examinethis stack and remove tasks for processing.There are a parallel for-Ioop and a parallelblock, both of which are also available in thesequential version of MuPAD

for identifier from beginning to endstep step width parallel

private private variables;statementsequence

end_for

The range from beginning to end is runthrough with the step width step width. For eachron the index variable identifier is set to the cur­rent value and a task is generated to execute thestatement sequence, which is then deposited onthe task stack. The private variables are a (pos­sibly empty) series of identifiers which are sep­arated by a ,. The usage of these variables by

10

the tasks is analogous to local variables in pro­cedures.A second form of the parallel for-loop runsthrough alloperands of an expression:

for identifier in expression parallelprivate private variables;statementsequence

end_for

As in the sequential case, all expression oper­ands are assigned, one after the other, to theidentifier. For each value a task is deposited onthe task stack.A parallel loop is only then ended when all thetasks it has generated are finished. The returnvalue is a expression sequence containing thereturn values of each task. The result of f or iin [1,2,3,4] parallel i A2 end_foristhe sequence 1,4,9,16.Parallel blocks execute statements in parallel:

parbeginpr i vat e private variables;statement sequence

end,J>ar

Bach statement in the statement sequence isdeposited as a task on the task stack. In order toexecute statements sequentially inside a parallelblock, a sequential block is available:

seqbeginstatementsequence

end_seq

Macro-parallelism can be efficiently used indistributed systems. In this case, all communi­cation has to be explicitly defined by the user.The system does not care for load balancing orscheduling. As a model a network of clusters,each running independently is used. Clusterscan communicate with each other by global var­iables or by exchanging messages via queues orpipes. Clusters are addressed via positive inte­gers.

Queues store incoming messages for a cluster.Clusters may send messages to the queues ofother clusters. Queues have names which can beany expression. A queue is organized on thefirst in first out principle. With wri tequeue (name, i, valuei , the expression value is writtenin the queue called name of the cluster i. Withreadqueue tnamer, a cluster reads the first

Page 12: mathPAD Special MuPAD issue -

element in its queue named name. As specialqueues those with the name "work" are availa­ble. If a cluster is idle, it tries to read a datumfrom this queue and evaluate it.

Pipes allow the establishment of a direct two­way communication channel between two clus­ters. (Because any cluster can write into aqueue, it is possible that the receiver has prob­lems identifying the sender of a message in aqueue.) With writepipe tname, t, valuei , theexpression value is written in the pipe calledname of the cluster i. Through readpipe (na­me, i) a cluster reads the next message in thepipe name connected to cluster i.

Net-variables constitute a distributed sharedmemory. An identifier a, which is assigned thevalue b by g 1oba1 (a, b) , has this value in allclusters.

11

Language

Page 13: mathPAD Special MuPAD issue -

mathPAD

Evaluation

Klaus Gottheil

In MuPAD terminology, evaluation is theexecution of a expression by the interpreter.It can be said, with good reason, that evalua­tion is the "actual purpose" of the inter­preter. In this context, what does "execution"mean?

MuPAD expressions

Before evaluation is tackled, the tenn expres­sion must be explained: A expression is ­expressed very simply - a tree.The leaves of an "expression-tree" are basicallyidentifiers (i.e, variable identifiers), constants(numbers, Boolean constants, strings) and spe­cial constructs, that are needed to identify sys­tem functions and procedures.Identifiers have, apart from the fact that theyhave names, another useful characteristic: Val­ues can be bound to identifiers, i.e., an expres­sion can be assigned to an identifier. (This isdone with the assignment operator ": =".)Through evaluation, an identifier, which isbound to a value, is substituted by this value(i.e., by this tree). For instance, with the assign­ment a : =b; b: =2; the value b is bound to thevariable a and the value 2 to b.The inner nodes of a tree are function calls orcomplex data structures, like lists, sets or tables.In the following, complex data structures willnot be dealt with, in order not to make thedescription too complicated.With function calls the first subtree identifiesthe function and the other subtrees identify thecurrent parameters of the call. Such anode canbe written as

F (Pt,···, Pn )

in "functional notation", where the function andthe parameter can stand for subtrees (not onlyfor leaves). In Lisp these nodes would be writ­ten as (F Pt ... Pn) .

The statements of the MuPAD language eire aIlrealized as functions and are also accessible to

12

the user as functions (e.g. as for the assignment": =" or as for the "i f then else" statement).For each statement there is a so called under­line-function (so called, because by conventionall the names of these functions begin with anunderline "_"). The statement

if a < b then a+2 else b end_if

can be just as weil be written as

_if( _less(a,b), -plus(a,2), b)

Here the legibility obviously suffers (Lispaccustomed bracket-artists will, of course, haveno problems with this).

Evaluation of expressions

Through evaluation a expression is transfonnedinto another one, in other words one tree isreplaced by another. In evaluation is a recursiveprocess:A leaf, which is not an identifier, is not alteredthrough evaluation. Likewise, if an identifierhas no value bound to it, then it is also notaltered. When an identifier has a value bound toit, then this value (i.e, this expression tree) isevaluated and the solution returned. Followingthe statements a: =b; b: =c ; c: =2; the iden­tifier a is nonnally, during interactive input,evaluated to 2. (More to the qualifications"interactive" and "normally" later.)As already mentioned the inner node of anexpression is a function caIl. Initially the firstsubtree of the node is evaluated. If the evalua­tion of the first subtree results in a function def­inition then the corresponding function iscarried out with the remaining subtrees of thenode as parameters. During the evaluation ofthe call s in (a+b+2) the identifier s in is eval­uated to the function definition of the systemfunction "sinus" and the function can then becalled with the expression a+b+2 (or the equiv­alent -pIus (a , b, 2) ) as parameter.If the evaluation of the first subtree of a func­tion call results in an identifier, then the func-

Page 14: mathPAD Special MuPAD issue -

tion is not bound to a definition. In this case, allthe remaining subtrees are also evaluated andthe new tree is returned in the form of a "formalfunction call". If fis, for instance, an identifierto which no value is bound, then f (4+3) willbe evaluated to f (7) because -plus (4,3)will be evaluated to 7 •

If the first subtree of anode is evaluated neitherto a function definition nor an identifier then theevaluation is terminated with an error. There­fore the expression u -plus" (2 , 3) is invalid,because the string cannot be evaluated to thefunction definition for the sum,

Execution of Procedures

As already mentioned, a function is executedwith the subtrees of the call as parameters. If thefunction is a procedure which is defined in thelanguage, then there are two forms of call: Nor­mally, the parameter expressions are evaluatedand the procedure is executed with these param­eters. The statements

f:= proe(x)begin

x*2end-proe;a:=2;f (a) i

define the procedure f and then assign the value2 to a. As expected the call f (a) returns thevalue 4.Conversely, if in the procedure definition theoption "hold" is given, then the parameters arenot evaluated before execution.The statements

g:= proe(x)option holdi

beginx*2

end-proeia:=2ig (a) ;

define the function g and again assign the value2 to a. The call g (a) then returns the expres­sion a *2 as the solution: The parameter a is notevaluated, the function g returns the identifier amultiplied by 2 as the result.The execution of a procedure takes place inthree steps: Firstly the actual parameters arebound to the identifiers of the formal parame­ters. Then the local variables of the procedure

13

Evaluation

which have been declared "loeal" are estab­lished. In the last step the procedure is evalu­ated, as already described. The last evaluatedvalue is then the return value of the procedurecall.The local variables are virtually "fresh" identifi­ers, to which, at first, no value is bound. If iden­tifiers with the same name exist before theprocedure call, then these values are not visibledurlng the procedure. Instead, durlng the evalu­ation of the identifiers the local variables areused. All other identifiers are handled as globalvariables; in this context the current, valid val­ues of the identifier for this run time are used.In the following procedure f, for instance, x isthe parameter and y is a local variable, while zis a global variable, because the identifier z isdec1ared neither as a parameter nor a local vari­able:

f:= proe(x)loeal y;

beginy:=2; x*y*z

end-proe

After the assignments y: =3; z: =NIL; thevalue 3 is bound to y, while z (due to theassignment z: =NIL) has no value. Because inthe expression x*y* z the local variable y isevaluated to 2, afterwards the expression f (2 )gives the value z *4. However, after the assign­ment z : =3; f (2) returns 12.The described method has one consequence,which is called dynamic scoping: For globalvariables those identifiers are used which arevisible at the execution time. In most "normal"procedural programming language, like Pascal,those variables are used which are staticallydeclared through the program text (through theouter procedure). This is called lexical scoping,In the following procedure g, the local variablez, which was global in connection with thefunction f above, is defined:

g: = proe ()loeal z;

beginz:= 4; f(2)

end-proe

Here, the expression g () always returns thevalue 16. In this context, the value of z outsideof g makes no difference to the call of g. During

Page 15: mathPAD Special MuPAD issue -

mathPAD

the evaluation of f (2) in the procedure g, thelocal variable z from 9 is used (this was not"known" in the definition of f).

Execution of System Functions

In the system functions, parameter evaluation isdependent on the given function. Most func­tions evaluate all their parameters before theexecution of the "actual" function. However,some functions do not, or only partially, evalu­ate their parameters.The assignment _assign (), for instance, doesnot evaluate its first parameter (the right handside of the assignment), if this is an identifier.Otherwise the variable b after the assignments

a:=b; a:=2;

would have the value 2 - an extremely confus­ing situation. However, the left hand side of theassignment is evaluated. Through the assign­ment

b:=2; a:=b;

the value 2, and not the value b, is bound to a

during interactive input.Another example for incomplete evaluation ofparameters is the procedure definition withproc... end-proc. In this case the proceduredefinition is not evaluated. It would be veryconfusing if, with the assignment

x:=13;f:= proc(x) begin x*2 end-proc;

the (naturaIIy incorrect) procedure definition

proc(13) begin 26 end-proc

was generated.Of course, the execution of system functions isdependent on the given function. In the follow­ing, onIy a few directions for the execution offunctions, like "+", "*" and """, which repre­sent the aigebraic operations, are given:With these functions the evaluated parametersare at first simplified and then transfonned intostandard form, in order that the expressions canbe more easily compared with other expres­sions.Simplification is carried out with simple rules.Firstly the associativity of the operation is used,in order to "flatten" the expression tree. Expres­sions in brackets of the form

14

-plus(a, (b,3))

can be simplified to

-plus(a,b,3)

due to the associativity of addition.After this rules like a + 0 =a or a x 0 =0 areused. As a consequence of this all O's areremoved from sums and multiplication withresuits in O. The use of these rules can be - andthis drawback cannot be denied - quite haz­ardous. One such hazardous rule isa I a =1;because it is possible that later a can take thevalue 0, so the substitution with 1 is wrong inthis case. If the variable a is defined by

a:= b*(c+l)/b;

with b not yet having a vaIue, then a is giventhe value c +1 through simplification. If after­wards b: =0 is defined, then the value of a isstill falsely defined as c--L, the variable a doesnot "know" the variable b from its definitionany more.Unfortunately, here, the user must live with thishazard, as otherwise expressions can veryquickly "explode", (Exploding expressions,while being physically harmless to the user, canrender the system useless and therefore causepsychic damage.) The user should be aware ofthe hazards of the simplification rules.The calculation of constants also belongs to thesimplification rules. This includes transforma­tions like

-plus(3,a,4) -+ -plus(a,7)

After simplification the expression is normal­ized. Here, for instance, in sums and productsconstants are moved to the end of an expressionand the remaining sub-expressions are sorted.The expression

z*3*al*a

is transformed into .

a*z*al*3

by sorting. The sorting order is difficult for theuser to predict, but luckily this is nearly aiwaysnot relevant.The expression b*a is always transformed toa *b through sorting. Therefore, sums and prod­ucts must always be conceived as commutative.If matrixes or non-commutative operators are tobe multiplied using symbols then the user will

Page 16: mathPAD Special MuPAD issue -

need to use his own functions. The calculatedexpression is then returned as the solution of theevaluation.

The Substitution Depth

In the evaluation of identifiers the substitutiondepth plays an important role. What is to beunderstood by this?If the original expression is considered beforeevaluation then the substitution depth is O. Eachtime an identifier is substituted by its value thesubstitution depth is increased by 1 and thevalue of the identifier is evaluated with this newsubstitution depth. After evaluating the valuethe old substitution depth is taken on again.This means that the substitution depth gives therecursive depth of the evaluation of identifiers.Evaluation can be controlled by declaring amaximal substitution depth. If the maximal sub­stitution depth is reached then the identifier isnot evaluated any further.Interactively entered expressions are fully eval­uated (fully means the user can still give a max­imal substitution depth). However, normally theexpression is evaluated to the point where nounbounded identifiers are present. After theassignment

a:=bi b:=e; e:=13i

the variable a, when interactively entered, isevaluated to 13, as expected.In procedures the maximal substitution depth is1, i.e., identifiers are substituted by their values,these are, however, not evaluated further. In thefollowing procedure f the local variable z isevaluated to y and not to the parameter x:

f:= proe(x)loeal y, z;

beginz: =y; y: =X; z

end-proe

The call f ( 13) returns the solution y and not13, as might have been expected.

Control of the SubstitutionDepth

The user can explicitly set the maximal substi­tution depth with the variables LEVEL and MAX­

LEVEL.

15

Evaluation

During evaluation substitution is carried out(when necessary) to the depth LEVEL. With theassignment

a:=b; b:=e; e:=13i

a is normally evaluated to 13 in interactiveinput. If however LEVEL is set to 2 then a isevaluated to e and b to 13.

By the way, LEVEL can be set to values otherthan 1 during procedures. In the procedure

f:= proe(x)loeal y, z, LEVEL;begin

LEVEL:=2; Z:=Yi Y:=Xi Z

end-proe

z is evaluated to the parameter x and not to y.

The call f (13) results in 13 and not y.The variable MAXLEVEL is used to detect infi­nite recursions, as in the seemingly harmlessstatement sequence

a:= a+1; a;

If a has no value before the assignment, then ais evaluated to a +1 in the second statement, thisthen to a+2, this to a+3 and so on, ad infinity.In order to detect such situations, a substitutiondepth of MAXLEVEL, during evaluation, is takenas an error and evaluation is terminated with themessage "Recursive Definition". Naturally thisis only a heuristic, which may lead to false errormessages in certain cases, but in most cases it iscorrect.

Fine Control of Evaluation

So far, for controlling evaluation, the procedureoption hold and the variables LEVEL and MAX­

LEVEL have been described. The system func­tions hold, val, level and eontext alloweven greater control of evaluation.The function hold can have any expression as aparameter. This is not evaluated but returned asthe result of the call. So, with hold the evalua­tion of an expression is prevented. For instance,the expression

hold(a+2+0)

is evaluated to

a+2+0

and not simplified any further.

Page 17: mathPAD Special MuPAD issue -

mathPAD

The function val also has an expression as aparameter, which, exactly like hold is not eval­uated. Furthermore all identifiers in the expres­sion which are bound to a value, are substitutedwith this. This expression is then evaluated nofurther, but immediately retumed as the solu­tion of va1. For instance after the assignment

a:=b; b:=2;

the expression

val(a+3+0)

is evaluated to b+ 2+0 and the expression

val(b+4)

to 2+4, but both are simplified no further. Themost important use of va1 is the quick anddirect access to the value of a variable, withouta time consuming evaluation of the value takingplace.The function level is given an expression asits first parameter and, optionally, a wholenumber as its second parameter. An expressionwith the form 1eve1 (a, n) is evaluated, by theexpression a being evaluated to the maximalsubstitution depth n instead of to the "current"depth given by LEVEL. The function level,therefore, temporarily overwrites the variableLEVEL. The variable MAXLEVEL remainsunchanged, on reaching the substitution depthMAXLEVEL an error message will still be given.If the second parameter is missing then a nearlyinfinite maximal substitution depth is assumed(to be exact 2147483647).On the interactive level, with the statement

a:=b; b:=c; c:=3;

the expression

level(a,l)

is evaluated to b and the expression

level(a,2)

to c. Also, the function level can be especiallyused to fully evaluate a variable in a function.context can be used for evaluation of arbitraryexpressions in the context of an calling proce­dure instead of the actual context. If contextis called in a procedure, then the argument isfirstly evaluated in the actual context. The resultis then evaluated in the context, from where theprocedure has been called. For instance:

16

i : = 2;f := proc(x)

option hold;begin

x, context(x)end.....proc

By calling f ( i) the sequence i, 2 is retumed.

Page 18: mathPAD Special MuPAD issue -

Polynomials

Klaus Gottheil

From version 1.2 on special data structuresand a1gorithms for polynomials will be madeavailable in the MuPAD kernel. These enablequick basic operations to be carried out onpolynomials.

Introduction

The computer algebra systems Maple andMathematica do not know any special datastructures for polynomials. They use "normal"expressions for the generation of polynomials.This has the advantage that no conversion ofpolynomials and expressions is necessary. Fur­thermore, the use of expressions as polynomialis intuitive because, from the users point ofview, certain expressions and polynomials are"the same",The MuPAD team decided in the planning ofversion 1.2 to introduce some special data typesfor polynomials (DOM_POLY). One of the rea­sons for this is that in MuPAD the terms ofsums are sorted by the internal simplifier. Thissorting does not conform with the canonic gen­eration of polynomials (of any ordering).Another reason is the memory space occupiedby expressions. The new data structure is farmore compact.Apart from polynomial expressions the varia­bles and coefficient ring are also stored in a pol­ynomial data structure. This type information isuseful when programming using polynomialsotherwise they must be transferred as extraparameters.To make the life of an interactive user easierexpressions can be given as arguments insteadof polynomials in the relevant functions. Theseare then intemally converted to polynomials.

The User's Point 01 View

As already mentioned polynomials have thedata type DOM_POLY. A normal expression canbe converted into a polynomial by the functionpoly. The call

17

p := poly(x* (x + a*y) + 12, [x,y]) i

generates the polynomial p with the variables xandy.Polynomials are given out in functional form,like tables, with the aid of the function poly.The polynomial p defined above is printed as

poly ( x A 2 + a*x*y + 12, [x,y] )

As a special feature the user can also define thecoefficient ring of the polynomial. Apart frompolynomials with expressions as coefficients theuser can also define polynomials for the ringZn := Z/nZ with positive integers n and alsowith domain elements as coefficients.The ring Z7 is written as IntMod (7 ) inMuPAD ("integer modulo 7"). The "ring ofMuPAD expressions" is signified by Expr inthe polynomials.

Particulars 01 the CoefficientRing

From the particulars of the coefficient ring thetype of polynomial can be deduced. The residuedass ring Zn is one of the most required rings.Polynomials in the form Zn are used, forinstance, for factorization. Operations on thesepolynomials must be as fast as possible.One possibility of calculating in Zn is to rede­fine the operations like _mult and -plusbefore calculation so that they calculate in Zn'When the polynomial operations evaluate thecoefficients as normal, due to the changes in thebasic operations, the calculation is carried out inZn' However, this has two disadvantages:Firstly the continual redefining of the basicoperations and the management of the "currentoperations" is tiresome, secondly the basicoperations as MuPAD procedures are very slowwhen compared with the kernel routines. Due tothis the basic operations for possible coefficientrings are implemented in the kernel.Apart from Zn and expressions, a domain canalso be used as a coefficient ring. This domain

Page 19: mathPAD Special MuPAD issue -

mathPAD

must make certain basic operations available sothat it can be used as a coefficient ring. (Anintroduction to the domain concept in MuPADis given in the article "Domains" in this issue ofmathPAD.)The use of a domain as a coefficient ring has theadvantage that the user receives anormal repre­sentation of the coefficients, provided that thedomain can realize with such a representation.For expressions this is not always certain.(MuPAD has, for instance, no normal represen­tation of rational functions. If the user usesMuPAD expressions to represent rational func­tions as coefficients then the zero function can­not always be recognized. With this the usermay get polynomials whose coefficients are notequal to 0, but are a representation of the 0 inthe ring of rational functions. Such polynomialsare not in canonical form.)

Polynomial ArithmeticPolynomials can be negated, added, multiplied,exponented and differentiated. The inverse of apolynomial is not defined. Polynomials can beused as operators. In this case they are consid­ered polynomial functions.In a sum or product all polynomials of one typeare grouped together and then processed inthese groups, A type conversion is not carriedout. The expression

2 * poly (x, [xl)

for instance stays like it is and is not returned asthe polynomial poly (2*x, [x] }, It would bevery difficult to guess the type of the solutionthat the user wants. In the example above thedesired solution could also be the expression2*x.The user can work as usual with the functionsop, subsop, subs and subsex on polynomi­als. However, one should note that these func­tions do not work very efficiently on the"visible" polynomial expression. In this case,one of the special polynomial functions shouldbe used whenever possible.A call of op with a polynomial as an argumentalways returns three operands: A polynomialexpression, a list of variables and a representa­tion of the coefficient ring.Polynomials are never implicitly evaluated dueto speed. Also functions that have a polynomial

18

as an argument and return an expression as thesolution do not evaluate the solution. If thesolution of such a function is to be evaluated thecall must be enclosed in eval.

Operations on Polynomials

The polynomial operations made available inMuPAD version 1.2 will only be listed in briefhere. Further information is available in theuser's manual. As already mentioned an expres­sion and optionally a list of variables can begiven instead of a polynomial in all functions.This can make interactive use easier.

poly converts an expression into a polynomial.Furthermore, with poly the user can change thetype of a polynomial.

expr converts a polynomial into an expression.

degree returns the total degree of a polynomialor the degree relevant to a variable.

degreevee returns a list of the exponents ofthe leading term.

leoeff returns the leading coefficient.

Imonomial returns the leading monomial.

1t erm returns the leading term.

ntheoeff returns the nth coefficient.

nthmonomial returns the nth monomial.

nthterm returns the nth term.

nterms returns the number of terms in a poly­nomial.

teoef f returns the coefficient of the last term.

coeff returns a sequence of all coefficients orthe coefficients of a term with a certain factor.

mapeoeffs maps a function to the coefficientsof a polynomial.

multeoeffs multiplies all coefficients of apolynomial with a factor.

divide carries out an Euclidean division oftwo polynomials. Furthermore, multivariate

Page 20: mathPAD Special MuPAD issue -

polynomials can be divided if an exact divisionwithout remainder is possible.

pdivide carries out a pseudo-division of twopolynomials.

icontent calculates the integer contents.

norm returns the norm of a polynomial.

evalp evaluates a polynomial at one ore morepoints.

genpoly generates a polynomial from anumber by a radix expansion.

iszero tests if a zero polynomial is given.

The Polynomial DataStructure

In MuPAD, polynomials have a sparse distrib­uted representation with lexicographic orderingof the monomials. This is true for both univari­ate and multivariate polynomials. The represen­tation of a polynomial of the form

n

L e'l e,C .• x I. X I.m

I 1 ••• m

i = 0

can be thought of as a list with the form

Here (cb (ei,b'" ei,m) represents the ith mono­mial of the polynomial. Naturally, only thosemonomials are stored whose coefficients are notequal to 0. The sequence of the monomials inthe list foIIows the lexicographie ordering of theexponents. The polynomial

3 2 5 23x y -7xy +x-5y +2

is equivalent to the list

(3, (3,2), -7, (l,5), 1, (l,0), -5, (0,2), 2, (0,0».

The coefficients are stored as normal MuPADexpressions. The exponents, however, arestored as machine integers. The sum of theexponents of a term must not exceed 231_1,

19

Polynomials

which should not cause practical problems. Theexponents are densely stored, i.e. also expo­nents that have the value °are stored in theexponent list of a monomiaI.Apart from the monomials a list of the variablesxI»... ,xm and the coefficient ring are stored in thepolynomial data structure. Furthermore theposition of the leading monomial relevant to thedegree ordering is also stored. The leadingmonomial can be quickly accessed relevant toboth the lexicographie and the degree ordering."Outwardly", for the user, the list of monomialsdescribed above is not visible. The function opalways returns a polynomial expression as thefirst operand of a polynomiaI.

A Recursive Representation

Although polynomials are distributively repre­sented, with the aid of domains a recursive rep­resentation is easily realized. For this purposethe MuPAD library contains the function Poly.With the aid of Poly domains can be generatedwhose elements are MuPAD polynomials.With the aid of these domains polynomials canbe defined whose coefficients are MuPAD poly­nomiaIs, in other words they have a recursiverepresentation. Here the advantages of domainsbecomes cIearly visible.

Page 21: mathPAD Special MuPAD issue -

mathPAD

Domains

Holger Naundorf

Domains are the key to object oriented pro­gramming in MuPAD. Here we would Iike tobriefty introduce the possibilities otTered bythese.

Introduction

Many computer algebra system users have thewish, sooner or later, to define their own types.For instance, MuPAD contains no type that rep­resents the elements of the group z" with addi­tion. Even if this type should exist in acomputer algebra system there is an infinitenumber of other types, all of which cannot becovered. If the user wants to write an algorithmthat works on this group he must make sure thatthe combining of the elements is carried outcorrectly. Of course, the developed program istailor-made for this group only. If the samealgorithm is to be used for elements of othergroups then it must be newly implemented.Normally only a few changes need be made ­the combinations are replaced by the correctones - but this is also error prone and time con­suming. Theoretically, in MuPAD the user canwrite a function that automatically converts thisprogram into one relevant to this function.However, this function is still to be written andthe number of different algorithms generatedtake up a lot of memory space and all do nearlythe same thing.

Domains

For this reason it is possible in MuPAD todefine individual data types - the domains. Anew domain can be generated with the aid ofthe function domain:

d: =domain ( ) :

A domain is a collection of data, that, with theaid of indices and the function doma t tr, can beread-out and altered. Both the indices and thedata can be any MuPAD data.If no entry exists

20

in the relevant index then domat t r returns thevalue FAlL.

domattr(d,"narne") :="example":domattr(d,"narne");

uexample"domattr (d, "x") ;

FAlL

In the description already given domains arevery similar to the data type DOM_TABLE. Thissimilarity is not accidental; for the implementa­tion of domains the principle of tables has beenused. However, the most important point indomains is that not only the user has the possi­bility of reading data from a domain, but thatthe MuPAD system does this, too. Now theentry d; returns example as its solution. Forthe domain output MuPAD returns the datumfound in the index "name" - the object to begiven out determines itself how it is to be givenout. In general, this is referred to as object ori­ented. In many other situations MuPAD tries toread data from a domain. In MuPAD, strings arenearly always used as indices because most ofthe time these have an intuitative meaning andare not changed during evaluation. In this waythe user does not have to protect the index withthe function hold during access. In order tosave the user paperwork MuPAD contains theoperator : :, a short form of domat tr. The sec­ond argument must be astring which is allowedas the name of a variable. The second argumentis written without quotes. With this the entryd: : name is equivalent to the commanddomattr (d, <nama "}. In contrast to allotherdata types in MuPAD, domains are not copiedbefore they are changed. Through this a changein a domain has an effect on all positions whichrefer to this domain. This is called the referenceeffect. In this way it is possible for a domain tocontain a datum which has got this domain as asub-datum:

Page 22: mathPAD Special MuPAD issue -

dl:=d:d::self:=d:bool(d=d::self and d=dl);

TRUE

This is important, because methods - anothername for a function stored in a domain - mustoften know which domain they belong to. Asthe reference effect is not always desirable theuser can make a copy of the domain with thefunction dorna in.

dl: =dornain (d) :

Although dl has exactly the same entries as d

the two domains represent different data andare, therefore, not recognized as the same:

bool(d=dl);FALSE

This is implemented in such a way becausechanges in one domain no Ionger affect theother domain:

dl: :x:="y":d: :X;

FAlL

Domain Elements

The concept of domains attains meaning withthe possibility of generating objects - domainelements - that can have a domain as a type.Exactly as the number i has the type DOM_INT

in MuPAD so the user can generate objects forany domain that have this domain as their type.A domain element can be generated with the aidof the function new:

e : =new (d, 5 , 6 , 7) :

generates an element of the domain d whichcontains the values 5, 6, and 7 as entries. Theuser can imagine a domain element as a sort oflist. These entries can be accessed with the aidof the function extop:

extop(e,2) ;6

With the function extsubsop the entries canbe changed (similar to the function subsop).The function extnops is used to determine thenumber of entries in a domain element.

Overloading FunctionsThe decisive point in connection with domainelements is that most system functions can be

21

Domains

overloaded. This means that a system functionwhich comes across a domain element searchesfor a method in the domain of the element withits name as an index, which can take over itsexecution. In a domain it can be easily laiddown, for instance, how the sine of an elementis to be calculated.

d: : sin: =proc (x )begin

sin(extop(x,l» ;end-proc:

sin(e);sin(5)

The function sin calls the found method with allits own arguments. Therefore it is also possiblewith the aid of domain elements to give the sinemore than one argument. The functions -plusand _rnul t - which represent + and * - can alsobe overloaded. However, the usual simple over­load mechanism does not come into play.Instead of this the method found in a domain isonly called with all arguments that He in thisdomain. From the individual solutions of themethod an equivalent datum is constructed.Connections in an algebraic structure are there­fore easily implemented.

Internal Methods

Not all operations on data are carried out bysystem functions in MuPAD. Domains alsocontain indices which do not represent systemfunctions but are still important for the inftuenc­ing of the behaviour of elements in a domain.Among these are:"evaluate": Determines how a domain element

is evaluated. Ifno entry is present the ele­ment evaluates to itself.

''func_caU'': Determines how a domain ele­ment behaves as the zero operand of astatement. With the aid of this method theprogrammer can generate his own types,which can represent functions or algo­rithms.

d: :func_call:=proc(f,x}begin

extop(f,l}*x"'2 +extop(f,2)*x+extop(x,3)

end-proc:e (2) ;

39

Page 23: mathPAD Special MuPAD issue -

mathPAD

''negate'': Determines how the additive inverseof a domain element is ealeulated.

''invert'': Determines how the multiplieativeinverse of a domain element is ealeu­lated.

''print'': Determines how a domain element isread-out. If no entry exists a standardoutput is chosen.

ei

new(Example,5,6,7) :d::print:=proc(x)

begin[extop (x) ]

end-proc:ei

[5,6,7]

There are other internally used methods whosedeseription would not be appropriate in thisjournal.

UsageIf a domain is to represent a ring or a field theuser needs only to define the relevant neeessarymethods and then he ean ealculate in the normalway. At the moment there are still weaknessesin this area:

• With + and * only elements of the samedomain ean be eonnected. Multiplieationwith other types, such as integers, is not eas­ily possible.

• Due to variables having no type it is not pos­sible to reeognize the elements of whiehtype they represent, during ealeulation. Thesimplifieation laws used are those relevant toR. Here errors ean be generated if, forinstanee multiplieation in the user's ownstruetures is not eommutative.

Logicallnterfaces

Due to the fact that at the time of implementa­tion of a domain it is not yet eIear if the chosenrepresentation of a domain element is optimal astriet differentiation between a logical and aphysieal view of a domain element must bemade. The Iogieal view of a domain must bedetermined in the first impiementation, thephysieal view ean be ehanged Iater if necessary.Due to this the following basic rules should befollowed:

22

• Eaeh domain should contain a method"new" with whieh it ean generate newdomain elements. This funetion checks if anargument is eorreet and then generates therelevant domain element. The domain usershould never generate new domain elementshirnself with new. In this way the user is pre­vented from generating non-standard or non­sense domain elements.

• The domain element user should not aeeessthe contents of a domain element with any ofthe ext . . . funetions. For this purpose onlythe normal funetions op, subsop, ete.should be used. These ean be redefined withthe relevant methods by the programmer ifneeessary.

Conclusion

To sum up it ean be said that MuPAD enablesobjeet oriented and polymorphie programmingby the integration of domains. The time neededfor the development of programs ean be drasti­eally redueed. Apart from this the code size eanalso be redueed. A further advantage is that theuser ean eonfigurate the system aeeording to hisown wishes and ean intuitively ealeulate withnon-predefined algebraie struetures.

Page 24: mathPAD Special MuPAD issue -

Domains and abelian Groups

Balger Naundorf

A problem that many a1gebraists are con­fronted with is that of calculation in abeliangroups. At the Paderbom university thesewere the Lp groups which occur in connec­tion with the notation theory of a1gebraiccurves.On the one hand you may want to carry outaddition of 2 elements of the group and multi­plication of an integer and an element of thegroup and on the other hand you would like tobe able to calculate using symbols. In the latterit is necessary to utilize associativity and dis­tributivity - that is the normal calculation rulesof + and *. Many computer algebra systemshave problems dealing with this task. It is at thesame time very difficult to solve. Here I wouldlike to introduce the principle by which this canbe solved in MuPAD.

Groups as Domains

As we have already indicated in this journal inthe artic1e "Domains" it is very easy in MuPADto represent an algebraic structure by a domain.Normal addition can be used for the additiveoperation in connection with group elements ­these are represented by domain elements. Thenormal simplification rules are still used for cal­culation with symbols. However one problemdoes occur and that is that the multiplicationdoes not try to combine group elements withintegers.

New Multiplication

At this stage, in many other systems the userwould have reached the limit of his possibilitiesand will have to capitulate or look for othersolution strategies. However, in MuPAD, theuser has the possibility of overcoming theweakness of the system by newly defining howmultiplication is to be carried out. In order toavoid the problem of having to implement theA- and D-Iaw hirnself, the user will have toreturn to normal multiplication. To do this the

23

user must temporarily store the contents of thevariable _mult in another variable and thenstore the new algorithm for multiplication in_mul t , This then carries out the following:

• Multiply the arguments of the function withthe aid of normal multiplication. Store theirsolution in x. In this step the symbolic sim­plification is carried out and the various lawsare applied.

• If x represents neither addition nor multipli­cation return x as the solution of the func­tion.

• If x represents multiplication check if both agroup element and an integer are containedin the product. If this is the case then multi­ply them and return the simplified product.

• x represents an addition and was obtainedby applying the distributive law. Check eachaddend to see if a group element and an inte­ger can be combined. Return the so-gener­ated datum.

Conclusion

Although some of the weaknesses of MuPADare exposed in this example it has shown theflexibility and power that this system offers. Itis nearly always possible for the user hirnself toovercome the weaknesses that exist in MuPAD.This is extremely important when the user con­siders that no program can be perfect.

Page 25: mathPAD Special MuPAD issue -

mathPAD

Axioms, Categories and Domains

Klaus Gottheil

In order to simpllfy the eonstruetion of newalgebraie struetures, the experimentalllbrary paekage dornains is avallable inMuPAD Version 1.2. With the aid of tbispaekage the user ean eonstruet parameter­ized domains. For this, knowledge of theeommon aspeets of eertain domain c1asses inthe form of generie algorithms ean be used.

IntroductionStarting with Version 1.2 the user is given a toolfor the implementation of his own algebraicstructures. This is realized in the MuPAD kernelby the data type "domain", These are nearlycompletely integrated into the MuPAD kerneland can use the already existing operations suchas +, *, and -. The interactive use of the sodefined structures is easy. An introduction to thedomain concept is given in the article"Domains" contained in this issue of mathPAD.Of course, it is not very effective to construct analgebraic structure like Z7 := Zl7Z "by hand",Here, the user is more likely to want to con­struct a structure like Zn in order to obtain allpossible remainder class rings of Z dependenton the "parameter" n. To use the MuPAD lan­guage: The user wants to generate a domaindependent on a parameter. To construct parame­terized domains so-called domain constructorsare used in the domains package.The user will often want to implement a domainby taking over an already existing implementa­tion ("inheriting" it) and changing some of itsentries. The new domain is derived from anexisting domain. In this case we can say that theoriginal domain is a super-domain of the newdomain and the deri ved domain is called a sub­domain of the original domain.A domain constructor defined with the aid ofthe domains package permits the specificationof such a super-domain. Naturally, the super­domain can in its own turn be dependent on thedomain parameters of its own sub-domain. A

24

domain constructor only needs to newly definethose entries that differ in their implementationfrom the super-domain. The domains generatedwith the aid of the domains package form ahierarchy (a forest of trees).The user will quickly notice that in the defini­tion of new domains certain domains have cer­tain things in common because they belong tothe same class of algebraic structures. Thus Z6and Z7 are both rings, they contain among otherthings the operators + and * and have neutralelements for these. In each ring the operation"raise to the power of a cardinal number" canbe easily implemented by continued squaring.Of course, it would be extremely ineffective ifsuch an operation had to benewly implementedfor each ring. Naturally, the user will want toimplement such an operation only once andthen use it for each ring.Classes of algebraic structures, such as "rings",are called categories in the domains package. Acategory "postulates" certain basic operationsand characteristics of those domains belongingto it. The actual implementation of these basicoperations is carried out by the domains. Withthe aid of these basic operations, further opera­tions can be defined for the category. These arerealized - as in the continuous squaring men­tioned above - as generic algorithms.If a new domain is now generated then the rele­vant domain constructor determines, by meansof the parameters, to which categories thedomain belongs. The constructor then enters theoperations defined. in these categories in thedomain. If the newly generated domain belongsto the category ring then the operation "raise tothe power of a cardinal number" is entered inthe domain. Naturally, the user has the freedomto implement such operations himself in thedefinition of domain constructors if he wishesto use special characteristics of the domain.

Page 26: mathPAD Special MuPAD issue -

Type

ISet

/"""SemiGroup OrderedSet

IMonoid

/"""Group AbelianMonoid

"""/AbelianGroup

IRng

IRing

/"""CommutativeRing SkewField

IIntegralDomain

IGcdDomain

IFactorialDomain

IEuclideanDomain

-,Field

Figure 1: Hierarchy of the Categories in theDomains Package

Like the domains, categories also form hierar­chies in the domains package. Thus everydomain that belongs to the category skew fieldautomatically also belongs to the category ring.In other words: Every skew field is a ring. Cate­gories only need to define those characteristicsand operations that are not made available bythe more general categories.In this context, the more general category of therings is called the super-category of the skewfields and the more specialized category of theskew fields is called a sub-category of the rings.In contrast to the domains, a category can havemore than one super-category. The commuta­tive groups have, for instance, both the groupsand the commutative monoids as super-catego-

25

Categories

ries. Categories not only form trees but alsoacyclic graphs. The - at the moment fairlysimple - hierarchy of the categories defined inthe domains package is depicted in figure 1.Categories can, in their own turn, be themselvesdependent on parameters. Thus, there are differ­ent categories of polynomial rings. These cate­gories are dependent on the coefficients ring. Inorder not to have to newly implement the rele­vant category of polynomial rings for each pos­sible category of coefficient ring the domainspackage contains so-called category construc­tors. These generate - as might be expected ­categories dependent on parameters.The characteristics of categories are postulatedwith the aid of so-called axioms. In the domainspackage these are mostly attributes whose exist­ence the user can ascertain. The category ringhas the axiom uni tElernent ( 11_rnul t 11 ) • Thisaxiom should show that a domain possesses aneutral element in connection with multiplica­tion. The axioms can be requested by the cate­gory and domain constructors in order to define,for instance, an operation dependent on them.Axioms can also - as the example aboveshows - be dependent on parameters. There­fore, the domains package contains axiom con­structors that generate parameter dependentaxioms.

Categories in MuPAD

The objects described above - from categoriesto axiom constructors - are realized in thedomains package as elements of specialdomains. Categories and axioms are elementsofthe domains Category and Axiom. The con­structors for domains, categories and axiomsare elements of the domains DornainCon­structor, CategoryConstructor andAxiornConstructor.If a new constructor is to be defined then themethod "new" of the relevant "meta-domain"must be used. Entities of these "meta-domains",that is domains, categories and axioms, are gen­erated in form of a function call with themethod 11 func_call". If, for example, Zrnodis a domain constructor for Zn then with thestatement Zrnod (7) the domain Z7 is generated.

Page 27: mathPAD Special MuPAD issue -

mathPAD

Constructing DomainsAs already mentioned domains are generatedwith domain constructors in the domain pack­age. A domain constmctor is defined as folIows:

DomainConstructor::new(name,parameters,(parameter-test, )super-domain,categories ,axioms,entries... )

The individual arguments have the followingmeanings:

name gives the name of the domain constmctor.This is only used for the output.

parameters gives the formal parameters of theconstmctor. This must be a list of identifiers.The list can also be empty.

parameter-test gives a statement that is used totest the actual parameters. If there is noparameter this statement is missing.

super-domain gives the super-domain fromwhich a new domain will inherit its imple­mentation. Here a statement must be giventhat evaluates to a domain or to NIL. WithNIL the domain has no super-domain.

categories gives the categories in which thedomain generated by this constmctor is con­tained. The statement given here must evalu­ate to a list of categories.Only the "smallest" categories need begiven. If a domain belongs to the categoryskew field then it automatically belongs tothe category ring.

axioms gives the domain axioms. As with thecategories this must be a statement that eval­uates to a list ofaxioms. Only those axiomsneed be given that are not already entered bythe categories.

entries is a sequence of equations with arbitrarylength in the form nameeentry. With this theentries in the new domains are defined. Inthe domains the value entry is stored underindex name.

26

The arguments are not evaluated during the def­inition of a domain constructor, The evaluationof the arguments takes place when a domain isgenerated from a constructor: The statementsfor testing the parameter and for defining thecategories and axioms can contain the identifi­ers from parameters. With the generation of adomain these "formal" parameters are replacedby the actual parameters of the domain. Onlythen are the so generated expressions evaluated.Apart from the formal parameters the entriescan also contain the special identifier this. Ongenerating a domain this is replaced by thenew domain.A domain constructor for Zn may look like this:

Zmod:= DomainConstructor::new(# Name #

Zmod,# Parameter: Modulus #

[ Mod ],# Parameter-Test #

(if domtype(Mod) <> DOM_INT thenerror("no integer modulus")

end_if i

if Mod < 2 thenerror("modulus must be > 1"}

end_if) ,# Super-Domain: not present #

NIL,# Categories #

[ (if isprime(Mod) thenField

elseCornmutativeRing

end_if) ],# Axioms: none #

[ ],

# Entries #"new" = proc(x} begin

new(this, x mod Mod}end-proc,"zero" = this::new(O},"one" = t h i s: :new(l},

) :

The constructor is called Zmod and Mod is themodulus parameter. If the modulus n is a primenumber then the domain Zn is a field, if not it isonly a commutative ring. Zmod has no super­domain and no axioms.Both the identifiers this and Mod are replacedby the current values (the domain and the mod-

Page 28: mathPAD Special MuPAD issue -

ulus) when a new domain is constructed. InZmod(7) the operation "new" has the form:

proc(x) beginnew(Zmod(7), x mod 7)

end...,proc

The representation of the domain elements isimplicitly set by the implementation of theoperations. It can also be dependent on thedomain parameters. In Zmod all domain ele­ments have the same simple form: They consistof exactly one entry, an integer from the rele­vant residue class.The algorithm structure may be dependent onthe category of the relevant domain. In Zmodthis concems the operation 11 invert ", whichcalculates the multiplicative inverse of a residueclass. If the modulus is a prime number and,therefore, the domain a field, the modularinverse can always be calculated. However, ifthe modulus is not a prime number the exist­ence of the inverse is dependent on the relevantresidue class. This must be reflected in the oper­ation 11 invert" of the relevant domain:

"invert" = (if isprime(Mod) thenproc(x) begin

this::new(l/extop(x,l»end...,proc

elseproc(x) begin

if igcd(extop(x;l), Mod) = 1then

this::new(l/extop(x,l»else

FAlLend_if

end...,procend_if)

Naturally, the user can also inquire during theexecution of the operation "invert" if thedomain element belongs to a field and reactaccordingly. Exactly how this takes place is inend effect a design decision in the implementa­tion of the domain constructor. The first alterna­tive has the advantage that the user need notmake any enquiries during the run time and istherefore more efficient.The entries of a domain are generated as fol­lows: Firstly the definition of the entry issearched for in the domain constructor. If it can­not be found there then it is looked for in thesuper-domain and then in its super-super-

27

Categories

domains. If the entry is not defined in any of thesuper-domains the definition is searched for inthe domain categories one after the other. Intheir own turn the categories carry out depthfirst searches in their super-categories for thedefinition.

The Definition of Categories

In the domains package each category must begenerated by a category constructor. The defini­tion of a category constructor is similar to thatof a domain constructor:

CategoryConstructor: :new(name,parameter,(parameter-test , )super-categories,axioms,entries... )

The arguments have analogue meanings tothose in the domain constructors:

name gives the name of the category construc­tor.

parameters gives the formal parameters of theconstructor. This must be a list of identifiers.

parameter-test gives a statement that can beused to test the actual parameters. If noparameters exists then this statement is alsonot present.

super-categories gives the super-categories inwhich the categories generated by this con­structor are contained.

axioms give the axioms for the generated cate­gory.

entries are a sequence of operator names orequations of the form index=entry. With anequation the entry is entered under the indexin the domains of this category. If only anoperator name is given this is an indicationthat this is a basic operation whose imple­mentation must take place elsewhere.

The arguments are also evaluated during thegeneration of a domain of the so defined cate­gory. For this and the parameters the domainto be generated and the actual category parame­ters are inserted.

Page 29: mathPAD Special MuPAD issue -

mathPAD

As an example we shaillook at a constructor forthe category of Euclidean domains:

EuclideanDomain:=CategoryConstructor::new(# Name #

EuclideanDomain,# Parameters: none #

[ ],

# Parameter-Test not necessary ## Super-Categories #

[ FactorialDomain ],# Axioms: none #

[],

# Entries #"rem" ,

) :

In this simplified example the category con­structor has no parameters. This means that theconstructor can only generate a single category.An Euclidean domain is a factorial domain thatcontains the additional operations "remn etc..The operation "rem" is a basic operation whoseimplementation cannot be given here. If "rem n

is carried out a run time error occurs. The basicoperations must be "filled out" by the relevantdomain constructors.The calculation of the greatest common divisorcan be defined by the Euclidean a1gorithm withthe aid of the basic operations:

"gcd" = proc(x, y)local tmpi

beginx:= this::normalPart(x) i

y:= this::normalPart(y);

while not this::iszero(y) dotmp:= this::rem(x, y)i

X:= Yiy:= tmp

end_whilei

this::normalPart(x)end-proc

The entries "iszero" and "normalPart " aredefined elsewhere in super-categories. Exactlyas with the domain constructor operations theidentifier this is replaced by the relevantdomain during the construction of a domain.

28

Definig AxiomsDue to the fact that axioms are only attributesand have no further functionality their construc­tors are considerably more simple than thedomain or category constructors. They aredefined as folIows:

AxiomConstructor::new(name,(parameters, )(parameter-test))

name gives the name of the constructor. If theconstructor has parameters they are given byparameters. Actual parameters are tested fortheir validity by parameter-test. To express thatan operation can be inverted there is the axiomconstructor invertible:

invertible:= AxiomConstructor::new(invertible,[ operator ],(if domtype(operator) <>

DOM_STRINGthen

error("wrong operator name")end_if)

) :

The expression invertible (" _mult") gen­erates an axiom that states that the operation"_mult" of a domain can be inverted.

General Nonsense?What advantages do the concepts introducedhere have over the implementation of domains"by hand"? The necessity of constructingparameterizable domains and the inheriting ofimplementations goes without saying. The usercan, of course, also generate parameterizabledomains with normal procedures. Such. amethod is doomed to be non-structured as eachdeveloper generates his own domains anddefines his own operations. Domain construc­tors standardize the implementation of domainsand allow for far better maintenance. Apartfrom this the domains package takes over manystandard tasks during construction, reducing thedevelopers work load and in addition unneces­sary error sources and code duplications areavoided.

Page 30: mathPAD Special MuPAD issue -

This is perhaps even more true in the use of cat­egories. The advantages of generic algorithms-avoidance of re-implementation for all possi­ble domains, and with this the lessening ofimplementation effort and a smaller chance oferrors occurring - are quite obvious. Thedeveloper of generic algorithms is guided to amore standardized form by the category con­structors. And, last but not least, the user canexpect a standardization in the use of thedomains.These advantages are not fictional. M. Monaganhas developed the library package GAUSS forMaple V which allows the definition of domainsand categories, see [2]. In GAUSS domains aresimple tables and domain constructors and cate­gories are Maple functions that manipulatethese tables. The domain operations are storedas table entries. The use of domains and theiroperators takes some getting used to becausethey are not integrated in Maple and cannot beoperated with the normal operators in the Maplelanguage. Apart from this the output of domainelements cannot be adapted to personal require­ments.Despite these deficiencies the package is beingused successfully, for instance, for the imple­mentation of a Gröbner bases package for dif­ferent polynomial data structures and differentterm orderings, see [1]. The implementationdetails can be "concealed" due to them beingmade abstract by the categories. This meansthat different data structures and orderings canbe used with one another and nevertheless onlyone "generic". algorithm for calculating theGröbner bases need be implemented. Anyonewho has seen the implementation of the "nor­mal" Gröbner bases package grobner inMaple will be able to appreciate this abstrac­tion.Most of the concepts in the domains packagecan be traced back to ideas in AXIOM, see [3].Axioms, domain and category constructors arelanguage constructs in AXIOM. In contrast tothe domains package these are anchored in thesyntax. All objects in AXIOM are strictly typi­fied which is, due to the lack of typification inthe MuPAD language, not possible in thedomains package. Many of the newer algo­rithms are firstly implemented in AXIOM

29

Categories

because it contains rieh algebraic structures thatthe user can utilize for his problems.A conflicting feature ofAXIOM is the auto­matie type conversion: The system tries to typ­ify the user entries as soon as they are entered,i.e. to convert type-free expressions intodomain elements. In the domains package theuser must explicitly convert types "by hand".Naturally, it is easier for the user not to have togive types. On the other hand it is extremelydifficult to determine the type of an expression.For this AXIOM uses time consuming and errorsusceptible heuristics.Normally, the user will not use the domainspackage directly at the "user's interface" butwill instead use it for the internal implementa­tion of the library package. There will be "inter­face routines" that accept expressions as entriesand then convert these internally to domain ele­ments. This conversion is non-problematic as inthis situation the implementor knows the prob­lem that is to be solved and therefore also thetype needed.Until now the domains package is only availa­ble in an experimental form. The infrastructureexists, but the algebraic "meat" is missing.Some of the basic categories starting at the cate­gory "type" through the categories "sets","serni-groups", "monoid" etc. to the category"field" already exist, but they do not have manyof their more important operations. All in allmuch more experience will have to be gatheredwhich will be beneficial to the infrastructure.However, this will be a part of a later MuPADversion.

Bibliography[1] D. Gruntz. Groebner Bases in GAUSS.MapleTech, (9):36-46, 1993.

[2] D. Gruntz and M. Monagan. Introduction toGAUSS. MapleTech, (9):23-35, 1993.

[3] R.D. Jenks and R.S. Sutor. AXIOM, The Sei­entific Computation System. Springer, 1992.

Page 31: mathPAD Special MuPAD issue -

mathPAD

The Graphical User Interfaces

Karsten Morisse

In order to work with the computer algebrasystem MuPAD no special input or outputdevices are necessary. A keyboard and ASCIIterminal are all that are neded. To make theinteractive work with MuPAD as convienientas possible, there is XMuPAD which is a gra­phical user interface for MuPAD under X·Windows and OpenWindows. Fur thermorethe Hypertext-System HyTeX, with the fullMuPAD documentation, is at the users dispo­sal.In the development of the user interfaces muchvalue has been laid on retaining the typical win­dows' characteri stic s, for example, the specifi ­cation of options for defining the window sizeer window position , and the drag and dropmechanism . For descriptions of these characte­ristics the reader is refered to the OpenWindowand X-Window documentation. In this contribu­tion the graphical interfac e is described. Apartfrom the environment and working methods ofXMuPAD and HyTeX a short descripti on of thetechnical implementation is also given. Allspecifications for keys, mouse buttons etc. referto the Sun SPARCstation.

XMuPAD

XMuPAD is a fully independant program. It hasno knowl edge of computer algebra . It is irnple­mented as an interface to the MuPAD kernelwith the help of the XView-Lib rary. XMuPADis invoked with the command

xrnupad [options]

The only important option for the user is the - L

option. The language of the on-Iin e documenta­tion can be stipulated with this option. Possibleparameters are german or english. Afterbeing called a Basic lVindow appears on thescreen, which consists of two comp onents

• a row of buttons,

• a text window for input and output.

30

• .~J Mur"IH~

Qyll l J~'!2'.~t:; •·..·•. tf~ til tlJ:)X~:;1fSf tti"g i :-i". f·;Jo; '-Toe1S · f V

' - '11 11 I'LPIO) 1. 2~ - ".1111 Prccessing Algebra Oa la Teo}

'-' 11 '-1- ' (cpyr jgnl Ic) 199M3 by B. Fu;:hss tei nu. AutlTlatll

!~l' lkll~efSity or Padelborn. Al l r1ghts roso rved.

) 1 d1tr (ln(x)h .dJ);

-, -.• 11 • x l n(x) (- 6)

Il he!( 1Z0);"81S02'91].Wg, 21CS1~B l I B~O~mS<6 152N GJ JlI 3st119 ~t 02g56 11 :rsn0 16J)'lS7\24'lm38mSS741652119&49; 130 ~1 5 7nm31l ~OSllS52S)4.4D85B~CB1 2 ' BSS69&4e1 , \

143S96S000S9&oliö05212S; 9&OCOC'OOOOOOCOOOJOoow:;ococ:ooa

>l Hil( tOf(I) ;I 1.2.116. 3. se . 5. 28. 7. 19. 1, . 10. 13. 9. 17. 1. H . 6. a . 5. 2~ . ~

. 31. J. 31. 3. ~ I. 2. ~J . 2. H . 2. ~1 . 2. 59. 2. 61. 1. 67. I . 71, L n. 1. B. 1. 83. 1. 89. 1. 91. 1. 101, 1. 103. 1. 107. I, 10~ . 1. 111. 1

:

".! ~t!\lon 1.2 'ft' ""'Ce G/I99i -

Fig. J: XMuPAD basic wind ow

Furthermore the MuPAD kernel is invoked as achild process on the UNIX level. XMuPAD'sfunction can be divided into three phases, whichare typical for interactive systems:

• During the input-phase the user enterscommands into the text window.Thisphase is ended with the <Return> key.

• During the evaluation-phase the inputof the first phase is interpreted .

• The third and final phase is the output ofthe solutions MuPAD has ca lculated.

The Text WindowThe Text window is a usual window for theinput of text , similar to the editor tex t edi t inOpenWindows . On the right hand side is ascrollbar with which the visible text section canbe changed.

InputCommands are entered with the keyboard at thecurrent insert position , which is made visiblewith the cursor. This insert position can be alte­red to anywhere inside the Text Wind ow by

Page 32: mathPAD Special MuPAD issue -

using the mouse (place the mouse cursor on thedesired position and press the left mouse but­ton) or the cursor keys. The command input iscompleted by <Return>. The currentinstruction is then read and sent to MuPAD tobe executed. An instruction is normally onlyone screen line long, however; it is possible toenter commands spread over more than one linewithout the parser interpreting each line sepera­tely. How this is done is described below. Theresult is printed as output directly under theinput line. The result is followed by the MuPADprompt character ». The current insert positionis now directly behind the prompt. AfterMuPAD has received the command, theXMuPAD is in its evaluation phase. During thistime the text window is inactive, and no inputcan be entered. This is shown as a small clockby the mouse cursor.

Special FeaturesIf there were no special features for the input ofcommands XMuPAD would be superftuous anda normal terminal window could be used.

<Shift Return> or <Enter>In order to input commands structured overmore than one line, the keys <Shift-Return>or <Enter> can be used to end one line.Through this the current line is concluded, anew line is inserted, and the current insert posi­tion moves to the beginning of this line. Howe­ver this newly entered command has not yetbeen transfered to MuPAD, i.e. it has not yetbeen executed. In this way a MuPAD commandof many lines length can be entered. On ente­ring <Return> the command is carried out.Hereby it is unimportant where the currentinsert position is. All lines above and below theinsert position are considered part of the com­mand. In other applications <Return> usuallystarts a new line at the current insert position. InXMuPAD a new line is started at the end of theinput.

New execution of old inputBy moving the current insert position into a pre­vious command and pressing the <Return>key it will be executed again. The insert posi­tion may be anywhere within the command,even when this is more than one line long. If theReplace Mode is OFF in the Settings Pull-

31

User Interfaces

down Menu, the output of the old command ispreserved and the new output is inserted beforeit. If the Replace Mode is ON the old outputwill be overwritten. In this case MuPAD givesno new input request, instead the current insertposition moves to the end of the first line of thenext command. If the Recalculate Mode isset to ALL then, not only will the current com­mand be carried out, but also all other com­mands entered during the current MuPADsession. Here, the order in which the commandsare carried out is laid down by the textual orderand not the input order. In this way it is possibleto carry out an interactive sequence ofinstructions if necessary with different startingvalues.

Insertion of new commands between oldonesAs described above, the input of a commandcan take place at any position in the text win­dow. It is also possible to enter a new commandbetween the output of an old command and theinput of the following command. Due to this theorder of all entered commands is influenced,which is of importance for the realization of theRecalculate Mode.

Basic Window ButtonsThe buttons in the basic window are orderedhorizontally. At certain times some of the but­tons are deactivated, i.e. clicking these buttonseffects nothing. This can be seen as the blackcontour and lettering of the button are changedto light grey when deactivated. The individualbuttons are described below.

Quit Button

The Qui t button is self explanatory - it termi­nates XMuPAD. It closes all XMuPAD win­dows and also ends the MuPAD process. Thisbutton is always active.

Interrupt ButtonThis button sends a signal to the MuPAD pro­cess to terminate the current calculation. Thisbutton is only active during the evaluationphase. During the input phase it is deactivated.

Status ButtonThe Status button opens a pop-up window,which gives status information about MuPAD.The information gives the output of the MuPAD

Page 33: mathPAD Special MuPAD issue -

mathPAD

commands byte s () and t ime ( ) . The statusbutton is only active during the input phase.

crU-"1lml (ras): ,,700,,-_ _

Fig. 2: Status Pop-up Window

Settings ButtonOn clicking this button a pulldown menu is ope­ned with which the user has the possibility ofcarry ing out differen t functions and can modifythe input and output functionality. The pull­down menu has the OpenWindows typical pus­hpin with which the menu can be pinned to thescreen. The Sett i ngs button is, as are allmenu items, only active during the input phase.

upper input field is used to enter the directory.The actual file name is entered in the lowerfi eld. The directory name need not be concludedwith a / . It is insened automatica lly betwe enthe two names. If <Return> is pressed whilstin the directory field the cursor goes to the filefield. By pressing the OK button the contents ofthe rext window are memorized in the specifiedfil e. If a file with this name already ex ists, abackup of the old file is made before it is over­written. For that purpose a % is added to thename of the old file. The entered names are sto­red between two calls of the status pop-up win­dow.

Save Te)d:

DIrectory: ... _

Ale: _""- _

Fig. 4: Save Pop-up Window

Chan ge Fant

With the menu item Change Font a furtherpop-up window is opened . With this item theuser can change the font of the window. Theuser can determine the font family, font styleand font size.

:;I Sett ings

( Delete I.st output )Clear Wlndow

Save Text

Change f ont

Pretty Prln!: TRUERecalculate Mode: OneRe place Mode: OnSeperate by IInes: Oft :/I' Font Sell!dioft

Fig. 3: Settings Pulldown-M enu

Delete last output

This item deletes the output of the last corn­mand. As the first item in the Pulldown-Menuthis is also the defau lt action. If the Setting sbutton is pressed without the menu being open,this action is automat ically executed .

Clear WindowThis item deletes the contents of the text win­dow. After this item has been activated the onlytext remaining in the text window is theMuPAD prompt » .

Save Text

The menu item Save Text opens a furtherpop-up window, the Save pop-up window. The

32

Seal. ~ Small

Fig. 5: Font Selection Window

With help of the following menu iterns differentmodes for the output in the text window can beset. The current status is shown in the menu .

Pre tty PrintWith this command the user can turn the forma­ted output (Pretty Printer) on and off.

Recalcu late ModeIt is possible in XMuPAD to execute a previouscommand again. To do this the old input is clik­ked with the mouse cursor and <Re t ur n> is

Page 34: mathPAD Special MuPAD issue -

pressed. Is the Recalculate Mod e se t to ONE

only the selected input is recalcul ated. Is theRecalculate Mode set to ALL not only willthis co mmand be reca lcu lated bu t all ot her fol­lowing commands in the text window.

Replace Mode

With this menu item the Replace Hode is tur­ned on and off. A description of how this modewo rks is to be found on page 4.

Se perate by Iines

With this menu item the user has the possibilityto seperate one inpu t fro m the other with a linestretching over the whole window.

Tools Bu tton

The Tools button open s the Tools PulldownMenu. This me nu comprises of entries to acri­vate other programs. At the moment con­necti ons with the MuPAD-Debugger. the helpsystem and the grap hic too l VCarn are imple­mented. By selecting He l p the on-line docu­mentation is activated. T his co nta ins both thecomplete MuPAD reference manual and helppages to all MuPAD co mmands (see alsoHyTeX on page 5). On se lec ting the Debuggerthe MuPAD-Deb ugger is implemented. So far itis not possible to refer back to previ ous MuPADinput because the debugge r is staned with anew Mu PAD process . The Tool s button is onlyactive during the inpu t pha se.

Tools

( Help )

Debugger

Graphics

Fig. 6: Too ls Pulldown-Me nu

Special Cases - Deviation s fromMuPADThe operation of XlvluPAD differs in a fewpoints from that of MuPAD.

UNIX S hell Com ma nd

With the funct ion sys tem (shon form r) it ispossible to g ive commands to the UNIX shell inMuPAD. T he performance of the system-com­mand demands spec ial a ttent ion beca use it isnot possible. for example. to start the Editor vi

33

User Interfaces

in a text window. In this case a new terminalwindow is ope ned in XMuPAD. within whichthe users default shell is stan ed. Tb c param eterof the syst em-command are executed . Thiswindow co ntains the Done butto n. On usingthis the window vanishes . However the contentsof the terminal window are preserved . Bymeans of a new system command the termina lwindow with the o ld con tent s reappears. Execu­ting the system co m ma nd in M uPAD is notwithout probl ems bec ause the X View-Libraryoffers no co ntra l mech ani smus for the processesin the terminal window. Bec ause of thi s inXMuPA D the s ystem com mand prov ides noresul ts in the termi nal window. The user rece i­"es no information about if the displaced com­mand has been executed, o r, if the executio n hasalready been ended . In an interactive session theuser can sec thi s in the terminal window.Funhermore the s ys tem co mma nd is no t blok­king XM uPA D, i.e . if s y s tem is called in acommand sequcncc the fo llowing com mand isnot de layed un til the she ll co mmand has beencompleted , but both commands are executedsimultaniously as two processes (one commandis executed by the shell, the other by MuPAD).

Us er Inlerrupl

In MuPAD the use r has the possibility with<Ct r l-C> to interrup t a runnin g eva lua­tion.There then appea rs a menu, in which theuser can select between

• abort - Brea king off of the current cal­culation

• cont inue - Con tinuation of the currentcalculation

• qui t - Ending the MuPAD ses sion

In XM uPAD the use r can generate an inte rru ptby c1icking the I nterrupt butt on. The userdoes not have the possibi lity to determine thefunher running of the caleulation in a menu asthe ca lcul ati on is irnrned iately stopped . Howe­ver thi s is not a se rious di sadvantage as two ofthe three me nu itc rns are covered by the Qu i tand Int e r r u p t button s.

Exec uli on 01 te x t input

The user can enter interactive text du ring therunni ng of a progra m and then as sign it to aidentifier with the function text input . Thiscommand also de ma nds special treatment inXMu PAD . In this ca se a funher window which

Page 35: mathPAD Special MuPAD issue -

mathPAD

offers the user a complete mouse orientated texteditor, is opened. After the input of the desiredtext and clicking the Done button the text ispassed to the MuPAD kemel.

HyTeX

HyTeX is a hypertext system developed at theUniversity of Paderbom by the group ofN. Köckler. In connection with XMuPAD. aspecially modified version of this program isused. As can be seen from the name HyTeX.this system is based on the TEX- or LATEX­System from D. E. Knuth. Besides a specialLATEX-Previewer it also contains some newcommands. Therefore, text production is noproblem for the TEXnician. HyTeX is used forthe complete on-line documentation. This inclu­des the MuPAD-reference manual and the helppages containing explanations of each MuPADcommand. HyTeX is started as a child processfrom XMuPAD and is at first represented by anicon on the screen. The window is only openedafter an explicit request from the user. This canbe done in different ways . On the one hand hecan open the contents list in the MuPAD refe­rence manual by activating He lp in the ToolsMenu (see Tools-Button on page 4). The secondpossibility is offered by the help function inMuPAD. With this the user can open the helppage of a given command.

HyTeX-WindowThe HyTeX window contains a LATEX previe­wer, which is provided with hypertext Fun­ctions. The previewer gives variousnavigational possibilities through the documen­tation, These will be described below.

Statie Bultons

This group of buttons contains those which,independant of which page can be seen, arealways in the HyTeX window. They are all to befound in the upper control line.

Next- und Prev Bulton

With the help of these buttons, the documentpages can be tumed over one by one. Next

turns the pages forwards, Pre v turns the pagesbackwards.

34

....... ... . " . " .", .. _ ..... . . '\.< ..... . 01.. ,. ......

.T!l ...·,·,, ' · .. 'o( ..ll

......._.'"1" "",~ _'10" ". , , .. , .•_ ;, ol ' '' _ . _ ,

ilil ..•...- ,·, ··..··,..,I . >, •• t . u, u , , lt , If , ," ," . Il. ", , , '''.lll.'''. '''. ''', 111. "•. "' . '''.' fI,'' ','''." , • • " . , , ,, ,, H ,., •

.... .11. ' ", 11 ."•. "' . "'. " '. Il'. "'.",. "t. ,,, , ,... , ,. , ,,,. ,, .

.. . . ... . . " , . ,. , " • ., U t " •

.. " or , ". . m ... ... .. . ... ,.. I " .. !••; ,•••; 4", >I ~", .

10. ,•• ,I ~ _ , .. ," 1 .' _ _ ,,, . " " . •••.. .. . .. ;, • • " •• •~,, ~ , I.~ . :11 ,,,,, ,w. ",. •, ,• I.; ..!r I, I _ , I , :..• •, 1 , ,,. " , ' ''', , ,, ~""~ I Io " , 1.. loa,,'. ,",;,," l .h .. ' I~ .. · ;, l l h '<f .. Io' t, ' ,;• • " d,, ' Io ., ..

ll .,.a lo , oll ," 1 , _ , ••,,101 ;11 " ~;, F 1< " . Ol.,..·._·· '····l'· '.. ,h._.~ ..."'"

,."",[iJ •.,,,,, ,

Fig. 7: HyTeX window

Retu rn Bullon

This button is of importance in connection withthe dynamic buttons and therefore, will bedescribed later.

Load Bulton

The Load button allows the loading of otherdocuments. Clicking on it opens another controlpanel, in which all the accessible documents arelisted.

Fig. 8: Load window

Page-Panel und -Slider

The Page-Panel is used to directly jump to achosen page, Instead of giving the page numberdirectly with the keyboard, the chosen page canbe set with use of the slider.

Seareh Bu lton

This button is used for searc hing in the docu­ment. After act ivating it the search menuappears. Herc the user can enter a text pattern,which is to be searched for in the document. In

Page 36: mathPAD Special MuPAD issue -

User Intertaces

the menu, the user can choo se if ca pita l andsmal1 1ette rs are to be recogni zed .

j ump s back to the correspondi ng page of thedocument.

S EA RCH

!t1 ccnve rt to lower <ase letters

Patte l"n: •"'-- - - - - -

OK to se a r c h )m

[lI Cancel )

Help Pages

As already mentio ned above, beside theMuPAD reference manu al , the on-line helpsystem is also integrated in HyTeX, forexample, in MuPAD or XMuPAD the user canrequest information about the system functionigcd with the co mmand

help ( " igcd " ) ;

or

?ig c d

Then , the co rres ponding page IS open ed In

HyTeX.

'"~ ·• .,.~..... L .. . ...

1'....u.1H

'" "'1:" - ..... ..~.,

.." <\~__, ) 1"~ ";,,-J;;,·~·Lko<""" J

.....", "'..... ! , ,."" _ : .- _ OIIl.......~';f

Fig. 10: Help page for igcd

The exac t co mmand sy ntax is described on suc ha help page . How the comma nd wo rks is descri­bed, so me examples for use are give n, andjumps to the help pages of related func tions orcommands are possible. Here, eac h ex amplehas also been given a box wh ich is mouse sensi­tive, i.e. something happens whe n it is cl icked.The differen ce to the dynamic butto ns is thathere no cross reference is carried out, bu t, theinput of the example is tran sfered to XM uPADand written in the XMuPAD text window. Th euser ca n now read the input again at leisu re, ifneed be modi fy it and then execute it with

S.lD mu ! :

;t" .. n. ".. I ~. ,,,. , •• , ' .....no>. ~ ;. i . '" ., . .. , __ " .t .. .... ... ;a" .... I.. I , "

,1.."."". " .,, 1

~~~ ."~": ::':,.;;,.~t:~~~ ;.'7;:;:,7~: ':.r~'; : ~ ::~'.~~;:::~.::.::,: ~: ::.:~;'t" ~. ; "~, io I• • , ' ....

Iii _, . t l - n , U ;

Fig. 9: Search Men u

Done Button

If the user cl icks this button the HyTeX windowdisappears. However, it does not d isappearco mpletely and ca n be made to reapp ear withuse of the help function or help buttons inXMuPAD.

Dynamic ButtonsTh e user has the possibilit y of mar king hisdocume nt with nodes and re ferences to nodes.These nodes can be co ns ide red as intern al textmarkers. Th ey are not visible in the text. Howe­ver, references to nodes are visib le and ca n beseen in the HyTeX window as rectangles orboxes. If the user cl icks on one of these boxes,the curso r jumps automatica lly to the corre­sponding node. In this way, the user has thepossibi lity, with personall y determi ned crossreferen ces, to skip through the docurnent . In theMuPAD doc ume ntat ion there are two types ofso ca lled dynamic buttons. On the one handthere are those in the co ntro l panel.over theactual text window, With these butto ns the usercan jump to the previous or next cha ptcr,section, etc . T hese button s can change fro mpage to page. On the other hand, there are thebuttons in the tex t, where , for example.explana­tions of term s are realized as cross referenc es.If the user has made such a jurn p, naturall y hewill wa nt to return to the sturring pag e(es pec ia lly with j umps of the second kind) assoon as possib le. For th is purpe se there is theRe t urn butt on . On jump ing, with the dynarnicbutton, to ano the r page, the previous page isinternally filed in a stack. A cl ick on Returntakes the up perrnost eleme nt of thi s stac k and

35

Page 37: mathPAD Special MuPAD issue -

mathPAD

<Return>. With this Leaming by doing theuser is quickly supplied with knowledge of thesyntax to be used.

Implementation DetailsXMuPAD is implemented with help of theXView-Library. This is a toolkit with varioustypes of window, buttons, menus etc. as weil asmany functions for controlling and modifyingthese objects. XMuPAD is an interface purelyfor the user of the computer algebra systemMuPAD. One of the first intructions fromXMuPAD is the calling up of the functionfork () and the starting of MuPAD as a newprocess. The input and output of this process areduplicated in a communication canal, throughwhich XMuPAD and MuPAD then communi­cate. The on-line documentation HyTeX is also

. started by MuPAD as child process. The com­munication execution functions analogue to theconnection between XMuPADand MuPAD:The input and output of HyTeX are duplicatedin a communication chanel through which thetwo programs communicate. With it the internalmarks, to which, on request of the user, the pro­gram jumps, are transfered to HyTeX.

36

Page 38: mathPAD Special MuPAD issue -

MuPAD tor the Apple Macintosh

Gerald Siek

MacMuPAD is the M uPAD version for theApple Macintosh, It incl udes the completeMuPAD language and functionality andoffers the benefits of the user-friendly Macin­tosh interface. MacMuPAD was designed inaccordance with the Apple User InterfaceGuidelines. Both experieneed and noviceMae users will find MacMuPAD easy andstraightforward to use.

MuPADMull t Process tng Algebra ce te Taal

Vers io n 12

Cc p ~ r1 ;ht Cl 1994 bv 11 . f ...:h" lel ner . AutOfl>llhUniver '11v ef Pflderba r n. All n ght. rese rv ee

Regi st ered 10 Gen l id Siek

The basic components of MacMu PAD are:

• Sess ion windowAll computations are displayed here

• Editor windowsFor addti onal notes

• Graphies interiaeeFor ereating 2D and 3D graphies

• HyperText he lp toolIncIuding the complete MuPAD manua land tutorial

The Session Window

The session window is the main part of theMaeMuPAD System. All input and output, allcomputations are displayed in this window.The user can type the MuPAD cornrnands asusual but may also use all weil known editingfeatures like cut&paste, cursor positioning bymouse, scrolling etc. MacMuPAD separa tesInput from Output and displays them in differ­ent colors. Furthermore, consecutive input andoutput lines are grouped in "blocks" which canbe edited, deleted, copied or evaluated as a

37

whole. The block types and their boundariesare displayed within the sess ion window.

UnUtl ll d M uPAD SlIulon0" ,- • •nl " , . 'C".. . >; ,

cos( ,, > . I n ( ,, )

• ' . .. b,, ( '. ...p, ' ; co.<" ) . ' n <P I )

.fi;:'"'i"i -i"-;;-·- _ ·_- _ ·_-_·_-, 11. 0

I"'"s, . <; , ,".,. e,,) - . 1".,,)

..,I

I , , ", , ' .. .!,{,' ~ \: ~

The user also may insert so-caJled "Text­Blocks". These blocks may contain additionaltext which is not to be eva luated.In addition to the session-window MacMuPADoffers a built-in ed itor for text doeuments.These editor windows can be used to enter addi­tional text, programs or calculations. The con­tents of an editor window can be easilytransferred to the session window to allow fur­ther evaluation. Both session and editor win­dows allow the user to perforrn editin gcommands like search & replace or choosing adifferent font and style. Of course, all docu­ments created by MaeMuPAD may be saved,re-opened or printed .Important settings like the PrettyPrinter, fonts,or the textwidth can be configured with menucommands.

The Graphics Interface

The graphics interface is used to create andmodify 2D and 3D graphies without typingcryptic commands. The user ju st opens theappropriate dialeg and enters the object defini­tion, it's range, color and titles. New objectscan be created with a single mouse-cIick, oldobjec ts can be deleted easily. Zooming, modify­ing the perspective or moving the titles - all thisis done using the mousc, All pictures can becopied to the cIipboard or saved in Macintosh

Page 39: mathPAD Special MuPAD issue -

malhPAD

PleT fonnat. This allows export MuPADgraphics to any other Maci ntosh app lication,

~ • mc [eilt scarcn \rUlon Plo t UNp unnaeu«

unuuen 1

• dlvldo - Division zvcit!r Polynotte

Aufruf:

dl v ld a(poly-l. polL Z [ . OPI I)dl vlde ( exp r_L e xpr_ 2 [ • i1lII ." J [ • Dpl ])I.-.lel: -- .. [ n pr .. . I

'f";

dlVl de ( p . q) ~l lt die IlfIMlnallten Po lynotM p Ilf<1 q. Will! MineOpQon6tl(teebell, '0 ...;""deI Te ~l ' uro. der1<.51 I teT!ehml, XI

- Flllyno_- AI'-' dilXke- eine der OpCIl... nQU Q. Rell oder Exa ct

pllJ'lllDlltar:

poly_i. pol y_2eapr , elpr_1. elp1_2

'"

All important settings of MacMuPAD ca n beconfigured with menu cornmands or dialogs

H 1 ~,D':~OOI)O

y 1- 19. 2 00000

z 116.000 111

cemereeetnt

foc1I1Point

H 10 .0 0 0 0 0 0

y 10 .0 0 0 0 0 0

z 10.000 111

The Help Tool

o IIcbuild stertun fil e

Requirements

MacMuPAD can be used on every Mac intoshcomputer with at least 4 MB RAM and abo ut 5MB disk space. At present MacMuPAD needssystem software version 7.0 or later

nonnceuon steck :

PARI Sta ck;

o tnt erecuu e M8 nuol Mode

~

o usu User Init Flic: [SelotV j<None>

I!I use Syste m InU File: [Sehid I IUse Default!:llb:MuPßII Inll

which are stored in a Preferences file in the sys­tern folder of your Mac intosh. Thi s allowsevery user to costumize MuPAD for his/her per­sonal needs even if MacMuPAD is loaded froma fi Ie server

Configuration

The built- in Hype rText help-tool inc ludes thefull MuPAD reference-rnanual, the MuPADtutorial and the help-pages. It serves as an on­line documentation for the complete MuPADlanguage.In MacMuPAD. the help-tool is activa ted byselecting the appropiatc menu item . Afte r open­ing the help window thc user may navigatethrough the docurnent as in every hypertext sys­tem. The MacM uPAD HyperText systerninclud es:

• Stepping thro ugh Ihe documenl page bypage

• Crossrelrences wilhin lhe docume nt text

• Jumping 10 important sec lions 01Ihe docu ­menl wilh men u commands

• Sle pping ba ck 10 previous ly read pages

• Inte raclive examples within lhe document

In general, the MacMuPAD HyperText systemoffers the same funct ionality us the HyTeX sys­tem used in thc UNIX version of MuPAD

38

Page 40: mathPAD Special MuPAD issue -

At first we want to produee a new graphies.This takes plaee, as already menti oned abov e,with the help of the Scen e menu . If the itemcrea te 3D-scene is chosen, a further windowappears, the so ea lled graphics manipulationwindow.

The Graphics

Thorsten Schulze

In this article we want to describe the MuPAD­graphies tool VCam ( Vi rtua l Camera) by show­ing a sampie session. The graphies tool is aeti­vated from the program XMuPAD by givi ng theMuPAD eo mmands p l o t3d ( ) or p l o t 2d () .These eommands ean be given either with aseries of arguments or without, whereby thesecond possibil ity was eoneeived for the inex­perieneed user. When the com mandplot 3d () ; is entered, followed by <Return>,the so-called base window of the graphics 100lsappears.

. hutIR' ; 1 q;l~w A:lN1- .!.I •

: seall ll, :=:;r • 2""11111•• i.!J •

() bl.n~N Il: L;o;.:,; LJ.!J"0 _

Pr~ I, Atwt ! !!li!)

llwi.~l'n !:J . I

UlI lltl"i .!J 11

Figure 2: Graphics Man ipulation Window

The partition ing of this window directly followsthat of the basic user model whieh is based onphotography. To understand this bet ter, the usershould imagine that he wants to take a photocontaining certain inform ations. For this pur­pose objects with individual parameters aregrou ped into a scene with further eharaete ristiesthat are valid for all objeets. Exaetly this user' smodel reflects the grap hies manipulation win­dow. In the upper part of thi s window the sceneeharacteristies are show n and in the lower partthe objec t specifications are given. To produee agraphies , the user must first define the objectmode. Thi s is earried out by choo sing thedesired opt ion in the Mode menu . For example,to depiet a space eurve the user should ehoosethe opt ion Curve. Now the user only needs tofix the parameters and the parameter range . Forthis the user enters the appropriate values intothe text field s x(u), y(u), z(u) and <; U <; . When

• ..,Illlfllt 0! J vca",,: lIu,wJn4,,, -,

.~!'! <'j ,. i'l ';":ti~) /~.~j ~r!.r.t:J . l?' !~'!.-Ils,:,) I

,

Figure I : Base Wind ow

This eon tains the ac tua l plotting area for pres­entation of the grap hics and a menu bar withcontrol funetions for the gra phies 1001s:

• Scen e :menu for the creation of new grap hies

• Modify...:for modifying existing graphics

• Save...:for savi ng existing gra phics

• Print...:for printing gra phics

• Defaults ...:for changing the default values

39

st~l.. !.l H~tl

i taT!lnl at •

d ll) ,.. ",nil),.. ..u _

luV'~(·Il C. U-:-

,,"~' .~..L~j ,

SllI'llllllllH S

~' !J~

"

Page 41: mathPAD Special MuPAD issue -

mathPAD

the user presses the Plot button in the upper sec­tion of the window, the graphics is drawn. Theactivation of the Plot button generates a newp lot3d () command that contains the valuesshown in the graphics manipulation window asarguments. This plot3d () command is thensent to the MuPAD kernel. The evaluated resultis then sent back to VCam and processed. Thegraphies appears VCam's base window.

Figure 3: Example of a graphics

Here, once again, it must be expressly stated,that - unlike other computer algebra systems ­MuPAD permits graphics commands to beentered direct1y in the graphics too1.Now we come to the changes the user canmake. In the area for the scene characteristicsthe following options can be changed or enteredagain:

• Title:Each scene can be given a title, The titlewill appear at a predefined position in thedrawing area of the base window. Thisposition can be changed interactively byclicking on the title and dragging it to thedesired position.

• Routine:By use of this menu, the routine used tocalculate the graphics data can be chosen.The option QuickDraw means that thegraphics data are calculated depending onthe numbers of Grid and Smoothness. Theoption QualityDraw means that the socalled fine structure algorithm is used forcalculating the graphics data. This meansthat depending on the smoothness ·of theobject further plot points are evaluated

40

automatically. However, this routine is notyet implemented in the current version ofVCam.

• Axes:We offer a choiee of four types ofaxisstyle. These can be chosen by means oftheicons, i.e, None, Origin, Corner and Box.

• Scaling:With the help of the icons the user canchoose between two scaling routines. Inthe first the graphieal data are scaled sothat distortion is only produced by per­spective transformations, so that spheresappear as spheres and not as ellipsoids. Inthe second the data are scaled so that thecanvas, that is the actual drawing area, isoptimally filled.

• Zooming:With the help of this menu we offer theuser somepossibilities of altering theviewing volume. If the second icon is cho­sen, the so-called zoom window appears.This will be explained later.

• Perspective:This menu is used to switch from auto­matie perspective to manual perspective.In case the item manual is chosen the so­called perspective window is activated, butmore about that later.

• Lighting:With the help of this menu the input of alighting model is possible. This, howeveris not yet implemented at the currentdevelopment stage.

Further functions can be called up by means ofthe three buttons in the upper part of the win­dow:

• Properties ...:This button is used to activate the so-calledproperties window, which serves forchanging further properties of the currentscene, like the labels of the axis and thenumber of tickmarks drawn at each axis.The properties window will be explainedlater.

• Reset:With the help of this button the user canrestore the entries of the last plot com­mand, or, if this does not exist, the defaultvalues are entered.

Page 42: mathPAD Special MuPAD issue -

• Plot:As already mentioned this button is used toenter the current graphics options in a newplot command, which is then evaluated.The graphics is then drawn in the alreadyexisting base window.

Of the functions in the lower part of the windowonly the most important shall be described here.All other functions are described in the MuPADreference manual or in the help system in XMu­PAD. In the lower part of the graphics manipu­lation window the specifications of the currentobject are shown. With the Add or Delete but­tons the user can add or delete objects from analready present scene. Other important optionsare:

• Mode:the object mode. Four possibilities areincluded here:

• Curve:This object is aspace curve.

• Cantour:This is a three dimensional object,whose contour lines are to be drawn.This option is not yet available in thecurrent version.

• Surface:This object is a surface.

• List:This is a list of points, which are to begiven by the user. This option is alsonot available in the current version.

The following options (and some others)are dependent on the object mode.

• Parametrization:The parametrization of the objects is givenin the text field. Hereby, we differentiatebetween the following cases:

• Mode = Curve:Because this is aspace curve three par­ametrizations, dependent on one varia­ble, have to be given. To make thisclear, these text fields are called x(u),y(u) and z(u). These three parametriza­tions then define the x-, y- and z-coordi­nates of the object.

• Mode = Surface:This object is a surface. In this casethree parametrizations dependent on

41

Graphics

two variables are to be given. This ismade clear by the names x(u,v), y(u,v)and z(u,v).

• Range:Here the parameter ranges have to begiven. In Mode = Curve only one rangeneeds to be given, whereas in Mode =Sur­face two parameter ranges are necessary.

All other options, like, for instance, the choiceof plot style or colour functions, are optional.Here we would like to draw your attention to afew details in which the graphics tool differsfrom other computer algebra systems. In theMuPAD graphics tool, extra plot styles are atthe users disposaI. These are in Mode = Curvethe plot style Impulses, with which the abscis­sae of the function values are drawn and inMode = Surface the style Transparent, withwhich the user can simulate transparent objects.Furthermore the user may decide which param­eter lines are to be drawn for the surfaces. Byusing the Smoothness value additional plotpoints can be included without the correspond­ing lines being drawn. This is shown in the fol­lowing example:

plot3d(CameraPoint = [0, 1, 30],Axes = None,

[Mode = Surface,[sin(u)*cos(v)+1.2,sin(u)*sin(v),O],u = [0, PI/2],v = [-PI, PI],Grid = [10, 10],Smoothness = [0, 0]],

[Mode = Surface,[sin(u)*cos(v)-1.2,sin (u) *sin (v), 0],u = [0, PI/2],v = [-PI , PI] ,Grid = [10, 10],Smoothness = [0,2]]);

On entering this command the graphics shownin figure 4 appears. Two circular discs havebeen constructed, both with the same amount ofsampIe points but with different Smoothnessvalues. If the user wants a similar graphics tothat on the right, but without using the smooth­ness function, then the amount of sampIe pointswill have to be raised. This leads to extraparameter lines being drawn. The command forconstructing such an object is:

Page 43: mathPAD Special MuPAD issue -

mathPAD

p1ot3d(CameraPoint = [0 , 1 , 30 ] ,Axes ;: NoA xes ,

[Mode = Su r face ,[sin(u) *cos(v)+l ,sin(u) *sin(v) , 0] ,u = [ 0 , PI/2] ,v = [ - P I , PI] ,

Grid = [10 , 28] ,Smoothne ss = [0 , 0 ] ] ) ;

Save as

Directot1-':

File;

vcam: Save -Popup

~ PopUP...

+- - --- - _._- - - ---( Save Scene »

Figure 4: Demo nstration of Smoo thness

As already mentioned above, now we wouldlike to deseribe the other pop-up windowswhich are aetivated by the buttons .The read window is aetivated by ehoosing theitem read scene... of the Seene menu in thebase wind ow.

VCam: Rsad-Pnpup

Directory: ...---' ---'- ~ _

File:

( Re.d file )

Figure 5: Read Window

Thi s window is used to speeify a file eontaininggraphies data , Thi s file is read by aetivating theRead File button and the eorrespond ing graph­ies is drawn in the drawing area of the base win­dow. The files, whieh ean be read by thegraphies tool, are either files in the ASCII for­mat or files eontaining graphies data saved inbinary format.The snve window is aetivated by use of theSave ... button in the base window. It is used tosave the graphies in various format s. The but­tons in this window are used to ehoose thedesired format und to speeify the file in whiehthe graphies data should be saved. Speci fieally,there are:

42

Figure 6: Save Window

• Save as:This button is used to choose the save for­mat. At the moment seven options areavai lable:

• Popup ...:The eurrent graphies in the base win­dow is saved in a further pop-up win­dow. The user then has the possib ilityof eomparing it with other graphies. Byusing the Replot button the savedgraph ies ean be reea lculated .

• Haster-File:The show n graphies in the base windowis saved as raster file. In this ease boththe text fields Direetory and Name areaetiva ted. Here the user must give thepath- and file names.

• Gif·File:The graphies in the base window issaved in GIF format. Aga in the path­and file narnes must be give n.

• ASCII·File :The graphies is saved in an ASC II fileand ean be read aga in by the graphiestool.

• MCODE-File:The shown graphics is saved in a filecontaining binary data. Like aheadbinary files ean be read agai n and theeorresponding scene will be drawn inthe base window.

• Plot-Comman d (File):By use of this format , the eorrespond­ing p1ot3d () or p1ot2d () COIll­

mand of the shown graphies is saved ina file.

• Plot-Command (XMuPAD):Like ahead, hut the comrnand is sent toXMuPAD and ean be ehanged there.

Page 44: mathPAD Special MuPAD issue -

• Directory:This text field is used to determin e the pathof the file in which the graphics is saved.

• File:Here the nam e of the file ca n be chosen.

• Save Scene :By ac tivating thi s button thc graphicsdrawn in the base window is saved in thespec ified format.

The prillt window is ac tivated by use of thePrint... bu tton in the base window. Th e prin twindow serves for printing the current sccne,i.e. the graphics drawn in the drawing area ofthe base window. Therefore the De stination andthe name of the printer are required . The sce neis printed by ac tivat ing the Print Scene butt on.

Graphics

the de fault va lues are grouped. Th e currentvalue is shown .

• Reset:This butto n is use d for revoking changes .

• Apply:With thi s but ton the changes are verifiedand are made available to the user,

• Store :By use of this button the curre nt defaultvalues are stored in a file named . vcam_­d e f a u l t s in the horne d irectory of theuser. This file will be read every time thegraphics too l is started. So the user canstore his perso na l default va lues in his ow ndefault file .

Figure 7: Print Window

In the def oults window the user ca n alter someof the preset default va lues. Th ese values arestored in a file named vc am_de f a u lt s , whichis read afte r start ing the graph ics tool. Thedefault va lues are used to preset the optio ns ofthe scene and the obj ects, so that the user hasnot to spec ify all options of the scene and theobjects. Furt hermore the user is ab le to store hisown default va lues with the help of the defaultswindow in his horne d irec tory, as will beexplained later on. Th e defaults window is acti­vate d by cl icking the Defaults ... button in thebase window. Thi s window is di vided into twoparts. These are :

• an area wi th a se ries of co ntro l functions.with which the user can decide whichdefault values he wa nts to change,

• an area in whic h the current default valuesare shown and changes can be made.

The contro l function area co ntains the follow­ing buttons and menus:

• Choice :This list co nta ins the categ ories in which

Destination:

Printer:

VCam: Print-Popup

~ laserwriter

. ~.@,y

(Printleene~

43

j vceee oefaull-Popup - . . .

Chnice .!J, seere ll~et ; (Ailll@J 5IN~ )

Sterte Dthulu:

"" II!IITI~ Tk kmark5 .!S-.. !.l=1 k

'""" •• ttatk,ro und 0

Labels •• foregm llnd •::::::11 lt-label K-1ll1 ~

y- labt l y-a.<1!

lolltlrle ~ Quldtlnw l-Labo l z"'"3Ii ls.,

R' •

Figure 8: Defaults Window

The area in which explicit changes ca n be madeis naturall y dependent on the ca tegory chosenunder Choice. For instance, in the figure abovethe user can see the curre nt default va lues fo r asce ne.These va lues are easily ch anged wit h themouse. Similar subwindows are avai lab le for allother values in Choice .The properlies window is activated by use ofthe Prope rties ... butto n in the graphics manipu­lation window. It is used to change further prop­ert ies of the current scene, like the backgroundand foreground co lours, the number of tick­rnarks and so on.The design of the propert ies window is similarto the one of the default s window. It is d ividedinto two areas: an area with co ntrol functionsand another area in which the explicit valuescan be changed. The co ntro l area contains the

Page 45: mathPAD Special MuPAD issue -

mathPAD

~ vcam: rrepertias-Papun

Choke ~ Scene '<m!D

canvas the user can see the view ing box withthe old perspective. This enables hirn 10 see theeffect the changes have had. Naturally theseparameters can also be changed with the use 01'the polar coordin ates. For this purpose the threesliders are used . The sliders on the right side 01'the window are serving for horicontal and vert i­cal ratation, whereas the slider on the bottom 01'this window is used to change the distaneebetween the camera point and the view ing box.Again the viewi ng box is drawn in both the oldand the new perspect ive.

Ticks, ~:dc:J

Bac~gro und 0Foreground •

srene-srejertfes

I

butto ns Choice , to choose the categories 01' theshown values . Res et and Apply 10 revoke orapply the changes .

x-Labe! :<'--"'''',-,i\~_ _

v-tabel ,--y-",,,,,,,I' ~_

r- tabel ,,''''''=I'_~_ Ofiglt,w~ . _

ICamerilhl int

" 2.s932o.~_

~' .~

r ~,c~oo

rou lPol1II,,~

v~

I O,~O

'" '"

Figure 10: Perspective Window

The zoom window is aetivated by use 01' theZooming menu of the graphics manipulationwindow. With the help of this window the userean aller the visible portion 01' the graphics .The zoo m window contains an area 01' co ntrolfunctions and a dra wing area , in which the cur­rent viewing box is show n. T he eontra l areaeontains the following buttons:

• Zoom In:By activating this button the visible por­tion 01' the graphics will be enlarge d by apredc fincd value .

• Zoom Out:This button is used to dimini sh the visibleportion.

• Reset :This button is used to revoke the changesmade in the zoo m window.

c,- v ,

---J,...._--:::;:--;:::'--@

Figure 9: Prop erties Window

The user can act ivate the perspecti ve lViIIdol\'by switching the automatic perspective to man­ual perspective in the graphics manipu lationwindow. This window is used to chan ge the per­spective in which the graphics data are drawn.In MuPAD the perspective is determined by use01' two three-dimensional points, the come rapoint, which defines the position of the camera,and the [ocal point, which specifies the direc­tion in which the camera is hold. These parame­ters can be changed interactively with help 01'the perspecti ve window. Again this windowcontains the usua l Reset button . In add ition itcontains:

• an area for entering the explicit perspectiveparameters in cartes ian coordinates.

• an area for entering the respective perspec­tive para meters in polar coo rdinates and

• a drawing area, in which the viewing box.i.e . the minimal box containing all graph­ics data, in the current perspecti ve isshown.

The user has two possib ilities 01' altering thepcrspcct ive parameters: firstly he can determinethe explicit values for the perspective parame­ters i.e. the camera point and the focal point.After this entry the user must hit the -cReturn»button such that the view ing box is dra wn in thenew perspecti ve. In the left hand corner 01' the

44

Page 46: mathPAD Special MuPAD issue -

Additionally the user is able to change the visi­ble portion by use of the mouse. Thi s is done byclicking into the paint area and dragging theviewing box to the desired position .

rtzoom In)

,,,

VCam: Zoom-POpup

Zoom Out)

Graphics

The ranges Ior u and v are bot h [- 1 .2 , 1 .2] .

Figure 12: Enneper's Su rface

The second graphics show s the correspo ndingGaussian map of the abo ve surface.

Figure I I: Zoo m Window

Finally we should mention that the graphicstool is still in an early development stage , whichcan lead to some of the described options notbeing avail able. T herefore we would like to ca llyour atte ntion to the enhancements for thegraphics tool which are being plann ed :

• Expansion of the three dimensional graph­ics by contour models and point lists.

• Impl ementation of the ligh ting model.

• Inclusion of animation routines.

At least we would like to show you some exam­pies which demonstrate the various graphicscapabilities . The first picture shows a so calledminimal surface, i.e. Enneper's surface. Thissur face is parametrized as folIows:

x u - 1 /3 *u~3 +U *V~ 2 i

y . _ - v - u "2 *v + 1/3 *v A3 ;z . _ u"'2 - v "2 ;

45

Figure 13: Gauss ian Map for Ennep er 's Surface

Page 47: mathPAD Special MuPAD issue -

Debugging

Oliver Kluge

The MuPAD-Debugger

MuPAD contains two possibilities of followingthe program execution in detail. The trace modemakes a protocol of the program execution. Inthis mode the user has no control over the exe­cution of the program. By comparison the inter­active, Une oriented source code debuggeroffers the following possibilities:

• User controllable program execution(step by step or by setting breakpoints).

• Identification of source text lines inwhich a ron time error has occurred.

• Displaying and changing of variablevalues.

This debugger mechanism, which is integratedin the system kerneI, has a character/line ori­ented user interface and offers, even on a text­only output device (ASen terminal), operationconvenience and gives very detailed informa­tion in text form. An interface based on Open­Windows, which offers even more convenience,is the program mdx. This is not integrated in theMuPAD system kernel (see page 42).The debugger is activated by the options in theMuPAD call. In order to do this the MuPADprogram can be called with three differentoptions. All three options can be used simulta­neously.A program, that is either to be executed undercontrol of the user (debug mode) or to be proto­colled (trace mode), must be a text file contain­ing a syntactically correct MuPAD program.This text file is either specified as usual in theMuPAD call or read with the function read.

Calling procedures, which are defined in thisfile, now gives detailed information about itsprogram execution.Under UNIX the debugger can be activatedwith use of the following command.

mupad [-g] [-t] [-v] [options]

46

-t : Turn on trace mode. During a programexecution the number of the line in thesource text in which the executedinstruction is to be found is shown. Inaddition to these the place in the sourcetext in which a (user defined) function iscalled and the function arguments arealso shown. The place where the (userdefined) .function is Ieft and the returnvalue of this function are given.

-v : Turn on verbose mode. During the exe­cution of a read instroction, i.e, duringthe reading-in of a MuPAD text file, theline numbers of the procedure defini­tions are displayed. Information aboutpossible positions in the source text forthe setting of breakpoints are displayedin the form #1ine# during the output ofuser defined functions.

-g : Turn on debug mode. In this mode theuser can interactively enter commandswith the keyboard to control the debug­ger. A survey of the control commandsis given in the following table.

Functions Commands

listing active procedures (d)own, (u)p, (w)here

displaying!changing (D)isplay, (p)rint,variables (e)xecute

breakpoint setting! (g)oto proc, (C)lear,deleting (S)top at, c1ear (a)ll

controlling program (c)ont, (n)ext, (qjuit,execution (s)tep, CTRL-C

In contrast to the graphics user's interface mdxMuPAD offers the user no windows. Here thesource text window, that shows the position inthe source text in which the program is to befound, is missing. Information about this posi­tion in the source text is therefore not displayedvisually but is described in text form.

Page 48: mathPAD Special MuPAD issue -

Interaction between the Debug­ger and the User

If MuPAO is stane d with the debugger tumedon i.e. with mupad - g, then additi onal informa­tion for the debugger is produced intemally.This information is transparent to the user.From the point of view of the user there is nodifference to the standard mode of MuPAO. Theinteractive debug mode is activated with thesystem function debug. The argument of thefunction debug can be any instruction. If thisinstruction contains a procedure call the promptmdx» appears and the user is now in the inputmode of the debugger, in which commands forcontro lling the program exec ution or com­mands for information about the program statuscan be given (see page 43). Ouring the execu­tion of the instruction only commands for the

mathPAD

debuggcr can be given. After the instructionshave been carried out the debugger reportsExecu t ion comp leted. and the user is onceagain in the input mode of MuPAO.

mdx: The X-Frontend of theDebugger

The program mdx is one of the graphic userinterfaces in MuPAO . This program requireseither the window system X or OpenWindows.It improves the user cornfort by:

• Simplify ing the input of debug com­mands.

• Visual processing of the informationgiven by the debugger.

• Simultaneously displaying the sourcetext and the program output in separatewindows.

iJ '~. MuPAD Debu90er.- . - •

File dlsp la ye d : test3 .. Displayed Iines : 1 1 1

Stop ped at f ln e : 3 Procedure : f ._---f : 'p roc \ a ) beg i n "'"Ai

""iU- ti4,"·' ,, -,yl

a· 35

end_proc:

h(a) :

endn roc :

-'

S~) !,;i Stop at )~-

'w__, .-~) Next ) ~) ~

Goto proc :

Qull ) Print ) Displ ay ) Clear ) Clear eil ) Down ) Execute :-, .. -) >r ead ~: test3 "):» debug( f (2 ) ) :

mdx>s

Enter procedure <f> .arg5 • 2 ~

proc dent h 0= 1

~mdx> -'

I I~

47

Page 49: mathPAD Special MuPAD issue -

Debugger

For this reason mdx is divided into five win­dows:

~ Contains general information about theeurrent status. This includes, among otherthings, the line number in whieh the programwas stopped and the line number of the fileshown in the souree window.

$ource Shows the souree text of the workingfile. After ealling the debugger the windowshows the first lines of the file if a file has beenspecified in the MuPAD eall, otherwise the win­dow remains empty. During the program exeeu­tion, the part of the text whieh includes the lineat whieh the program stops, is shown. The userean determine whieh part of the program isshown in the window by using the Goto procbutton.

Buttons Often used debugger eommands can beearried out by elieking them with the mouse.Commands that are not included here ean bedireetly entered into the eommand window withthe keyboard.

commandAll output produeed by the exeeutionof the program, as weIl as some output evokedby the debugger eommands, appears in thiswindow. Input, to both MuPAD and the debug­ger, must be entered in this window.

DiSDlav The output of variable values, that areto be permanently shown, appears in this win­dow.

The souree, command and display windowshave aserollbar on the right hand edge, to ena­ble the user to see the entire text in eaeh win­dow.

Command survey

'NiXt Exeeution of all instruetions in the eurrentline. The debugger then stops at the next work­ing line. If the executed instruction contains thecall of a user defined function then this will beearried out without the debugger stopping in thefunetion.

'SIiQ Analogue to Next, only now the debuggerstops inside the user defined function.

48

I;Qiil The program is earried out until aninstruetion is found that is in a line marked witha breakpoint, or until the program is finished.See also Stop at.

If the debugger stops then the status lines dis­play in whieh line the debugger stops [ Stoppedat: ], in which file this line is [ Displayed file: ],and in whieh procedure it stops [ Proeedure: ].The source text window eontains the part of theprogram in whieh the line is at whieh thedebugger has stopped. Which lines are includedin this text seetion is given by [ Lines: -- ]. Theline in whieh the debugger stops is showninversely.

Gala proc The specified proeedure in the inputfield is shown in the souree text window.

rJiii1 Terminates the execution of the program ifthe debugger is in input mode. The debuggerreports Execution cornpleted, and the useris then in input mode. Quit in input mode termi­nates the MuPAD session. A running programean be stopped with Ctrl-C. The debugger isthen in input mode.

Execute The eommand speeified in the inputfield is executed. The eommand need not beonly single instruetions but ean be put togetherfrom any series of instruetions. One applieationis, for instance, the interaetive inftuencing of aprogram exeeution by the user altering the vari­able values.

~ All proeedures that have been ealledfrom the beginning of the program executionuntil this point in time are shown in the terminalwindow. Besides the proeedure name the user isalso informed of the eall position in the form ofa line number and a file name.

Ili2 In the souree text window the line is shownfrom whieh the shown proeedure has beenealled. The status line of the debugger is alsoupdated. If the procedure that the user has inter­actively entered, has been reaehed, then themessage Top level reached appears in theterminal window.

DQWä This ean only be used if at least ope Uphas been previously used. The procedure fromwhich Up was called is shown in the source textwindow. If the eurrent procedure, i.e. the proce-

Page 50: mathPAD Special MuPAD issue -

dure in which the debugger stops, has alreadybeen reached, then the message Bottom

level reached appears in the terminal win­dow.

Clearall Deletes all breakpoints.

Clear The user can specify with a double dickof the mouse in which line in the source textwindow the breakpoint is to be deleted. SeeStop at.

stOD atThe user can specify with a double dickof the mouse in which line in the source textwindow a breakpoint is to be set. In order togive a specific procedure a breakpoint the usermust load this into the source text window. Seealso Goto proc.

'Eiiii1 The user specifies the expression whosecurrent value is to be shown by marking theexpression with the mouse in the source textwindow. The value of the variable is displayedin the terminal window. See also Execute.

DIsplay The user specifies the variable whosevalue is to be shown by marking the variablename with the mouse in the source text window.The value of the variable is displayed in the dis­play window. Apart from this the current valueof the variable is permanently shown from thispoint on. However, an update only takes placewhen the debugger is in input mode, i.e. whenthe program execution is halted.

Each of the previously described commandswhich can be carried out by clicking on theappropriate button with the mouse, can also beentered directly into the terminal window withthe keyboard.

Internal Program Structure 01the Debugger

Data produced during program execution nevercontain relevant debugger information. Onlythe data produced by the parser in a read­instruction contain the relevant information.But, even here, only one piece of informationper source text line is necessary, independent ofthe number of internal data produced by thisline. Due to this the parser is the only modulethat generates debugger information and also

49

mathPAD

makes sure that no unnecessary information isproduced. In order to store the information thedebugger needs an independent category type(CAT_DEBUG). This type stores debugger infor­mation. Information consists of a 32 bit integerthat stores the line number and file name incode. Since a datum contains categories and theevaluator works on categories, from the internalviewpoint of the system, no difference existsbetween algebraic data, e.g. numbers, anddebugger information. The debugger is neitheran attachment nor an addition of an existingdata structure, but is an extension of the systemby a category type which neither changes thestructure and characteristics of existing cate­gory types nor affects them. If a category of thetype CAT_DEBUG is evaluated then the debuggerkerneI is activated and this then takes over thefurther processing. In the normal mode this cat­egory type is ignored by the evaluator. Thisresults in the evaluator having no run-time lossin normal mode and the execution speed is onlyminimally affected even when debugger infor­mation is present. The parser is the only modulewhose execution speed is reduced when thedebugger is tumed on. But this does not affectthe execution speed of a loaded programbecause only the evaluator is responsible for theprogram execution.

Page 51: mathPAD Special MuPAD issue -

mathPAD

Data Structures and MemoryManagement

Karsten Morisse

IntroductionDuring the development of a computer alge­bra system data structures must be verycarefully chosen. The kernel of such a systemis nearly entirely occupied with generating,analysing or manipulating objects. To a largeextent the efficiency of these operations isdependant on the construction of the datastructures. The assignment of the data struc­tures should take the following aspects intoaccount:

• For the efficient storage of the objectsthat are found in many computer algebrasystems dynamic changing of the datamust be possible. Due to this the ques­tion of the data structure is closely con­nected with the question of memorymanagement.

• Essentially, computer algebra consists ofdata manipulation, i.e. the execution ofthe basic operations: Extraction and sub­stitution of data, generation and deletionof data. An efficient execution of theseoperations is aprerequisite for an effi­ciently working computer algebra sys­tem.

• A uniform construction of data struc­tures simplifies many algorithms in thecomputer algebra kernel. This detail isalso important for the servicing andmaintenance of the algorithms.

In this contribution I would like to give aninsight into the MuPAD kernel and introducethe data structures used. We must differentiatebetween the data structures from the user'spoint of view and those from the internal pointof view. In reality all the data types available tothe user, like sets, tables or expressions, areonly modelIed on one internal data type whichcan, in its turn, contain other internal types. The

50

internal data types are provided by the memorymanagement.

Memory Management

The memory management is apart of Mammut(Memory Allocation and Management Unit),which forms the interface between the kerneland the hardware (or operating system). Mam­mut is a universally applicable memory man­agement that is nearly optimally suitable as thefundament for implementing a computer alge­bra system. Internally, for all data a uniformdata structure, the S-pointer, is used. An S­pointer is apointer to a header. Such a header isa (C-) structure which consists of the followingcomponents:

• da t - Apointer to a header. This is a ref­erence to the data which are hiddenbehind the header. This data area isinternally split into a so-called mem-partand a point-part. The mem-part can storedata of any C-type, whereas the point­part consists of an arbitrary quantity ofS-pointers. The mem-part and thepoint-part are stored in one memoryblock. With this the normal C-addressarithmetic can be used to transit the dataarea.

• signature - Each datum is given a sig­nature. It is internally guaranteed thatidentical objects are given the same sig­nature. However, the reverse is notalways guaranteed. It may happen thatdifferent objects have the same signa­ture.

• size - Numbers the size ofthe data areathat belongs to the header. This size ismeasured in terms of number of S-point­ers. Therefore, this size consists of thesum of the mem-part and the point-partof a S-pointer.

Page 52: mathPAD Special MuPAD issue -

• count - The number of S-pointers in thepoint-part.

• re f s - The number of S-pointers thatpoint to the header. By using this refer­ence counter an expensive garbage col­lection can be omitted during run-time.An object is deallocated the moment thevalue 0 is reached in re f s.

• status - Status information is stored inthis structure. Internally, this is a bit­field with the size 16. The individualcomponents are:- type - Specifies the memory manage­

ment type of the datum.- system - A set bit shows that the data

in the data area was not laid down bythe memory management. In this man­ner libraries that manage their ownmemory can also be used.

- unmovable - A set bit indicates thatthe memory cannot be moved.

- memtype - The memory type of thememory.

- lock - Is used to block the header inthe parallel case.

Header

data signa- size count refs statusture

"point mern

. Fig. 1: S-Pointer

Figure 1 is a schematic diagram of an S-pointer.All headers generated by the memory manage­ment have a uniform size irrespective of thedata contained. The data area of a header, i.e,the point - and mem-parts, can be of any size. Inthis way algebraic expressions consisting ofassociative operators and their operands can berepresented internally by n-ary trees in acanonic manner. Anode of the tree consists ofreferences to the operator and its connectedoperands. Although outwardly the memorymanagement only shows one data type, the S­pointer, this flexible structure is sufficient torealize many different data types. This takes

51

Data Structures

place by different usages of the point- andmem-parts in the data area of the S-pointer. Inthis way the memory management makes manyelementary types available. All these types arestrictly typified, i.e. internally the user can rec­ognize which type a datum has. ~ This informa­tion can be gained from the type component ofthe status part of a header. This mechanismsimplifies the internal realization of the MuPADkernel. Principally it works with only one datatype, the S-pointer. The user does not need totransfer extra information to functions thatmore closely specify the parameters. Functionswork on S-pointers and the actual stored dataand their types can be extracted from the datumwithout any problems. The elementary types ofmemory management are internally namedMMM_<name>. Examples for this are:MMM_STRING, MMM_PARI or MMM_CATEGORY.

The MuPAD user has no direct access to thememory management types. Only the data typeson the domain level are available to hirn. Thesetypes all belong to the memory managementtype MMM_CATEGORY. These types have spacefor at least one structure consisting of two Cshort values in the mem-part. The first value catspecifies the domain type as a number; the sec­ond value spec has, according to the type, adifferentiating meaning. In this part, forinstance, the sign of a number or expression aresituated. In the point-part the actual data arestored. In some domains references to memorymanagement types can be found here, and otherdomains may contain references to furtherdomains. In this manner all the types which aredirectly accessible by the MuPAD user are typi­fied in two ways. Firstly, by the memory man­agement type MMM_CATEGORY and secondly bythe domain type. A complete description ofMammut can be found in [Nau92].

Domain Types

From the user's point of view all data types areof the Mammut type MMM_CATEGORY. I wouldnow like to introduce you to some of thesedomains. In MuPAD we differentiate betweenelementary and compound domain types (amore complete overview of the available cate­gory types is given in [FGK+93]).

Page 53: mathPAD Special MuPAD issue -

mathPAD

Elementary Domain TypesFrom the user's viewpoint the elementarydomain types consist of one object and are gen­erally not decomposable. All numerical typesare processed with the aid of the PARI-GP­package (see [BBC+91]). This concerns boththe internal representation and the arithmetic.The memory management type MMM_PARI isused for storage. For this purpose the PARI datastructure is directly embedded in the mem-partof an S-pointer. By using adetour through twoextra references the PARI long number arithme­tic can be used in the kernel. All numerical datatypes are constructed as depicted in Figure 2.The actual datum is stored in PARI format inthe MMM_PARI object and the concrete type, e.g.DOM_INT for integers is contained in the catcomponent.

POlnt Mem

cat spec

DOM_IN'l

"

Fig. 2: Numerical Domain Types

For the storage of character strings (up to 2"32­1 in length) the type DOM_STRING is used. Thestring is stored as anormal C string in the mem­part of the MMM_STRING object. As furtherinformation the length of the character string isnoted before the string.

POlnt --r.rem

cat spec

DOM_-STRING

~r

MMM_STRING

Fig. 3: Strings

Identifiers have the type DOM_IDENT. The signof the identifier is stored in the spec compo-

52

nent. Internally MuPAD has no subtractionoperator. Instead, a substraction is representedas addition with the additive inverse. An identi­fier with a negative sign is logically treated asthe expression a * (-1 ) . Therefore, the operands~f -a are a and -1, and its type is multipIica­non ("_mult"). Division is handled analogue.Internally, a division operator does not exist.Division is represented as multiplication withthe multiplicative inverse. Internally, thisinverse is marked with the relevant sign in thesp:c component. An identifier with this sign islogically treated as the expression a A ( -1 ) . Theoperands are a and -1 and the type is exponenti­ation ("--power"). A further sign is the logicaln~g~tion. Internally, this is also indicated by abit 10 the spec component, but externally it isrepresented by a call of the function _not. Theidentifier name is stored in a MMM STRING

object. The point-part of the MMM- STRING

contains some references that have differentmeanings according to the identifier type. Forenvironment variables references to C routinesare contained there. These are, for instance,called when assignment to the variable aremade. For normal identifiers the run-time stackis located there.

POlnt Mem

cat spec

DOM_-IDENT

U

MMM_STRING

Fig. 4: Identifier

Compound Domain TypesBy using the compound domain types manydata (even with different domain types) can becombined to a single datum. With some typesany number of data with any domain type canbe combined, whereas with others adefinitenumber of data with a certain domain type arenecessary.Sets and tables are stored in an associativememory (internal memory management typeMMM_ASS_MEM). This content addressed mem-

Page 54: mathPAD Special MuPAD issue -

ory is realized internally by the use of hashtables. The set elements to be stored are associ­ated with an empty object. For tables, the tableentries are associated with the relevant index.The cat component contains the concretedomain type.

POlnt Mem

cat spec

DOM_SE'!

"MMM_ASS_MEM

Fig. 5: Sets and Tables

The type DOM_LIST is used for groupingobjects of any domain type to a datum whilestill maintaining their order. The point -partcontains the references to the list entries whichmay have any domain type.

POlnt Mem

cat spec

DOM_-LIST

" " "

Fig.6: Lists

The type DOM_PROC is used for the storage ofprocedures. The point-part of such a datumcontains 6 references. The first is an MMM_CODEobject, This is a reference to the internal routineMEV_eval_interpreter. This generic func­tion is called for the evaluation of a procedurecall. For this the standard arguments inside theevaluator, the procedure call in the form of anexpression and the procedure definition aretransferred. It updates the stack (the formalparameters are written in the stack with the val­ues of the corresponding actual parameters,local variables are written in the stack without avalue) and then evaluates the procedure body.The second entry in the point-part refers to anexpression sequence of the formal procedureparameters. The third refers to the expression

53

Data Structures

sequence of the local variables. An emptysequence is indicated by a DOM_NIL. The fourthentry refers to the procedure body. Generallythis is an statement sequence. The fifth entryrefers to the remember table of a procedure. Thelast entry refers to the name which in its turncan be any MuPAD datum. If these are missingDOM_NIL is to be found instead. The options ofa procedure are stored in the spec componentof the mem-part with the aid of three bits. TheOPTIONS_CHECKED_BIT teIls us that theoptions of the procedure have already beenevaluated. The HOLD_BIT teIls us that with aprocedure call the transferred parameters willnot be evaluated. Finally the REMEMBER_BITmakes sure that a remember table is set up andmaintained.PolynomiaIs are stored internally in a sparse,distributive representation. This is carried outby using the memory management type MMM_­DIST_POLY. The exponents and the coefficientsof the terms are stored in this. However, theuser has no direct access to this structure. Fur­ther entries in the point-part are a list of varia­bles and the coefficient ring of the polynomial.The sequence in the list shows the order of thevariables. The first element of the list is the pri­mary variable; the other entries are the second­ary variables. The coefficient ring is given bythe identifier Expr, an expression IntMod (n)oradomain.

Point Mem

cat spec

\"DOM_-

r-- POLY<,

" \ -.MMM_DIST_ DOM_LIST

DOM_IDENr

POLY DOM_EXPR

Fig. 7: PolynomiaIs

The type DOM_DOMAIN is used to storedomains. The point-part consists of a refer­ence to the memory management type MMM_DO­MAIN which, in its turn, contains several entriesin the point-part. The first entry is a DOM_TA-

Page 55: mathPAD Special MuPAD issue -

mathPAD

BLE in which the methods and other character­istics of the domain are stored,The other entriesare also used to store methods and characteris­tics of the domain. In some cases access to themethods through the tables is too slow, there­fore, this direct access mechanism has beenmade available. However, the user has no inftu­ence on this technique because it is only availa­ble inside the kernel.

POlnt Mern

cat spec

DOM_-DOMAIN

"

MMM_DOMAIN

Fig. 8: Domains

The elements of a domain are stored in the typeDOM_EXT. The point-part of such a datum maycontain any number of entries. The first entry isa reference to the domain to which the elementbelongs. The other entries are references toobjects which can be of any type. The user hasfree choice of representing a domain element.

POlntspec

objects of any type

Fig. 9: Domain Element

The most general domain type in MuPAD is theexpression. All algebraic expressions con­structed with operators and their operands andall instructions of the MuPAD programminglanguage are stored in objects of the typeDOM_EXPR. The storage is done through refer­ences in the point-part of the DOM_EXPR

54

object. For each operand of an algebraic expres­sion there is a reference to this datum. The partsof an instruction that are stored are those com­ponents not consisting of key words. So that theevaluator can determine how it is to behavewith a DOM_EXPR object it must be informed ofthe exact type of the object. For this purposeeach object contains a further reference in thepoint-part. This entry, called the zero operand,is the first entry in the point-part and can referto any MuPAD datum. This DOM_EXPR object isinterpreted in functional notation. During theevaluation of this datum the following takeplace: Firstly, the type of the zero operand ischecked. If this is a functional environment or aprocedure the relevant routine is executed withthe other sons as arguments. If there is an iden­tifier without a value a function call which canbe evaluated no further is retumed. If the identi­fier can be evaluated, e.g. to a functional envi­ronment or a procedure it proceeds as above.With other domain types a function call is inter­preted as the call of a constant function and thezero son is retumed as the solution. With this aglobal concept for a functional programminglanguage is realized. The zero son describes thefunction; the other sons are the arguments of thefunction. This representation, friends of LISPwill be pleased to hear, is also outwardly availa­ble to the MuPAD user. For each operator andeach instruction there is a functional equivalentin the form of an underline function. Forinstance, the addition operator has the function-plus; the instruction : = has the function_assign.The chosen data structure for algebraic expres­sions is very near to the mathematical interpre­tation of such an expression; i.e, an associativeoperator connecting any number of operands.Storing is carried out in form of a n-ary tree.The root of the tree represents the entire expres­sion. The following nodes are the operator andoperands. The latter can be identifiers (leaves ofthe tree) or algebraic expressions formed byoperators of a higher priority (sub-trees of thetree). The data structure of the n-ary tree, espe­cially the identical construction of expressionsand instructions, and their technical realizationaid the basic routines such as the simplifier toattain a high execution speed. The individualreferences can be accessed by simple C address

Page 56: mathPAD Special MuPAD issue -

arithmetic due to the point-part of each datumconsisting of a compounded memory block.Due to this a very laborious climb down to theoperands, which would have been necessarywith a binary oriented data structure, can beavoided. Apart from the high execution speed, auniform data structure has a further advantage;many algorithms are simplified in the kernel.Typical examples of this are the functions usedfor data manipulation. Generally, the i-th oper­and is obtained by access to the i-th reference inthe point-part of a datum. Usually it is notnecessary to examine the datum more closely.By using a uniform data structure for algebraicexpressions and instructions a further veryimportant characteristic of MuPAD is revealed:The complete fusion of these objects. Apartfrom the natural differences in functionality inprincipal there is no difference between instruc­tions and algebraic expressions. Instructions arealgebraic data in MuPAD and can, therefore, begenerated and manipulated during the systemruntime exactly like data of any other type. Forillustration we have included some examples ofDOM_EXPR objects (see figure Figure 10 and

Data Structures

Figure 11). The individual nodes are only repre­sented schematically. An exact differentiationbetween the rnern- and point-parts is notincluded to avoid confusion. For the same rea­son we have not taken the single data represen­tation into account. Identical objects arerepresented multiply although internally theyare only stored once.

Bibliography

[BBC*91] C. Batut, D. Bernardi, H. Cohen, M.Oliver and N.-P. Skoruppa. The PARI-GP pack­age. mathPAD, 1(3):30-32, September 1991.Sonderausgabe DMV-Tagung.[FGK+93] B. Fuchsteiner, K. Gottheil, A.Kemper, O. Kluge, K. Morisse, H. Naundorf, G.Oevel, T. Schulze and W. Wiwianka. MuPADBenutzerhandbuch. Birkhäuser Verlag BaselBoston Berlin, 1993.[Nau92] H. Naundorf. Mammut: Memory allo­cation management unit. Diplomarbeit, Univer­sität-GH Paderborn, Juni 1992.

Fig. 10: The algebraic expression a+b*c*g + d* (c-s e-s f )

55

Page 57: mathPAD Special MuPAD issue -

mathPAD

Fig. 11: The statement if a-cb then m . - a else m . _ b end_if

56

Page 58: mathPAD Special MuPAD issue -

Design and Implementation of theKernel

Andreas Kemper

In the following contribution I would Iike topresent a survey of the design and implemen­tation of the computer algebra systemMuPAD's kernel. For tbis purpose the indi­vidual components of the system, their func­tion and technical realization, together withthe interaction of the components will bedescribed. I will deal with the data structurefor the presentation of a1gebraic objects andthe mechanism for evaluating these data indetail. A further focal point is the presenta­tion of the associative memory which isemployed at various locations in the kernei,in order to increase the speed of the systemand to bound the size of the data produced.

General ConstructionUnder UNIX the MuPAD package comprises ofmany, mostly independent processes, which,when running simultaneously, take over differ­ent tasks. The central element of these proc­esses is the so-called kemel, in which the actualalgebraic operations take place. The other pro­grams are the tools, which make the use of thesystem easier and support the presentation ofthe algebraic data. All these programs commu­nicate with the kernel and in some cases witheach other.The user can use the graphical user interfaceXMuPAD for support in the use of the system.To simplify the operation of the kernel's lineoriented source text debugger the speciallydeveloped tool mdx can be used. This tool ena­bles a comfortable graphical operation of thedebugger. The documentation of the system isavailable on-line, in the form of the hypertextsystem HyTeX 1• In addition there is a graphics

1.Adevelopment ofthe work group ofN.Köckler at the University ofPaderbom

57

tool for the graphical depiction of the objectshandled by the system.In the following I would like to deal only withthe MuPAD kernel. This is also available in aterminal version without the surface and extratools described above. Even this minimal ver­sion enables interactive use of the debuggerrealized in the kernel. 115 algebraic capabilitiesare not in any way reduced by the other compo­nents being missing. From the users viewpointthe system consists of a cyc1e of user input,evaluation of the produced datum and output ofthe solutions. This reftects the internal realiza­tion of the kernel. In addition to the initialisa­tion routine it carries out a loop that firstly callsthe parser to read the user's input. Here theinput is examined syntactically and then theappropriate data structure is built up. If thisshould be the reading of a program in the debugmode then information is provided for thedebugger. The next, and far more complicatedstep, inc1udes the evaluation of the produceddata structure. The techniques used here will bedescribed in detail later. The solution of theevaluation is returned in the form of a logicallynew data structure by this module. In the laststep this data structure is displayed on the mon­itor by the output module.

Memory ManagementThe basis of the kernel implementation is Mam­mut, the Memory Allocation Management Unit.This is a universally applicable memory man­agement that optimally supports the demands ofa computer algebra system. In the kernei, Mam­mut takes over the allocation, manipulation, andrelease of each dynamic object. With this Mam­mut provides the lowest level of the system.Each Mammut object consists of a static partwith a constant size and a dynamic part whichcan be independently moved by the memorymanagement. The aim of this movement is to

Page 59: mathPAD Special MuPAD issue -

mathPAD

prevent memory fragmentation, a typical prob­lem of computer algebra systems. With thisrepeated demanding and releasing of differentsized memory objects, a mixture of large andsmall, used and unused areas arises, so thatmemory demands for large objects cannot besatisfactorily met, although enough memory isavailable.This can be avoided by moving the individualobjects. In this way the many small free areascan be combined to a few larger areas for futureuse. Unfortunately this mobility of data parti­tions has the disadvantage that a double refer­ence, a so-called Handle, is necessary in orderto access its contents, due to the memory loca­tion of the relevant data being changed at will.By using the handle this problem is avoided.Another possibility of accessing the correctmemory location is to mark certain referencesin this dynamic area so that their value is auto­matically updated when movement takes place.Both these possibilities have certain advantageswhen compared with the usual access with asimple reference. Which method is used in thekernel is dependant on the concrete situation. Itis, for instance, certainly more advantageousduring the step by step execution of a moveablearea to mark the used pointers as references inthe dynamic part and then to proceed as usualby counting the pointers forward and backward.The repeated access with a handle is certain tobe more time-consuming.The static part (header) of a Mammut objectneed not be moved because of its uniform size.This is due to the fact that each area of this formthat is vacated can immediately be filled by anew header. Access to a header can be carriedout with a simple reference. The header con­tains the reference to the dynamic part of theobject, so this part contains the already men­tioned handle. If the dynamic part is movedthen only this reference in the relative headerneed be updated. In this way the user can accessthe moved object at an times. Among otherthings, the dynamic part of a Mammut objectcontains an area used for storing any number ofreferences to other Manmmut objects. The sizeof this area, and therefore the number of refer­ences contained in it, can be determined when anew object is requested. The references areplaced in sequential order in this area, so that

58

certain entries can be accessed in a constanttime. Due to this it is possible to efficiently real­ize the n-ary trees which are used by the kernelas data structures.A further important aspect is the possibility ofmultiple logical representation of physicallyexisting objects. With this the Unique DataRepresentation which tries to store identicalalgebraic expressions or parts of these onlyonce, is supported. In the following, I wouldlike to describe this process in more detail.The parallel version of the system realizes thememory management of a Shared MemoryMachine, so that the algorithms of the sequen­tial kernel can be used unchanged in manyareas. Large changes are only necessary in therealization of the stack and the implementationof the parallel elements of the programminglanguage.

Data Structures

The choice of the appropriate data structures isof fundamental importance in the implementa­tion of a computer algebra system. Nearly allkernel algorithms are employed in producingthese objects, analysing them or altering themin one form or another. How elegantly, andtherefore, simply and quickly, this can takeplace is to a great degree dependant on the con­struction of the data structures. As a conse­quence, the developer must clarify which sort ofalgorithms will work on these objects and howthe working of these algorithms can be opti­mally supported by the data structures, beforethese structures are designed.In this context an important aspect is a verynear uniform construction of an data types.With this many procedures .can be simplifiedand greater legibility and maintenance of theprogram can be attained. This is of great signifi­cance in a project which is undergoing contin­ual development. A first step in this direction isthe constant use of the Mammut module. Due tothis, an dynamic data objects have a uniformstructure that in many cases makes a more exactdifferentiation between data objects unneces­sary. This simplifies and accelerates many algo­rithmsAnother important point is that the data struc­tures duplicate the inner logic of the depictedalgebraic objects. From this point of view n-ary

Page 60: mathPAD Special MuPAD issue -

trees have been chosen as the basic structures.Here the nodes of the tree are formed by theMammut objects and the references which orig­inate in these objects (see above) are used aspointers between the individual nodes. Thisstructure comes very near to that of the mathe­matical interpretation of an algebraic expres­sion as an operator with any number ofoperands. Here the operator and operands aredepicted as sons of anode. In this case the firstson is interpreted as the operator. In order toensure the already described uniformity theattempt is made to store nearly all algebraicdata in such a functional form. Therefore, alloperators of the system are functionally stored.The expression

a+b+c

is represented by the function call

-plus(a, b, c)

and consequently by anode with four sons-plus, a,b and c.The work of the kernel and especially the evalu­ator consists on the one hand of evaluatingexpressions of any form and on the other handof carrying out instructions such as assign­ments, loops and conditional branches. Theinterpreter, which is integrated in the evaluator,carries out procedures in exactly the same man­ner. This occurs automatically during the inter­active input of instructions or on callingprograms.As, from a logical point of view, there is noappreciable difference between algebraic dataand program constructs, such as procedure defi­nitions and instructions, there is no differenceon the data structure level between theseobjects. In this manner instructions and proce­dures are also functionally stored, so that anassignment of the form

a := b

is depicted as

_assign(a, b)

and therefore as anode with the sons_assign, a and b.With this method it is possible to manipulateinstructions and programs exactly like expres­sions. As a consequence these can be passed tofunctions, decomposed and reconstructed in any

59

Kemel

required order. The internal representation isdirectly accessible by the system user. For thispurpose the so-called underline functions, suchas -plus or _assign, can be used in the input.Lists, sets, tables and arrays deviate from thefunctional storage. Sets are rea1ized with thehelp of associative memory, which is, of course,built of Mammut objects. Lists consist of oneobject whose references can all be interpretedas list elements. Arrays of various dimensionsalso consist of such list-like structures whichmay consist of severallevels.However, anode in the data structure of analgebraic expression does not only contain ref­erences to other nodes. It also contains informa­tion which takes up the same amount ofmemory space in each node. In this informationis, amongst other things, the so-called signa­ture, which gives a hash value for the subtreeformed by these nodes and their sons. The use­fulness of these signatures will be described inmore detail in connection with the evaluator. Asa data area of constant size which is present inevery data object is being dealt with here, it isuseful to include it in the static part of anode, inthe header. As the header, as already mentioned,cannot be moved and, unlike the other parts ofan object, can be reached by a simple reference,the signature can be very efficiently accessed.The objects of the system management are sub­ject to strict typification. This internal type mustbe given at the generation of each new object.There exists, for example, the type MMM_PARI

which is used to store a numerical object of thePARI2 packet, which realizes the arithmetic inthe system. Another important type,MMM_STRING, is used for depicting any charac­ter string. Dependant on the node above, thiscan be interpreted by the system as an identifieror a string. Most of the objects have the Mam­mut type MMM_CATEGORY. From the point ofview of the kernel these objects represent com­plete algebraic data and are once again typified.All objects of the type MMM_CATEGORY alsohave a uniform construction in their data partand differ only in the number of referenceswhich have been included in them. Apart from

2. PARI is an arithmetic packet from C.Batut, D. Bemardi, H.Cohen and M.OJivier

Page 61: mathPAD Special MuPAD issue -

mathPAD

these references and one entry, which is usedfor typification, category objects contain a bit­array in which the datum sign and various ftagsfor supporting the evaluator are stored. All thefundamental functions of the evaluator work onthe level of objects belonging to the typeMMM_CATEGORY, i.e. both the input and outputof the functions consist of objects of this type.In order not to break this rule there is aseparatecategory CAT_NULL, which corresponds to theNULL pointer.The category CAT_DEBUG plays a special role.It is used to store information for the debugger.It enables the debugger to assign instructions ina program to a given text passage in the sourcetext file. For this purpose data such as the linenumber and the file name of the respective fileare stored. When the evaluator is in normaloperation, i.e, the debugger is turned off, thesecategories are ignored or simply not produced.Only in the debug mode does the evaluation ofsuch a category lead to areaction by the inte­grated debugger or to communication with themdx-tool, if debugging is being carried out withits help.Due to the excellent construction of the datastructures the realization of the manipulationfunctions such as op and subsop can be greatlysimplified. As a rule the i-th operand can beobtained by accessing the i-th son of anode. Inthis case it is generally not necessary to exam­ine the given datum in any more detail. Theexpression type is also determined by the firstson. At this point it becomes especially clearhow a carefully chosen data structure can sim­plify the necessary algorithms. Each specialcase in the data structure, which deviates fromthe rule above, leads to additional work in therealization of the manipulation functions. Thisis similarly true for many algorithms in the ker­nel.

The EvaluatorThe evaluator tasks are the substitution of iden­tifiers, the execution of system functions andthe simplifying of expressions. The executionof user defined functions is also induced by theevaluator. The actual execution of the programis taken over by the interpreter, that in its turnneeds the evaluator. Therefore both these mod­ules cannot be clearly separated. Also reading

60

from and writing in, for instance, tables andarrays is carried out by the evaluator. A furtherimportant evaluator task is the transformationof algebraic data into normal form, becauseonly this enables the efficient comparison ofalgebraic objects. For this purpose the internalsimplifier is used.To assist the evaluator several associative mem­ories are used. These prevent the multiple eval­uation of the same datum and in this mannergreatly increase the system speed.Generally the evaluated solution of an algebraicexpression is an entirely new expression. How­ever if parts of the old datum can be used againbecause they have already been evaluated, i.e,not changed by evaluation, then the relativesubtrees are logically copied and inserted in thetree depicting the solution. This ensures that thesame datum is not as ever possible multiplystored. The logical copying is carried out by thememory management. Generally the systemdoes not strictly adhere to the unique data repre­sentation. Should this happen then on eachchange in a datum and each generation it mustbe examined to see if a corresponding datum isalready present as a data structure or if a treeexists which contains the relative subtree. Theeffort required for this is certain to exceed anyuse that can be obtained from it. Therefore thestrategy in the kernel is to use the equality of adatum only when it can be recognised withoutfurther effort. One of these cases is the proce­dure for evaluating operands as describedabove. In the same way during a substitution thevalue of an identifier is read from the stack andthe identifier is replaced by a logical copy ofthis datum. Naturally it may be necessary hereto further evaluate the new value dependant onthe substitution depth.The process of expression evaluation is carriedout recursively. To evaluate a sum the evaluatoris firstly applied on each term. If they are oper­ands of a commutative operator the evaluatedsons are then sorted to make simplification inthe next step easier. In this case such simplifica­tion consists of, for instance, the contraction ofterms to a product. Equal terms can be easilyrecognized after sorting because they must beneighbouring operands. Numerical constantsare added in exactly the same way and the solu­tion is written as the last term of the sum, The

Page 62: mathPAD Special MuPAD issue -

signatures already described above, define aorder on the set of algebraic expressions in anatural manner. The sorting of the separateexpression operands is carrled out on the basisof this order.However, an evaluation can also be the analysisof an indexed identifier, where a value must beread from a table, array, or list. Tables, arrays,lists or sets also need to be evaluated beforethey can be worked with further. In the case oflists and sets this takes place by the evaluationof their elements. If at least one operand hasbeen changed then the solution is stored in anew object. In all other cases only a logicalcopy is necessary.

Evaluation of the System Functionsand OperatorsThe evaluation of the system functions andoperators is carrled out in MuPAD by a specialmechanism. The basic idea is that the function­ality of a system function or an operator storedobject can be reached by a simple substitutionof the relevant identifier. For this purpose thisfunctionality is stored with the help of a so­called function environment. This is aseparatecategory type that contains three sons. The firstis responsible for evaluation, and the secondcontrols the output of the relevant system func­tion or the algebraic expression. The third entrymay consist of a table in which further charac­teristics can be stored, These are informationsabout the type of the expression build with thisfunction environment or a procedure to differ­entiate or to expand the expressions of this type.The first two sons consist in general of objectsof the type CAT_EXEC, whose operands canconsist of normal algebraic expressions or Cfunctions. For this purpose the memory man­agement offers the possibility of directly inte­grating C functions in special objects so thatthese can be used as Mammut objects. These Cfunctions are used for the actual execution ofevaluation or output. To support these tasks theother operands of a CAT_EXEC node containinformation, like the operator priority, the sys­tem function name or the appearance of theoperator symbol for the output. The name of thesystem function is, for instance, necessary to beable to return function calls which cannot beevaluated further. Alternatively the first or sec-

61

Kemel

ond son of a function environment can consistof a user defined procedure which then takesover the evaluation or output.The function environment is stored in the stackunder the relevant function name. At the start ofthe evaluation of a system function the left handoperand is evaluated to such a function environ­ment. For this only a normal evaluation of therelevant operand is necessary. From the result­ing structure the C function to be called or theprocedure definition is calculated and carrledout with the original function call as a parame­ter. If this is a C function then the operandswhich are attached to the relevant son of thefunction environment are passed on as furtherparameters. The result of this call is also thesolution of the evaluation.With this mechanism it is also possible to glo­bally change an operator or a system functionby assigning the function name to another or achanged function environment. The functionenvironment can also be changed in order toalter, for instance, only the output of an opera­tor.

Signatures

A basic concept of the kernel consists of thesignatures. These are, as already described, asort of hash value which is assigned to eachdatum subexpression in the kernel, The signa­tures make sure that two identical data struc­tures are given the same signature value.Inversely identical signatures must not meanidentical expressions. Apart from this signaturesdefine a simple (and artificial) order on the setof all algebraic objects. This order is not a gen­eralization of the lexical order of identifiers.The calculation of a signature value for anyalgebraic datum is carried out during the evalu­ation or simplification due to MuPAD only hav­ing the characteristics described above for datain normal form. Here, starting in the leaves ofthe relevant tree, the signatures are written inthe nodes. The signatures of the leaves (identi­fier, strings and numerical constants) are calcu­lated from the sequence of ASen characters orfrom the signatures of the PARI data structures.The expression signatures that consist of manysubexpressions are calculated with the help ofthe signatures of the individual subexpressions.

Page 63: mathPAD Special MuPAD issue -

mathPAD

The signatures are an important aid in the com­parison ofexpressions. In this case the signaturevalues can be compared. If these are not identi­cal then the expressions are also not identical.Only in the case of identical signatures is anactual comparison of the data by recursivelycomparing the node's sons necessary. A gooddistribution of signatures makes certain that thiscase only seldom arises and that an actual com­parison is rarely necessary when the expres­sions are not identical. The comparison ofalgebraic data is necessary in many modules ofthe kernel. The use of signatures in the kernel isof central importance in the simplifier duringthe sorting of operands, by the assimilation ofidentical sons and by the realization of the asso­ciative memory. The associative memory usedhere is realized with the aid of hash tables and,therefore, must always carry out a comparisonto definitely identify an object.

Associative Memory

On the kernel level a separate module imple­ments associative memory with various associ­ative mechanisms available. Here any data canbe joined with another in an associative mem­ory. This offers a wide range of uses.One area of usage for this memory is sets andtables. Sets are realized in the form of associa­tive memory, as each element of the set is asso­ciated with itself. On entering a new element ina set it is first checked to see if a value isalready associated with the relevant element. Ifthis is not the case then the new datum can beentered into the set. Analogue is the implemen­tation of tables, Here the index of an entry isassociated with the relevant value. At.the sametime this memory has the possibility of givingitself a signature, dependant on its entries. Thisis necessary because a set or table is a validalgebraic datum and therefore must also becompared with other data.Another wide field of use of this data structureis the evaluator. Here the many associativememories lead to a considerable acceleration.One phenomena in computer algebra is thatidentical subexpressions are repeatedly presentdue to substitution and evaluation and, there­fore, must be repeatedly evaluated. To preventthe multiple execution of one and the same pro­cedure associative memory is used on many

62

levels in the evaluator to remember alreadyevaluated algebraic data together with theirsolutions. When an algebraic subexpression isevaluated the first step is to test, with the aid ofsuch memory, if the appropriate expression hasalready been evaluated. If this is the case, thesolution can be directly taken over and the eval­uation is finished. In the other case evaluation iscarried out and finally, together with its solu­tion, added to the associative memory. Unfortu­nately, the contents of such an associativememory are deleted after an assignment hasbeen carried out because with this the values ofvariables change and the existing associationcan become invalid. Generally this affects onlya small number of entries but a more exact anal­ysis is hardly possible in a reasonable time dueto the complex interdependencies. However,after the execution of an assignment, the varia­ble to which a value is assigned is examinedwith the aid of a time stamp to see when it waslast substituted by the evaluator. If this tookplace before the last deleting of the memorythen a further deleting is not necessary.A further special feature are the different asso­ciation methods made available by the associa­tive memory. In the first case, on reading fromthe associative memory, an equivalent entry islooked for in order to obtain its bound value.For this it is only necessary that the givendatum and the relevant value in the memoryboth represent the same datum. In contrast tothis in the second association method the datamust be also physically identical, i.e, only acomparison of the physical addresses is carriedout during the search for an entry. Naturally,this means a remarkable acceleration, butmeans also that not all associations are recog­nized. This means that this method cannot beused in every area. An implementation of setswith this method .leads inevitably to errors.Conversely this method is appropriate in theevaluator because if no association is foundhere the normal evaluation process is begun andthe solution is not influenced. In this case onlythe execution time is lengthened. These twomethods should be carefully considered in eval­uations. On the one hand, in the second methodmore data must be evaluated, but on the otherhand, the amount of searching in the associativememory is less. Whichever method is used is

Page 64: mathPAD Special MuPAD issue -

also influenced by the extent to which theunique data representation is observed. Anexact observance leads to two identical objectsalways having the same physical address and,therefore, on using the second associationmethod all entries are also found. A furtherexample of an appropriate use of associativememory is the treatment of strings described inthe next section.

The Interpreter

In order to work with the constructs of theMuPAO programming language the systemcontains, as already rnentioned, an interpreterfor executing the instructions and procedures.The main task of this interpreter is the construc­tion of a stack for the different global and localvariables and the formal parameters of the userdefined procedures. Apart from this the retrac­tion from procedures and the termination ofloop constructs must be regulated. For the exe­cution of both of these the same mechanism canbe used because the program contructs do notdiffer in their internal presentation from the sys­tem functions. The organization of the stackplays a central role. Basically, this is set up bythe relevant function calls of the evaluatorwhich are fitted into one another like boxes.With this, for instance, the storage of the returnaddress on leaving the procedure is unneces­sary. A stack which stores all the values forassigned and local variables in each active pro­cedure must be built up for the implementationof the dynamic scope rule. The stack of eachvariable is appendixed to the data structure ofthe appropriate identifier or the string under it.This is only possible because by the exact usageof the unique data representation for strings,two identical objects of the type MMM_STRING

are never physically separately stored. To ena­ble this, a further associative memory is formedat the system start and this contains all theseobjects. It is relatively simple to control theconformation to the unique data representationbecause new strings can only be generated bythe concantenation of identifiers and strings orby the parser. This is carried out by each newstring being controlled against the contents ofthe appropriate associative memory. The stackof an identifier (simplified) consists of a simplechained list that is used as a stack by objects

63

Kemel

being attached to the beginning of the list ordequeued. This takes place on entry into a pro­cedure or when it is left. The individual entriescontain the current valid value of the identifier.The reading of this value can be carried out bysimply accessing the upper list element. Thiscan always be quickly accessed because in thecase of the value reading the relevant identifieris present under which the relative string andwith this the stack are found. An additionalnumbering of the individual boxes allows thecontrolled dequeuing of parts of the stack, as isnecessary, for instance, in the case of a run timeerror. In the parallel version of the kernel thisconcept must be extended, as different taskshave different values for one and the same vari­able. With this, different tasks can access com­mon global variables. In order to realize this,each variable has many stacks, one for eachcluster and processor. Oue to skilful storage ofits own stack depth and that of its predecessor,together with the number of the relevant proces­sors, each task can efficiently access the con­tents of a variable.

Page 65: mathPAD Special MuPAD issue -

mathPAD

The Structure of Libraries

Klaus Gottheil

In this document the conditions for the con­struction of Hbraries are proposed.This concems the conditions for the constmc­tion of library functions and libraries, the load­ing of routines and the file stmcture of libraries.A certain amount of uniformity in the constmc­tion of libraries leads to a great increase in theirmaintainability and makes the user's life easierby ensuring that the libraries can all be used in auniform way.

The Libraries from the User'sPoint of View

Firstly we shall describe how the user can use a"typical" library. We shall use the librarygroebner as an example. This library is usedto calculate Groebner Bases. Before the usercan use the groebner library he must load it byusing the loadlib command:

» loadlib("groebner");TRUE

The TRUE teUs us that the library has reallybeen loaded and that no errors have occured. Ifthe library is loaded a second time with thecommand loadl ib (perhaps indirectly througha read command), it is not re-loaded. A secondcall of loadlib results in:

» loadlib("groebner");FALSE

The result FALSE shows us that the library hasnot been re-loaded. If an error occurs during thereading of a library loadlib returns an error.After the library has been loaded the identifiergroebner has a value:

» groebner;domain{"groebner")» info(groebner);"Library 'groebner':Calculation of Groebner-Bases forpolynomial ideals""Interface:"gbasis spoly greduce

64

The identifier groebner has a domain as itsvalue. Because this domain is used especially tomanage a library it is called a library domain.By using the function info the user can obtaininformation about the library domain. Thelibrary functions are entries in the Library­Domain. The library groebner makes only threefunctions available extemally: gbasis, spoly andgreduce. These are those interface functionsshown by info. However, these functions arenot stored under their own names. After load­ing, the function spoly, for instance, is not yetknown:

» spoly;spoly

The function spoly is entered in the librarydomain under the index "spoly":

» groebner::spoly;proc(p, q, 0)

local Ip, lq;beginif args(O) = 2 then

o:=hold(DegreeOrder)end_if;if testargs() then 000

This has the advantage of avoiding a coUisionbetween the names of different libraries. Theuser can use the functions as normal withgroebner: : spoLy:

» read("gbasisl"):» groebner::spoly(pl,p2,LexOrde~);

poly(yA2*x*z*(-2)+yA2*5-y*x*z A3,

[y, x , z])

The user will often not want to use the functionas the fairly clumsy groebner: : spoly butwill simply want to use the name spoly. To dothis the name spoly must be exported. Byusing the function export the name of a libraryfunction becomes globally known:

» export(groebner, spoly);» spoly{pl, p2, LexOrder);poly(yA2*x*z*(-2)+yA2*5-y*x*z A3,

[y, x , z])

Page 66: mathPAD Special MuPAD issue -

Only those library functions listed by the func­tion info can be exported: in this case onlygbasis, spoly and greduce. To export all thefunctions of a library the user can simply enterthe library in the export command:

» export (groebner) ; "Warning: 'spoly' already has avalue, not exported"

The warning is given because the identifierspoly already has a value (spoly has alreadybeen exported). Iii such cases the function is notexported. If a function whose identifier alreadyhas a value is to be exported then this value willhave to be deleted:

» spoly:= NIL:» export (groebner, spoly);

This is all that the inexpierienced user needs toknow about libraries. However, for the imple­mentation of libraries there are certain condi­tions which must be met to obtain the describedfunctionality.

Conditions for Libraries

There are two aspects which must be heededwhen implementing a library: The first aspectconcems the naming of the library functions. Inorder to avoid name c1ashes libraries are imple­mented as special domains, so-called librarydomains. The functions of the library interfaceare implemented as methods of the relativedomain. If required the names of the interfacefunctions can be made globally known by usingthe method export. The second aspect con­cerns the loading of a library. To make the func­tions of a library available they have be definedin a so-ca1led library file. The MuPAD functionloadlib makes use of this library file to loadthe library.

The Library Domain

The functions and variables of a library shouldbe packed in a library domain so that name con­fticts can be avoided. Each library domainshould contain the entries "interface" and"info":

• interface is a set containing the namesof the methods of the domain which canbe direct1y called by the user as libraryfunctions. In practice, these methods formthe interface of the library.

65

Libraries

• info contains astring with informationabout either the library or a procedure.

The function export uses the entry "inter­face" to make the names of individual or allfunctions of the library interface globallyknown. The names of the interface functionsand the entry "info" are used by the functioninfo to return information about a library. Weshall continue using the library groebner as anexample. This library makes the three functionsspoly, greduce and gbasis available to theuser. The library domain and the methods of thedomain are defined in the relative library filegroebner .mu as follows:

groebner:= domain():groebner::name:= "groebner":groebner::info:= "Library'groebner': Calculation ofGroebner-Bases for polynomialideals":groebner::interface:={hold(spoly) ,hold(greduce), hold(gbasis)}:

The entry u name" is used for the output of thelibrary domain itself. The identifiers of theinterface functions are bracketed with hold.This is a safety measure in case one of the iden­tifiers should already have a value when thelibrary is loaded. Otherwise not the identifierbut its value is entered in the set.

The Loading of Libraries with loadlib

Normally a library is not implemented in onefile but in many different files. One of the rea­sons for this is that the user will not want toload all the functions of a library but only thosethat are really necessary. This avoids the mem­ory becoming blocked with unnecessary func­tions. With the function loadlib only theactuallibrary file of the library is loaded. At thesame time care is taken that the library is notloaded more than once. The library domain isdefined in a library file, furthermore all func­tions related to the library with the relevant filesare made known. These files are loaded ondemand. The MuPAD function loadprocmakes it possible to define functions so thattheir definitions are loaded from a file at the firstfunction call. The mechanism of loadlib isreally quite simple. In the example above thelibrary file groebner. mu is simply loadedfrom the directory LIBFILES. In its turn this

Page 67: mathPAD Special MuPAD issue -

mathPAD

file contains MuPAD commands with which thefiles of the Iibrary can be loaded as required.For this the function loadproc is used:

dir:= pathname(uGROEBNER") :loadproc(hold(groebner::spoly),dir. "spoly .mu") :

Here spoly is a method of the Iibrary domaingroebner. The method spoly is itself definedin the file spoly.mu in the directory GROEB­NER. Only on calling groebner: : spoly thefile GROEBNER/spoly.mu is loaded and thefunction executed.

Orginization of the Files of a LibraryAmong the directories contained in READ_PATHor LIB_PATH there must be a directory calledLIBFILES. This directory contains the Iibraryfile for the Iibrary which is to be loaded withloadlib. A Iibrary file should have the samename as the relative Iibrary supplemented withthe suffix .mu, As already mentioned it must becontained in a sub-directory with the nameLIBFILES. Furthennore, each Iibrary shouldhave its own directory containing the files of theIibrary. This should be contained in the direc­tory that contains the directory LIBFILES. Thedirectory name should be the name of theIibrary written in capital letters. The files of thelibrary groebner are contained in the directorycalled GROEBNER. The directory contains thethree files spoly .mu, greduce .mu and gba­sis .mu. Altogether there are the files Iistedbelow:

Library-File Implementation

LIBFILES GROEBNER

groebner.mu spoly.mu

greduce.mu

gbasis.mu

Tabelle 1: Library groebner

Directions for Programming

Testing ParametersDuring the programming of procedures the userwill often be confronted with the problem that

66

the arguments must be exactly tested when aprocedure is called. This is of course time-con­suming. If however the procedure is called byother procedures the user can be fairly sure thatthe parameters are correct (except in the case ofany programming errors). In this case an expen­sive "testing" of parameters is no longer neces­sary. One solution of this problem is to alwayswrite two procedures: one to test the parametersand an auxillary procedure to do the actualwork (and which can be directly called fromother procedures). This, of course, leads to theproblem that the user has twice as many proce­dures as before and that the auxillary proceduremust also be documented otherwise only theprogrammer hirnself can use it. Furthermorethere are problems with the domains. Here theuser will want to call the auxillary proceduredirectly, if possible. This will, however, not bepossible because in general the user does notknow the name of the auxillary procedure.The function testargs offers a solution to thisdilemma. With the aid of testargs the usercan determine if a procedure has been called bythe user directly or by another procedure andexecute the relevant test. The expression tes­targs () returns TRUE if and only if it is exe­cuted in a procedure that was called from theinteractive level - in other words by the user. Iftestargs is called in a procedure which wasin its turn called by a procedure FALSE isreturned. The user can control the testing ofparameters as folIows:

p := proc(x) local ... ,beginif testargs() then

Test parameter x ...end_ifi

The actual algorithm follows here...endJ>roci

The condition "normally" was made above: tes­targs has two states, the normal status describedabove and a test status. In the test status tes­targst) always returns TRUE, i.e. the parame­ters are always tested. This is useful whilesearching for errors during programming. Moredetails are to be found in the help pages of tes­targs.

Page 68: mathPAD Special MuPAD issue -

Error Handling

Messages should only be returned in the case ofan errors. If the results are valid then no errormessage should be returned with error. Suchmessages can be very disturbing when a func­tion is called from another function. If a func­tion in certain circumstances cannot return asolution it should return the message FAlL. If alinear system of equations is, for instance, notsolvable the solution FAlL should be returned,but no error message should be given. All mes­sages should be given in English.

File Names

When giving file names - perhaps for the func­tions read or loadproc - the path souldalways be created with the function pa thnameso that it is independent of the operating system.In UNIX the expression

p~thname("GROEBNER") . "spoly.mu"

returns the string "GROEBNER/ spoly . mu" andon a Macintosh it returns the string " :GROEBN­ER: spoly .mu", By using pathname thelibrary can be used with both operating systems.The individual componants of a pathnameshould not be longer than 8 characters (MS­DOS), and the use of capital letters in the nameshould be of no importance. Special characterssuch as I, \ and : must not be used. More detailsare to be found on the help pages of pathname.

Comments

Comments should be written in English so thatour foreign collegues can also understand them.Bach function should be given a descriptioncontaining the following points: What does thefunction do? Which algorithms were used?Especially important: Where do the algorithmscome from (the source should be given)? Whatsignificance do the parameters have? What isthe return value of the function? Which side­effects does the function have? Which globalvariables have been used? In the function itselfthe individual steps and all local variablesshould be described. The importance of the glo­bal variables should also be explained. Further­more, the conditions under which the variablescan be loaded or even altered, and any possibleside-effects, should be described. The use of"metacharacters" in comments has proved suc­cessfu1. These can for example be used to

67

Libraries

extract certain comments from the source. Inthe groebner library the description of theinterface functions are in comments of the form#++ ... ++#. In contrast the description ofinternal functions are in comments of the form# - - ... - - #. Such comments can easily beextracted from the sources e.g.by using awk.

Appendix: The groebner Libr­ary# groebner.mu -- the 'groebner'library for Groebner-Bases #

#++ User Functions:

spoly - returns S-Polynomial of pand q

greduce - reduces polynomial pmodule polynomials in list S

gbasis - returns reduced Groebner­Basis for polynomials in list S

The polynomials must have rationalcoefficients. ++#

groebner:= domain():

groebner::name:= "groebner":groebner::info:= "Library'groebner': Calculation ofGroebner-Bases for polynomialideals" :

groebner::interface:={hold(spoly),hold(greduce),hold(gbasis)}:

loadlib (" isa") :

loadproc(hold(groebner::spoly),pathname("GROEBNER") . "spoly.mu") :

loadproc(hold(groebner::greduce),pathname("GROEBNER") . "greduce.mu") :

loadproc(hold(groebner::gbasis),pathname("GROEBNER") ."gbasis.mu"):

The File spoly.mu#++

spoly -- returns S-polynomial of pand qspoly (p, q [,0])

p,q - polynomials over therationals

o - term ordering (LexOrder orDegreeOrder)

++#

Page 69: mathPAD Special MuPAD issue -

mathPAD

groebner::spoly:= proe(p,q,o)

loeal lp, lq;begin

if args(O) = 2 then0:= hold (DegreeOrder)

end_if;if testargs() then

if args(O) <> 3 and args(O) <> 2 thenerror(Uwrong no of args")

end_if;if not isa::rational-poly(p) or not isa::rational-poly(q) then

error(Unot a rational polynomial")end_if;if op(p, 2 .. 3) <> op(q, 2 .. 3) then

error(Upolynomial types don't match")end_if;if 0 <> hold(DegreeOrder) and 0 <> hold(LexOrder) then

error(Uunknown order")end_if

end_if;

# get LCM of leading terms #lp:= lterm(p, 0);lq:= -lterm(q, 0);groebner::term_lem(lp, lq);

# the S-polynomial #divide(%l, lp, Exaet) * p + divide(%l, lq, Exaet) * q

end-proe:

#--

groebner::term-Iem -- returns LCM of the terms p and q

groebner::term_lem(p, q)

p,q - terms (polynomials mit one non-zero eoeffieient)

--#

groebner::term_lem:=proe(p,q) loeal n, i;begin

n:= nops(op(p, 2»;degreevee (p) ;degreevee (q) ;max ( (% 1) [i], (%2) [i]) $ i =1 .. n;poly (_mult (op(p, [2,i)A(op(%1,i» $ i=l .. n), op(p, 2 .. 3»

end-proe:

68

Page 70: mathPAD Special MuPAD issue -

MuPADMulti Processing Algebra Data Tool

Fact SheetMuPAD - a system for symbolic and numericcomputation, parallel mathematical program­ming and mathematical visualitation.

Overview

The program consists of a sma ll kern elwritten in 'C' and Libraries written in theMuPAD programming langu age. Allfeatures described may be used inlerac­tively or via the programming language.Contral structures for programming arealso avail able at the interactive level.

Kernel and library are machin e indepen­dant.

In addition to the term inal-based user in­terlace window-based interiaces existfor the X-Window-System and the Ap pleMacin tosh.

The MuPAD programm ing language

has various built-in constructs for paral­lel programming, accessible at any levelof programming exp erience . First paral­lel implementa tio ns exist.

MuPAD is devoted to the sci entilicco mmunity and freely dist ribu ted fornon-commercial US8.

sion of exp ressions, taylor se ries and or­der te rms, diffe rentia l ope rator .

Integer factorisat ion , integer GCD andLCM, exte nde d Eudide an algori thm .prime number test, prime number gener­ation, Eulers phi function, random nurn­ber generation.

Number Theory

User deli ned types and data st ructures,operator overloading, object orientedpro gramming , ge neric algorithms .

As experimental libra ry: pa rametrie do­mains, domain constructors, categories,category constructors, axiomes.

Polyno mials

Coefficient mapping and extraction, de­gree, leadingcoefficient, term and rno­nomial (Iexical an d degree order), trai! ­ing coe ffic ient, number of terms, nth co­efficient, division and pseudo-division,evaluation, integer content, norm, factor­isation.

Domains

Operato rs

Arithmetic (+, - , " / , " mod, div), rela­tional {e. >, <=, >=, =, <» , Boolean [and,or, not), set operations (union, inter­s eet , minus), concatenation (. , #),range ( •• ), sequenc ing ( , and $), do­main attribute access ( , , ). assignment( , =), last output (%), user defined opera­tors. System functions and operatorsmay be overloaded by user definedtypes.

Arithmet ic

Absolute vaiue, exponential, logarithm,sq uare root , sign, trigonometrie and hy­perbelle functions and inverses, round­ing, ceil and fioor, truncation, modularcomputation, factorial, maximum andminimum, numeric evaluation, extractionof numerator and denumerator, fraction­al part, real and imaginary part, set uni­on, intersection and difference. setmembership. differentiation and expan-

Symbolic and Numeric Computation

Data Types ve rsa , run- time generation and manipu­lat ion of procedures.

Data Manipu lati on

Operand extraction, counting and substi­tution , object type testin g, ind eterminateextraction, concatenation of strings andlists, set manipulation. extraction, sortingand substitution 01 list, set. table and ar­ray elements, mapping operands tofunctions, string searching, patternmatching, parsing, conversion of stringsand polynomiatsto ex pressions and vice

Constants

E, PI , I , FALSE, TRUE, various systemconstants.

integers and rat ional numbers of anylength, float ing point and com plex nurn ­bers of arbitray pre cis ion , multivariatesparse polynomials , strings , Booleans,variable identifiers, dynamic li515, setsand tables, arrays of any dimension,user defined types (domai ns) and ob­[ects, a rich set of expressions, proce­dures and statements , wh ich are firstdass data objects.

User Interfaces

General

Selection of printing and error level, linewidth, formatted or non-formatted out­put, verbose printing during procedureexecution, recalling of earlier results.Une editor for raw terminal interface.

X-Windows Version

Look and feei of Ope nLook, editing andrecall 01 input and output, scroli back.two- and three-dimensional plotting withmouse-controlled interface, on-line man­ual and tutorial with hypertext fun ctional­ity, pasting 01examp les from these do­cuments into the inputwindow, mouse-

co ntrolied interiace for source code deb­ug ger .

Maci ntosh Version

Mac-iike interiace with notebook tune­tionality, structured session documents.editing of text documents, graphics andhyp ertext sys tem as in the X-Windowsversion.

Page 71: mathPAD Special MuPAD issue -

Graphics

General

Any property of a plot may be set inter­actively in VCam or defined in a plot­command.

VCam

Graphics front-end for 2- and 3-dimen­sional plott ing, running unde r X-Win­dows and MacOS ; thightly coup led withthe MuPA D kernel. Defining functionsmay be entered and manipu lated direct­Iy in VCam, objects can be added ordeleted by mouse-dick.

Programming Facilities

General

Functional programming language withprocedural extensions and Pascal-Iikesyntax. Procedures and statements areordinary data objects and may be mani­pulated at run-time. Any language con­struct is available as system function.Any system functlon may be overwrlttenby user-defined procedures. Unnamedfunctions. Formatted output of procedu­res.

Language Constructs

Assignment. expression, statement se-quenca, if then eIif else .e nd_i f , for fram ta Btep .da ... end_for, while da end_-while, r epe at until. . . end_repe at ,case. . . o f .. . da o t .he rwf.ae . . . end_ -caae , proc ( ) . . . b egin. . . end-proc,break, next , ez-rox, return, parameterlists of varying length.

Parallel Programming

General

There are two levels of parallellsm inMuPAD : micro-parallelism on a pro­cessor cluster with high speed commu­nication facilil ies (a multl -processor ma­chine for examp le) and macro-parallel-

Availabili ty

2D-P lotting Facilities

Two-dimensional seenes, graphs, cur­ves; multiple objects per scene; objectstyle may be points, lines or impulses;options for titling, labeling, colour selec­tion, smooth colouring by height, axes

Evaluation

The programmer can control any aspectof expression evaluation and variablesubstitution: holding evaluation, evalua ­tion in an outer context, defining subs ti­tution level, additional evaluation, retrie­ving values direetly. Proeedures may re­member calcuiatlons to speed up execu­tion . Results are stored in a history tab lewhich may be accessed by procedure s.

Input and Output

Reading and writing of text and binary(M-Code) files, opening and closing offiles, reading and writing of MuPAD da­ta and raw text, printing output to file,writing a session protocol to file. Enter­ing expressions or text interaetively.

Debugging

Exeeution tracing, verbose proeedureexecuHon, different printing and error le-

ism on a network of clusters with medi­um- to low-speed eommunication.

Micro·Parallelism

Automatie task creation and distributionby the system. Easy-to-use languageconst ructs: parallel for-Ioop, parallei and

Documentation

scaling and style, automatie viewingbox, grid and smoothness.

3D-Plotting Facilities

Three-dimensional seenes, graphs, sur­faces, space curves; multiple objec ts perscene; object style rnay be point s, lines,impulses, wire frame, mesh, x-line, y-li­ne, hidden line, colour patches, trans­parent; opt ions for titling , labeling, colourselection, smooth co lour ing by height,axes scaling and style, automatie vie­wing box, camera point and focal point,grid and smoothness .

vels, error trapping. A source code de­bugge r allows to step through procedu­res, print and observe values of varia­bles, aite r values of variables, executeinst ructions, disp lay the procedurestack. The debugger is integrated Intothe kernel and may be used via corn­mand language or a eomfortable win­dow-based user interfac e (availabie un­der the X-Window-System).

sequential blocks, private and globa lvariables, task abortion.

Macro-Parallel ism

Blockinq and non-blocking messagequeues and pipes, global network-widevariables, topoiogy informations.

MuPAD Version 1.2 is now availablefor Sun SPARCstation (under SunOSand Solaris), IBM RS6000 , SiliconGraphics, PC's (under L1 NUX) and Ap­pie Maeintosh. Prereleased versionsexist for 80386- based MS-DO S sys­tems and Sequent Symmetry. Aversionfor SUN Multiprocessor systems is inpreparation. Please call for others.

M IlPAD Benutzerhandbuch.iuv german) by B. Fuchssteiner et. al., Birkhäuser,Base l, 1993.M IlPAD Tlltor;al,(in english) by B. Fuchssteiner et. al., Birkhäuser, Basel, 1994 .(English manual will soon be available.)

Further Information

MuPAD-Distribution , Fachbereich 17, University of PaderbornD 33095 Paderborn, Germany.E-mail: MuPAD- d i [email protected]