constraint semantics of nut

40
ROYAL INSTITUTE OF TECHNOLOGY Department of Teleinformatics ESTONIAN ACADEMY OF SCIENCES Institute of Cybernetics Constraint Semantics of NUT Jaan Penjam, Enn Tyugu November 16, 1993 TRITA-IT-9309 IOC-CS-58/93 ISSN 1103-534X ISRN KTH/IT/R -- 93/9-SE

Upload: independent

Post on 13-Nov-2023

1 views

Category:

Documents


0 download

TRANSCRIPT

ROYAL INSTITUTE OF TECHNOLOGY

Department of Teleinformatics

ESTONIAN ACADEMY OF SCIENCES

Institute of Cybernetics

Constraint Semantics of NUT

Jaan Penjam, Enn Tyugu

November 16, 1993

TRITA-IT-9309

IOC-CS-58/93

ISSN 1103-534X

ISRN KTH/IT/R -- 93/9-SE

Constraint Semantics of NUT

Jaan Penjam, Enn Tyugu

email: [email protected], [email protected]

ROYAL INSTITUTE OF TECHNOLOGYDepartment of Teleinformatics

Electrum 204S-164 40 KISTA

INSTITUTE OF CYBERNETICSAkadeemia tee 21

EE-0026 TALLINN

This work concerns the results obtained in the project Knowledge-BasedSoftware Tools funded by NUTEK. This report was written in the framework ofthe Agreement between the Institute of Cybernetics of the Estonian Academyof Sciences and the Department of teleinformatics of the Royal Institute ofTechnology from November 12, 1992.

c 1993 by Inst f�or Teleinformatik, Kungl Tekniska H�ogskolanc 1993 by Institute of Cybernetics

AbstractNUT is a programming system for knowledge-based programming with fa-cilities for automatic program synthesis. The system allows to specify compu-tational problems in OO style. Concepts and objects can be treated in NUTas functional constraint networks. Constraint satisfaction problems are solvedusing algorithms for automatic program synthesis described earlier for the PRIZsystem.

Contents1 Introduction 12 Functional constraints 43 Constraints in the NUT Language 73.1 Structural Constraints : : : : : : : : : : : : : : : : : : : : : : : : 83.2 Equations : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 103.3 Programs as constraints : : : : : : : : : : : : : : : : : : : : : : : 123.4 Identity relations : : : : : : : : : : : : : : : : : : : : : : : : : : : 144 Speci�cation of Computational Problems 165 Some Important Extensions 205.1 Variables of Type any : : : : : : : : : : : : : : : : : : : : : : : : 205.2 Higher Order Functional Constraints : : : : : : : : : : : : : : : : 215.3 Production Rules : : : : : : : : : : : : : : : : : : : : : : : : : : : 226 Summary 25A Di�erential Equation Solver 26A.1 Classes for solving di�erential equations : : : : : : : : : : : : : : 26A.2 Class texts : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 28A.2.1 The adder class : : : : : : : : : : : : : : : : : : : : : : : 29A.2.2 The integrator class : : : : : : : : : : : : : : : : : : : : 29A.2.3 The clock class : : : : : : : : : : : : : : : : : : : : : : : 29A.2.4 The xy_hist class : : : : : : : : : : : : : : : : : : : : : : 30A.2.5 The clean_graph class : : : : : : : : : : : : : : : : : : : 30A.2.6 The graph class : : : : : : : : : : : : : : : : : : : : : : : 30A.2.7 The process class : : : : : : : : : : : : : : : : : : : : : : 31A.3 Example of solving the di�erential equation �x = �2 _x� 5x. : : : 31A.3.1 The problem class : : : : : : : : : : : : : : : : : : : : : : 31i

Chapter 1IntroductionThe NUT system is the most advanced representative of the family of pro-gramming systems called PRIZ. This family includes systems PRIZ ES, Solver,MicroPRIZ, ExpertPRIZ, NUT etc., which have been developed in the last 20years in the Institute of Cybernetics of the Estonian Academy of Sciences. Allthese systems support a knowledge-based programming style and they have beensuccessfully used to solve engineering problems as well as in scienti�c investiga-tions of AI.The NUT language was outlined as an extension of an object-oriented pro-gramming language with features of automatic program synthesis, and its fulldescription appeared in [T~ougu et al. 1986]. But the language was never im-plemented in the precise correspondence with it. The �rst implementation ofa version of the NUT language was done as a part of a Soviet new generationcomputer project START on the Pirz workstations which were developed in theframework of the same project [Kotov et al. 1989] and [T~ougu 1991]. In 1990,the NUT system was implemented in various UNIX and X Windows Systemsenvironments [Matskin 1991]. The work on implementation of NUT was com-pleted at the Royal Institute of Technology in Stockholm where it is now beingused for educational purposes [Matskin and T~ougu 1992].An attempt is made in the NUT to amalgamate di�erent programmingparadigms each of which claims to be a good platform for the future com-puting: logic programming, object-oriented programming, constraint program-ming, knowledge-based programming. When one combines di�erent methodsand techniques, always a rather natural question arises how to merge underly-ing paradigms into a new one which will preserve the merits of all of its con-stituents. Quite a success has been achieved in combining logic and constraintprogramming. Two very promising approaches have evolved: constraint logicprogramming [Ja�ar and Lassez 1987] and concurrent constraint programming[Saraswat 1990]. A recent work [Smolka et al. 1993] is an example of mergingconstraint programming with object-oriented programming.1

6 -�������Speci�cationprocessing

Constraintsolving ObjectmanipulationOOPCCPPCFigure 1.1: Three dimensions of computing in NUTHaving a closer look at the NUT system, one can see the following threedi�erent modes of computations in it:� speci�cation processing (inheritance, delegation etc.);� object manipulation (sending and processing messages);� constraint solving (synthesizing and running programs on sets of rela-tions).These are three orthogonal dimensions of computations which can be com-bined in various ways, Fig. 1.The combination of speci�cation processing and object manipulation is whatwe call object-oriented programming. A coordinate plane determined by theaxes of Speci�cation processing and Constraint solving form constraint program-ming. Combination of object manipulation and Constraint solving is almost cov-ered by concurrent constraint programming and logic constraint programming.This coordinate plane corresponds also to the most interesting and novel part ofthe NUT system. This is a kind of constraint object programming which is stilldi�erent from the approach taken in [Smolka et al. 1993], �rst of all, because itapplies a speci�c technique of constraint solving by program synthesis.The aim of this report is to present constraint semantics of NUT classes. Wedescribe the way how speci�cations written in NUT are translated into func-tional constraint networks suitable for application of di�erent satisfaction tech-niques. Some of these techniques are described in [T~ougu and Uustalu 1994].Finally, these constarint networks are used for de�ning semantics of statements2

compute and subtask in the procedural part of the NUT language. The seman-tics of these statements is determined by constraints given in a class and cannotbe represented in a traditional way.The report starts with introduction of functional constraints (Chapter 2)followed by the presentation of the means available in NUT to specify constarints(Chapter 3). In Chapter 4 we shall describe speci�cation of computationalproblems i.e. constarint satisfaction problems in NUT. Then some extensionsof basic concepts of NUT language are described in Chapter 5. These extesionsare important to give generality to the system and allow e�ective solution ofreal problems.In the report, di�erent features of the NUT language are demonstrated onsmall examples. In order to give an idea of a complete speci�cation of a problemdomain, a collection of classes for solving ordinary di�erential equations is givenin Appendix A.

3

Chapter 2Functional constraintsLet X = fx1; x2; . . .xng be a set of problem variables. We shall consider con-straints as relations over the set X specifying which combinations of values ofproblem variables are acceptable. Formally, constraints can be written as inter-preted formulae in �rst-order predicate calculus. Let us denote constraints asfollows: Ax1(x1); Ax2(x2); � � � ; Axn(xn);Ax1;x2(x1; x2); Ax1;x3(x1; x3); � � � ; Ax1;xn(x1; xn);Ax2;x3(x2; x3); Ax2;x4(x2; x4); � � � ; Ax2;xn(x2; xn);...Axn�1 ;xn(xn�1; xn);Ax1;x2;x3(x1; x2; x3); � � � ; Axn�2;xn�1 ;xn(xn�2; xn�1; xn);...Ax1 ;x2;...;xn(x1; x2 . . . ; xn):In special cases, constraints may be simply atomic formulae, i.e. predicateswhich determine domains of variables (in the case of unary predicates) or "local"relationships between tuples of variables.A Constraint Satisfaction Problem (CSP) is represented by a conjunction ofall constraints involved:Q(x1; x2; . . . ; xn) � Ax1(x1)& � � �&Axn (xn)&Ax1;x2(x1; x2)& � � �&Ax1 ;x2;...;xn (x1; x2 . . . ; xn):The CSP is solvable if the formula9x1; x2; . . . ; xnQ(x1; x2; . . . ; xn) (2:1)4

is constructively derivable. The proof of the solvability of the CSP is calledconstructive if during derivation individual constants �x1; �x2; . . . �xn are indicatedwhich satisfy the formula (2.1) for the underlying interpretation.In general, a CSP may have no complete solution when the amount of usableresources is limited. For e�ciency considerations partial constraint satisfactionproblem is regarded [Freuder and Wallace 1992] or/and additional restrictionsare set to the formulae representing expressions and to the interpretation offunctional and predicate symbols. Two popular restrictions are that constraintsmay contain no functional symbols and domains of potential values of problemvariables are �nite [Mackworth 1992].In this paper we shall restrict ourselves to the two following types of con-straint formulae:� ground atoms Ax(x) � P (x) where P is a predicate specifying a domain ofx. We call the predicate P characteristic predicate of the class of objectsP if the predicate symbol P is interpreted as `argument x belongs to theclass P';� functional constraints Ax1;...;xm;y(x1; . . . ; xm; y) which has an interpreta-tion where y has at most one value satisfying the relationAx1;...;xm;y(x1; . . . ;xm; y) for any tuple of values of x1; . . . ; xmIn the last case, a constraint de�nes a function y = f(x1; . . . ; xm) and canbe put down as a formula X1; . . . ;Xm �!f Y (2:2)where X1; . . . ;Xm are propositions representing computability of x1; . . . ; xm re-spectively. The formula (2.2) itself expresses the property that if the objectsx1; . . . ; xm have suitable values then one can compute a value for y using func-tion f .Functions determined by functional constraints may be of the second order aswell. This means that a constraint may bind some objects g1; . . . ; gl of functionaltype which stand for arguments of the mapping F of the functional constraint.Formally, a constraint Ag1 ;...;gl;x1;...;xm;y(g1; . . . ; gl; x1; . . . ; xm; y) contains thesecond order functional dependency if the following holdsy = F (g1; . . . ; gl; x1; . . . ; xm):Objects g1; . . . ; gl can obtain their values dynamically during solution of thecurrent CSP [T~ougu and Uustalu 1994]. In this case, we still maywish to specifytype of an object gi, saying that gi must be a function computing vi fromui1; . . . ; uiki. This is expressed by the formulaUi1; . . . ;Uiki �!gi Vi:5

The constraint Ag1 ;...;gl;x1;...;xm;y(g1; . . . ; gl; x1; . . . ; xm; y) will then be repre-sented by the following formula:(U11; . . . ;U1k1 �!g1 V1); . . . ; (Ul1; . . . ;Ulkl �!gl Vl);X1; . . . ;Xm �!F Y:(2:3)Let us notice, that the relation Ag1;...;gl;x1;...;xm;y(g1; . . . ; gl; x1; . . . ; xm; y)binds the objects g1; . . . ; x1; . . . ; y, but not the objects u11; u12; . . . ; v1; . . ..Higher order functional constraints provide generality to the language ofconstraints, and allow some interesting applications, see Sec.5.2.

6

Chapter 3Constraints in the NUTLanguageNUT is an object-oriented programming language and environment for speci-fying problems by means of constraints with built-in methods for solving con-straint satisfaction problem. As any object-oriented language, NUT has classand object as its basic notions.Class is a carrier of common features of objects of the same type, i.e. ofobjects with similar structure and with the property to react similarly to certainchanges of their environment (receiving the same messages from other relatedobjects).Let us introduce a predicate C(x) for every class C which is true for anyobject x of the class C and false otherwise. There are some prede�ned classessuch as num, text, bool etc. in the NUT system. Hence, there are a numberof unary predicates de�ned:� num(x) { x is a rational number, or that is the same, that x is an objectof the class num;� text(x) { x is a string of characters;� bool(x) { x is a boolean value;etc.Similarly, the predicate triangle(ABC) means that the object ABC belongs tothe class of triangles. The di�erence here is that a concept of triangle has to bespeci�ed and stored into the knowledge base by a user as the class triangle.Formally, every object x might be treated as a tuple of its attributes x =(x1; x2; . . . ; xn) which represents aspects of an object essential for underlyingconsideration. A number of attributes considered in any particular situationis assumed to be �nite. A class C determines relationships between attributes7

of objects belonging to the class. Each class C has its characteristic predicatewhich can be speci�ed asC(x) � 9x1; x2; . . . ; xnQ(x; x1; x2; . . . ; xn) (3.1)where x1; . . . ; xn are its attributes. This is a constraint speci�ed by the class C.The matrix Q in the formula (3.1) is the conjunction of "smaller" constraintsrepresenting relations between the attributes. So, using the class mechanism, auser can built up the hierarchy of constraints.There are the following means in the NUT system to specify various con-straints:� constraints for structure of objects;� equational constraints over numeric objects;� constraints as di�erent kinds of identity relations;� constraints as messages which may be accepted by an object together withits (pre)programmed reaction to the message.All these constraints can be represented by �nite sets of functional constraints.3.1 Structural ConstraintsAn object in NUT can have a �xed number of components which are objectsagain. The names and types of these components are aspects to be speci�edby the class of the object. Considering objects with complex structure we sup-pose that there are two di�erent operations one can apply to objects and theircomponents. One can separate a component from the compound object to treatit further independently, and vice versa, one can incorporate objects of propertypes into a new object as its components.For example, the situation where a class Z de�nes its objects to consist oftwo components x and y of classes X and Y respectively, can be speci�ed in theNUT language asClass Z:(var x:X; y:Y);This is a structural constraint that binds any object z of class Z with itscomponents which we denote by z:x and z:y. Semantically, this means that forevery object z of the class Z there exist functions selectx , selecty and composeto separate components z:x and z:y from the object z and to unite the twoobjects into the object of class Z respectively. In other words, belonging to theclass Z means for an object z that there are objects z:x and z:y, such that the8

following constraints are satis�ed:Az:x(z:x) � X(z:x) (3.2)Az:y(z:y) � Y (z:y) (3.3)Az;z:x(z; z:x) � selectx(z) = z:x (3.4)Az;z:y(z; z:y) � selecty(z) = z:y (3.5)Az:x;z:y(z:x; z:y) � true (3.6)Az;z:x;z:y(z; z:x; z:y) � compose(z:x; z:y) = z (3.7)The class Z de�nes therefore a predicate Z(z) as a conjunction of the for-mulae (3.2)-(3.7).The constraints (3.2) and (3.3) determine the domains (given by classes) ofcomponents z:x and z:y. Other relations are functional constraints and mightbe reformulated as follows: Z �!selectx Z:X (3.8)Z �!selecty Z:Y (3.9)Z:X;Z:Y �!compose Z (3.10)Constraints (3.4) and (3.5) can be treated as equations de�ning abbreviationfor selection operation selectx and selecty respectively. Afterwards we shall useelsewhere "dotted notation of selection", i.e. z:x instead of selectx(z). Torepresent computability of such a selected element the proposition Z.X will beused. For example, assuming that abbreviation, one can reduce the de�nitionof the characteristic predicate of class Z as follows:Z(z) = X(z:x) & Y (z:y) & Z:X;Z:Y �!compose Z:On the other hand, a set of implications in the form of formulae (3.8){(3.10) permits a simple graphical representation of the constraint network. Aconstraint network is a graph where nodes are used for representation of objectsinvolved and functional constraints (implications). The nodes of objects aredenoted by names and types (classes) of the corresponding objects and thenodes of constraints are labelled by their names (see next sections) or/and bythe functions realizing them. We shall omit some labels, for example classesof objects or function symbols, if there will be no confusion. In Fig.3.1, theconstraints (3.8){(3.10) are presented as a network.A hierarchy of classes (and corresponding constraints) can be de�ned in themanner described above. Besides structural constraints, a class may containother kinds of conditions to be satis�ed. In the following sections we showhow these constraints are interpreted as implications in a propositional calcu-lus. Every additional restriction for components of a class will complement itscharacteristic predicate by one or more atomic constraint.9

tt � �� � � �� � t� �� �

��

� � � � � � ��@ @ @ @ @ @ @R - @@@@@@@I �������z.x:Xz.y:Y z:Zselectx

selectycomposeFigure 3.1: Constraint network of the class Z3.2 EquationsAn equation f(x1; . . . ; xn) = 0 (3:11)over numeric objects is a constraint which allows to �nd some xi if all otherx1; . . . ; xi�1; xi+1; . . . ; xn are given. This is valid only when we know the methodhow to compute xi from other variables of the equation. Let us denote by f�1ithe function which solves the equation (3.11) in respect of a variable xi:xi = f�1i (x1; . . . ; xi�1; xi+1; . . . ; xn)so thatf(x1; . . . ; xx�1; f�1i (x1; . . . ; xi�1; xi+1; . . . ; xn); xi+1; . . . ; xn) = 0:An equation may be a partially solvable constraint in the sense that notalways it can be solved in respect of all unknowns. For instance, the equationx21 + 2x1 + 3 = 0cannot be solved in real numbers at all, and the corresponding function f�1idoes not exist. Besides that we have to accept that sometimes we do not knowhow to get the function f�1i even when it exists, as there is no general e�ectivemethod to solve equations.The NUT language permits to include equational constraints over numericcomponents into class declarations. For instance,10

Class W:(var x,y:num;relR: 2*x - y = 0);means that an object of class W has two numeric components x and y con-strained by the equation 2x� y = 0.The semantics of an equation (3.11) is de�ned by a conjunction of constraintsAix1;...;xn � X1& � � �&Xi�1&Xi+1& � � �&Xn �!f�1i Xifor every variable xi for which we know a function f�1i . In the case of the classW above, the equation R generates two assignments:x := g1(y) = y=2and y := g2(x) = 2 � x:Hence, the constraint de�ned by the class W can be presented as the predicateW (w) � Num(w:x) & Num(w:y)& W:X & W:Y �!compose W& W:X �!g1 W:Y& W:Y �!g2 W:X:The constraint network corresponding to the given speci�cation of the classW is shown in Fig.3.2.Combining structural and equational constraints permits us to de�ne rathercomplex concepts as classes of objects of hierarchical structure. For example,the following two classes altogether specify a concept of line segment in two-dimensional space.Class Point:(var x,y:num);Class Bar:(var P,Q:Point;length, angle:num;rel (P.x - Q.x)^2 + (P.y-Q.y)^2 = length^2;P.y - Q.y = (P.x - P.y) * tan(angle));Here we can point out the expressive power of the NUT language - rathershort class descriptions consisting of some equations taken from school text-books generate a large number of constraints speci�ed. Similarly to the class Zin the previous Section, the characteristic predicate Point consists of 5 atomicconstraints. Therefore, the declarations of end points P and Q in the speci�ca-tion of the class Bar introduce 2�5 = 10 constraints. Two new constraints will11

tt t� �� � � �� �� �� �� �� � � �� ��

�� � � � � � ��@ @ @ @ @ @ @R - @@@@@@@I �������� � � � � ��B B B B B BN

������� BBBBBBMw:x:Numw:y:Num w:Wselectx

selectycomposeR1 R2Figure 3.2: Constraint network of the class Wbe added by speci�cation of domain Num for length and angle, and 10 moreconstraints are generated by the two equations as they are solvable with respectto all unknowns. To conclude, the class Bar speci�es 32 constraints for everyobject of this class.This example demonstrates a problem speci�c for equational constraint sys-tems: equations may not have unique solutions. For instance, there are in�nitelymany values of variable angle which satisfy the last equation in the class Barfor �xed valuation of other variables. The NUT system uses some heuristicsto choose the solution, however it is recommended to avoid usage of equationswith multiple solutions. In many cases speci�cations with equations of thiskind can be transformed into the "equivalent" ones with unique solution. Thisis mainly a knowledge engineering task we do not consider here which allowsone to use the NUT system for solving practical problems such as they arosein CAD systems or implementing semantics of programming languages (see[Kalja and Pahapill 1992], [Penjam 1990]).3.3 Programs as constraintsNUT permits a exible mechanism for message passing between objects. Thisis used for invoking methods available for an object of a class. Besides that,a method corresponds strictly to a set of functional constraints between the12

components of the object. A set of constraintsX1; . . . ;Xm �!f1 Y1 ...X1; . . . ;Xm �!fn Ynwhere f = (f1; . . . ; fn) can be speci�ed in NUT as a method with a name R inthe following way:R : x1, ... , xm -> y1, ... , yn { f };Hence, there is correspondence between functional constraints and methodsspeci�ed by a class.Let us look at the example:Class compl:(varre, im : num;mod, arg : num;relretomod : re, im -> mod, arg {mod:=sqrt(re^2 + im^2);arg:=arccos(re/mod)};modtore : mod, arg -> re, im {re:=mod * cos(arg);im:=mod * sin(arg)});The two relations retomod, modtore of the class compl are speci�ed by thefollowing two parts. First, they have external views of constraints which specifytheir input and output parameters and give some type information, i.e. explicitinformation about their input and output parameters written to the left and tothe right of an arrow:re, im -> mod, argmod, arg -> re, imThis external information of constraints is used for planning computations whena constraint problem is solved (see [T~ougu and Uustalu 1994] in this book).Second, speci�cation of these relations contain programs written in an imper-ative language which is a part of NUT. These programs implement the methods.This is the semantics of the speci�cations used in object-oriented computations.The second relation describes a method with an input variables mod and argand output variables re and im which can be invoked by a message modtore.Any method speci�ed in the class de�nes a node of the constraint networkof every object of the class. This node is labelled by the name of the methodand there are arcs binding the node with inputs and outputs of the method. Ifthere is an object C1 of class compl, methods retomod and modtore give thefollowing two nodes: 13

s � �� � ss � �� � sZZZZZZZZZZ} -�� � � � � � � � � �> Z Z Z Z Z Z Z Z Z Z~� -����������=modtore C1.argC1.modC1.reC1.im retomodLet us remark that any solvable arithmetic equation can be replaced by aset of speci�cations of methods representing its functions fi (cf. previous Sec.).For example the equation y = 2x is equivalent to the following methods:relR1 : x -> y {y:=2*x};R2 : y -> x {x:=y/2};3.4 Identity relationsNUT has a large number of speci�c language constructions that allow to describespeci�cation transformations which are usual for object oriented programming.Some of these features can be e�ectively speci�ed using di�erent kinds of identityrelations.Identity in the NUT means that two (or more) objects have the same com-ponent values. This does not mean automatically that these objects are of thesame type, however there must be some correspondence between the types ofcomponents of related objects.In the simplest case when two numeric objects x and y are de�ned to beidentical, it means that there is an equationx = ytogether with its standard semantics as it was described in previous Section.Identity relation between objects is syntactically speci�ed in the same form, i.eit looks like an equation. However, the semantics of such a relation is morecomplicated and depends on the order of components being speci�ed in classes.Omitting here details one can read in [T~ougu 1988, page 78] we demonstratethis feature in the case of binding construction.Bindings are amendments to types introduced by the speci�cations of com-ponents, and they introduce additional constraints. Let us consider an examplewhere one has de�ned a triangle as a connection of three line segments:14

triangle : ( varAB : Bar ;BC : Bar P=AB.Q;CA : Bar P=BC.Q, Q=AB.P;perimeter : num;relperimeter=AB.length+BC.length+CA.length);The binding P=AB.Q In the speci�cationBC : Bar P=AB.Qsays that the end point of side AB is identical to the �rst point of side BC, i.e.sides AB and BC have a common point.Bindings can be considered as syntactic sugar, i.e. they can be syntacticallyeasily transformed into the remaining part of the language, except for the casewhere type variables are involved. Bindings enable us to write speci�cations in ashorter form. Let us compare the last class speci�cation with another equivalentone where identity of points is de�ned explicitly using equation.triangle : ( varAB, BC, CA : Bar ;perimater : num;relAB.Q=BC.P;BC.Q=CA.P;CA.Q=AB.P;perimeter=AB.length+BC.length+CA.length);Despite of di�erent syntax, in both cases, the identity relation AB.Q=BC.Pgenerates two equations, one for both components of the point: ABC:AB:Q:x =ABC:BC:P:x and ABC:AB:Q:y = ABC:BC:P:y. Both equations, in turn,generate 2 constraints as this was described in Sec. 3.2.15

Chapter 4Speci�cation ofComputational ProblemsNUT performs partial constraint satisfaction by means of algorithms for struc-tural synthesis of programs ([Mints and T~ougu 1983] and [T~ougu and Uustalu 1994]).A request for program construction can appear in the NUT system in di�erentforms. First, we discuss the simplest and generally applicable form. A messageof the following form can be sent to any object x in the NUT system:x.compute(y,..., z)where y,..., z are components of the object x. This is a request to compute valuesof y,...,z and to save these values in the object x. In order to compute the valuesof y,...,z, the class of x, extended with the already existing values of componentsof x will be used as a speci�cation of this problem. This message fails, if someof components in the list are not computable from the given speci�cation. Letus consider the following class declarations.Class circle : ( vara, d, p, S : num;reld= 2 * r;S= pi * r ^ 2;p = 2 * pi * d );Class square : ( vara, d, p, S : num;reld^2 = 2 * a ^ 2;S = a ^ 2;p = 4 * a );16

a=13Figure 4.1: A computational problemClass problem1 : ( varq : square;c : circle;relc.d=q.a;q.a=13;x=q.S - c.S );Now, after creating an object fig by means of the following statementfig:=new problem1we can compute the solution of the problem shown in Fig. 4.1 simply by sendingthe message fig.compute(x).The list of components in parentheses may be empty:fig.compute().In this case, all components which are computable will be evaluated and thevalues will be kept in the state of the object fig. The message compute withempty list of components never fails.Another possibility to specify a request for program construction is to askfor automatic synthesis of a method.If a class speci�cation contains su�cient information for computing compo-nents y1,..., yn from other components x1,..., xm, then a method, let us call it r,with the axiom x1,..., xm �! y1,..., yn can be synthesized, using the followingspeci�cation in the relations part of the class:r: x1,..., xm -> y1,..., yn {spec}17

The keyword spec in the program part is a request for sythesizing a programfrom the class speci�cation where this keyword is being used. The input andoutput variables of the program are given in the axiom of the method.As an example, we can extend the class problem1 by adding there a methodfor computing the value of the desired result :Class problem2 : ( varq : square a=13;c : circle d=q.a;relresult: -> x {spec}x=q.S - c.S );Now the following sequence of statements will compute the result:fig:=new problem2;fig.result()In order to set a program which solves the problem for an arbitrary value of theside of the square, we have to drop the binding a=13 in the speci�cation of theclass, and add the input variable q:a into the axiom of the method result:Class problem3 : ( varq : square;c : circle d=q.a;relx=q.S - c.S;result: q.a -> x {spec} );Then we can write fig:= new problem3;fig.result(13)for computing the desired result for the side x of the square. One can add moremethods of this kind to the class problem1, for example:Class problem4 : ( varq : square;c : circle d=q.a;relx=q.S - c.S;result: q.a -> x {spec};reverse: x -> q.a {spec};fromradius: c.r -> x {spec} );However, in general, every method of the form18

r: x -> y {spec}can be modelled by an assignment and the message compute, as shown belowfor the method reverse in an object w of the class problem4:w:= new problem4;w.x(13);w.compute(q.a);

19

Chapter 5Some Important Extensions5.1 Variables of Type anyIn this section we describe some important features of NUT language which giveit exibility for speci�cation of constraints.The type variable any provides an interesting form of polymorphism to thelanguage, which can be used in object-oriented computations as parametric poly-morphism, but has a more general interpretation in speci�cations - componentsof an object of type any can be referred to before the type of this object willbe concretely speci�ed. The following class represents computationally a con-cept of maximum of a function. It can be used in a combination with any classrepresenting a function which has numeric components arg, val for representingargument and value of the function.Class max : ( varargmax, maxval:num;fun:any;relr:(fun.arg -> fun.val) -> argmax, maxval {g} );where g is a method for �nding maximum of a function. For example, if afunction is represented by the classClass f : ( vararg,val:num;relval= 1 - arg ^ 2 );then the following class speci�es a problem of �nding maximum my of thefunction represented by f and the value of the argument mx at the maximumof the function: 20

Class problem5 : ( varmx,my ; num;function : f;m : max fun = function,argmax = mx, maxfun = my );5.2 Higher Order Functional ConstraintsLet us look at the implementation of the method r in the class max:r:(fun.arg -> fun.val) -> argmax, maxval {g};The axiom shows us that the program g, which is an implementation of themethod, has one argument and this argument must be a function. The programg can be written directly in the NUT language. It will contain statements whichcall its functional argument. These statements are called subtask statements ofNUT, because a nested implication in an axiom de�nes a subtask in programconstruction. In the present example, this is the subtask of �nding a functionfor computing fun:val from fun:arg, de�ned by the implicationfun.arg -> fun.valIn a program, the subtasks are referred to by the number showing theirposition in the axiom of the program, and their calls have the following form:subtask <integer>(<parameters>)The integer is the subtask number, parameters are passed positionally byvalue to the variables in the subtask. The subtask statementsubtask 1(x, y)in the text of a program g means a call of the function for computing fun:valfrom fun:arg synthesized automatically on the class where the method is de-scribed. Value of x is passed to fun:arg and, after the execution of the function,value of y is received from fun:val. There are two kinds of subtasks with subtlebut important di�erence in semantics. A subtask which has the form[<arguments> -> <results>]in an axiom, and has been used above, requests the synthesis of a program onthe current state of the object where the method is executed, i.e. it takes intoaccount all values of components available at this time. Another form of thesubtask is [<class name> |-- <arguments> -> <results>]21

This subtask requests synthesis of a program on a new object of the givenclass and uses purely the properties of the class, ignoring the environment wherethe request was given.We demonstrate the usage of a higher order function on an example of aclass map which models the corresponding functional operator, i.e. it computesan output array b, mapping the function onto elements of an input array aand applying it to them. A virtual component mapfun represents the functionimplicitly. The function must be synthesized according to the subproblem[mapfun.arg -> mapfun.res].The object mapfun has class any, but it must contain components arg andres which represent argument and result values of the mapped function.Class map : ( vara,b:array of num;virmapfun:any;relr:[mapfun.arg -> mapfun.res] a -> b{for i to length(a) dox:=a[i];subtask 1(x,y);b[i]:=yod} );By describing other functional programming operators: �lter, reduce etc.,one can easily develop a set of concepts for functional programming in NUT.However, syntax of this functional language will be di�erent from the conven-tional syntax of functional programming languages.5.3 Production RulesUsing purely functional constraints does not allow us to specify abstract featuresof objects. To overcome this shortage NUT has been extended by Horn clauselogic. This is intended for meta-level reasoning about problems and speci�ca-tions and provides generality and logical power to the NUT system.Using productions in speci�cations one can represent facts and rules. Pro-ductions can be used for generating new facts and also for computations almostlike in Prolog. The following are examples of facts:-> father ( John, Jack ) ;-> father ( Jack, Jim ) ;and this is a rule: 22

father (@x,@y) & father(@y, @z) -> grandfather (@u, @x,@z);The rules contain metavariables which are identi�ers beginning with thecharacter @ and denote objects of the NUT language. The rule given aboveenables us to produce a new fact:-> grandfather(,John, Jim)from two given facts. The words father and grandfather denote predicateswhich can be:� abstract predicates without any particular realization,� names of programs,� names of classes.In the latter case they are characteristic predicates of classes and this type ofpredicates is especially useful for describing general laws for classes and objects.For instance, the following rulepoint(@u) & point(@v) -> bar(@t, @u, @v)says that if we have two objects of the class point, then we can form a newobject of the class bar. This rather general rule can be applied for extendingspeci�cations in solving a number of geometric problems.Another example of this kind is a rule about distance on a straight line: ifthe distance from point A to point B is equal to L1 and the distance from pointB to point C is equal to L2, then the distance from A to C is L1 + L2. With aclass distance:Class distance : ( varA, B : Point;Length : num );we can write a speci�cation of the following from:R: distance A = P, B = Q:or, more brie y: R: distance P, Q:if we use positional binding of components of a class. (P is bound with the �rstand Q with the second component.)We can use the class distance in a completely di�erent way and write anatomic formula: distance (@x, @y, @z) .23

This formula contains three variables @x, @y, @z which can be uni�ed with theobjects R, P , Q of the speci�cation:R: distance P, Q;and the NUT system can transform it automatically into the following atomicformula: distance (R,P,Q).This can be used as a fact in a production; for example, the law for distancecan be written as follows:collinear(@x, @y, @z) &distance(@u, @x, @y, @L1) &distance(@v, @y, @z, @L2)-> distance(@w, @x, @z, @L1 + @L2);This production means that whenever there are three collinear points @x;@y;@zand there is a distance @u of the length @L1 between the points @x and @y,and another distance @v of the length @L2 between the points @y and @z, thena new speci�cation for distance can be introduced automatically for the points@x and @z.

24

Chapter 6SummaryDevelopment of NUT is an attempt to incorporate constraint programming intoan object-oriented programming framework. This has been done by 1) usingclasses as a source of information for constraint satisfaction; 2) introducing aspecial type of messages - the compute messages, which are requests for au-tomatic program construction and execution. This is a dynamic way to applyprogram synthesis, when existing values of components of objects are taken intoaccount. Methods can be synthesized also purely from class speci�cations, nottaking into account the previous results of computations. This is done, when thekeyword spec is being used as a body of a message. This is a static approach toprogram synthesis. Synthesized programs can appear as values of parametersof methods, adding a avour of higher-orderness to the language, which givesus the most dynamic way to synthesize programs.AcknowledgementsWe are much indebted to Mari K~opp, Mihail Matskin and Benjamin Volozhfor polishing the present version of the NUT system. We wish also to expressour gratitude to our other colleagues at the Estonian Academy of Sciences bywhom the �rst version of NUT was designed and implemented. The authorswould also like to thank Tarmo Uustalu for our fruitful discussions on the NUTsystem and many helpful comments on this paper. We thank Tarmo Uustaluand Claes Thornberg who wrote the speci�cations of classes for solution ofdi�erential equations presented in the Appendix A.25

Appendix ADi�erential Equation SolverThis is a software package developed in the NUT system for solving ordinarydi�erential equation represented by their structural schemas. The program syn-thesis is essentially used for deriving a program for computing states of theelements of the equation to be solved. The equation itself is speci�ed by thecalss problem. This can be described not only textually, but also graphically,using scheme editor [T~ougu and Volozh 1993] of the NUT system, but the latterfeature is not explained in the framework of this report.A linear di�erential equation with constant coe�cients can always be writtenas x(n) + an�1x(n�1) + . . . + a1 _x+ a0x = f(t);where x is a continuous function depending on t and the coe�cients an�1; . . . ; a1; a0are constants.There are several numerical methods to solve di�erential equations numeri-cally. We shall use Euler's method to compute approximations:x(t + �t) � x(t) + �t _x(t)_x(t + �t) � _x(t) + �t �x(t)...x(n�1)(t + �t) � x(n�1)(t) + �t x(n)(t)where x(n)(t) = f(x(n�1)(t); . . . ; _x(t); x(t); t)A.1 Classes for solving di�erential equationsIn order to specify and solve di�erential equations and to display the resultgraphically, the package is built up starting from the following cosiderations.26

� Equations are speci�ed using the following computational elements:{ adder, with two components for inputs, two components for the co-e�cients of the inputs and one component for output. The output iscomputed instantaneously from the inputs and the coe�cients.{ integrator, with one component for the current value, which is alsothe output, one component for the next value, and one time factor.It is used to compute x(n)(t+ �t) from x(n)(t), �t and x(n+1)(t). Thetime factor T has the same meaning as 1=�t.{ clock, which is needed to specify di�erential equations where x(n)is a function of t as well as of x(n�1); . . . ; _x, and x. It has the samecomponents as the integrator class. The next value of the clockis computed from the current value of the time and the time factor.The output is the new current value. Semantically the clock is anintegrator with constant input function f = 1.Note that, in order for an equation to be meaningful, the clock and allintegrators should have the same time factor.� The class process is used for executing the numeric method through itsonly method run. An equation to be solved should be speci�ed in theform of a scheme composed of computational elements. For examples ofsuch scheme speci�cations, see �gure A.1. The scheme would be a viewof a particular problem class, which would have process as a superclass.The current states (next states, initial states, and �nal states) of the com-putational elements used in the equation speci�cation would be collectedtogether into global current states (next states, initial states, and �nalstates) of the process by aliasing, inheritable from the process class. Themethod run, also inheritable from the class process, involves a subtaskof computing the global next state from the global current state, which isaccomplished by using the methods of the computational elements usedin the equation speci�cation.� The classes clean_graph and graph are two alternative formalizations ofthe concept of graph. A graph is an computational element that stores thehistory of any two parameters of the scheme (in the form of two arraysof equal length), and it is meant to be used for graphically displayingtheir relationship. The history is built incrementally during the run ofthe process. Conceptually, the state of the graph is the history of themonitored parameters up to the current time instant. clean_graph is thesemantically clean formalization of this viewpoint. Unfortunately, it iscomputationally ine�cient, since states as histories rapidly become largeobjects in the run of the process, and as such they are also included inits global state. The concept of history is speci�ed as an auxiliary classxy_hist, used in clean_graph. 27

xx’x’’x’’’b

c1

a

x’’’ = a x’’ + b x’’ + c x

txx’a

b

x’ = a x + b tFigure A.1: Example schemes.Computationally more feasible, but semantically more cumbersome is theclass graph, where only the length of the history arrays is stored in thestate that is included in the global process state, and the arrays themselvesare kept local.In both classes, displaying of the graph is implemented in the methoddraw. This method uses the component finalstate as an input parame-ter. It is meant to obtain a value as a result of invoking the method runwhich the particular problem class would inherit from the class process.The component drawing_ready acts as a \control variable". If NUT isby some means forced compute it, the graph is drawn (as a side-e�ect).A.2 Class textsFrom the discussion in the previous section we can easily de�ne some classeswhich will allow us to solve di�erential equations with the NUT system. Whatwe need is a class for adding numeric values and one class for integrating, i.e.to compute x(t + �t) from x(t), �t and _x(t). These two classes are adder andintegrator respectively. The adder class has two components for inputs, twocomponents for coe�cients and one component for output. The output is the28

computed immediately from the inputs and the coe�cients. The integratorclass has one variable which is the current value, which is also its output value,and one component for the next value. The next value is computed from thecurrent value, the input and a time factor. The inverted value of the time factorhas approximately the same meaning as the step �t in the previous section.A.2.1 The adder classvar k1, k2 : num;in1, in2 : num;out : num;rel out = k1 * in1 + k2 * in2;A.2.2 The integrator classvar initstate : num;vir state, nextstate, finalstate : num;var T : num;in : num;out : num;rel advance : nextstate = state + in / T;out = state;A.2.3 The clock classvar initstate : num;vir state, nextstate, finalstate : num;varT : num;out : num;rel advance : nextstate = state + 1 / T;out = state;init initstate := 0; 29

A.2.4 The xy_hist classvar xs, ys : array of num;l : num;A.2.5 The clean_graph classvar initstate : xy_hist;vir state, nextstate, finalstate : xy_hist;var x, y : num;drawing_ready : bool;rel advance : x, y, state -> nextstate{nextstate <- state;nextstate.l := nextstate.l + 1;nextstate.xs[nextstate.l] := x;nextstate.ys[nextstate.l] := y;};draw : finalstate -> drawing_ready{del_pict();dr_graph(finalstate.ys,finalstate.xs,finalstate.l);drawing_ready := true;};init initstate := [[0],[0],0];A.2.6 The graph classvar initstate : num;vir state, nextstate, finalstate : num;var x, y : num;xs, ys : array of num;drawing_ready : bool;rel advance : x, y, xs, ys, state -> xs, ys, nextstate{nextstate := state + 1;xs[nextstate] := x;ys[nextstate] := y;};draw : xs, ys, finalstate -> drawing_ready30

{del_pict();dr_graph(ys,xs,finalstate);drawing_ready := true;};init initstate := 0;xs := [0];ys := [0];A.2.7 The process classvar time : num;alias state = (all.state);nextstate = (all.nextstate);initstate = (all.initstate);finalstate = (all.finalstate);rel run : [ state -> nextstate]initstate, time -> finalstate{state <- initstate;for t := 1 to time + 1 dosubtask 1(state, nextstate);state <- nextstate;od;finalstate := state;};A.3 Example of solving the di�erential equation�x = �2 _x � 5x.To solve the equation �x = �2 _x� 5x considering the initial conditions _x(0) = 1and x(0) = 0, one needs to start with drawing out the structural scheme of theequation (see Fig. A.2) and specifying the following class of the problem.A.3.1 The problem classsuper process;rel time = 50;% scheme beginvar 31

Figure A.2: Structural sheme of the equation �x = �2 _x� 5x.I2: integrator initstate=0,T=5;clock: clock T=5;graph: graph;I1: integrator initstate=1,T=5;S1: adder k1=-2,k2=-5;rel I1.out = S1.in1 ;I2.out = S1.in2 ;I2.out = graph.y ;clock.out = graph.x ;I1.out = I2.in ;S1.out = I1.in ;% scheme endThen the NUT system can compute the result solving the constraint satis-faction problem speci�ed by the following statements32

Figure A.3: The solution of the equation �x = �2 _x� 5x.P := new problem;P.compute(graph);and draws a graph shown in Fig. A.3.33

Bibliography[Freuder and Wallace 1992] Freuder E.C., Wallace R.J. (1992) Partial Con-straint Satisfaction. - Arti�cial Intelligence, 58, pp. 21{70.[Ja�ar and Lassez 1987] Ja�ar, J., Lassez J.-L. (1987) Constraint Logic Pro-gramming. - Proc. of the 14th ACM Symposium on Principles of Pro-gramming Languages. Munich, pp. 111 { 119.[Kalja and Pahapill 1992] Kalja, A., Pahapill, J. (1992) Small Knowledge CADSystems. - InformationModelling and Knowledge Bases III: Foundations,Theory and Applications, IOC Press, Amsterdam, pp. 347{356 the 14thACM Symposium on Principles of Programming Languages. Munich,1987, pp. 111 { 119.[Kotov et al. 1989] Kotov, V., Nariniani, A., Tyugu, E. (1989) The USSRAcademy of Sciences START Project. - Information Processing 89(IFIP'89). North Holland, pp. 623 { 626.[Mackworth 1992] Mackworth A.K. (1992) The Logic of Constraint Satisfac-tion. - Arti�cial Intelligence, 58, pp. 3{20.[Matskin 1991] Matskin, M. (1991) NUT System papers. - Computer ScienceDepartment. Aarhus University, DAIMI MD { 59.[Matskin and T~ougu 1992] Matskin, M., Tyugu, E. (1992) The NUT language.- TRITA-TCS-SE-92-TR. Royal Institute of Technology, Stockholm.[Mints and T~ougu 1983] Mints, G., Tyugu, E. (1983) Justi�cation of the Struc-tural Synthesis of Programs. - Science of Computer Programming, 2,no.3, pp. 215 { 240.[Mints and T~ougu 1988] Mints, G., Tyugu, E. (1988) The Programming SystemPRIZ. - Journal of Symbolic Computations, 5, pp. 359 { 375.[Mints and T~ougu 1990] Mints, G., Tyugu, E. (1990) Propositional Logic Pro-gramming and the PRIZ system. - Journal of Logic Programming, 9no.2-3, pp. 179 { 194. 34

[Penjam 1990] Penjam, J. (1990) Computational and Attribute Models of For-mal Languages. - Theoretical Comp. Sci., 71, pp. 241 { 264.[Saraswat 1990] Saraswat, V. (1990) Concurrent Constraint Programming. -Proc. of the 17th ACM Symposium on Principles of Programming Lan-guages. San Francisco, pp. 232 { 245.[Smolka et al. 1993] Smolka, G., Henz, M., Wurtz, J. (1993) Object-OrientedConcurrent Constraint Programming in Oz. - DFKI RR-933-16. Saar-brucken.[T~ougu et al. 1986] Tyugu, E., Matskin M., Penjam J., Eomois P. (1986) NUT- An Object-Oriented Language. - Computers and Arti�cial Intelligence,5, no.6, pp. 521{542.[T~ougu 1988] Tyugu, E. (1988) Knowledge-Based Programming. - Addison-Wesley, N.Y., 1988.[T~ougu 1991] Tyugu, E. (1991) Three New-Generation Software Environments.- Communications of the ACM, 34, pp. 46{59.[T~ougu and Uustalu 1994] Tyugu, E., Uustalu, T. (1994) Higher-Order Func-tional Constraint Networks. - In Constraint Programming. NATO ASISeries F:Computer and Systems Sciences, (to appear).[T~ougu and Volozh 1993] Tyugu, E., Volozh, B. (1993) Semantic Processing ofSchemes: Concepts and Implementation. TRITA-IT-9304, KTH, Stock-holm.35