**Table 8.3 Continued**

in instance methods of class', self class yourself `printString`].

text := text asText.
text size > 10 ifTrue: [text
  emphasizeFrom: 1
to: 9
  with: (Array with: #bold with: #color → ColorValue blue)].
^text

**textMenu**

^PopUpMenu
  labelList: #((again undo) (copy cut paste) (accept cancel))
  values: #(again undo copySelection cut paste accept cancel)

**VBExample methodsFor: transcript**

**showOnTranscript: aString**

transcript cr; show: aString

**transcript**

transcript isNil ifTrue: [transcript := TextCollector new].
^transcript

**VBExample methodsFor: selectionInList**

**aspect**

^self list

**list**

^OrderedCollection with: 'aaaa' with: 'bbbb' with: 'cccc'

**listChange: aSelection**

aSelection isNil ifTrue: [^nil].
self ins: 'You have selected an item in the selectionInListView' cat: '<selectionInList>' in:
instance'.

**listMenu**

^PopUpMenu
  labelList: #((menu1 menu2)(menu11 menu12))
  values: #(menu1 menu2 menu11 menu12)

"Or the following method

^PopUpMenu
  labels: 'menu1 \\ menu2 \\ menu11 \\ menu12' withCRs
  lines: #(2)
  values: #(#menu1 #menu2 #menu11 #menu12)."
<table><caption>**Table 8.3 Continued**</caption><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>menu1</td><td>self ins: 'A menu item in the selectionInListView is selected' cat: '<selectionInList>' in: 'instance'.</td></tr><tr><td>menu11</td><td>self menu1</td></tr><tr><td>menu12</td><td>self menu1</td></tr><tr><td>menu2</td><td>self menu1</td></tr><tr><td colspan="2"><strong>VBExample methodsFor: switch</strong></td></tr><tr><td>switchOff</td><td>"When the switch is turned off, code in this method is activated"</td></tr><tr><td>self</td><td>ins: 'A switch is turned off,'<br/>cat: '<switch>'<br/>in: 'instance'</td></tr><tr><td>switchOn</td><td>self<br/>ins: 'A switch is turned on,'<br/>cat: '<switch>'<br/>in: 'instance'</td></tr><tr><td colspan="2"><strong>VBExample methodsFor: button</strong></td></tr><tr><td>button</td><td>"This is the method specified in the VBExampleView openOn: aMethod, that is one of the arguments to 'self button...'. Hence, the user can insert a desired action here that is to be associated with the button press"</td></tr><tr><td>self</td><td>ins: 'A button is pressed'<br/>cat: '<button>'<br/>in: 'instance'</td></tr><tr><td colspan="2"><strong>VBExample methodsFor: private</strong></td></tr><tr><td>ins: aString</td><td>Transcript cr; show: aString</td></tr></tbody></table>
<table><caption>**Table 8.3 Continued**</caption><tr><td>Ins: aString cat: c1 In: I1</td><td>Transcript cr; show: aString, 'its method is located in category', c1, 'in', i1, 'methods of class', self class printString</td></tr><tr><td>Ins: aString cat: c1 In: I1 cl: k1</td><td>Transcript cr; show: aString, 'its method is located in category', c1, 'in', i1, 'methods of class', k1</td></tr></table>

about how to modify this example code. As constructed, the skeleton code framework contains messages to the transcript such that as the prototypical framework is operated, messages appear in the transcript that direct the user on how to change the code for an application. The code for ViewBuilder is part of the code package that is described in the Appendix.

## 8.13 Comparison to ST/V Interface

This text employs examples written in ST-80 for illustrating problems in engineering analysis and design. It is worth noting, however, that ST/V (Digitalk, 1986) is suitable for undertaking the same activities described in ST-80. For the most part, Smalltalk code for the two Smalltalk versions is quite similar. The model-view-controller is called the model-pane-dispatcher in ST/V, but operates in a very similar fashion. The transition between using these two versions of Smalltalk requires little effort for experienced programmers.

### References

* Adams, S. (1987). *Pluggable Gauges User's Manual*. Knowledge Systems Corporation, Cary, NC.

* Jiang, Zhihe, and John R. Bourne (1991). A Visual Programming Environment for Building Smalltalk-80 Views. *Journal of Object-Oriented Programming*, May.

* Krasner, Glenn E., and Stephen T. Pope (1988). A Cookbook for Using the Model-View-Controller User Interface Paradigm in Smalltalk-80. *Journal of Object-Oriented Programming*, Vol. 1, No. 3, August/September, 26-49.

* Smalltalk/V, Tutorial and Programming Handbook (1986). Digitalk, Inc.
Exercises

8.1 See if you can build the **DisplayDemo** example yourself. Study the implementation carefully and determine how the model, controller, and view communicate.

8.2 Make a list of the different display entities described in this chapter. Now write a sentence for each type of view explaining when it would be useful. Can you think of any display entities that have been left out of ST-80 that would be useful? For the things left out, describe how to implement them.

8.3 Smalltalk supports design of user interfaces consisting of several graphical components organized in a window. Release 4 organizes all components placed on a **ScheduledWindow** into a whole-part hierarchy. Explain how components of the hierarchy interact with each other. For example, explain how resizing the **ScheduledWindow** affects its interior components.

8.4 In Exercise 3.2, ACOM cards were created for a specific application. Building on the cards created in that exercise, create drawings of the way that the applications proposed using the ACOM cards would look, if implemented.

a. Consider using the following types of elements in the views:

1. Lists: Use to select items from.

2. Buttons: Press to get an action.

3. Moveable forms: Small icons that you can move around and place on the screen.

4. Switches: For example, "on-off," or "radio-button" switches.

5. Text windows, to give information.

6. Graphics representations of things.

7. Animation, for example, sequences of images moving along a path at some rate.

8. Mouse cursors that change the way they look depending on where they are on the screen.

9. Pop-up menus, pop-up dialog boxes.

10. Dictionaries for help and information.

b. Consider what other types of graphics user interface constructs would be useful and invent them. You can get help by looking ahead to the examples in Chapter 9; however, before looking up this information, it would be useful to
consider what you think should be done. Only after that, look up and see how
other applications have been created.

c. Build a series of sketches ("storyboards") that explain how your application would work, if it were implemented.

8.5 Explain how the class **SelectionInListView** operates.

8.6 For the **PictureView** example presented in Section 8.11, add the suggested updating method to the code. Explain why update works for this example.

8.7 If you have access to ViewBuilder, recreate the **PictureView** example using ViewBuilder.

*Exercises for Users with Version 2.5 and Release 4*

8.8 In class **Pen**, examine the method *new* which permits drawing directly on the display. Add the method *new: aForm* that draws on a new form specified by the user. (*Hint*: Look at the method *new* in class **Pen** and modify this method.) This problem can only be worked using Version 2.5 of ST-80 because there is no class **Pen** in Release 4.

8.9 Because **Pen** has been removed from Release 4, how can you draw on a view?

8.10 An interesting demonstration of drawing with a pen is an example of drawing a dragon curve. The code for this curve (from ST-80 Version 2.5) is

Pen Class
dragon: order

order = 0
ifTrue: [self go: 10]
ifFalse: [order > 0
ifTrue: [self dragon: order -1; turn 90; dragon: 1-order]
ifFalse: [self dragon: -1-order; turn -90; dragon: 1 + order]]

Reimplement this code in Release 4 using the *displayLineOn:* method for drawing on a graphicsContext.
# Part Three
# Applications in
# Engineering

The third and final section of this text deals with applications in engineering. The specific intention is to show that object-oriented methodologies are useful across a broad range of engineering applications. To set the stage, Chapter 9 examines the larger subfields of engineering from an abstract point of view to determine if there are commonalities that can be alleged to exist between the different branches in engineering. Then, practical examples of problems solved using object-oriented methodologies are given and related directly to the tools described in Part Two of the text. Constraint-related methods are examined in Chapter 10, the methodologies for capturing and representing knowledge are explained in Chapter 11, integration of object-oriented systems with the external world are discussed in Chapter 12, rapid prototyping methodologies are presented in Chapter 13, and object-oriented simulation is examined in Chapter 14. Finally, in Chapter 15, some conclusions about the lessons learned from these examinations and evaluations are presented.
<figure><img src="image_106.png" /></figure>
# Relating
Engineering
Problems to
Object-Oriented
Methodologies

## 9.1 Objective

The hypothesis discussed in this chapter is that many engineering problems can be cast into, or at least facilitated by, an object-oriented problem-solving framework. To argue for the validity of this hypothesis, the nature of engineering will be explicated by example through brief looks at typical engineering tasks in traditional engineering domains. An attempt will be made to abstract these tasks to show that they are directly mappable to object-oriented problem-solving methodologies.

## 9.2 The Nature of Engineering

### Introduction

Engineering is the application of the scientific methodology and thought processes to the solution of real-world problems. Work in engineering spans the continuum from design to basic engineering science. Design is the process of creating new artifacts for our world. Basic engineering science seeks to uncover new truths about our world that will eventually contribute to the solution of real-world problems. Many of the various engineering subfields tend toward one of these two extremes, whereas other subfields have strong components across the continuum.

Few would disagree that the major component of engineering is problem solving, both algorithmic and heuristic. Many engineering problems are
solved using mathematical methodologies captured in algorithms, whereas other problems use inexact "rules of thumb," or heuristic reasoning.

The unifying thread of engineering is problem solving. Major conceptual methodologies support problem solving, such as knowledge organization and reasoning methodologies. Knowledge organization is an essential ingredient of engineering practice, required for concept derivation, background information composition, and analytical reasoning. Library information and common-sense knowledge have long served the engineering profession; however, as the limits of knowledge about things and how they work grow, traditional knowledge organization methods may be insufficient for future generations of engineers. Similarly, reasoning has traditionally taken two forms: *algorithmic* and *heuristic*. The former deals with clearly procedurally specifiable methodologies, for example, the calculation of a Fourier transform, stresses on mechanical parts, friction and wear coefficients, and so on. Normally derived from basic scientific principles, algorithmic methods have been a fundamental ingredient in the engineer's tool kit for many decades. Heuristic reasoning is seemingly quite different; heuristics, or rules of thumb have also been a traditional tool in the engineer's tool kit. Much of the "feel" of engineering lies in the application of heuristics to problems. An expert engineer can often solve problems quickly through the use of heuristic approximations. This type of reasoning may well represent a mental distillation of algorithmic methods into "intuition," or a sense of what the outcome would be if an algorithmic method were applied to a problem. Indeed, heuristic and algorithmic methods are simply different ways of approaching problem solving in less and more structured ways.

## Engineering Science and Design

Engineering science and the pure scientific method differ very little, perhaps only with respect to ultimate goals. That is, science seeks new knowledge without specific purpose other than understanding the world better. Engineering science has the same thrust but with the goal of understanding in order to facilitate application. Acquiring new knowledge requires observation and experimentation, evaluation, and modeling. Analytical methodologies attempt to decompose a problem into subparts, whereas synthesis seeks to recompose parts into a whole.

At the opposite end of the engineering spectrum lies design, the set of activities that leads to the creation of new objects. Design consists of conceptualization, specification, the use of analogy and analysis, prototyping, refinement, and simulation. Following design lies manufacturing, testing, and maintenance which are also part of engineering.
The tasks of engineering, discussed previously, are generalizable across disciplinary areas of engineering and, indeed, to other disciplines as well. There are clear parallels between the engineering method and the object-oriented methods which will be explicated later in this chapter. Concepts discussed in previous chapters concerning abstraction, encapsulation, reusability, and object-oriented methods for analysis and design are not often discussed in engineering. It appears plausible to suggest that the techniques that have been studied should be applicable to a wide range of engineering problems. After a deeper examination of problem solving in engineering, an attempt will be made to show how object-oriented problem-solving techniques can facilitate engineering.

## The Engineering Fields

The next paragraphs examine the characteristics of several engineering fields in an attempt to discover commonalities and abstractions of the kinds of activities that are conducted in engineering. Table 9.1 displays a listing of some of the most prominent engineering fields, along with a rough assessment of the amounts of design and engineering science components found in each area. This assessment is shown as a continuum across the *design ↔ science* spectrum.

<table><caption>**Table 9.1** Loose Approximation of the Design and Engineering Science Components of Subdisciplines in Engineering</caption><thead><tr><th>Subfield</th><th>Design</th><th>Engineering Science</th></tr></thead><tbody><tr><td>Civil engineering</td><td></td><td></td></tr><tr><td>Chemical engineering</td><td></td><td></td></tr><tr><td>Electrical engineering</td><td></td><td></td></tr><tr><td>Computer engineering</td><td></td><td></td></tr><tr><td>Mechanical engineering</td><td></td><td></td></tr><tr><td>Biomedical engineering</td><td></td><td></td></tr><tr><td>Environmental engineering</td><td></td><td></td></tr><tr><td>Agricultural engineering</td><td></td><td></td></tr><tr><td>Aerospace engineering</td><td></td><td></td></tr><tr><td>Materials engineering</td><td></td><td></td></tr><tr><td>Manufacturing industrial engineering</td><td></td><td></td></tr></tbody></table>
*Civil Engineering.* Generally speaking, civil engineering is concerned with the analysis and design of structures, including buildings and transportation systems. Design in civil engineering often requires extensive analytical tools; yet other aspects utilize heuristic elements of design. Knowledge organization, reasoning, and algorithmic solutions are all needed in civil engineering.

*Chemical Engineering.* Chemical engineering applies basic knowledge about chemistry to the design and operation of plants and processes for the production of materials for use in our society. For example, chemical engineers study methods for designing plants and processes to manufacture such products as paper, pharmaceuticals, fibers, paints, and so forth. Simulation of plants, understanding of constraints in processes, and design analogy are components of the knowledge needs of chemical engineering.

*Electrical Engineering.* Electrical engineering is concerned with electrical phenomena, including electronic circuits, computers, communications, control, and the study of systems. Electrical engineering is both knowledge and design intensive. Characterized as the broadest engineering field, electrical engineering requires all the basic knowledge intensive tools, as well as both algorithmic and heuristic reasoning techniques.

*Computer Engineering.* Computer engineering is concerned with the design of computers and the software required to operate computer systems. Computer engineering deals with all aspects of computer systems, including design and fabrication of computers, as well as the creation of application software, for example, software for computer-aided design and electronic simulation. In contrast to computer science, which seeks to discover new knowledge about computation, computer engineering is a practical field emphasizing design.

*Mechanical Engineering.* Mechanical engineering deals with machines and mechanical processes. Mechanical engineering requires considerable three-dimensional visualization capabilities, relies heavily on analogy for design, and shares many common algorithmic methodologies for control with electrical engineering.

*Biomedical Engineering.* Biomedical engineering is concerned with the application of engineering principles to the field of medicine. Biomedical engineering is one of the more science-oriented engineering disciplines, tending toward the use of analytical methods more than design.

*Environmental Engineering.* Environmental engineering seeks an understanding of how to improve our environment through the use of engineering methodology.
gies. Modeling and simulation are heavily used and there are many cross linkages with chemical engineering.

***Agricultural Engineering.*** Agricultural engineering applies engineering principles to food and food production. Combinations of analytical methods apply here, as well as heuristic reasoning.

***Aerospace Engineering.*** Aerospace engineering deals with the design and fabrication of airplanes, rockets, and the other elements of aeronautical endeavors. One of the more highly mathematically and computationally bound engineering disciplines, heuristics tend to play a minor role.

***Material Engineering and Science.*** This field studies the basic properties of materials. The basic scientific method is found in this field in much more prominence than design. Presentation and understanding of information are critical.

***Manufacturing/Industrial Engineering.*** Turning designs into reality is the responsibility of manufacturing and industrial engineers. Methodologies for automating manufacturing facilities are studied, as well as applying engineering methodologies to industrial processes.

***Education.*** Education in engineering is normally broken into subfields, including those discussed previously. An analysis of the attributes of the activities in each of the engineering subfields argues that there should perhaps be more common educational activities because the engineering disciplines appear to share many common needs and methods.

## 9.3 Evaluation of Common Requirements in Engineering

Examination of the fields of engineering permits consideration of the commonalities in the different engineering fields and identification of the abstract activities that provide bridges across the fields.

### Knowledge Representation

Knowledge representation appears to be a central issue in all the engineering fields. Indeed, the need to represent knowledge extends into every corner of human inquiry, because representation is almost a prerequisite to understanding and problem solving. What is knowledge representation? In
examining the fields of engineering, knowledge in engineering is the representa-
tion of the area of interest in terms of a *model*, where a model may take on very
different representations depending on the area. For example, a model might be
a complex set of equations that describe a physical phenomenon being studied
or a set of constraints in a spreadsheet. The term *model* is so broad that it can
be used in most cases to simply indicate that knowledge is being organized in a
way to make concepts more understandable. In this chapter, with particular
reference to the *model* of the model-view-controller paradigm, a *model* is any
representation technique that describes the problem being examined without
reference to the *view* or *controller*.

Laws, Algorithms, and Methodologies

Basic knowledge about the physical laws, the algorithms that imple-
ment procedures, and the methodologies that describe ways of accomplishing
activities are the most usual knowledge that needs representation in engineering
problems. Laws, as manifested in algorithmically specified equations, are the
backbone of engineering. Basic “commonsense” engineering relates to the laws
derived from basic science. Algorithms, of course, are the manifestation of
mathematical expressions in a computer-consumable form. Methodologies can
be described as plans, or sequences of steps that when applied to a problem
result in a solution. Most engineering activities include considerable use of
mathematics and statistics for problem solving.

Engineering Reasoning

Reasoning methodologies are not as clearly understood as the use of
laws, algorithms, and methodologies for problem solving. Reasoning can often
take the form of applying well-understood algorithms to a problem. However,
problems are not always amenable to the use of solutions that fit a problem
exactly. Hence, there is a need for representation of heuristic reasoning meth-
ods that capture rules of thumb.

Domain-Specific Knowledge

Each domain in engineering has detailed specific knowledge that must
be representable in retrievable and understandable fashions. For all the engi-
neering fields discussed previously, it is clear that domain-specific knowledge is
essential. Each field works with different knowledge; yet it is plausible to make a
conjecture that all could utilize common organization and understanding
methodologies.
## Presentation and Visualization

Common to all the engineering disciplines is the clear need for presentation and visualization facilities. Presentation mechanisms have become well developed in engineering, resulting in many graphics and computer-aided-design packages that permit engineers to view the results of analysis and design activities. However, mechanisms for visualization are not so well developed. Decomposition of problems and the graphical visualization of problem parts and how parts interact is an immature field. For example, the visualization of causal relationships in design and trade-offs in the design process are currently difficult to visualize in engineering design. For assisting in understanding knowledge, automated visualization tool kits are also underdeveloped. There are few methods available that provide simple pluggable graphics interfaces to engineering systems.

## Modeling and Simulation

In many ways, review of the engineering fields leads toward the observation that modeling and simulation are central to the engineering effort. Modeling, of course, is directly related to knowledge representation in that the model of a system is indeed the representation of information about the system. Simulation, in contrast, is the behavioral manifestation of the model and its results are best presented in an easily observable (i.e., graphical) fashion.

Many simulation systems used in engineering require users to interpret the results of a quantitative simulation but provide few facilities for understanding how the simulation relates to the problem. “Tedious” and “difficult to use” are terms that could be applied to many traditional simulation systems. Why? Probably because there is a fundamental cognitive mismatch between the representation and the problem. Historically, in most cases, simulation systems were developed using procedural languages long before the concepts of mapping programming languages to the world were invented. Hence, traditional simulation systems reflect the mismatch between the programming paradigms used and the needs of the engineering simulation.

## Control

Control is an aspect of engineering common to electrical, chemical, and mechanical engineering. Automatic control, which is control untouched by humans, is usually algorithmic and mappable to procedures. However, the ability to experiment with control algorithms has been severely limited by the
algorithmic nature of the coding methodologies. Perturbations to, and experimentation with, control methods are hard to visualize in simulated systems.

A second method of control is the direct linkage of direct-manipulation interfaces to systems that require control. Humans controlling complex systems need long experience and understanding to provide reasonable control. For example, control of a nuclear power plant requires definite expertise or disastrous results could occur. Direct-manipulation interfaces with built-in intelligence could assist in providing more intelligent control for complex devices that would assist a human user.

Next, a direct comparison of engineering problem-solving requirements and object-oriented methods will be undertaken.

## 9.4 Engineering and Object-Oriented Problem-Solving Methodologies

The characteristics of object-oriented problem solving for engineering will be described in general in this section. Section 9.5 will present several examples that tie together the general concepts presented in this section. Figure 9.1 compares typical engineering and object-oriented problem-solving methods. The left column displays the typical steps involved in engineering design and the right column displays the equivalent steps using object-oriented techniques.

### Concept Formation

The first step in understanding how to solve a problem is to organize the concepts about a problem. In analytical problems, the end-point goals for the analysis are specified, and for design problems, the specification for the object being designed is created. The engineering method has no clear formalism at this point; indeed, ad hoc methodologies for concept formation seem to be the norm. For object-oriented methods, the same is essentially true, except that the framework into which the problem will ultimately be cast gives some structure to concept formation. For example, one can consider several alternative structures for a model, ask what an ideal view should be, and question how the system created should perform. Although such questions fit cleanly to problem understanding in the context of the MVC-paradigm organizations presented in the previous chapter, it appears that the same questions might also lead to engineering design concept formalisms.
<figure><img src="image_107.png" /><figcaption>**Figure 9.1** Comparison of Engineering Problem Solving and Object-Oriented Problem Solving.</figcaption></figure>
## Problem Decomposition

Once concepts are formed, a problem should be decomposed into understandable parts. Decomposition is a typical engineering methodology that works for object-oriented systems as well. For the latter, however, one can decompose according to whole-part hierarchies and inheritance hierarchies (see Chapter 2), whereas in engineering design and analysis, decomposition is traditionally only whole-part.

## Background Review/Organization

Problem solving requires background knowledge. Typical engineering efforts review background material and attempt to secure as much information as possible in the domain of interest. For software systems, this would include searching for code that can be used in an application. For object-oriented methods, a review of objects in available class libraries is needed so that a minimum amount of coding will be required.

Organization of knowledge in an application is critical for the design of any system. In engineering systems, attributes of the designed artifacts will need to be specified according to accepted norms and referenced to constraints that may change attribute values. Similarly, for object-oriented design, the influence of objects on each other as manifested in the methods in protocols needs to be clarified. Once knowledge grows to a level that exceeds raw human comprehension, automated tools for organizing knowledge must be sought, for example, hypertext organizations of information that permit handling large amounts of information (see Chapter 11).

## Prototypical Design

Once preliminary design decisions are made for both engineering designs and object-oriented designs, specifications can be made and a prototype created. In engineering, it is typical to fabricate a rather complete specification for the end product and to work to build that product. In contrast, object-oriented design prefers the so-called "scruffy" approach in which a prototype is built from a very loose design and refined continually until the product is complete (some say that object-based systems are "debugged" into existence). The fact that these design preferences even exist gives some hint about the nature of design using traditional techniques and design using objects. In the traditional top-down approach, a complete specification drives the creation of a system, yielding little to experimentation or modification along the route. Thus, initial conceptualization and specification must be correct. In contrast, object-
oriented methods permit simple refinement as implementation of a prototype
proceeds. In part, this capability is due to the modularity afforded by object-ori-
ented systems and, in part, to the capability for refinement by inheritance.

Analogy is used in engineering design; that is, old techniques and knowledge that have worked before are examined and reused to the greatest extent possible. Although analogy is heavily used in engineering, there is no explicit formalism for supporting reuse as there is in object-oriented design. Standard engineering components such as circuits, electrical components, and mechanical subassemblies are commonly reused in the process of engineering design. This type of reuse is roughly analogous to object-oriented design, although no specific formalism is widely used to assist engineering designers in reusing existing components. Reusability of objects in the object-oriented methodology is a key factor in object-oriented design. Designing from reusable components permits the creation of new objects much more quickly than having to begin from scratch. Auer's (1989) observation perhaps captures the essence of this concept: "The fastest way to produce code which is well designed, written, and tested is to already have it."

## Constraint Satisfaction

Constraint satisfaction is the process of considering trade-offs. Financial constraints can be handled in engineering projects in a direct fashion using spreadsheets, for example. However, beyond simple understandable numeric relationships, the matter of understanding trade-offs becomes difficult. For example, consider the creation of a new product in which there are various competing constraints: time to market, customer satisfaction, quality, development costs, and product costs. These different quantities and qualities impose constraints on the design and ultimate manufacturability of a product. In engineering systems, working with constraints of this type are poorly handled. Constraint satisfaction in object-oriented methodologies is also a problem, perhaps less so because of the built-in abstraction provided by inheritance using abstract classes and the constraining paradigm afforded by the model-view-controller. Indeed, the trade-off problem discussed previously may be no easier to understand using object-oriented methodologies, but the code would likely be easier to code and maintain than traditional code.

## Simulation

There are few, if any, clearly systematic methods for simulation in traditional engineering. Each domain contains hundreds if not thousands of special-purpose simulation systems which may or may not meet the needs of any
particular user. Most packages have been built without regard to interfacing
with other packages; hence, there are virtually no standards! This situation is,
unfortunately, true also in the object-oriented programming world. However,
there is a conceptual base for standards in simulation, both analog and digital.
Various ideas for interfacing to simulation packages and creating simulation
frameworks will be discussed in upcoming chapters.

The analogy between simulation in an engineering design and an
object-oriented design is the rapid prototyping/debugging cycle in the latter.
Simulation in engineering yields knowledge about whether the projected prod-
uct will work. In creating object-centered systems, applications are often de-
bugged into existence yielding the same type of knowledge, except that the
knowledge now permits a prototype of the product to continually mature during
rapid refinement cycles.

Refinement

Refinement is required in any analytical or design setting. Certainly,
the coupling of refinement steps and simulation is suitable, because it is not cost
effective to manufacture a product until a simulation of the product has been
satisfactorily refined. Refinement in object-oriented design is not as critical; in
fact, refinement needs to be taken more seriously in object-oriented program-
ming. There is a tendency, once a program works, to simply stop coding.
Refining steps should be to abstract the common features of objects and to
reorganize the class inheritance hierarchies, so that the objects created can be
reused by others.

Fabrication

Fabrication is the actual creation of an entity from a design. In
engineering, this step is taken by actually manufacturing the product. In
programming, the step is taking by extensive testing and polishing of the user
interface.

System Creation Considerations

*Presentation Methods.* There are, of course, many alternatives for presentation of information and different techniques for implementing user interaction with engineering and computing systems. Problems in presentation of information are essentially the same for both engineering and computing systems. Engineering systems, although often designed for special purposes, have reached the
point where presentation and user interface considerations are essentially the same as for systems that are software intensive. In general, one can hardly make a clear distinction between a hardware-intensive system and a software-intensive system. In both, there is a significant need for interaction with the user and presentation of information. In fact, some hardware systems are now actually software systems that mimic hardware (e.g., the modern oscilloscope has a highly developed user interface that appears similar to an interface to a traditional hardware oscilloscope, but is, in fact, created by software!).

For computer-based systems that organize information, interpret findings, provide control, give advice, and assist in the analysis and design of systems, the direct-manipulation methods discussed in the previous chapters are among the most appropriate type of interface. Decisions about the modalities of presentation, such as whether to use video, voice commands, speech output, command line interfaces as well as GDMIs, remain a difficult problem for the designer. In building most engineering systems, because integral computer facilities are normally part of most complex engineering systems, these issues must be addressed by engineering designers. These same considerations are also true for software designers using object-oriented techniques. The object paradigm, per se, does little to assist in understanding how best to construct the user interface for a system. The major advantage to the object-oriented techniques discussed in this text are the organization and simplification capabilities afforded by the MVC factorization methodology.

*Inference*. A second issue deals with the level of inference or "intelligence" that systems should contain. It is easy to understand the plausibility of adding intelligence to most engineering systems. For example, an intelligent measurement instrument would have the capability of making inferences about what is measured or an intelligent traffic control system could adapt its control strategies to the information it secures on-line about the current state of traffic. In computer systems, the same notions are plausible and can be extended to the concept of monitoring the user of a computer system and adapting the way that the system presents information based on the needs of the user. Large analysis and design systems could contain mechanisms for making inferences during analysis or design sessions to permit dynamic restructuring of analysis or design procedures according to the inferences made.

*Design Frameworks*. The concept of frameworks relates to problem solving in engineering. A framework is a skeletal tool that helps a user construct or analyze situations. Smalltalk-80 can, in fact, be considered a framework, because the language plus the environment facilitates the design of software systems. In the electronics world, frameworks capture specific knowledge about components and methodologies that are useful for design. Other domains have similar frameworks that capture knowledge in their domains. The evolution of
design, analysis, and synthesis frameworks speaks to the continually evolving and expanding knowledge that exists in the world. There are clear needs to capture this knowledge and present it to users in a way that the knowledge is readily usable. Object-oriented analysis and design methodologies precisely fit this need!

***Knowledge Organization and Modeling.*** In the design of any engineering system, ways of organizing knowledge and capturing and presenting models of the world in which the designed systems work are critical. Knowledge can be organized as frames, in rules, captured in objects or in many types of data structures. Again, as discussed previously for the framework problem, organizing schema are needed to permit designers/analysts to create standard and sharable organizations of knowledge and models. Until this step is taken, design frameworks will remain monolithic entities with little capability for sharing information. Object-oriented techniques, trading particularly on the encapsulation concept, have the potential to fill this need for methods for standardization or, at least, provide conversion protocols between different applications that use different kinds of representation mechanisms.

***Refinement.*** In today's engineering systems, there is often little capability for changing the characteristics of a system once it is built. For most software packages, this rigidity is also found, but to a lesser extent. It is plausible to suspect that future systems will permit augmentation of system capabilities by the user to fit specific needs. Although few current commercial engineering packages permit such flexibility, one can see the outlines of these possibilities in object-oriented packages that permit refinement because of the specialization of classes.

## Summary of Abstract Concepts

In the preceding sections, a number of abstract concepts associated with engineering design, analysis and synthesis, knowledge representation and modeling, simulation, visualization, understanding, and analogy were discussed. In several cases, it was suggested that object-oriented methodologies permit implementation and facilitation of these abstract concepts in real systems. In the early 1990s, systems that are completely inspectable, modular, and that allow simple and understandable extensions are not yet commonplace and no frameworks have been developed to assist users in organizing knowledge according to these abstract concepts. It is postulated that the object-oriented methodologies described in this text will assist in reaching the goals of producing flexible, understandable, and adaptable engineering systems in the future.
Early examples of the capabilities of such systems exist in simulation and design frameworks, knowledge browsing systems, and inference systems. The next section of this chapter demonstrates some early steps taken in creating object-oriented systems for use in engineering domains. Examples are given in several primary areas in engineering.

## 9.5 Characterizing Problems Using the Model-View-Controller Paradigm

The model-view-controller paradigm of Smalltalk-80 provides a unique and useful organizing methodology for creating real working systems for engineering analysis and design problems. Some concrete examples of systems that have been built or designed based on the MVC are described next. Note that the utility of the concepts presented are not limited to ST-80; however, because ST-80 has one of the best developed environments for supporting building examples using the paradigm, only ST-80 examples are given. In each example, the components examined in detail in Chapter 8 will be discussed. The reader is encouraged to consider each example and attempt to relate the programming structures that support each application to the fundamental models, views, and controllers discussed previously.

### Civil Engineering

Figure 9.2 revisits the traffic flow example presented in Chapter 1. In this example, the primary purpose is to permit visualization of traffic approaching an intersection. The user is able to change stochastic (i.e., random) variations in traffic density in order to study the influence of how control of the lights at the intersections will affect waiting queues. The main view of the traffic flow simulator shows a diagram of a street plan feeding a highway. The concept is to provide the user control of the traffic lights and specification of the random variation of the arrival of automobiles at the intersections. The display permits viewing of the traffic density on the highway, as well as the waiting queues at the intersection of the feeder streets.

A canvas view (see the Appendix) is used for displaying the street pattern, which can be drawn using a **FormEditor** (Version 2.5) or host platform drawing package (Release 4) and used in a **CanvasView**. The small rectangles shown represent the automobiles queuing at the lights. Ordered collections are used to represent each queue for each light. The arrows in the view represent the direction of traffic flow. The only animation components in this image are adding and removing small iconic images, which simplify creating the appear-
<figure><img src="image_108.png" /><figcaption>**Figure 9.2** A Traffic Flow Simulator.</figcaption></figure>

ance of animation. On the left of the window is (1) a list of buttons for controlling the simulation and (2) a scrollable **SelectionInListView** that contains the different options for probability distributions. Each button, when pressed, permits more options to be explored in a separate view. For example, "Add Street" will allow editing of the image used in the canvas. A more sophisticated system would allow automated addition of or modification to a street. The "Change Direction" button produces a crossHair cursor which the user can position over the arrows in the canvas; clicking once changes the direction, twice terminates. Setting light and flow rates brings up a table which allows selection of the lights and specification of their stochastic attributes and specification of the flow rates on each of the streets.

The top of the window shows the output results: Two diagrams are displayed in individual views that indicate traffic flow rates on the highway and on the streets. Note the selection buttons at the left of each of the data displays which allow choosing which intersection to view and whether to examine traffic
flowing east or west on the highway. The flow graphs are created by drawing on the image. The underlying model of this simulation is a discrete-event simulation system which will be discussed in Chapter 14.

## Chemical Engineering

Figure 9.3 shows an example of an assistant system created for simulating chemical separation problems in chemical engineering (Debelak, 1990). The main view contains a network of representations of chemical separator systems. The concept is that a compound containing various chemical components is to be separated into various products and subproducts by arranging a series of separators, each of which will separate components in different ways. The user can select building a specialized system by using the buttons marked "add separator" and "connect separator." The input to the system can be selected using the compound dictionary shown at the top left of the view and pressing the button marked "select feed," where the "feed" is the input to the series of separators. There are various rules attached to the simulation, such as "select the cheapest compound to remove first," which are embodied in rules. These rules can be edited by pushing the "edit rules" button.

<figure><img src="image_109.png" /><figcaption>**Figure 9.3 A Chemical Separation Assistant System.**</figcaption></figure>
Flow rates can be set, as indicated. For each of the separators, various constraint equations can be used to propagate information forward about the materials separated in the simulated system. Each separator contains its own constraints which can be modified by pressing the button marked "set constraint" in the separator representation. Also, information about each separator can be inspected by pressing "inspect." Gauges are used at the output of each separator to show the amount of material in the compound at each stage of the process. Finally, "run" permits the simulation to run with the values set.

## Electrical Engineering

Figure 9.4 displays a view from a diagnostic system created to analyze failures in electronic circuit boards. Based on the Dempster-Shafer theory (Shafer and Logan, 1987), the system displays a hierarchical diagram of causes and effects (shown in the large view in the background of the figure and in the "greeked" view at the bottom left of the window) and a view of the components on a view of the actual circuit board. The organization of the view is simple: A series of control buttons are at the top of the window. In different parts of the diagnostic process, buttons appear with labels; at some points the labels are blank, thus providing no action. A transcript is provided at the left of the view and a **FillInTheBlank** pop-up view is used to secure information from the user, as shown. By answering questions about the status of a physical board, recommendations on how to repair a circuit board are given. The probe shown on the figure is interesting. It is simply an opaqueForm (i.e., an OpaqueImage) that can be moved to different positions on the board to permit sensing of what the proper voltage is at that point. Points are sensed by comparison of the probe point location with a dictionary of points at which voltage levels are available.

Figure 9.5 shows a second electrical engineering example dealing with circuits. In this example, an electronic lab bench is simulated that permits the placing and monitoring of electronic components. The array of buttons to the left allows placing of various types of electronic components on the canvas as opaqueForms (opaqueImages in Release 4) and controlling of the operation of the system created. This particular example was taken from a prototype of a tutorial system for electronics built in Smalltalk-80.

## Mechanical / Manufacturing Engineering

Figures 9.6 and 9.7 display two views of parts of a system built for the evaluation of statistical process control (Bourne et al., 1989). This system was designed (1) to acquire knowledge about the causes of out-of-control conditions
<figure><img src="image_110.png" /><figcaption>Figure 9.4 Electronic Diagnostic System. (©1989 Association for Computing Machinery, Inc. Reprinted by permission.)</figcaption></figure>
<figure><img src="image_111.png" /><figcaption>Figure 9.5 A Simulated Electronics Laboratory.</figcaption></figure>
<figure><img src="image_112.png" /><figcaption>Figure 9.6 A Knowledge Acquisition View for Statistical Process Control. (With permission; Kirk Karwan and James Sweigart.)</figcaption></figure>
<figure><img src="image_113.png" /><figcaption>Figure 9.7 The Diagnostic View for a Statistical Process Control Advisory System.</figcaption></figure>
in manufacturing processes and (2) to diagnose problems in malfunctioning manufacturing processes. Because the knowledge acquisition part of the system precedes the use of the system for diagnosis, two separate views were created. The first view, as shown in Figure 9.6, was used to acquire knowledge in the form of a hierarchical, or fishbone, diagram which related causes of problems to the problem. The window layout consisted of control buttons at the top of the window, a transcript view, four SelectionInListViews that corresponded to the successive subelements of parts of the tree, and a graphical view of parts of the tree. Once this information was collected, including probabilistic information, links between events and problems, and historical information, the system could be used for diagnosis as shown in Figure 9.7. This figure shows the diagnostic view, in which the fishbone diagram is exhibited and diagnostic results given in the left view of the window. This figure is basically the same as the diagnostic system described previously for electronic systems.

## Environmental Engineering

An example of using the MVC paradigm in ST-80 for building a groundwater tutoring system in environmental engineering is shown in Figures 9.8 and 9.9. This system has multiple views which are activated from a control panel that allows the opening of several different windows. Figure 9.8 shows an "information center," which basically systematizes information about groundwater into a set of hypertext graphs. As shown, there are a series of views, each containing information. The graph in the second view holds a set of nodes and links. Each node contains additional information which, when pointed to by the cursor and when the mouse button is clicked, appears in successive views and the textView at the bottom of the window. Figure 9.9 shows how data can be easily displayed for the groundwater problem. The problem is described graphically at the top right with attendant data just below. A family of curves is plotted to the left of the view based on the data acquired. As usual, a series of buttons are arrayed along the bottom of the window to provide control. Complete details of this system are contained in Bourne et al. (1989).

## Biomedical Engineering

Figure 9.10 shows an example of the use of the MVC paradigm in solving a biomedical engineering problem (Haden, 1989). This example shows a large view on the right of the window which is used to display different sections of the brain and to enlarge and reduce images. These images are CAT scans
<figure><img src="image_114.png" /><figcaption>Figure 9.8 The Information Center for the Groundwater Advisory System. (With permission; Academic Computing.)</figcaption></figure>
<figure><img src="image_115.png" /><figcaption>Figure 9.9 Interaction of Flow and Solute Transport in the Groundwater Advisory System. (With permission; Academic Computing.)</figcaption></figure>
<figure><img src="image_116.png" /><figcaption>Figure 9.10 A User Interface in Biomedical Engineering: Display of CAT Scans. (With permission; G. Haden.)</figcaption></figure>
that provide multiple-color images; the black-and-white images shown here
provide a striking display when viewed in color. The design of this system was
similar to the systems described previously; all control information is on the left
of the window. There are some different features, however. For example, there
is a transcript window at the top of the view that provides continuous informa-
tion about the display. Next, buttons are shown as checkboxes with the names
beside them. This type of display can be easily created by instantiating small
buttons and writing the names of their function adjacent to the button rectangle
(see the class DialogView). Gauges are used for color control in this example
and SelectionInListViews provide other image information as shown at the
bottom of the figure. Perhaps the most interesting part of this example is the
finding that one is not constrained by the original "look and feel" of the ST-80
system: It is simple and straightforward to create alternative view appearances.

So, what are the lessons learned from examination of these different
examples in several subfields of engineering? One lesson is that it is surprisingly
easy to use the same representation paradigms to represent and visualize
information in different fields. Although these examples do not, of course,
pretend to represent all of the things that are possible to do in engineering, they
do at least provide some evidence that information factoring into the MVC triad
is useful in a variety of engineering situations. It would not be surprising to find
that the methods suggested can be broadly applied. Another lesson is that it is
easy to transform the tools supplied into unique and interesting displays of
information. The last lesson is that it is straightforward to integrate these
visualization and display tools with algorithmic methods as in the environmental
engineering example.

9.6 Capitalizing on Abstraction and Reusability

To build object-oriented systems that assist in solving engineering
problems most efficiently, one needs to capitalize on abstraction and reusability.
As discussed in some detail previously, there are currently no high-level abstract
objects that can be specialized that deal with topics such as design, analysis,
analogy, and so on. However, there are various lower-level abstractions in the
ST-80 system that can be used for system building. Furthermore, there is
considerable code that is reusable and does not have to be recreated. The next
few paragraphs examine some of the classes that can be used for system
building. The reader should consider if it is possible to build abstract and
reusable classes that are more specific to engineering that would augment the
classes discussed next.
<table><caption>**Table 9.2** Common Abstract Classes</caption><thead><tr><td>Class Name</td><td>Description</td></tr></thead><tbody><tr><td>Object</td><td>Superclass of all classes in ST-80</td></tr><tr><td>Stream</td><td>Superclass of all stream operations, PostionableStream, ReadWriteStream, TextStreams, etc.</td></tr><tr><td>Collection</td><td>Superclass of many classes including: Bag, OrderedCollection, Set, Array, String, Dictionary</td></tr><tr><td>Magnitude</td><td>Superclass of arithmetic operations including: Number, Fraction, Integer, Float, Point</td></tr><tr><td>Model</td><td>Adds dependencies to the class Object</td></tr><tr><td>View</td><td>Superclass of the views, e.g., ListView,TextView</td></tr><tr><td>Controller</td><td>Controller for the MVC triad: including StandardSystemController and ControllerWithMenu</td></tr></tbody></table>

## Abstraction

Table 9.2 displays a number of common abstract classes in ST-80 that are subclassed in the ST-80 system. These abstract classes, when subclassed, provide many of the classes commonly needed by Smalltalk programmers. Most classes have been discussed extensively in previous chapters. This listing is provided to link with consideration of building of abstract classes for supporting applications. When building applications, it is useful to keep the abstraction paradigm in mind and to try hard not to reinvent new code. For example, in building representations for electronic circuits in Chapter 3, the TwoInputGate was discussed as an abstract class for the AndGate and OrGate. The TwoInputGate is never instantiated but provides a common protocol for its subclasses. Similarly, if one were creating a system for use in chemical engineering dealing with flow through pipes, one might create a class called Pipe, which could be subclassed into, for example, PipeWithFriction and PipeWithLeak.

## Reusability

The issue of reusability is very keenly argued in many quarters. Engineers and programmers who create new software normally do not consider the possibility of code reuse, except for using libraries of functions or using standard modules that solve specific problems (e.g., an FFT module). Most often, software is written "from the ground up" and the concept of spending
<table><caption>**Table 9.3** Common Reusable Classes in Smalltalk-80</caption><thead><tr><th></th><th></th></tr></thead><tbody><tr><td><strong>The classes used for models</strong></td><td></td></tr><tr><td>Arrays</td><td></td></tr><tr><td>Ordered and SortedCollections</td><td></td></tr><tr><td>Sets and Bags</td><td></td></tr><tr><td>Dictionaries</td><td></td></tr><tr><td>Strings</td><td></td></tr><tr><td><strong>The classes used for views</strong></td><td></td></tr><tr><td>Buttons</td><td></td></tr><tr><td>DialogView</td><td></td></tr><tr><td>Text and CodeViews</td><td></td></tr><tr><td>ListView and SelectionInListViews</td><td></td></tr><tr><td>Various Pluggable GaugeViews</td><td></td></tr><tr><td><strong>The classes used for controllers</strong></td><td></td></tr><tr><td>StandardSystemController</td><td></td></tr><tr><td>ControllerWithMenu</td><td></td></tr></tbody></table>

time to understand how to reuse code is a foreign one. Moreover, the reuse of code is discouraged because of code infringement and the rights of writers of software. In making a new commercial product, one wishes the code to be completely new. Hence, there is a problem! Reusability permits rapid building of new systems; yet code must be in the public domain or part of purchased packages before it can be used. ST-80 code is completely reusable—but only to those who purchase the license for ST-80. Fortunately, licenses are quite inexpensive, particularly for university users. The point to be made is that, if progress toward reusability of code in engineering is to be made, libraries of useful abstractions in code will need to be made available or widely sold.

Table 9.3 displays some of the more prominent classes that are reused frequently by Smalltalk-80 programmers. The classes shown are by no means all that one should consider; however, these classes were used extensively to create the examples given previously. Consider that Table 9.3 only shows one "foreign" package of tools, Pluggable Gauges (Adams, 1987)—used for creating gauges in one of the systems described previously; the remainder of the standard tools are in the ST-80 package. If many pluggable components became available for use, it is anticipated that programming productivity would soar.

## 9.7 Building Object-Oriented Solutions to Problems

The major advantages of creating object-oriented solutions to engineering problems in ST-80 are (1) the availability of excellent graphics and user
interface facilities, (2) reusability of classes, and (3) integrated environmental tools that facilitate creation of applications. In considering building an application in the model-view-controller paradigm, it is useful to think of the MVC triad as representation (= model), the user interface (= view), and control (= controller).

The application builder should first consider the representation desired to determine if the information that needs to be represented can be cast into one of the available classes in ST-80. Usually, this is possible, although it may be useful to create other representations for special purposes. For example, representing a semantic net would require additional representation capabilities (see Chapter 11).

The most thought in building an application should be given to the user interface as manifested in the views. This line of thinking is somewhat different than normal application building techniques. Designing starting with the interface has the advantage that one can consider a series of scenarios or “storyboards” that represent what the user should see. The idea of a storyboard is that one creates a story of the interaction with the system. Because system components are directly controlled in the direct-manipulation interface, the application builder can readily allocate interface connections (buttons, etc.) to the conceptual components of the application.

In initially building an application, it is normally not necessary for the programmer to consider control aspects. The default facilities provided by the StandardSystemController and ControllerWithMenu are usually sufficient for an initial prototype.

There is, in some applications, the need to interface to other application programs or framework packages outside Smalltalk. Next, how to integrate such external programs to MVC-built systems will be examined.

## 9.8 Coupling to Traditional Solutions: Building an Integrated Problem-Solving Environment

Even though this text promotes the use of object-oriented solutions to engineering problems, there remain various problems that can be solved directly using “traditional” solution paths. Next, we consider the nature of traditional methodologies and tools and discuss how such systems can be integrated with the object-oriented approach.

### Traditional Solutions

Typical computer-based programs that provide solutions to complex problems have almost always been domain-knowledge intensive. For example,
many complex and detailed design and simulation packages and algorithmic analysis packages have been created with great effort over a period of many years. Recoding such packages in an object-oriented style would be unreasonable, because detailed knowledge has been gathered and much effort expended to create special-purpose application packages. If such packages can be used to assist in problem solving, it is worthwhile to consider "coupled" systems in which object-oriented methods are coupled to standalone application packages. Efficient software realizations of algorithms fall in the domain of "traditional" solutions. For example, it would make little sense to recode a fast Fourier transform algorithm in an object-oriented paradigm if it already exists. Instead, it makes more sense to simply integrate the code with the object-oriented code.

## Coupled Systems

Figure 9.11 graphically indicates the nature of coupled systems for object-oriented systems. The central core of the diagram shown contains the ST-80 language and environment. A C-language interface is shown around the core that provides an interface to various types of traditional code including, but not limited to, simulation packages, frameworks, drawing and word processing packages, algorithms, and inference tools. ST-80 provides a C-language interface that permits message sending in ST-80 that results in execution of a C procedure. Variables can be passed and returned between the languages. The basic methodology used is to link C object files to the Smalltalk virtual machine and to provide primitive calls that are built into methods that call C code. For example, a Smalltalk method for running a primitive in a class called `InferenceEngine` might be

run

"InferenceEngine run"

<primitive: 10001>

The `"<primitive: 10001>"` statement provides a link to specific user-defined compiled code that will be executed when the message *run* is sent to the class *InferenceEngine*. Details about how to interface primitives to Smalltalk-80 are given in Chapter 12.

## Inference

Inference engines can be built in Smalltalk with some effort [see, e.g., Piersol (1987)], yet are relatively slow in comparison with optimized inference
<figure><img src="image_117.png" /><figcaption>**Figure 9.11** Coupling Smalltalk-80 to External Software.</figcaption></figure>

engines written in completely compiled languages. An inference engine is
computer code that supports the running of rules of the general form:

IF (various conditions) THEN (various actions).

A typical use of inference engines has been to build expert systems. In building applications of various types using object-oriented techniques, inference capabilities are of use in such activities as (1) inferring what the user knows and does not know (e.g., for forming a user model), (2) providing advice based on information acquired, and (3) analyzing heuristic information. Two advantages of some inference systems built using C or other compiled languages are high speed and the optimization of rules into networks [see, e.g., OPS5; Brownston et al. (1986)]. Coupling engines of this type to Smalltalk makes sense in order to improve system reasoning performance.
## Algorithms

Algorithms coded in compiled procedural languages can be coupled to Smalltalk in order to secure a speed advantage. For applications that do not require intensive computation, coupling to algorithmic implementations outside Smalltalk does not make sense. In general, one can hope for only, *at best*, an order-of-magnitude speedup. Moreover, the compilation facilities of Smalltalk have improved with each successive release; hence, differences in speed between Smalltalk and procedural languages may well disappear in time.

## Simulation Packages and Frameworks

Complex simulation packages and existing design and analysis frameworks are good candidates for coupling to object-oriented problem solutions. Using the same argument as for algorithms, speed improvements can be achieved. However, the greatest gains are likely because simulation code that has been developed over long periods of time can be used and does not have to be recoded.

## Word Processing, Equations

Although early releases of the Smalltalk environment (Versions 2.5 and earlier) contained the capabilities for word processing and building of equations using the form editor, these capabilities were not as well developed as some commercial packages designed specifically for these tasks. Text editing capabilities remain about the same in Release 4. However, integration of Release 4 with the host environment permitted using the word processing and equation editing facilities of the host software. For example, using Microsoft Windows, any of the standard word processing programs are probably more useful than the ST-80 editing capabilities. It is worth noting, however, that Xerox Special Information Systems markets a superb text editor written in ST-80 that is part of the Analyst package, an integrated office environment (XSIS, 1989).

## The Architecture of Coupled Systems

Figure 9.12 displays an architectural diagram which shows how coupled systems can be implemented in the ST-80 environment. At the top of the figure is the standard user interface. In the second layer, various application
<figure><img src="image_118.png" /><figcaption>**Figure 9.12** The Architecture of Coupled Systems.</figcaption></figure>
MVC triads are shown which are supported by various classes in the third layer of the diagram. Within various classes, there should exist methods that contain primitives that have links to packages external to the ST-80 environment. Inside ST-80, sending a method to a particular class that has the primitives implemented gives no hint that external code is being called; the programmer can program entirely in Smalltalk but retain the speed and complexity reduction capabilities afforded by using coupled systems. On the negative side, as soon as special-purpose links to external programs are added, Smalltalk programs become much less portable.

## 9.9 Summary

Object-oriented methodologies fit engineering problems. In this chapter, an attempt has been made to show that common problems in engineering can be either solved or facilitated by using object-oriented methodologies. Ideas surrounding the needs of engineering science and design were projected into specific examples of building systems for use in several different engineering domains. Various common needs were identified, including representation of knowledge and simulation. The upcoming chapters will take a closer look at these and allied areas that are useful for engineering problem solving.

### References

Adams, S. (1987). *Pluggable Gauges User's Manual*. Knowledge Systems Corporation, Cary, NC.

Auer, Ken (1989). Which Object-Oriented Language Should We Choose? *Hotline on Object-Oriented Technology*, Vol. 1, No. 1, November, 1-6.

Bourne, J., H. Liu, C. Orogo, S. Uckun, K. Hensley, and C. Buenzli (1989). Intelligent Systems for Quality Control. *Proceedings of the Third International Conference on Expert Systems and the Leading Edge in Production and Operations Management*. Management Science Department, University of South Carolina, May, 321-332.

Brownston, L., R. Farrell, E. Kant, and N. Martin (1986). *Programming Expert Systems in OPS5*. Addison-Wesley, Reading, MA.

Debelak, K. (1990). Personal Communication.

Haden, Gerald (1989). Medical Image Processing: Using Object-Oriented Programming Techniques. MS Thesis, Vanderbilt University, Nashville.

Piersol, K. W. (1987). *Humble V2.0 Reference Manual*. Xerox Special Information Systems, Xerox Corporation, Pasadena, CA.
Shafer, G., and R. Logan (1987). Implementing Dempster's Rule for Hierarchical Evidence. *Artificial Intelligence*, Vol. 33, No. 3, 271-298.
XSIS (Xerox Special Information Systems), Analyst (1989). Xerox Corporation, Pasadena, CA.

Exercises

9.1 Consider each of the domain examples given in Section 9.5. Give a critical appraisal of the examples and develop a similar example of your own in each field. This task will require consultation with others in the various disciplines discussed.

9.2 Take one of the examples in Exercise 9.1 that you are very familiar with and describe the specific characteristics of the model-view-controller that you would create for the application.

9.3 As a more complex exercise, develop a detailed architecture for the system you described in Exercise 9.2, patterned after the architectural example given in Section 9.8.

9.4 Imagine that you are asked to describe how a system would be developed for the application that you have chosen to work with in the preceding exercise. Create a series of scenarios that you can present to a group. One technique is to create a set of "storyboards" that describe how a user would interact with the application. In this case, a "storyboard" set would consist of multiple sketches of the user interface at different times and would also show how the interface relates to a model or models and to control of the application.

9.5 At the beginning of this chapter, the commonalities between engineering fields were mentioned. See if you can find out what some commonalities are. Write a short paper (e.g., not more than 5 pages) about interfield analogies in engineering. For example, consider how design is conducted in different engineering fields, such as electrical engineering and chemical engineering. Interview knowledgeable persons in these fields and determine how they do design. Then compare and contrast your findings.
# Constraint Methods

## 10.1 Basic Constraint Concepts

What is the meaning of the term *constraint*? The dictionary defines a constraint as: "something that restricts, limits or regulates" (Morris, 1981). In mathematical terms, "A constraint consists of a set of variables and a relation on these variables" (Güsgen, 1989) and in terms of objects, "A constraint expresses a desired relationship between one or more objects" (Leler, 1988). A favorite example used to explain constraints is the representation of the Fahrenheit to centigrade conversion equation (Abelson and Sussman, 1985; Leler, 1988):

$$C = 5/9 (F - 32)$$

or

$$F = 1.8 * C + 32$$

This simple relationship between the two variables C (centigrade) and F (Fahrenheit) can be expressed graphically as shown in Figure 10.1. This figure illustrates propagation of information in two directions in the graph. From centigrade to Fahrenheit the constraint is shown in the gray part of each circle; in the reverse direction, the constraint is shown in white. For each case, a numerical example is given: Converting 10°C to 50°F is shown in the first case and converting 70°F to 21°C is shown in the second case. The operations specified are inverses of each other when the data flows in opposite directions. In this simple case, the meaning of constraint is simply a mathematical relationship between the variables entering a node. In more complex situations, more complicated combination functions or even symbolic computations could be used in a node.
<figure><img src="image_119.png" /><figcaption>**Figure 10.1** Example Constraint Graphs for Temperature Conversion. Circles are operators; gray indicates forward propagation (to the right); white indicates reverse propagation (to the left). Squares indicate variables.</figcaption></figure>

Note in the temperature conversion example, the direct analogy between the constraint graph and the object-oriented methods discussed in this text. Each node can be considered to contain a mathematical relationship, with the kind of relationship determined by which inputs are present. That is, for example, when an input to the leftmost constraint is present, the multiplication constraint is used, and in the reverse direction, division is used. Objects can be used to represent each constraint, for example:

```
Object subclass #Constraint
    instanceVariableNames:
        'constraintHolderForward
        constraintHolderReverse
    input
    output'
    classVariableNames:"
    poolDictionaries"
    category: 'constraint-examples'
```
where the input and output values are stored in the designated instanceVari-
ables and the constraintHolders contain blocks of code that couple the input to
the output and the output to the input, respectively.

Propagation of information through a simple network of this type is
called local propagation (Steele, 1979). When there are circularities in the
graph, one cannot solve the graph directly; relaxation methods (Leler, 1988) can
be used to find a solution.

In the context of previous chapters when ST-80 implementation of
dependencies was discussed, it is worth noting that there is a direct analogy to
the dependencies studied in Chapter 8 and the constraint graphs. In the MVC
paradigm, objects can contain a list of dependent objects to which a message is
sent whenever information in the object (model) is changed. It is easy to see
how the dependency methodology is essentially the same as a constraint graph.
Each object is linked to another (equivalent to adding to the dependents list)
and an action is taken when data arrives at a node, which is equivalent to
*update*: in the MVC.

Most interest in constraint programming has been in the area of
equation solving and graphical solutions. Various examples abound; some of the
more prominent are reviewed in the following discussion. The major emphasis
in the topic from the viewpoint of engineering analysis and design is the direct
mapping of the constraint methodology to the simulation of physical systems. In
the examples given in the previous chapters about engineering systems, several
systems were discussed that utilize the constraint technique. For example, the
chemical engineering example involved propagation of information among vari-
ous separators and the digital circuit simulator passed information between
chips in a circuit. A detailed look at the latter example will be given later in this
chapter.

10.2 Using Constraints

The history of the use of constraint techniques begins with the
dissertation of Ivan Sutherland in 1963 on SKETCHPAD (Sutherland, 1963)
which investigated the use of graphics as a communications medium for user-
machine interaction. In SKETCHPAD, the user interacted with the display
using a light pen to manipulate a drawing. Concepts such as "rubber banding"
and other graphics manipulation ideas, which are now commonplace, were
introduced by Sutherland in this landmark work that was well before its time.
The "rubber band" concept serves to illustrate the graphics constraint idea. In
this metaphor, a line appears to follow the cursor as it is moved on the screen
and does not become permanent until the user, for example, clicks the mouse
button. If one wishes to create a graphical image, a square for example, the
lines drawn can be made to snap to vertical and horizontal constraints. That is, the lines can be constrained to be only vertical or horizontal. This idea is incorporated in most modern computer drawing packages.

TK!Solver (Frank et al., 1987) is a constraint solution system for numerical problems that is rule based in the sense that one is permitted to enter constraint equations in any order according to a specified format. Once entered, TK!Solver solves the equations, using relaxation techniques (Borning, 1981). Relaxation changes the numerical values in sets of equations to try to minimize the error expressions of the constraints. The basic idea is to represent approximations to the constraints as a set of linear equations and find a least-mean-square fit to the equations. The solutions created to sets of equations by TK!Solver are provided for any of the variables entered in the system; hence, an output can be determined in terms of an input, and vice versa. Equations and data can be stored in simple declarative statements. Also supported in TK!Solver Plus is the ability to combine logical operations as well as mathematical calculations. TK!Solver has enjoyed some commercial success during the last decade.

ThingLab (Borning, 1979, 1981) was probably the first attempt to create a constraint-based simulation laboratory. Based on roots in Smalltalk, ThingLab extended the capabilities of Smalltalk by providing the user the ability to graphically program constraint relationships. The ThingLab view, constructed in Smalltalk, was quite similar to the ClassBrowser of Smalltalk with four selection-in-list views across the window and a picture view (i.e., the display of the constraint diagram) across the bottom of the window. The four selection-in-list views contained: (1) the names of classes of objects that could be displayed, (2) the aspect of the object selected (e.g., the prototype of the object), (3) messages, and (4) arguments to the messages. To use the browser, one could make selections across the four views; for example: "triangle → prototype → inset → line," where "triangle" was selected in the leftmost list, "prototype" in the next list, and so forth. This style of interface provided the capability for the user to create objects in the picture view without understanding the syntax of any language. Borning presented using ThingLab to create a temperature conversion system that included gauges on the input and output of the constraint network. Figure 10.2 displays a drawing that shows how ThingLab could represent the temperature conversion problem. The gauges show the relationship between centigrade and Fahrenheit; changes in one gauge propagate through the constraints and register on the other gauge.

Steamer (Hollan, Hutchins, and Weitzman, 1984) was constructed to evaluate the use of artificial intelligence for computer-based training systems. The domain chosen was for training naval personnel about steam engines in ships. The major advance made in this project was the representation of a steam propulsion plant on a computer screen, complete with gauges and dials that
<figure><img src="image_120.png" /><figcaption>**Figure 10.2** The ThingLab Style Representation of a Temperature Conversion Constraint System.
[After Borning (1981).]</figcaption></figure>

monitored the operation of the steam engine. Steamer was implemented using object-oriented methods in ZetaLisp using Flavors. Figure 10.3 shows a graphical rendition of a steam engine that is presented to the user of the system. The conceptual fidelity in this system was good, in that the user could recognize the schematic of the engine and relate it to the physical system. Furthermore, operating the system produced the close-to-reality results needed for teaching how the system operated. Steamer is described here because it can be considered to be a constraint-based system in that objects representing the various elements in a steam propulsion system were implemented as objects that acted as constraints in the overall description of the engine.

Constraints other than mathematical equation solvers or graphics constraint systems are also well known such as constraints in spreadsheets or symbolic equation-solving systems. In spreadsheets, equations at cells in a matrix constrain values at other cells in the matrix. Perhaps the spreadsheet is the most commonly used constraint-based system. Other systems also exist for symbolic manipulation, for example, MACSYMA (MathLab, 1983), used for solving symbolic mathematical equations.
<figure><img src="image_121.png" /><figcaption>**Figure 10.3** A Model of a Steam Propulsion Plant. [After Stevens (1982); with permission. © Bolt Beranek and Newman, Inc.]</figcaption></figure>

## 10.3 Implementing Constraints: An Example for Digital Circuit Simulation (DCS)

This section of the chapter shows how to implement a simple constraint system for the digital circuit simulation system that appears in different aspects in several sections of this textbook. The implementation shown is in ST-80 and demonstrates only single directional flow of information. In digital circuits, actual information flows in just one direction through electronic components; hence, it would make no sense to implement bidirectional flow for this example.

### DCS Concepts

In Chapter 3, a discussion of object-oriented analysis culminated in the demonstration of the use of ACOM (application/class organization method)
<figure><img src="image_122.png" /><figcaption>**Figure 10.4 An And Gate.**</figcaption></figure>

notecards for analyzing the component elements of an application. The application addressed in that chapter was a digital circuit simulator. The descriptions of the components of the digital circuit simulator specified on ACOM notecards in Chapter 3 will be turned into ST-80 code and tested in this chapter.

First, as background, the utility of digital circuits is to combine logical operations to create various electronic systems such as adders, counters, flipflops, and even, at a much higher level of complexity, digital computers. The purpose of a digital circuit simulator is to create computer models of actual physical electronic devices which mimic the behavior of the physical devices themselves. For very simple circuit elements, this is not difficult to understand. Consider the two very simple circuits shown in Figures 10.4 and 10.5 which display an AND gate and a combination of an AND gate and an OR gate, respectively. The AND gate's behavior is simply that a 1 appears on the output (C) whenever a 1 is placed on both inputs (A and B) simultaneously. Likewise, output of the OR gate is a 1 whenever either input is high (a 1). The digital circuit combination of an AND gate and an OR gate shown in Figure 10.5 will obey these combination rules, propagating information from the input to the output (i.e., A and B to E) according to the wiring of the circuit and the definition of the *constraints* contained in each of the circuit elements.

Complexity in the design of digital circuits can be lowered by using hierarchical design; that is, each element in a circuit can represent combinations of other elements in a hierarchical fashion. Consider Figure 10.6 which shows an example of how circuit elements can be combined hierarchically. At the top level of this figure is shown a D flipflop, a gate that has two states Q (1) and notQ (0) that change back and forth depending on the state of an input clock signal. The actual implementation of the D flipflop is a collection of AND gates connected as shown in the lower plane in the figure. At the top level of the representation, only the functionality of the flipflop is observable and the

<figure><img src="image_123.png" /><figcaption>**Figure 10.5 A Very Simple Digital Circuit.**</figcaption></figure>
underlying implementation, in terms of the interconnected AND gates, is hidden. This style decomposition can be carried on to various levels in order to create systems of arbitrary complexity. To simulate the behavior of the flipflop, the combined behaviors of the AND gates will yield the behavior of the flipflop. The problem, of course, in circuit simulations of this type is that implementation of the behavioral characteristics of the top-level circuit in terms of their constituent elements will result in very slow simulations when the number of circuit elements grows large. Nevertheless, the concept of hierarchical design is a powerful one. Next, specific methods for implementing the behavior of primitive AND, OR, and NOT gates is examined. Using the information given in the following discussion, it would be straightforward to implement the flipflop example given in Figure 10.6.

<figure><img src="image_124.png" /><figcaption>**Figure 10.6** Hierarchical Digital Design Concept.</figcaption></figure>
<table><caption>**Table 10.1** The Block Evaluation Protocol</caption><thead><tr><th>Message</th><th>Explanation</th></tr></thead><tbody><tr><td>value</td><td>Evaluate the block represented by the receiver</td></tr><tr><td>value: anArgument</td><td>Evaluate the block represented by the receiver using one argument</td></tr><tr><td>value: value:</td><td>Use two arguments</td></tr><tr><td>value: value: value:</td><td>Use three arguments</td></tr><tr><td>valueWithArguments: arguments</td><td>Use anArray of arguments</td></tr><tr><td colspan="2"><strong>Example</strong></td></tr><tr><td>[:x:y | (x*x) + (y*y)] value: 3 value: 4</td><td></td></tr><tr><td>returns: 25</td><td></td></tr></tbody></table>

## Implementing Constraints

Implementing a constraint or relationship between several variables is quite simple in ST-80. The concept of a block may be utilized in which code may be stored for later execution. A block has the form:

[:variable1 :variable2 | localVariable1 localVariable2 | codeBlock...]

where the variable names preceded by colons are variables that are passed to the code block. Above, where "codeBlock..." is shown, Smalltalk code would be inserted. A block with no arguments can be evaluated simply by sending the message *value* to the block and values can be passed to a block using several different messages, for example,

constraint value: aValue
constraint value: aValue1 value: aValue2

Table 10.1 displays a partial set of messages for block evaluation and gives a simple example. This style of forming constraint expressions is quite convenient for specifying the behavioral characteristics of gates in the digital circuit simulation. The specific implementation for several elementary gates will be discussed in the next section.

## Models

In this chapter, the description of building a digital circuit simulator will focus on the model; Chapter 13 will examine the interface to the user.
<figure><img src="image_125.png" /><figcaption>**Figure 10.7** The Digital Circuit Simulator Example Class Hierarchy.</figcaption></figure>

Figure 10.7 displays a simple hierarchy created for the DCS. **Gate** is a subclass of **Object**; **OneInputGate** and **TwoInputGate** are subclasses of **Gate** and both **AndGate** and **OrGate** are subclasses of **TwoInputGate**. **Gate** is used in Chapter 13 to keep track of the location of any gate on the screen; hence, it is a superclass of all other gates that need to inherit this capability.

The digital circuit simulation system hierarchy could be quite complex. For example, many electronic components such as nand, nor, plus, times, invertors, memory elements, clocks, analyzers, meters, power supplies, signal sources, probes, and so forth could be implemented. The example system presented contains only the minimum components needed to explain a few basic concepts. The reader is encouraged to add additional circuit elements as an exercise. Table 10.2 lists the components defined for the example system.

<table><caption>**Table 10.2** Components in a Digital Circuit Simulation</caption><thead><tr><td>Component Name</td><td>Description</td></tr></thead><tbody><tr><td>AndGate</td><td>Two inputs, one output; when two inputs are high, the output is high; inherits from TwoInputGate</td></tr><tr><td>OrGate</td><td>Two inputs, one output; when either input is high, the output is high; inherits from TwoInputGate</td></tr><tr><td>NotGate</td><td>One input, one output; inverts the input; inherits from OneInputGate</td></tr><tr><td>Wire</td><td>Connects components</td></tr><tr><td>TwoInputGate</td><td>Abstract component; two inputs, one output</td></tr><tr><td>OneInputGate</td><td>Abstract component; one input, one output</td></tr><tr><td>Gate</td><td>Abstract component; monitors display location</td></tr></tbody></table>
<table><caption>**Table 10.3 Constraints for DCS Components**</caption><thead><tr><td>Component</td><td>ConstraintBlock</td></tr></thead><tbody><tr><td>AndGate</td><td>[:input1 :input2 | (input1 = 1) & (input2 = 1) ifTrue: [1] ifFalse: [0]]</td></tr><tr><td>OrGate</td><td>[:input1 :input2 | (input1 = 1) | (input2 = 1) if True: [1] ifFalse: [0]]</td></tr><tr><td>NotGate</td><td>[:input | (input = 1) ifTrue: [0] ifFalse: [1]]</td></tr></tbody></table>

## Gate Models

Table 10.3 presents the constraint code for each of the gates used in the DCS. As shown, each constraint contains the number of input variables of the gate. The output value is returned as the value of the block evaluated.

## Wire Model

Table 10.4 displays the definition and protocols for the class **Wire**. **Wire** is a subclass of **Object**; instances of **Wire** are used to connect components in the digital circuit simulator. Basically, a wire remembers its value and where each end of the wire is connected. If a value is sent to a wire object using **set**: *aValue*, the wire remembers the value sent and propagates the value to where ever the wire is connected.

## Implementing Delays

In the example given, delays are not implemented. However, it would be quite straightforward to insert delays in the constraintBlocks for each of the components. ST-80 provides a class named **Delay** which permits real-time delays, useful for animation. For example,

(Delay forMilliSeconds: 1000) wait.

or

(Delay forSeconds: 1) wait.

will delay the process in which the delay is embedded for 1 second. One can
<table><caption>**Table 10.4** The Wire Protocol and Code</caption><thead><tr><th>Protocol</th><th>Method</th><th>Comment</th></tr></thead><tbody><tr><td>Initialize</td><td>init</td><td>Sets value = 0, makes output an OrderedCollection</td></tr><tr><td>Access</td><td>inputConnection: aGate<br>outputConnection: aGate<br>set: aValue<br>value</td><td>Connects input<br>Connects output<br>Sets the value<br>Retrieves the value</td></tr><tr><td colspan="3"><strong>Object subclass: #Wire</strong><br>InstanceVariableNames: 'InputConnection outputConnections value name pointsDescribingWire' classVariableNames: '' poolDictionaries: '' category: 'digital-demo'</td></tr><tr><td colspan="3">Wires are used to connect digital components.</td></tr><tr><td colspan="3"><strong>Wire methodsFor: access</strong></td></tr><tr><td colspan="3"><strong>getWirePoints</strong><br>^pointsDescribingWire</td></tr><tr><td colspan="3"><strong>InputConnection: aGate</strong><br>inputConnection := aGate.</td></tr><tr><td colspan="3"><strong>name</strong><br>^name</td></tr><tr><td colspan="3"><strong>name: aName</strong><br>name := aName</td></tr><tr><td colspan="3"><strong>outputConnection: aGate</strong><br>outputConnections add: aGate.</td></tr><tr><td colspan="3"><strong>set: aValue</strong><br>value := aValue.<br>outputConnections empty? ifTrue: [Transcript show: self name printString.<br>Transcript show: self value printString.<br>Transcript cr.] ifFalse: [outputConnections do: [:eachGate | eachGate propagate]]</td></tr><tr><td colspan="3"><strong>storeWire: aWire</strong><br>pointsDescribingWire := aWire.</td></tr><tr><td colspan="3"><strong>value</strong><br>^value</td></tr><tr><td colspan="3"><strong>Wire methodsFor: Initialize</strong></td></tr><tr><td colspan="3"><strong>Init</strong><br>value := 0.<br>outputConnections := OrderedCollection new.</td></tr></tbody></table>
<caption>Table 10.5 Code for the Digital Circuit Simulator</caption>

### Object subclass: #OneInputGate
*   `instanceVariableNames`: 'inputWire outputWires constraint delay'
*   `classVariableNames`:''
*   `poolDictionaries`:''
*   `category`: 'Digital Demo'

### OneInputGate methodsFor: initialize

#### init
*   `delay` = 0.
*   `outputWires` = OrderedCollection new.

#### input: aWire1 output: aWire2
*   `inputWire` = aWire1.
*   `outputWires` add: aWire2.
*   `inputWire` `outputConnection`: self.
*   `aWire2` `inputConnection`: self.

### OneInputGate methodsFor: action

#### propagate
*   `constraintOutputValue` |
*   `constraintOutputValue` =
*   `constraint` value: `inputWire` value.
*   `outputWires` do: [:aWire | aWire set: `constraintOutputValue`]

### OneInputGate subclass: #NotGate
*   `instanceVariableNames`:''
*   `classVariableNames`:''
*   `poolDictionaries`:''
*   `category`: 'Digital Demo'

### NotGate methodsFor: initialize

#### init
*   `super` `init`.
*   `constraint` =
*   [:input | (input = 1)
*       ifTrue: [0]
*       ifFalse: [1]].

### Object subclass: #TwoInputGate
*   `instanceVariableNames`: 'inputWire1 inputWire2 outputWires constraint delay'
*   `classVariableNames`:''
*   `poolDictionaries`:''
*   `category`: 'Digital Demo'

### TwoInputGate methodsFor: access

#### constraint
*   `^` `constraint`

#### inputWire1
*   `^` `inputWire1`
<table><caption>**Table 10.5** Continued</caption><thead><tr><th>Method</th><th>Class</th></tr></thead><tbody><tr><td><strong>InputWire2</strong></td><td><code>InputWire2</code></td></tr><tr><td><strong>TwoInputGate methodsFor: action</strong></td><td><code>TwoInputGate methodsFor: action</code></td></tr><tr><td><strong>propagate</strong></td><td><code>propagate</code></td></tr><tr><td><code>constraintOutputValue</code></td><td><code>constraintOutputValue</code> := <code>constraint value: inputWire1 value: inputWire2 value.</code></td></tr><tr><td><code>outputWires do: [:aWire | aWire set: constraintOutputValue]</code></td><td></td></tr><tr><td><strong>TwoInputGate methodsFor: initialize</strong></td><td><code>TwoInputGate methodsFor: initialize</code></td></tr><tr><td><strong>init</strong></td><td><code>init</code></td></tr><tr><td><code>delay := 0.</code></td><td><code>delay := 0.</code></td></tr><tr><td><code>outputWires := OrderedCollection new.</code></td><td><code>outputWires := OrderedCollection new.</code></td></tr><tr><td><strong>input1: aWire1 Input2: aWire2 output: aWire3</strong></td><td><code>input1: aWire1 Input2: aWire2 output: aWire3</code></td></tr><tr><td><code>inputWire1 := aWire1.</code></td><td><code>inputWire1 := aWire1.</code></td></tr><tr><td><code>inputWire2 := aWire2.</code></td><td><code>inputWire2 := aWire2.</code></td></tr><tr><td><code>outputWires add: aWire3.</code></td><td><code>outputWires add: aWire3.</code></td></tr><tr><td><code>inputWire1 outputConnection: self.</code></td><td><code>inputWire1 outputConnection: self.</code></td></tr><tr><td><code>inputWire2 outputConnection: self.</code></td><td><code>inputWire2 outputConnection: self.</code></td></tr><tr><td><code>aWire3 inputConnection: self.</code></td><td><code>aWire3 inputConnection: self.</code></td></tr><tr><td><strong>TwoInputGate subclass: #OrGate</strong></td><td><code>TwoInputGate subclass: #OrGate</code></td></tr><tr><td><code>InstanceVariableNames:</code></td><td><code>InstanceVariableNames:</code></td></tr><tr><td><code>classVariableNames:</code></td><td><code>classVariableNames:</code></td></tr><tr><td><code>poolDictionaries:</code></td><td><code>poolDictionaries:</code></td></tr><tr><td><code>category: 'Digital Demo'</code></td><td><code>category: 'Digital Demo'</code></td></tr><tr><td><strong>OrGate methodsFor: initialize</strong></td><td><code>OrGate methodsFor: initialize</code></td></tr><tr><td><strong>Init</strong></td><td><code>Init</code></td></tr><tr><td><code>super init.</code></td><td><code>super init.</code></td></tr><tr><td><code>constraint := [:input1 :input2|</code></td><td><code>constraint := [:input1 :input2|</code></td></tr><tr><td><code>(input1 = 1) | (input2 = 1)</code></td><td><code>(input1 = 1) | (input2 = 1)</code></td></tr><tr><td><code>ifTrue: [1]</code></td><td><code>ifTrue: [1]</code></td></tr><tr><td><code>ifFalse: [0]</code></td><td><code>ifFalse: [0]</code></td></tr><tr><td><strong>TwoInputGate subclass: #AndGate</strong></td><td><code>TwoInputGate subclass: #AndGate</code></td></tr><tr><td><code>InstanceVariableNames:</code></td><td><code>InstanceVariableNames:</code></td></tr><tr><td><code>classVariableNames:</code></td><td><code>classVariableNames:</code></td></tr><tr><td><code>poolDictionaries:</code></td><td><code>poolDictionaries:</code></td></tr><tr><td><code>category: 'Digital Demo'</code></td><td><code>category: 'Digital Demo'</code></td></tr><tr><td><strong>AndGate methodsFor: initialize</strong></td><td><code>AndGate methodsFor: initialize</code></td></tr><tr><td><strong>init</strong></td><td><code>init</code></td></tr><tr><td><code>super init.</code></td><td><code>super init.</code></td></tr><tr><td><code>constraint := [:input1 :input2|</code></td><td><code>constraint := [:input1 :input2|</code></td></tr><tr><td><code>(input1 = 1) &amp; (input2 = 1)</code></td><td><code>(input1 = 1) &amp; (input2 = 1)</code></td></tr><tr><td><code>ifTrue: [1]</code></td><td><code>ifTrue: [1]</code></td></tr><tr><td><code>ifFalse: [0]</code></td><td><code>ifFalse: [0]</code></td></tr><tr><td><strong>AndGate class</strong></td><td><code>AndGate class</code></td></tr><tr><td><code>InstanceVariableNames:</code></td><td><code>InstanceVariableNames:</code></td></tr></tbody></table>
make an assignment such as

```
minuteDelay := Delay forSeconds: 60
```

and then send "minuteDelay wait" at some later point. For example, for the digital circuit simulation system, different delays might be inserted into each of the constraints to simulate various delay times present in different gate types. Thus, one might have a constraintBlock that contains

```
[:input1 :input2|andGateDelay wait.
(input1 = 1) & (input2 = 1)
ifTrue: [1]
ifFalse: [0]]
```

where andGateDelay has been set to be a particular time delay.

## Code for the Digital Circuit Simulator Example

Table 10.5 displays the code for the digital circuit simulation models presented previously. Code is organized in the form provided by printing out classes in the ST-80 system. The initial information presented for each class shows its superclass, instance variable names, class variable names, poolDictionaries, and the category in which it is contained. Then, in alphabetic ordering by protocol, the methods are shown for both instance and class methods. The printouts capture all information contained in the system browser, including comments, shown here in italics after the initial definition of the class.

## 10.4 Wiring and Testing Example Digital Circuit Simulations

Several examples of how to wire together objects and test the digital circuit simulations are given next. To facilitate the testing and observation of variables in these examples, variables have been declared as global to make it easy to inspect changes in the examples given. In normal programming practice, the use of global variables, as shown in these examples, would not be employed.

*Testing a Component.* The easiest example to begin with is to create one digital component and test it. To create the AND gate shown in Figure 10.4, one can follow the steps given in Table 10.6 which shows first the creation of three wires: A, B, and C. A new AND gate, called And1 is created and the wires just
<caption>**Table 10.6 Example of Creating an AND Gate**</caption>

**AndGate class methodsFor: examples**

**example1**

"AndGate example1"

A := Wire new init. "Create a wire with the global name A"

B := Wire new init. "Create a wire with the global name B"

C := Wire new init.

And1 := AndGate new init. "Make a new AndGate"

And1

input1: A "Attach the wires on the Gate"

input2: B

output: C.

B set: 1. "test by setting the inputs"

A set: 0. "and inspecting the output wire"

C inspect.

A set: 1.

C inspect.

<caption>**Table 10.7 Example of Wiring Together Two Gates**</caption>

**example2**

"AndGate example2"

A := Wire new init. "make wires"

B := Wire new init.

C := Wire new init.

D := Wire new init.

E := Wire new init.

And1 := AndGate new init. "make the and gate"

And1

input1: A

input2: B

output: C.

Or1 := OrGate new init. "make an or gate"

Or1

input1: C

input2: D

output: E.

B set: 1.

A set: 1.

D set: 0.

E inspect.
<figure><img src="image_126.png" /><figcaption>Figure 10.8 Testing the Circuit in Figure 10.5.</figcaption></figure>
<caption>**Table 10.8** Example of Creating the Functionality of a NAND Gate</caption>

**example3**

"AndGate example3"

A := Wire new init. "Create a wire with the global name A"

B := Wire new init. "Create a wire with the global name B"

C := Wire new init.

And1 := AndGate new init. "Make a new AndGate"

And1

input1: A "Attach the wires on the Gate"

input2: B

output: C.

Not1 := NotGate new init. "Make a new NotGate"

D := Wire new init. "and an output wire"

Not1 input: C output: D.

A set: 1. B set: 1. D inspect. "test the combination NAND gate"

A set: 0. B set: 0. D inspect.

instantiated attached using the *input1 input2 output* message. Table 10.6 displays the code used for each of these steps. At the end of the table, the behavior of the gate created can be tested by sending the input wires created 1's and 0's and inspecting the output by sending the output wire the message *inspect*. This latter message will create an inspector window in which one can observe the value contained in the wire object as new values are placed on the input wires.

*Wiring Gates Together*. Table 10.7 demonstrates how to wire together two gates as shown in Figure 10.5. First, all the wires in the simulation are identified (A, B, C, D, and E) and new wires created using "Wire new init." Next, the two logic components are created and the wires for their inputs and outputs specified. Finally, the circuit created is tested. Figures 10.8a, b, and c demonstrate the testing of this circuit. In each of the three cases, A, B, and D are set to different values and E is inspected. As shown, in each case the wire E is

<figure><img src="image_127.png" /><figcaption>**Figure 10.9** The Half-Adder.</figcaption></figure>
<caption>**Table 10.9** Example of Creating a Half-Adder</caption>

### example4

"AndGate example4"

"A Half Adder example"

A = Wire new init.

B = Wire new init.

C = Wire new init.

D = Wire new init.

E = Wire new init.

F = Wire new init.

And1 = BasicAndGate new init.

And1 input1: B input2: A output: C.

And2 = BasicAndGate new init.

And2 input1: D input2: E output: F.

Or1 = BasicOrGate new init.

Or1 input1: A input2: B output: D.

Not1 = BasicNotGate new init.

Not1 input: C output: E.

A set: 1. B set: 0. F inspect. C inspect.

inspected and the value that the wire contains shown in the right window of the
inspector. The reader should verify that the values shown are correct.

**A Nand Gate.** Table 10.8 displays an example of creating the functionality of a NAND gate, that is, a combination of an AND gate followed by a NOT operation. As in the previous example, wires are defined and the output of the AND gate is connected to the output of the NOT gate.

**A Half-Adder.** The final circuit example is shown in Figure 10.9, along with the testing code in Table 10.9. This circuit is the same half-adder circuit described in an earlier chapter. The functionality of the half-adder is to sum the two inputs, providing a summation and a carry signal at the output. Hence, a 1 and 0 on the two inputs create a sum equal to 1 and a carry equal to 0. Setting both inputs to 1 creates a 0 sum and a 1 for the carry. The annotations provided on the figure match the designations for the wires given in Table 10.9.

## 10.5 Enhancing the Digital Circuit Simulation System: An Example in Tutoring Systems

Figures 10.10 and 10.11 provide a concrete example of the use of the constraint propagation methodologies for implementing a tutorial system for digital circuits (Balasubramanyam, 1990). Figure 10.10 shows a window created
<figure><img src="image_128.png" /><figcaption>Figure 10.10 A Digital Circuit Tutorial System Implemented Using Constraints.</figcaption></figure>
<figure><img src="image_129.png" /><figcaption>Figure 10.11 The Instructor Interface to the Digital Circuit Tutorial System.</figcaption></figure>
that assists a student in learning about digital circuits. The individual circuits that can be used are graphically depicted as icons on the left side of the figure and a graphics view in which a circuit can be graphically composed is shown immediately adjacent to the right of the icons. The remainder of the views in the system communicate with the student giving the problem statement, providing tutoring, and furnishing text presentations about aspects of the circuit created. Control is via the buttons shown at the top of the figure and include help and choosing whether the student wants to learn about how digital expressions can be expressed graphically, or vice versa. Figure 10.11 displays the instructor interface in which the instructor can structure the knowledge that is to be presented to the student. The same capabilities are used; that is, the icon builder mechanisms remain but capabilities are added for providing text editing and structurization of lessons.

The design of the electronics tutor evolved from the simple constraint mechanisms described previously. The ability to create icons related to objects that constrain descriptions of the behavior of electronic components coupled with the capability of coupling components together with wire objects provides a powerful mechanism for assisting students in visualizing how signals propagate through an electronic circuit.

## 10.6 A Petri Net Example

The final example of a constraint propagation system is the implementation of a Petri net simulator. The example given here will be expanded and discussed in Chapter 14, including a comparison with discrete-event simulation methods. Petri nets (Peterson, 1981) are useful mechanisms for simulating activities in the world. Petri nets have four parts: (1) a set of places that represent conditions, (2) a set of transitions that represent events, (3) an input function that represents a precondition to a transition, and (4) an output function that represents a postcondition of a transition. Places can be thought of as nodes in a semantic net that hold tokens representing the fulfillment of conditions. Arcs are drawn between places and transitions to indicate flow between entities in a Petri net. Transitions provide control by firing when each of their input places contain at least as many tokens in them as arcs from the places to the transitions. Imagine a series of repositories for tokens (i.e., the places) that are separated by transitions and a set of tokens (things) that can migrate through the net according to conditions placed at the transitions. When a transition fires, tokens on the input are placed at the output and propagation proceeds until no further propagation is possible. Consider the example shown in Figure 10.12 which demonstrates the use of a Petri net for modeling the building of a house. The transitions in this net are shown by the narrow
<figure><img src="image_130.png" /><figcaption>Figure 10.12 Building a House: An Example of the Use of Petri Nets.</figcaption></figure>
<figure><img src="image_131.png" /><figcaption>**Figure 10.13** Petri Nets for the New Product Introduction Cycle. [With permission; Dehner (1990).]</figcaption></figure>
rectangles and the places are denoted by circles. Beginning at the input place "start," a transition "stExcava" (start Excavation) is made to the new place (i.e., condition) "finExcava" (finish Excavation). Activity in the net continues throughout the net, sometimes dividing into parallel activities until the house is built. This example is an implementation of an example given by Peterson (1981), page 72.

The example of the house building system is constructed as a timed Petri net; that is, at a transition, a delay can be introduced to simulate the amount of time an activity will take. Class Delay, as discussed previously, is used for this implementation. The remainder of the implementation is quite similar to the digital circuit simulator except that objects in the simulation obey the Petri net rules, as indicated previously, and use a time delay to introduce more realism into the simulation. The top right of the window of the example shown contains a transcript that shows which node is firing as the simulation runs.

Figure 10.13 displays another implementation of a Petri net simulation for a different domain—that of introducing a new product (Dehner, 1990). The figure shown displays part of the new product introduction process which deals with mechanical, electrical, and software design. The transition nodes are shown as rectangles in this diagram and places are implicitly embedded in the arcs. As design of a product moves from transition to transition in this simulation, the rectangular forms containing text are reversed from white to black while the transition occurs. In this way one can observe the simulated progress of a design along the parallel paths in the simulation.

Petri nets pass discrete events (tokens) between transitions. The transitions contain constraints that are in the form of decisions about when and where to pass a token. Because the actions taken by the transitions are discrete, Petri nets are useful for modeling and simulating physical systems in which noncontinuous models are used. The two preceding examples have presented a first look at simulation using discrete events; Chapter 14 will give a more detailed presentation and specifically examine how to create discrete-event simulators.

## 10.7 General Use of Constraint-Based Techniques

This chapter has attempted to develop the case for using constraint-based techniques for simulation of engineering activities. Constraint techniques are useful for many different types of simulations, including solution of mathematical equations and representation of physical objects that can be separated into discrete components, each with internalized behaviors (e.g., digital circuits, pipes, etc.). Finally, constraints implemented in objects can realize even relatively advanced concepts such as Petri nets that provide a logical framework for
simulation of many types of models. Adding time to simulations has been shown to be easily added in the ST-80 framework using the **Delay** class.

Finally, the major lesson to be learned from this chapter is that object representations can be used naturally to model and simulate the real world. Objects have built-in capabilities for maintaining state, implementing behavior, and communicating that makes the object-oriented paradigm ideal for constraint-based systems. There are, however, other simulation methodologies such as discrete-event-based simulation that can be used to enhance simulation capabilities for timed simulations. These methods will be examined in Chapter 14.

## References

Abelson, H., and G. J. Sussman (1985). *Structure and Interpretation of Computer Programs*. McGraw-Hill, New York.

Balasubramanyam, Ravi (1990). A Tutorial System for Digital Circuits. MS Thesis, Vanderbilt University, Nashville.

Borning, A. (1979). *ThingLab*—A Constraint-Oriented Simulation Laboratory. PhD Dissertation, Stanford University.

Borning, A. (1981). The Programming Language Aspects of ThingLab, a Constraint-Oriented Simulation Laboratory. *ACM Transactions on Programming Languages and Systems*, Vol. 3, No. 4, October, 353–387.

Dehner, J. (1990). Personal Communication.

Frank, W., L. Kloepping, M. Norddahl, K. Olafsson, and D. Shook (1987). *TK!Solver Plus Manual*. Universal Technical Systems.

Güsgen, H. W. (1989). *CONSAT: A System for Constraint Satisfaction*. Morgan Kaufmann, Los Altos, CA.

Hollan, J. D., E. L. Hutchins, and L. Weitzman (1984). *STEAMER: An Interactive Inspectable Simulation-Based Training System*. *AI Magazine*, Vol. 5, No. 2, Summer. In *Readings from the AI Magazine* (1988) 581–593.

Jiang, Zhihe (1990). An Intelligent Petri-Net-Based Simulation System. MS Thesis, Vanderbilt University, Nashville.

Leler, William (1988). *Constraint Programming Languages*. Addison-Wesley, Reading, MA.

MathLab, MACSYMA Reference Manual (1983). The MathLab Group, Laboratory for Computer Science, MIT, Cambridge, MA.

Morris, William (Ed.) (1981). *The American Heritage Dictionary of the English Language*. Houghton Mifflin, Boston, MA.

Peterson, J. L. (1981). *Petri Net Theory and the Modeling of Systems*. Prentice-Hall, Englewood Cliffs, NJ.

Steele, G. L. (1979). The Definition and Implementation of a Com-
computer Programming Language Based on Constraints. MIT Artificial
Intelligence Laboratory Technical Report 595, MIT, Cambridge, MA.
Sutherland, I. E. (1963). SKETCHPAD: A man-machine graphical
communications system. Technical Report 296, MIT Lincoln Labora-
tory, Cambridge, MA.

Exercises

10.1 Extend the half-adder example to implement a full-adder. Refer to the diagram for a full-adder found in Figure 3.12.

10.2 Add additional components to the example system, for example, a NAND gate, a logic level sensor, and so on. Verify that the components that you create work correctly.

10.3 Add delays to the constraints of the DCS example and test.

10.4 Verify and explain the code given in Tables 10.6 through 10.9.

10.5 Review the STEAMER project by reading the paper by Hollan, Hutchins, and Weitzman listed in the references. Write a short paper about how to create constraints similar to those in STEAMER.
<figure><img src="image_132.png" /></figure>
# Representing and Using Engineering Knowledge

A key problem in creating computer-based systems for applications in engineering is understanding how to represent knowledge. Knowledge can be represented in so many different ways that it may be difficult to match available representational structures to problem requirements. There has been little guidance available to designers of applications on how to choose representations and how to understand the rationale behind the choices that are available. Most frequently, system designs involving knowledge-intensive tasks are driven by which software packages are available and/or prior designer familiarity with various representation paradigms. This chapter will try to systematically uncover the rationale behind using several different representation methodologies and to show how the different techniques relate to each other. Many of the representation types discussed are derived from the field of artificial intelligence (AI). This field has been seriously engaged for some decades in attempting to unravel the representation issue (Brachman and Levesque, 1985). First, an attempt will be made to summarize the general characteristics of engineering knowledge and the general representation categories that are appropriate for different tasks. Next, basic concepts in knowledge representation will be presented and finally, examples for each of the major representation categories will be given. An explicit effort will be made to reveal when object-oriented methodologies are useful and when these methodologies can be beneficially combined with other approaches.

## 11.1 Engineering Knowledge

What is engineering knowledge? Most engineers give little thought to this question. Rather, consideration of knowledge structurization is almost
implicit in problem solving, unseen yet fundamental. Software application projects created by engineering students normally follow no formal software engineering process, such as the waterfall model (Royce, 1970). This model of the software engineering process steps designers through the following type of problem-solving script: requirements analysis, specification fabrication, software design, implementation, integration, and finally operation. A test and verify cycle is included at each stage of the design. The lack of software systemization in engineering has translated into the preeminence of ad hoc software methodologies for engineering problem solving. Even relatively rigidized methodologies for software specification do not yet appear to have greatly influenced knowledge-intensive engineering problem solving. For example, the waterfall method is not widely used, except implicitly, in many engineering applications. Indeed, there appears to be considerable difficulty in linking traditional software engineering methods (Schach, 1990) to knowledge-intensive engineering problem solving. In part, this situation derives from the complexity of understanding the characteristics of engineering knowledge and the difficulty of specifying ways to represent that knowledge. Specification of techniques for organizing the building of software (i.e., the field of software engineering) has not become widespread for building engineering applications. An allegation made in this text is that the introduction of object-oriented methodologies in engineering will eventually alleviate this situation.

Next, common knowledge types used in engineering are examined. For several different fundamental engineering tasks, such as design and analysis, the knowledge types required are discussed.

## Models

Engineers use models extensively to describe the way the world works and to organize knowledge for designing new entities. The major need for a model is for capturing and organizing knowledge in frameworks in a way that permits easy viewing, understanding, and retrieval. In addition to the need for capturing declarative knowledge, engineering uses two other dominant modeling activities: (1) creating and using mathematical models and (2) employing heuristic models or "rules of thumb." Knowledge represented by these three modeling types serves as the core of the engineering discipline.

*Declarative Models.* Models that capture declarative knowledge are essential. Declarative knowledge (i.e., static knowledge) can be thought of as encyclopedic knowledge in a particular case. Reference information, libraries of designs, tabular listings of algorithms and their actions, histories, anecdotal information, glossaries, and interpretations are among the kinds of declarative information
that need to be captured. Some attempts have been made to capture knowledge on a grand scale (e.g., the CYC project; Lenat, Prakas, and Shephard, 1986); unfortunately, human knowledge is too broad to permit encyclopedia capture. A more reasonable solution is to capture extensive knowledge in restricted domains.

Techniques for organizing, understanding, and communicating knowledge are essential. Without domain-specific knowledge, algorithmic and reasoning methodologies become virtually useless. Hence, a critical requirement for knowledge representation in engineering (or any field, for that matter) is the creation of acquisition, access, inquiry, and manipulation of static knowledge methodologies that can be used in applications as well as analysis and design systems.

***Mathematical Models and Algorithms.*** The working of the world in terms of physical-law-based mathematical equations has traditionally been a central part of knowledge representation methods used by engineers. Many facets of the dynamic world that engineering seeks to characterize can be described in terms of differential equations. Both static and dynamic behaviors of systems as well as stochastic (random) behaviors can be modeled mathematically. Mathematical techniques, descriptions, and algorithms have been built, taught to students, and used in engineering for many years.

Algorithms are defined as “Any mechanical or recursive computational procedure” (Morris, 1981). Algorithmic descriptions of procedures for doing things tend to become almost “black-box” or object-like in nature over some period of time. The term *black box* refers to an encapsulated procedure which takes an input and produces an output, without the user needing to understand the internal working of the procedure. In contrast, an observable system is termed a *glass box*. In time, new knowledge about a procedure moves from the glass-box stage to the black-box stage; that is, the knowledge becomes encapsulated. Encapsulated procedures are routinely used throughout engineering without a deep understanding of the internal working of procedural contents. An example is the use of the fast Fourier transform (FFT) in various fields. The FFT converts time-domain signals to frequency-domain signals, providing the user with an understanding of the frequency content in a signal. Such analyses would be useful, for example, in measuring the vibration in a helicopter blade, examining vibrations in a tall building, understanding sonar signals, or computing the frequency components of brain waves. Users of algorithms of this sort are content to understand the requirements for input into the black box and understand the implications of the data produced. A direct analogy can be made with the basic nature of object-oriented encapsulation in which the user is shielded from understanding the internal functioning of an object and must only send a message to the object to elicit a desired behavior.
*Mental Models*. The term *mental model* is used to indicate a model formed in the mind (Gentner and Stevens, 1983). The term is not often employed in engineering but is useful in this description to indicate the distinction between mathematical models and heuristic or rule-of-thumb models of how things work. Engineers, as problem solvers, use mental models of the world in terms of rules and, in all likelihood, qualitative models. Rules capture heuristics in terms of causality, that is,

IF (a condition or conditions is true) THEN (a conclusion)

and qualitative models capture the working of physical mechanisms in terms that indicate qualitative relationships. Each of these model types are explained next.

*Rules: Reasoning Models*. The use of rules has been studied extensively in the area of “expert systems” (Hayes-Roth, Waterman, and Lenat, 1983) in which attempts have been made to mimic the reasoning of experts. By capturing many causal relationships in a domain, numerous software systems have been built during the last decade that mimic the reasoning of experts. The use of these so-called “shallow” reasoning systems has been commonplace in engineering. A shallow model is one that captures only surface level causalities but does not deal with “deep” or algorithmic law-related knowledge. There remain many debates about the utility of “shallow” versus “deep” reasoning. For the purposes of this text, both are considered important—the first captured in rules and qualitative models and the second in physical-law-related algorithms.

*Qualitative Models*. Qualitative models (Bobrow, 1985) can be thought of as mental models of physical systems. Quantitative information is absent for qualitative models and changes are represented in terms of qualitative change. Whereas quantitative representations employ equations that relate directly to physical laws, qualitative models describe how things work in a much less precise way, usually simply in terms of variable increases, decreases, or no change. For example, if a variable (e.g., the pressure in a model of a steam plant) in a model increases, that increase may cause another variable to decrease. In turn, that decrease may cause other changes, and so forth. This type of description is excellent for visualization and understanding how causality-linked components operate in a physical system.

The use of qualitative mental models in engineering is probably quite widespread, even though there has been little attention given to this concept in many engineering circles. Consider, for example, the use of a model of a steam engine. Although the way a steam engine works is describable by mathematical
equations, it is also describable by qualitative relationships such as "if the pressure at point A is increasing rapidly, then the plant is about to blow up." Experts who understand physical systems may well capture complex models in these terms, permitting almost instant visualization of relationships between entities in a system. Such models aid in understanding how a physical system works without having to understand equations that describe a system.

## Knowledge Types Needed for Engineering Tasks

**Analysis.** To build applications for engineering analysis, declarative knowledge models, algorithms, and rules appear to be the dominant representation techniques required. Analysis includes situation observation and application of evaluative techniques. Here, declarative knowledge representations that provide information on how to conduct analyses are primary requirements followed by the availability of algorithmic tools that permit transformation of data into understandable terms. Once evaluative data is secured, rule-of-thumb methods for interpretation are employed. These steps are typically carried out when humans analyze problems. Machine-based analysis and/or machine-facilitated analytical systems can capture these same steps using the representational mechanisms described.

**Design.** Design, the creation of new artifacts, begins with a specification of requirements and ends with the product, as discussed in Chapter 9. Representation must include ways of specifying what has been done in the past because much of design is conducted by making analogies to prior designs. In design, heuristic reasoning is required perhaps more than in any other engineering activity. Design is thought by some to be more “art” than algorithms, meaning that designers create through innovation and experience. To capture this type of knowledge for building automated design systems, knowledge in the form of heuristic rules should be captured. Also, in design, the capability of evaluating design trade-offs is required. Such knowledge can be captured in rules as well, or perhaps in the form of networks of constraints.

**Simulation.** For simulation, a *runnable* model of an engineering system under study is required. The goal of simulation is to verify the behavioral operation of a system prior to actually fabricating a design. The implementation of a simulation might be a constraint model, a discrete-event model, or a set of interconnected algorithms which permit interpretation of the behavior of the system. Chapter 14 will contain information about the implementation of simulation systems using object-oriented methods.
## Knowledge Organization and Object-Oriented Methods

The previous paragraphs explain some of the representation needs that are required in engineering. There are doubtless other needs as well. However, the systematic linking of representation mechanisms with engineering task needs is a continuously evolving study and no consensus knowledge about the proper means for understanding these linkages is yet available. However, an interesting observation is that different engineering tasks have similar representational needs: knowledge in the form of declarative knowledge, algorithms, rules, constraints, and qualitative models. In the upcoming sections of this chapter the ways that the object-oriented representation model can be used to facilitate knowledge representation tasks will be examined.

### 11.2 Representing and Acquiring Knowledge

To be useful in building computer-based systems, knowledge must be acquired and cast in some machine-consumable fashion. Books, video media, algorithms and system implementations in computer code, verbal anecdotes, and other materials currently comprise the vast corpus of engineering knowledge. To capture this knowledge in a machine-understandable way will require a significant effort in building knowledge-based organization methodologies. This section will examine some general techniques that can be used for this purpose. Subsequent sections will look at specific implementation strategies.

#### Representation

Two dominant forms of knowledge representation have been categorized: declarative and procedural knowledge. Declarative knowledge is “what is” or static knowledge. Procedural knowledge is “how to” knowledge or knowledge that is represented as a series of steps. During the early history of work in knowledge representation, there were many arguments about which representation style was better (Barr and Feigenbaum, 1981). Although there was considerable debate on this issue, the issue resolved itself as people came to recognize that both types of knowledge were important. From the discussion in earlier parts of this chapter, it is indeed evident that both types of knowledge are needed for representing knowledge in engineering.

Over the last two decades, there has been voluminous experimentation with different styles of knowledge representation [see, e.g., Brachman and Levesque (1985)]. The major categories that have been examined by legions of
investigators include logic-based methods, procedural representations, semantic networks, rule systems, frames, scripts, and, more recently, objects.

*Logic.* Early logic-based systems described the world in terms of mathematically representable sentences such as

"All transistors have three leads"

Logic systems capture many rules of this sort and through a logical inference process are able to make deductions about other facts. Prolog (Clocksin and Mellish, 1984) is an example of a logic-based language that became popular for programming in logic (see Chapter 5).

*Procedural Systems.* The original concept of procedural systems was to capture knowledge in small bits of code about how to do things. Now, in light of detailed evaluations of representational needs, the use of procedures is well established as one of the techniques needed to represent knowledge. In object-oriented methodologies, methods are implemented by procedures!

*Semantic Nets.* The word *semantic* is defined as "pertaining to meaning" (Morris, 1981). Semantic nets are pieces of knowledge linked together in a network which, when taken as a whole, have meaning. Originally developed by Quillian (1968), semantic nets were invented to serve as a model for human associative memory. As shall be seen in this and later chapters, the representation technique is useful for many different kinds of knowledge. A semantic net consists of nodes that represent objects and links that represent the interrelationships between nodes.

*Rule/Production Systems.* Early research on rule systems [see, e.g., Newell and Simon (1972)], then called production systems, also focused on explicating human cognition. In the 1980s, research and development of rule systems that captured human reasoning for practical purposes gained high visibility and became used throughout industry to capture heuristic knowledge in the form of if-then rules. Systems with these characteristics have become widely popular and are often referred to as expert systems.

*Frames.* Frames were developed for capturing static knowledge about the world and during the 1980s became the dominant technique for representing declarative knowledge. Frames permit representing prototypical forms which have slots (names) and values with which one can capture information that describe things. Chapter 2 presented an example of capturing knowledge in frames and also described methods of enhancing frames to couple procedures to frames. As will
be described in the upcoming paragraphs, frames and object descriptions have virtually identical characteristics for describing declarative knowledge! This point will be made clear via an example later in this chapter. Frames also share representational mechanisms with semantic nets, requiring only small changes to permit addition of different kinds of linkages to pull together nodes of information with different meanings.

*Scripts*. The term *script* comes from a theatrical metaphor in which actions are scripted to give players directions of what to do. Scripts, as popularized by Schank and Abelson (1977), permit descriptions of sequences of actions that should be carried out to accomplish some goal. For example, a script could be created to fabricate a printed circuit board. Scripts share a common ground with procedural methods and, indeed, can be thought of as simply packaged procedures.

*Objects*. Finally, the most recently investigated representation paradigm is that of objects, the central topic of this text. Objects combine most of the good features of representation techniques investigated in the past and, in addition, include other features as have already been discussed in some detail in previous chapters.

Of the major historically useful representation paradigms listed previ-
ously, frames, semantic nets, rules, and objects have played dominant roles. The
novice user who simply wishes to represent knowledge in an application has a
difficult problem in choosing which of the popular representations should be
used because there are massive overlaps between the capabilities of the differ-
ent techniques. Furthermore, once one or more representations are chosen, one
must acquire knowledge prior to use. Next, the acquisition process will be
examined to be followed by implementation examples.

The next sections examine the different representation types using
examples and relate the characteristics of the representations to the object-ori-
ented style.

11.3 Frames, Semantic Nets,
and Object Representations

Frames

In Chapter 2, the general concepts of frames were discussed, including
how to attach procedures to frames. For the purposes of comparison of frames
and object representations, the example of a frame shown in Table 11.1 will be
used. This frame gives the basic outline of a frame that describes the character-
istics of a computer. As shown in this partially filled out example of a frame,
<table><caption>**Table 11.1** Example Characteristics of a Frame</caption><tr><td>(defFrame ComputerCharacteristics</td></tr><tr><td>(physical</td></tr><tr><td>(memory</td></tr><tr><td>(options</td></tr><tr><td>(type {simm sip chip} typeConstraint)</td></tr><tr><td>(maxMem {2 4 8 16 32} memoryConstraint)</td></tr><tr><td>(mounting {vertical horizontal})</td></tr><tr><td>(cpuSpeed {16 20 25 33})</td></tr><tr><td>(userAcess {mouse Keyboard})</td></tr><tr><td>)</td></tr><tr><td>(functional</td></tr><tr><td>(software</td></tr><tr><td>(editors</td></tr><tr><td>(word (characteristics (memory 2</td></tr><tr><td>(speed &gt; 12)</td></tr><tr><td>(suitability suitPointer)</td></tr><tr><td>(cost 140)</td></tr><tr><td>)</td></tr><tr><td>)</td></tr><tr><td>(wordPerfect (characteristics</td></tr><tr><td>(...))</td></tr><tr><td>)</td></tr><tr><td>(compilers...)</td></tr><tr><td>(spreadsheets...)</td></tr><tr><td>(databases...)</td></tr><tr><td>)</td></tr><tr><td>(cost</td></tr><tr><td>(vendor</td></tr><tr><td>(HP</td></tr><tr><td>(models</td></tr><tr><td>{QS16 RS20 RS25 QS16S} typeinformer)</td></tr><tr><td>)</td></tr><tr><td>(IBM</td></tr><tr><td>(...)</td></tr><tr><td>(Apple</td></tr><tr><td>(...)</td></tr><tr><td>)</td></tr><tr><td>)</td></tr><tr><td>)</td></tr></table>

information might be included, such as the physical, functional, and cost characteristics of a computer. In each of the subcategories, additional specifications would be included. For example, for physical characteristics, information about memory, the type of mountings that are available, cpu speed, and user access methods could be included. Of course, many additional attributes might be added as well. Note the way that subframes are nested: memory, mounting, cpuSpeed, and userAccess are all subframes that contain additional information. Furthermore, any subframe can be extended in the same way. Note the
<figure><img src="image_133.png" /><figcaption>**Figure 11.1** Strict Hierarchical and Tangled Hierarchies.</figcaption></figure>

syntax of showing alternatives with curly braces "{...}." A purely declarative frame would simply contain information with no additional procedural information. Thus, one might retrieve the information that (computerCharacteristics physical memory options type) would contain (simm sipp dram).

The example frame displayed in Table 11.1 is strictly hierarchical; that is, each node in the tree has only one ancestor. If multiple ancestors are permitted, then the tree is said to be "tangled." If the tree is organized such that nodes further removed from the root can inherit information from multiple nodes closer to the root, then the organization is said to permit "multiple inheritance." Consider the example in Figure 11.1 in which single inheritance is shown with solid lines and multiple inheritance with dotted lines. The nodes "corolla," "camry," and "lexus" inherit information from both hierarchical structures shown. The total structure is said to be tangled and, because information is inherited from more than one place, inheritance is multiple.

Some implementations of frames extend the paradigm to include active values, or procedures that run when a slot or slots are accessed in the frame. In the example, the names of procedures to run when information in a frame is accessed are shown following the alternatives in curly braces; for example, typeConstraint and memoryConstraint. Various implementation strategies exist such as running one procedure when a value is put into a slot or running another procedure when values are accessed. In this example, running the procedure "typeConstraint" might put information into other slots in the
same frame (or another frame, for that matter). Suppose that the subframe "cost" contains information about vendors and that some of the slots in that subframe have places to fill in the memory type. Furthermore, suppose that the programmer has created a program to examine trade-offs in selecting computer characteristics. If the user selects a particular memory type (e.g., SIMM), the procedure "typeConstraint" could access another slot and put in that slot the information that SIMM had been selected. Then, if a particular style of computer is selected, the SIMM constraint might limit the available manufacturer selections to the ones that used SIMMS as a memory mounting methodology. Thus, based on this concept of interlinking sets of constraints attached to values of slots in a frame, one could construct a system that would permit trade-offs between interrelated sets of information to be made.

A cautionary note is worthwhile here. From Table 11.1 and the preceding discussion, it is easy to see that the complexity of representing information in this fashion increases very rapidly as more detail is put into the frame. Procedures can be attached to slots or rules can even be run that manipulate the same or other frames. After some time of adding information in this way, conceptual spaghetti results. Furthermore, implementing interacting constrained relationships in this way results in the near impossibility of modification. Representing frames in graph form with links and their effects shown graphically would assist the user in understanding how a frame-implemented constraint system works, however.

*Representing Frames in Objects.* Frames are essentially identical to objects as far as the representation of tree-like hierarchical knowledge is concerned. It is quite simple to mimic static frame representation by using dictionaries in the instance variables of objects. Consider Figure 11.2 which shows the same implementation that was presented in Table 11.1 implemented in an object/dictionary style. An object, perhaps in a class called **DeclarativeInformation**, contains instance variables, one of which might be "computerDesign-Knowledge." In this instance variable, one could store the dictionary "computerCharacteristics," and in the slots of this dictionary other dictionaries containing more information could be stored. One could even add procedures in dictionary slots to completely mimic the frame-based active value methodology. However, the same problems encountered in frames would appear. Because objects are utilized, improved understandability is achieved by making procedural methods in objects and attempting to divorce control from representation.

The end point of this discussion of frames versus objects is that frame and object representations can be used in the same conceptual way. Frames organize knowledge in hierarchical or tangled organizations. Objects also have the capability for representing just the same structures.
<figure><img src="image_134.png" /><figcaption>**Figure 11.2** Frame Representation in Objects: Recasting the Frame of Table 11.1.</figcaption></figure>

## Scripts

The concept of a script is simple. One of the definitions of the term is that a script is the text of a play. Generalizing this concept extends the definition to mean that a script captures knowledge about sequences of events. Hence, scripts can be a useful representation mechanism for capturing lists of actions, such as a series of steps necessary to solve a problem.

There are various ways that one could implement a script. Because the intention is to record a set of procedures, a list of actions could be captured as procedures in a frame slot or as different terms in several slots in a frame. Actions could also be captured in if-then rules or in a list of functions. Also, scripts can adapt to a context by having alternative actions to take based on input data.

Table 11.2 displays a simple way to implement a script in ST-80. For demonstration purposes this example can be executed in a workspace, if desired. A local variable "aScript" is defined and bound to a new ordered collection. Three blocks are added to "aScript" that can be executed at a later

<caption>**Table 11.2** Implementing a Script</caption>

```
aScript|
aScript := OrderedCollection new.
aScript add: [Transcript show: 'action I'];
    add: [Transcript show: 'action II'];
    add: [Transcript show: 'action III'].
aScript do: [:aBlock| aBlock value].
```
time. Each block can contain any executable code; in this case a simple message is written on the transcript. Once "aScript" contains an ordered collection of executable blocks, the blocks can be passed one by one to another block using the *do*: message. Then, sending *value* to each executable block will run any code specified inside the block. The reader is encouraged to type in other specific actions in the blocks and observe the running of this script.

## Semantic Nets

Figure 11.3 displays a semantic net representing the meaning about transistors. The primary relationships in this diagram are the "isa" links which represent the inheritance linkages in the net. The term "isa" is commonly used to mean "is a" which refers to the inheritance property of the link. That is, a transistor *is an* electronic device and a Mosfet *is a* transistor, and so forth.

<figure><img src="image_135.png" /><figcaption>**Figure 11.3** Example of a Semantic Net. [After Bourne et al. (1989).]</figcaption></figure>
<figure><img src="image_136.png" /><figcaption>**Figure 11.4** An Application Built Using a Semantic Net. (With permission; Academic Computing.)</figcaption></figure>

Other kinds of links can be used, such as `isPartOf` and `hasPart`, to represent other types of semantic relationships. In principle, many kinds of links could be defined; however, the more link types that are created, the more complex the organization of the net will become.

Creating a network representation system in Smalltalk-80 is an interesting exercise. Figure 11.4 displays the window of an ST-80 application called NRL (Network Representation Language) that was created to permit construction of networks (Bourne et al., 1989). Table 11.3 shows the objects and their instance variables that were created for this application and Figure 11.5 recasts the same information as a class network.<fnref n="1" /> The design intent of NRL was to permit users to create semantic nets by moving forms onto a canvas to create network nodes and to provide the ability to connect nodes with different types of links. This general network representation system has served as the basis for

<footnote n="1">¹NRL was originally created in ST-80, Version 2.5. The hierarchy shown is changed for Release 4, by the substitution of `ControllerWithMenu` for `MouseMenuController`. The Release 4 version is available as indicated in the Appendix.</footnote>
<table><caption>**Table 11.3 Class Hierarchy for NRL**</caption><thead><tr><th>Object ()</th></tr></thead><tbody><tr><td>View ('model' 'controller' 'superView' 'subViews' 'transformation' 'viewpoint' 'window' 'displayTransformation' 'insetDisplayBox' 'borderWidth' 'borderColor' 'insideColor' 'boundingBox')</td></tr><tr><td>NetView('activeNode' 'canvas' 'greekedView' 'externModel' 'partMsg' 'acceptMsg' 'menuMsg' 'displayLabel')</td></tr><tr><td>ContextEditorView ('parentNet')</td></tr><tr><td>Object ()</td></tr><tr><td>Controller ('model' 'view' 'sensor')</td></tr><tr><td>MouseMenuController ('redButtonMenu' 'redButtonMessages' 'yellowButtonMenu' 'yellowButtonMessages' 'blueButtonMenu' 'blueButtonMessages')</td></tr><tr><td>CanvasController ('scrollBar' 'marker' 'horScrollBar' 'horMarker' 'oldPoint' 'corner')</td></tr><tr><td>NetController ()</td></tr><tr><td>BrowserController ()</td></tr><tr><td>ContextDisplayController ()</td></tr><tr><td>ContextEditorController ()</td></tr><tr><td>InstructorController ()</td></tr><tr><td>NetViewPluggableController ('lastLoc')</td></tr><tr><td>Object ()</td></tr><tr><td>SemanticNet ('nodes' 'links' 'label' 'student' 'studentRecord' 'levels')</td></tr><tr><td>NRLContext ('contextnodes' 'contextlinks' 'name' 'associatedNode' 'locations' 'textLocations')</td></tr><tr><td>Object ()</td></tr><tr><td>Links ('input' 'output' 'name' 'sensor')</td></tr><tr><td>AttributeLinks ()</td></tr><tr><td>HierarchyLinks ()</td></tr><tr><td>RelationalLinks ()</td></tr><tr><td>Object ()</td></tr><tr><td>NetNodes ('nodeContext')</td></tr><tr><td>ConceptNode ()</td></tr><tr><td>LessonNode ('questions' 'currentQuestion' 'currentChoice' 'tmpVal')</td></tr><tr><td>AttributeNode ()</td></tr><tr><td>InstanceNode ()</td></tr></tbody></table>
<figure><img src="image_137.png" /><figcaption>**Figure 11.5** The Class Hierarchy for NRL.</figcaption></figure>

various types of representation schemes, several of which will be subsequently described. NRL is available in the public domain, as described in the Appendix.

Figure 11.4 contains several application design features of interest. The left view contains the network represented on a **CanvasView** which is scrollable in two directions (see Chapter 8 and the Appendix). In the bottom right of this view is a small "greeked" view that is the same view "shrunkBy" the amount needed to fit in the window. In the remainder of the view, information about the network is shown that is related to each node in the network. In this example, the application is using the semantic net as a tool for teaching. More information about this application is given in several places (Bourne et al., 1989; Antao et al., 1990) and is discussed in more detail in the next section.

## Hypertext/Hypermedia

Closely allied to semantic net representations are concepts in hyper-text and hypermedia. These two relatively new terms are defined as follows.
<figure><img src="image_138.png" /><figcaption>**Figure 11.6** Traditional Hypertext. (With permission; Academic Computing.)</figcaption></figure>

Hypertext is nonlinear text and hypermedia is nonlinear media. These concepts can be explained by examining Figure 11.6 which displays a set of text in a window in the upper left of the figure. Highlighting words or phrases in the text, as shown, can pop up other windows that contain more information about the highlighted items. When the items that appear are text, the knowledge organization is hypertext, and when presentations other than text are shown (e.g., such as video, animations, sound, etc.), then the presentation combination is called hypermedia, because different types of media are used. Information can be organized in a hierarchical graph as well, as shown in Figure 11.7. Arraying information in this fashion is called graph-based hypermedia (Bourne et al., 1989). The methodologies used for creating semantic nets described in the previous section work well for creating graph-based hypertext/hypermedia systems.

The importance of including hypertext/hypermedia as a representation in building applications is that this knowledge organization can be (1) used
<figure><img src="image_139.png" /><figcaption>**Figure 11.7** Graph-Based Hypertext. (With permission; Academic Computing.)</figcaption></figure>
by the program and (2) accessed and displayed to the end user. Knowledge captured and organized in this graphic fashion permits browsable representations of knowledge which facilitate direct modification and observation of the contents of nodes. Hence, in applications that are built for engineering analysis and design, as well as other systems, hypertext graphs can be included for presenting and organizing knowledge about the application. The utilization of the knowledge captured in this fashion could facilitate various tasks, such as (1) teaching how to use an application, (2) defining terms, or (3) exploring knowledge in a domain.

## Knowledge Chunking and Browsing

Another concept associated with knowledge organization is concerned with capturing representing, and browsing knowledge. To capture knowledge, one can handcraft domain-specific graphs of knowledge using semantic nets or hypertext, as indicated previously. A related, yet more general approach, is to build small "chunks" of knowledge that are accessible via a browser, much like the class browser of Smalltalk. Consider, for example, the knowledge browser shown in Figure 11.8 which displays a browser tailored for engineering knowledge (van der Molen, 1989). Arrayed across the top of the view are views listing

<figure><img src="image_140.png" /><figcaption>Figure 11.8 A Knowledge Browser.</figcaption></figure>
<figure><img src="image_141.png" /><figcaption>Figure 11.9 A Network of Knowledge Chunks for Presenting Tutorial Information.</figcaption></figure>
(1) the general area, (2) the subject area within the general area, (3) modules in the subject area, and (4) items for the module. Different perspectives for the items are selected by pressing the buttons shown at the bottom left of the figure. The perspectives or views of the knowledge listed are, for the most part, familiar. For example, laws, texts, examples, graphics, and so forth are listed.<fnref n="2" /> The utility of this type of knowledge browsing system is for constructing lessons in computer-based training systems. This browser is directly modeled on the class browser of ST-80.

Figure 11.9 shows another part of a tutoring/training system consisting of a network of linked knowledge chunks that display the presentation sequence of lessons to be given to a student. This representation is a semantic net that was built using the NRL methodology discussed earlier in this chapter. In this example, the presentation sequence proceeds from the top to the bottom of the graph, presenting lessons in the form of knowledge chunks with branch points along the way to change the flow of control depending on the way that the student answers questions posed by the system. For example, introductory information is first presented ("intro"), and after an introductory question, either basic, pulse, or equipment introductory knowledge chunks are presented based on the selection of the student.

## 11.4 Rules, Procedures, and Algorithms

Rules, procedures, and algorithms all represent sequences of "how to" knowledge, that is, sequences of things that are to be done. An algorithm captures a methodology for solving a problem in a finite number of steps. The implementation of an algorithm is made by concatenating sequences of executable computer statements known as procedures. Rules are also procedural because sequences of rules capture a line of reasoning. Reasoning using rules proceeds either from data toward a goal or attempts to prove goal statements by reasoning from the goal, by proving subgoals and ultimately reaching the data.

Forward-chaining rule systems reason from data toward a goal and backward-chaining rule systems reason from the goal to data. The common architecture for rule systems is to have some type of "working memory" or temporary storage area in which data is stored. Forward-chained rule systems match the items in their if parts (known as antecedents) against working memory and if an item is there, they fire the rule which may produce a message or deposit a new item in working memory. The inference engine (i.e., the program machinery that matches the elements in working memory with the

<footnote n="2">²EOI = Events of Instruction; Assoc = Associations.</footnote>
rules) continues to test each rule until no more rules can fire and leaves the results in working memory. In contrast, backward chaining starts with a number of goals and runs all the rules that can directly or indirectly prove the hypothesis. A hypothesis is a tentative goal solution, of which there may be several that would prove a goal. In backward chaining, there may well be a long chain of rules representing many subgoals that must be found before a hypothesis is proven.

Rule systems have been deeply examined and explained in a wide variety of papers and textbooks (Giarratano and Riley, 1989; Brownston et al., 1985). Both forward- and backward-chaining inference methods are widely used; which paradigm to use depends on the nature of the problem to be solved. Forward chaining is particularly useful for making inferences from data and backward chaining is normally employed for securing conclusions starting with several different hypotheses that should be proved. Depending on the characteristics of the problem, either or both of the methods might be used. Commercial tools for inference are normally based on one technique or the other, yet some incorporate both techniques (e.g., ART, the Automated Reasoning Tool). The interested reader is referred to the two texts listed previously for detailed information on rule systems.

The importance of this discussion on rule systems is that rules permit making inferences, a task that is difficult to do in pure object-oriented systems. Hence, if inference is needed in an application built using object-based methods, it may be necessary to build a simple rule system or to interface the object-oriented system to an existing rule system. Both methods will be illustrated in the remainder of this section.

To illustrate the simplicity of a forward-chained rule system, Table 11.4 demonstrates how to construct this type of inference system in ST-80. All

<table><caption>**Table 11.4** A Forward-Chaining Rule System for ST-80</caption><tr><td>Object subclass:</td><td>#RBS</td></tr><tr><td>instanceVariableNames:</td><td>'rules facts'</td></tr><tr><td>classVariableNames:</td><td>"</td></tr><tr><td>poolDictionaries:</td><td>"</td></tr><tr><td>category:</td><td>'Trivial RBS'</td></tr></table><p>This is a simple example that implements a forward chaining rule system. All methods in RBS inference are accessed by sending messages to 'self'</p><table><tr><td>RBS methodsFor:</td><td>Inference</td></tr></table><table><tr><td>forwardchain</td><td></td></tr><tr><td>rules do:</td><td>[:rule](self tryrule: rule)</td></tr><tr><td>ifTrue:</td><td>[↑true]</td></tr><tr><td>↑false</td><td></td></tr></table>
<table><caption>**Table 11.4 Continued**</caption><thead><tr><th></th><th></th></tr></thead><tbody><tr><td><strong>infer</strong></td><td>self forwardchain ifFalse: [↑nil]. "continue to forwardchain until no rules fire"<br>self infer</td></tr><tr><td><strong>store: fact</strong></td><td>(facts includes: fact)<br>ifTrue: [↑false]<br>ifFalse: [facts add: fact. ↑true]</td></tr><tr><td><strong>testIfPartOfRule: rule</strong></td><td>[ifs progress]<br>ifs := rule first. "get the antecedents"<br>ifs do: [:if((facts includes: if) "do the facts include the antecedents?"<br>ifTrue: [progress := true]<br>ifFalse: [↑false]].<br>↑progress</td></tr><tr><td><strong>tryRule: rule</strong></td><td>(self testIfPartOfRule: rule)<br>ifTrue: [(self use ThenPartOfRule: rule)<br>ifTrue: [↑true]<br>ifFalse: [↑false]]<br>ifFalse: [↑false]</td></tr><tr><td><strong>useThenPartOfRule: rule</strong></td><td>[thens]<br>thens := rule last.<br>thens do: [:then](self store: then)<br>ifTrue:<br>[Transcript cr; show: (rules keyAtValue: rule)<br>asString, 'deduces', then; cr. ↑true]<br>ifFalse: [↑false]]</td></tr></tbody></table>

**RBS methodsFor: Initialize**

**example**

facts add: 'a'; add: 'b'.
rules at: #rule1 put: #((('a' 'b') ('c'))).
rules at: #rule2 put: #((('c') ('d'))).
rules at: #rule3 put: #((('d') ('e'))).
rules at: #rule4 put: #((('e') ('f'))).
rules at: #rule5 put: #((('f') ('g'))).
rules at: #rule6 put: #((('g') ('h'))).

"Temp := RBS new.
Temp init; example; infer.
Temp inspect"

**init**

rules ← Dictionary new.
facts ← OrderedCollection new.
<figure><img src="image_142.png" /><figcaption>**Figure 11.10** Example of a Rule from CLIPS and the Result of Running the Inference Engine.</figcaption></figure>

methods for inference are contained in the protocol of the class **RBS** named "inference" and consist of six simple methods that are easily understood. In the class **RBS** "initialize" protocol, an example is given that illustrates the use of this class. The reader is encouraged to use this code and create a rule system in ST-80. The example first creates an instance of **RBS**, initializes the system, and makes six simple rules and two facts. Finally, the message *infer* is sent to the system. The method *infer* runs itself until no more rules fire. The *useThen-PartOfRule*: contains a message to the transcript which prints out a message for every rule firing that yields a way for the user to observe the functioning of this simple system.

There are many types of rule systems available for both forward- and backward-chaining inference procedures. Among the popular forward-chaining rule systems are CLIPS (Giarratano and Riley, 1989) and OPS5 (Brownston et al., 1985). Figure 11.10 displays the syntax and use of a typical forward-chaining rule system. This example is from CLIPS, and OPS5 differs in only minor syntactic details (e.g., the symbol "⇒" in CLIPS is "→" in OPS5). Shown at the top of the figure is the definition of a rule named "gain." The syntax of the rule is that rule antecedents (the if part) precede the "⇒" and consequents (the then part) follow. In the antecedent, two slots named "voltageIn" and "voltageOut" are created with variables in the two slots that are bound to any data with variables that have the same slot names when the rule runs. The consequent contains what is to be concluded; in this case, the value of the gain computed between the input and output is added to working memory. Following the definition of the rule, the way that the rule is run is shown. First, two working memory elements are asserted and the inference engine is instructed to run. The result is that the elements in the if part of the rule match the elements in working memory and the rule is fired (i.e., the consequent is executed) and the result is posted in working memory. Note the mechanism of binding variables "inputV" and "outputV" to the values "1" and "5" respectively and the use of these values in the consequent to compute the gain
(GAIN = output voltage/input voltage). The prepended "?" to "inputV" and "outputV" indicates that "inputV" and "outputV" are variables.

Although there are several variations on the rule running theme, the basic data-driven rule execution method is to match all rules in an inference system against working memory (the data) until no rule fires as all the if parts of the rules are compared to working memory. Quite complex inference schemes can be constructed in this manner; however, once the number of rules become large, it is quite difficult to understand the functioning of the body of rules and, in consequence, it is difficult to maintain and modify.

Various large commercial inference systems include both forward and backward chaining such as KEE (Kehler and Clemenson, 1984) and ART. Such systems contain various rule acquisition and building tools, as well as visualization aids. Furthermore, there are at least two inference systems written in Smalltalk, for example, HUMBLE (Piersol, 1987), a backward-chaining system manufactured by Xerox Special Information Systems, and SMART, created by Knowledge Systems Corporation.

How do rules relate to graphs? The answer is: very closely. Indeed, some rule systems such as CLIPS and OPS5 convert the rules created into a graph to permit more rapid execution. Consider, for example, Figure 11.11 which gives an idea of how a set of rules might be converted to a simple graph. Two rules are shown in this example and three facts. In a forward-chaining rule system, adding facts to working memory and then running the rules would result in "c" being concluded first and then "e" being concluded. Note that "c" had to be concluded before the second rule would run. Adding data to the input nodes

<figure><img src="image_143.png" /><figcaption>**Figure 11.11** Mapping Rules to a Graph.</figcaption></figure>
of the graph produces the same result; as shown, asserting "a" and "b" results in concluding "c" and asserting "d" results in "e" being concluded. Rather than constructing code to interpret rules, it is more efficient to create a graph that will produce the same results. An order of magnitude or better improvement in speed is often observed by converting rules to graphs.

The format of rules and the representation capabilities of object-oriented systems are not well matched. Rules are procedural and require an imperative style of programming (i.e., a series of code statements) to implement forward chaining or backward chaining—not the style that has been discussed throughout this text for object-oriented programming. Nevertheless, representation of knowledge in rules is frequently desirable in building applications in which heuristic decisions need to be made. The alternatives available to the system builder are: (1) write the needed code procedurally in the object-oriented language, (2) write an inference engine, or (3) couple the object-oriented program to an inference engine. The first option should be taken if the number of rules is small and if the rules are changed infrequently. The second option can be selected if there are only a few rules but changes are often required. The third option should be chosen if there are many rules. These options are particularly relevant to Smalltalk-80. Because ST-80 runs more slowly than common procedural languages such as C, coupling to an efficient graph-based inference engine written in that language will result in a significant speed up. The next chapter will discuss how to build such an interface and will demonstrate the resulting class created for coupling CLIPS to ST-80.

### 11.5 Acquiring Knowledge

Once representation methodologies have been selected for building an application, knowledge must be acquired in the specific domain of interest. There are various options available for acquiring knowledge that include: (1) entering the knowledge by hand, (2) using a knowledge acquisition tool to organize knowledge, and (3) permitting the system to discover knowledge as it works. By far the most common method is the first. The second option is utilized in a number of experimental knowledge acquisition systems, and the third method remains as basic research. In the first and most frequently used case, the user is required, for example, to create rules, frames, or objects. The methodology for object creation has been discussed in Chapter 3 in terms of analyzing a problem to capture object specifications. If rules are the representation used, then rules are written which can be data driven or goal driven. In the first case, that is, forward chaining, conclusions are made by writing rules that examine the data first and work toward a conclusion. For goal-driven rule systems or backward chaining, the possible conclusions that can be made
(hypotheses) are listed and an attempt is made to collect rules that will prove
the hypotheses. Either one or the other of these two modes of thinking about
solving a problem using rules are normally used in the knowledge acquisition
process. If frames are used in a representation, slots in the frames must be filled
with information much like that in the computer frame example shown earlier.

For handcrafting knowledge entry into specific representations, the
dominant method has been to debrief an expert and then directly enter
the secured knowledge into the representation used. Individuals performing the
latter task have come to be known as "knowledge engineers" (Hayes-Roth,
Waterman, and Lenat, 1983). More advanced methods employ tools for assisting
the user. For example, the KEE system (Kehler and Clemenson, 1984) uses
graphical tools for frame building. Beyond methods that simply provide visual-
ization and organization support are tools that actually assist in classification of
the knowledge [see, e.g., Kitto and Boose (1988)] according to a taxometric
scheme. Some knowledge acquisition systems can be tuned to assist users in
acquiring and categorizing knowledge into areas such as anticipatory, circum-
stantial, refining, and qualifying knowledge (Eshelman et al., 1988) that satisfy
the requirements of a particular domain.

Learning or discovery systems are the least developed and possibly the
most interesting category for acquiring knowledge. During recent years, systems
that learn by examining cases have become popular (Hammond, 1989) as have
neural nets (Rummelhart and McClelland, 1986) which learn from collecting
many observations. These techniques are most useful for data that can be
separated into distinct categories.

11.6 Representational Relationships

Although a number of different representation methodologies were
mentioned in the outset of this chapter, three primary representation tech-
niques emerged that are suitable for building knowledge-intensive applications;
*rules*, *frames*, and *objects*. Rules are best for representing knowledge about
inference and frames are superior for capturing static knowledge. Rules can be
represented in frames and frames can be used to conduct inference by using
procedures attached to slots. Furthermore, knowledge represented in frames
can be represented in an identical manner in objects. Rules can be represented
either by coupling to an external rule system or by recoding the knowledge into
procedures. Moreover, rule systems can be written using objects. The point is
that one can "mix and match" the various styles of representation—not quite
freely, but any goal that one has can probably be achieved with any of the
representations. Object-oriented representations tend to be the easiest to main-
tain and understand due to the modularity of declarative knowledge. Rules,
however, are best understood in a rule format, that is, a listing of near-English
language rules that capture a reasoning process. Objects, however, can repre-
sent reasoning by making rules into the form of a constraint graph which also
permits easy understanding by observation of graph connections.

The preceding explanation of the differences between representations
leads to the following conclusions. Most representation mechanisms can be used
for problem solving. Some are better than others for some tasks. The viewpoint
taken in this text is that the optimal system architecture will permit the use of
different representations but will not force the use of a methodology. In line
with the general theme of the text, the conclusion is made that object-oriented
methodologies will satisfy most application needs, with the exception of infer-
ence. For cases in which fast and robust inference engines are needed, it is
perhaps best to couple object to rule paradigms.

11.7 Identifying the Knowledge Organization Needed for Problem Solving

Problem solving consists of several facets, including problem analysis, creation of plans to pursue, and understanding ways of dealing with dead ends (i.e., unreachable solutions) and incomplete knowledge and data. To produce applications that have the components of problem solving built into the software, it is essential that a representation scheme be provided that can capture the knowledge needed to solve problems. As discussed previously, there are a number of prominent ways of representing knowledge for this purpose. Yet, there are few clear guidelines for making proper paradigm selections. Some alternatives are clear. For example, it is clear that rules should be used to capture reasoning. However, it is not as clear what kind of rule system should be used and why. Furthermore, there are alternatives to rules, such as coding the information in procedures or creating graphs that have the same effect as rules. Another clear alternative is representing declarative knowledge, such as the information in text books or manuals. Hypertext/hypermedia methods, presented in some form of a semantic net or frame, are quite useful for this style of representation. Knowledge captured in nets or frames can serve as useful background knowledge for problem solving. Both frames and nets are directly represented with objects. Object-oriented methods hold the edge for creating simulations, especially in situations in which a simulated system can be directly mapped into objects with behaviors that mimic the behavior of the objects in the real world.

In summary, there are many useful knowledge representation method-
ologies available, including the primary methodologies of rules, frames, and
objects. Research on knowledge representation is continually evolving. The
methods that we have discussed will work for producing many applications; yet, it can be anticipated that new advances will, at some point, replace or augment the techniques discussed in this chapter. As shown, object-oriented methodologies can be used for implementing most, if not all, representations required to solve problems.

## References

Antao, B. A. A., A. J. Brodersen, J. R. Bourne, and J. R. Cantwell (1991). Building Intelligent Tutorial Systems for Teaching Simulation in Engineering Education. *IEEE Transactions on Engineering Education*.

ART, The Automated Reasoning Tool. Inference Corporation. Los Angeles.

Barr, A., and E. Feigenbaum (1981). *The Handbook of Artificial Intelligence*, Vol. 1, William Kaufmann, Los Altos, CA.

Bobrow, D. G. (Ed.) (1985). *Qualitative Reasoning about Physical Systems*. MIT Press, Cambridge, MA.

Bourne, John R., Jeff Cantwell, Arthur J. Brodersen, Brian Antao, Antonis Koussis, and Yen-Chun Huang (1989). Intelligent Hypertutoring in Engineering. *Academic Computing*, September, 18-48.

Brachman, R. J., and H. J. Levesque (Eds.) (1985). *Readings in Knowledge Representation*. Morgan Kaufmann, Los Altos, CA.

Brownston, L., R. Farrell, E. Kant, and N. Martin (1985). *Programming Expert Systems in OPS5*. Addison-Wesley, Reading, MA.

Clocksin, W. F., and C. S. Mellish (1984). *Programming in Prolog*. Springer-Verlag, New York.

Eshelman, L., D. Ehret, J. McDermott, and M. Tan (1988). MOLE: A Tenacious Knowledge Acquisition Tool. In *Knowledge Acquisition Tools for Expert Systems*, J. Boose and B. Gaines (Eds.), pages 95-108. Academic, New York.

Genter, D., and A. Stevens (1983). *Mental Models*. Lawrence Erlbaum Associates, Hillsdale, NJ.

Giarratano, J., and G. Riley (1989). *Expert Systems: Principles and Programming*. PWS-KENT, Boston, MA.

Hammond, K. (Ed.) (1989). *Proceedings: Case-Based Reasoning Workshop*. Morgan Kaufmann, San Mateo, CA.

Hayes-Roth, Frederick, Donald A. Waterman, and Douglas B. Lenat (1983). *Building Expert Systems*. Addison-Wesley, Reading, MA.

Kehler, T. P., and G. D. Clemenson (1984). An Application Development System for Expert Systems. *System Software*, Vol. 3, No. 1, January, 212-224.
Kitto, C. M., and J. H. Boose (1988). Heuristics for Expertise Transfer: An Implementation of a Dialog Manager for Knowledge Acquisition. In *Knowledge Acquisition Tools for Expert Systems*, J. Boose and B. Gaines (Eds.), pages 175-194. Academic, San Diego, CA.

Lenat, D., M. Prakas, and M. Shephard, (1986). CYC: Using Common Sense Knowledge to Overcome Brittleness and Knowledge Acquisition Bottlenecks. *AI Magazine*, Vol. 6, No. 4, Winter, 65-85.

Michalski, R. S., Jaime G. Carbonell, and Tom M. Mitchell (1983). Machine Learning. Tioga Publishing, Palo Alto, CA.

Morris, William (Ed.) (1981). *The American Heritage Dictionary of the English Language*. Houghton Mifflin. Boston, MA.

Newell, A. and H. A. Simon, (1972). *Human Problem Solving*, Prentice-Hall, Englewood Cliffs, NJ.

Piersol, Kurt W. (1987). *HUMBLE V2.0 Reference Manual*. Xerox Special Information Systems, Xerox Corporation, Pasadena, CA.

Quillian, M. R. (1968). Semantic Memory. In *Semantic Information Processing*, M. Minsky (Ed.), pages 227-270. MIT Press, Cambridge, MA.

Royce, W. W. (1970). Managing the Development of Large Software Systems: Concepts and Techniques. *Proceedings of WestCon*, August. Rummelhart, D. E., and J. L. McClelland (1986). *Parallel Distributed Processing*. MIT Press, Cambridge, MA.

Schach, S. (1990). *Software Engineering*. Aksen Associates. Homewood, IL.

Schank, R. C. and R. P. Abelson, (1977). *Scripts, Plans, Goals, and Understanding*, Lawrence Erlbaum, Hilldale, NJ.

van der Molen, H. (1989). Knowledge Acquisition in Intelligent Tutoring Systems. Class Project, EE 355, Vanderbilt University, Nashville.

## Exercises

11.1 Explain the difference between declarative and procedural knowledge. Give an example of each.

11.2 What are three ways to represent knowledge? Briefly summarize the advantages and disadvantages of each technique.

11.3 Frames, semantic nets, and objects are very similar in concept. Describe the similarities and differences among these different representation methodologies.

11.4 Explain the differences between the terms syntactic and semantic.
11.5 Is hypertext more like a system for programming or more like a system for indexing information?

11.6 As engineering knowledge grows, the corpus of the body of this knowledge cannot be understood by a single individual. How would you design systems that could assist individuals and teams working together to understand and deal with the complexity of engineering knowledge in the 21st century?

11.7 Rule systems are useful for making inferences. When would it be useful to include rules in an application? Consider, for example, the use of rules for capturing scarce expertise or for monitoring the user and modifying what the user sees on the screen.

11.8 Write a simple script in the form shown in Table 11.2. Show how you can use a script to control the flow of actions in an application.

11.9 Do engineers really use rules of thumb in problem solving? Or are models, simulations, and algorithms always used? What do you think?
<figure><img src="image_144.png" /></figure>
# Integrating Object-Based Environments with the Real World

## 12.1 Concepts

Prior to this chapter, computer-based application systems have been treated as essentially divorced from the physical world. In previous chapters, the only connection to the outside world discussed has been the graphics and direct-manipulation interfaces to users that were examined intensively in Chapter 7. Yet, for creating applications in engineering other types of interfaces are frequently required. For example, many engineering tasks need the ability to acquire data, communicate electronically with others, and control a host of different types of instruments. These needs can be met in an object-oriented system such as Smalltalk-80 by enhancement of the basic environment. This chapter will explore the capabilities already present in the ST-80 environment for interacting with the world and discuss how to add additional features. Several examples will be presented to indicate how an enhanced environment could be employed to solve various engineering tasks. It is worth noting that the concepts discussed are general in nature and not completely specific to the ST-80 environment. Nevertheless, ST-80 examples are given, in part because these examples can be implemented using the techniques described throughout the text but also because of the clarity in code presentation that Smalltalk and the object-oriented paradigm affords.

Figure 12.1 displays a block diagram of a computer system that contains many types of computer I/O (input/output) cards attached to their related peripherals. The peripheral devices shown cover the common types of devices manufactured to connect computer systems to the outside world. There are other devices that can be added, such as image scanners. It is unlikely that any computer would ever be configured in the way shown; however, it is useful
<figure><img src="image_145.png" /><figcaption>**Figure 12.1** Computer Peripherals and Their Connection to the External Environment.</figcaption></figure>
to indicate that a wide range of functionality can be achieved by adding different types of cards. Serial cards permit communication with external devices, such as modems for indirect access to the telephone network. Serial cards can also be used to drive printers or any other serial devices, such as serial printers or a serial mouse. Parallel cards are useful for driving multiple input and output lines for controlling printers and other parallel devices. Note that typical printers are either serial or parallel and sometimes even both types of connections are available. LAN (local-area network) cards allow access to networks that use coaxial cable or fiber-optic cable for rapid transmission of information. Analog to digital (A to D, or A/D) and digital to analog (D/A) cards convert externally acquired analog signals to digital signals, and vice versa. IEEE-488 cards implement a control and communications protocol that is useful for accessing and manipulating instrumentation. Video drivers permit control of video sources, including digitizing video information. Finally, voice input and output capabilities permit implementation of a verbal interface with a computing system.

The most popular types of interfaces to the external world will be examined next, followed by a description of how to interface external devices and non-Smalltalk procedures to ST-80. Examples of the use of various interface types will be presented in the remainder of the chapter.

## 12.2 The External Environment

Table 12.1 lists four major areas that can enhance computer I/O capabilities by connecting computer peripherals to the external environment. *Communications* is the best known category, because most computers interface to other computer systems either via a modem, hardwired cable, or network connection. Intercomputer communications, either via direct serial connections or local-and wide-area networks, is a widely used medium for transmitting information and facilitating human communication through electronic mail. An additional communications medium, the IEEE-488 bus, basically a multiwire cable, is a standard for communication between computers and instrumentation. *Control* is another prominent category in which computer peripherals are directly interfaced to various types of instrumentation or other devices such as printers. The IEEE-488 bus is also widely used for control of instrumentation. *Analog signals* acquired from the world outside a computer system must be converted to digital representation prior to use by a digital computer; the converse is true as well. Analog to digital converters (A/D) and digital to analog converters (D/A) are widely used I/O devices that provide this transformation. Finally, the communications capability of computers can be enhanced by the addition of new modalities, such as video and voice. Video permits the
<table><caption>**Table 12.1** External Environment Connections</caption><thead><tr><th></th><th></th></tr></thead><tbody><tr><td><strong>Communications</strong></td><td>Serial<br>Local-area net<br>IEEE 488</td></tr><tr><td><strong>Control</strong></td><td>Parallel<br>IEEE 488</td></tr><tr><td><strong>Acquisition of signals and creation of signals</strong></td><td>Analog to digital<br>Digital to analog</td></tr><tr><td><strong>Modality enhancement</strong></td><td>Voice input<br>Voice output<br>Video presentation</td></tr></tbody></table>

viewing of scenes from the world, including animation. Voice communication (both input and output) interfaces add additional capabilities to the typical screen, keyboard, and mouse interfaces.

## Serial Interfaces

Figure 12.2 illustrates the way serial connections are made between a serial card in a computer and a serial device. A typical cable between the two devices contains 3 to 10 connections. Below the diagram is shown how wires in a serial cable are allocated to different tasks. The most used connections are pins 2, 3, and 7 of a common 25-wire cable which provide links for transmitting data, receiving data, and ground, respectively. The remaining connections are used for applications that require control of the data transmission (such as stopping the transmission of data due to printer speed) and control of a modem, for example. Signals are sent in series on the receive and transmit wires in the cable. Figure 12.3 illustrates the way serial information is transmitted. High and low bits are sent at a fixed rate (e.g., 9600 baud). After an initial low bit to indicate "start," eight high and low data bits, which represent a byte of information, are sent. Codes that represent bytes of information belong to a set of codes defined by the American Standard Code for Information Interchange, and are thus referred to as ASCII codes. Individual numbers, characters, and symbols are assigned byte codes. For example, an "A" has an ASCII value of 65 and a "1" has a value of 49.
<figure><img src="image_146.png" /><figcaption>Figure 12.2 Serial Communications. Numbers shown are pins commonly used.</figcaption></figure>

<figure><img src="image_147.png" /><figcaption>Figure 12.3 Serial Information Transmission.</figcaption></figure>
<figure><img src="image_148.png" /><figcaption>Figure 12.4 Parallel Interface.</figcaption></figure>

## Parallel Interfaces

Figure 12.4 shows a multiwire connection between a parallel interface in a computer and a parallel device. The major distinction between this configuration and the serial interface discussed previously is that data is sent *in parallel* across all the wires simultaneously. Each lead is dedicated to a different bit, in contrast to each bit being sent serially across a pair of wires in the serial interface. As a consequence of the parallel nature of this interface, parallel interfaces can normally transmit data at much faster rates than serial interfaces.

## LANs and WANs

LAN stands for local-area network and WAN for wide-area network. Figure 12.5 shows a connection of a LAN card from a computer to a network cable. Cables, in order to achieve high speed, are typically coaxial or optical fiber. Local-area nets are commonly used to wire together local clusters of computers, for example, those not separated by more than a mile. Connection to wide-area networks, which permit national and international communications, are typically via bridges (i.e., hardware protocol conversion interfaces) to network cables that utilize leased telephone lines or use fiber-optics cable utilized by various communications companies.
<figure><img src="image_149.png" /><figcaption>Figure 12.5 ThinLan Connections.</figcaption></figure>

<figure><img src="image_150.png" /><figcaption>Figure 12.6 Analog to Digital and Digital to Analog Connections.</figcaption></figure>

## Analog to Digital and Digital to Analog Conversion

Figure 12.6 depicts a combination card with both A/D and D/A capabilities. Normal connection to the world outside the computer is via a set of leads from the card that connects to a box or connector panel from which connections are made to an external process, for example, a laboratory experiment or process that is to be controlled. Signal amplitudes, if not similar to the input range of the A/D card, normally need to be amplified or attenuated prior to being fed to the A/D converter. Examples of this latter requirement might be the amplification of the voltage measured from a strain gauge or the signals secured from electrodes placed in a muscle.

## IEEE-488 Protocol

The IEEE-488 bus is a very popular communications and control protocol standard (Gates, 1989) that has been promoted by the Institute of Electrical and Electronic Engineers. It is used as a standard by hundreds of
<figure><img src="image_151.png" /><figcaption>Figure 12.7 IEEE-488 Connection to Instrumentation.</figcaption></figure>

instrument manufacturers which fabricate literally thousands of different instruments. A bus, in this case, is nothing more than a cable consisting of 24 lines, 8 for data, 5 for management, and 3 for handshaking (i.e., requesting and acknowledging) and ground and auxiliary lines. The bus can be connected as a "daisy chain," star, or in various other topological combinations. One computer serves as a controller for all the instruments. As shown in Figure 12.7, various instruments can be connected directly to an IEEE-488 interface card. Another option is shown in Figure 12.8, in which the serial port of a computer is connected to a hardware serial to 488 bus converter which connects to the various instruments.

<figure><img src="image_152.png" /><figcaption>Figure 12.8 Connecting to an IEEE-488 Bus Using a Serial to 488 Converter.</figcaption></figure>
## 12.3 Interfacing Procedures and External Devices to the ST-80 Environment

### Concepts in Interfacing

In previous chapters, the graphics interface and rapid prototyping capabilities of the Smalltalk-80 environment have been discussed in some detail. This robust environment, however, has few "hooks" to the real world, with the exception of the serial interfaces. Furthermore, the ST-80 language has some perceived deficiencies in speed and seamless integration with software written in other languages. To ameliorate these two problems, ST-80 provides a mechanism for integrating C-language routines into the system, such that the routines can be easily used as methods in Smalltalk classes. This capability solves the two problems just mentioned by (1) permitting the writing of drivers for peripheral cards in C and (2) allowing simple and direct access to compiled C programs. Examples of both these capabilities will be given later in this chapter. The C language is one of the most widely used procedural languages and, in addition, produces very efficient code. Hence, combining these capabilities with the strong object-oriented graphical environment of Smalltalk results in a complete system with a wider range of strong capabilities.

### External I/O Access Using ST-80

ST-80 provides several classes for interfacing to UNIX, DOS, and Macintosh operating system primitives that permit I/O access. Figure 12.9 displays the class hierarchy for accessing the facilities of supported operating systems. As shown, there are separate classes for DOS, Macintosh, and UNIX errorHolders (i.e., repositories for error handling). The major superclass is IOAccessor which serves as a superclass for classes that implement specific I/O for three operating systems: Mac OS, DOS, and UNIX. ST-80 implements subclasses of IOAccessor that contain interfaces to Disk and "TTY" (i.e., serial communications<fnref n="1" />). As shown in the figure, other subclasses could be implemented that would support other types of I/O devices (e.g., IEEE-488 instruments). Also, subclassing IOAccessor permits adding interfaces for other operating systems. Note how the inheritance property of ST-80 simplifies the capturing of I/O interfaces for different operating systems within the same environment.

<footnote n="1">¹In Objectworks\Smalltalk, Release 4, TTY communications classes are located in \utils\serial.st.</footnote>
<figure><img src="image_153.png" /><figcaption>**Figure 12.9** Class Hierarchy for Various Operating Systems. (DOS, MAC, and UNIX are abbreviations for **DosIOAccessor**, **MacIOAccessor**, and **UnixIOAccessor**, respectively.)</figcaption></figure>

This feature, in part, is why ST-80 can be moved relatively easily between various hardware platforms.

## An Interface to Procedures

The second area of interfacing is the ST-80 interface to procedures written in the C language. C represents a good choice for melding with the ST-80 environment due to its popularity and wide availability. Furthermore, C code can be written that will interface to other languages such as Fortran or Pascal, so that code written in these languages can be interfaced to the ST-80 environment as well.

Table 12.2 presents an example of an ST-80 class named **CLIPS** that interfaces methods in this class to the C functions of the CLIPS inference engine (discussed in Chapter 11). Functions in CLIPS are accessed through primitives in the **CLIPS** class methods. A blackboard of information is kept in a data structure implemented in C. Functions for accessing the blackboard and
<caption>Table 12.2 Interfacing to the Clips Inference Engine</caption>

**Object subclass:** #CLIPS
**InstanceVariableNames:**"
**classVariableNames:**"
**poolDictionaries:**"
**category:** 'ITS-CLIPS'

**CLIPS class**
**instanceVariableNames:**"

**CLIPS class methodsFor:** primitives

**assert:** aString
`<primitive: 10118>`

**bload:** aFileName
`<primitive: 10106>`

**bsave:** aFileName
`<primitive: 10107>`

**clearClips**
`<primitive: 10102>`

**exciseRule:** aString
`<primitive: 10119>`

**loadRules:** aFileName
`<primitive: 10104>`

**readBB**
`<primitive: 10120>`

**resetClips**
`<primitive: 10101>`

**run:** aRunLimit
`<primitive: 10103>`

**CLIPS class methodsFor:** examples

**example1**
"CLIPS example1"
CLIPS clearClips.
CLIPS loadRules: 'gain.rul'.
CLIPS assert: 'voltageIn 1'.
CLIPS assert: 'voltageOut 5'.
CLIPS run: -1.
Transcript cr; show: CLIPS readBB.
Transcript cr; show: CLIPS readBB.
"example rules in clips"
"(defrule gain
(voltagein ?inputV)
(voltageOut ?OutputV))
->
(assert (gain = (/ ?outputV ?inputV)))
<caption>**Table 12.2 Continued**</caption>

```
(defrule adjustGain
  (gain ?value&: (< ?value 10))
  →
  (bbadd adjustGain))"
```

**example2**

```
"CLIPS example2"

CLIPS clearClips.
CLIPS bload: 'c:\clips\mab.bin'.
CLIPS resetClips.
CLIPS run: -1.
Transcript cr; show: CLIPS readBB.
Transcript cr; show: CLIPS readBB
```

running the inference engine are accessible in the class **CLIPS** using the syntax `〈primitive: xxxxx〉`, where `xxxxx` is a unique numeric value identifying a primitive written in C. Each method calls a different primitive, passing a predetermined number of variables. The mechanism for passing this information and constructing the interface will be described in the following discussion. Readers not interested in these details should skip to Section 12.4.

Examples of the use of the **CLIPS** class interface to the CLIPS inference engine are shown at the end of Table 12.2. In the first example, the working memory of CLIPS is cleared ("clearclips"), rules in an external file are loaded, two strings are loaded into working memory, and the inference engine is run. The "-1" argument to CLIPS indicates that the inference engine should run until no more rules fire. The example rules shown in the comment are the contents of the rule file loaded. The values of *voltageIn* and *voltageOut* are bound to the two variables *?inputV* and *?outputV*, respectively, which are subsequently used to compute the value of the gain. The second rule accesses the value posted in working memory by the first rule and, if the gain is too low, posts information on the blackboard accessible to Smalltalk to "adjustGain." This last string is the information that can be read by Smalltalk by sending the message "readBB" to the class **CLIPS**. The second part of the example shows these steps and prints the information on the system transcript. When the "readBB" message is sent a second time and the results printed, a message that the blackboard is empty is displayed in the transcript. To accomplish these interactions between Smalltalk and C, several specific interfacing procedures are required which are explained next.
## The C Interface to ST-80

ST-80 can be interfaced to software written in the C language. Although it is not the intention of this text to show "advanced" concepts or explicit details of code not related to ST-80, the next paragraphs are included to give the reader an idea of how the interface between ST-80 and C can be constructed. The information to be imparted from the example includes (1) how to set up a C routine for interfacing, (2) the characteristics of what can be put in the routine, and (3) how to name and link to ST-80. The code and libraries used will differ for different hardware platforms. Different C-language compilers are required for each different platform. The High-C Compiler (MetaWare, 1989) is used for a DOS platform. The Macintosh (MPW C) and UNIX machines require different C compilers.

The basic steps for creating your own primitive is to create a C routine called UPinstall(). This routine should add your C program by invoking a routine called UPAddPrimitive. For example, a file might contain C code of the following form:

```c
#include "userprim.h"                 /* initial definitions */
char *UPinstall()
{
    UPAddPrimitive(10010, cfunc, 2);   /* the number, name of the
                                        C function */
    return "Test primitive";          /* and number of arguments */
}

void cfunc(receiver, arg1, arg2)
    upHandle receiver, arg1, arg2;
{
    /* insert any C code here */
}
```

In the preceding code framework, a user primitive number is specified in the UPAddPrimitive function to identify the user primitive code. These numbers are to range between 10,000$_{10}$ and 19,999. There are many functions available for the user to employ for passing arguments, converting data between C and Smalltalk, and so on. The reader is referred to the Objectworks \ Smalltalk User's Guide (1991) for more information on the user-defined primitive interface. Inside any Smalltalk method, the C code can be directly accessed by referring to the primitive number. For example, one might create a test class such as **PrimitiveTestClass** containing a class method `test: with:` to try out the interface.
test: arg1 with: arg2

“PrimitiveTestClass test: 3 with: 4”

(primitive: 10010)

“Note the same primitive number as above”

Now, whenever the preceding code in the quotes is executed, the method *test: with:* and its arguments will be passed to the C code inside the primitive numbered 10010<sub>10</sub>.

To complete the installation of the code, the original Smalltalk object file is linked with the object file obtained by compiling the C-coded primitive function. Then, rather than using the original executable file for running Smalltalk (i.e., ST80.exe), a new executable file that includes the primitive code created is utilized (e.g., ST80user.exe).

The preceding description extends somewhat beyond the intended scope of this text and is included so that readers who wish to use these methods can have a better understanding of some of the potentially difficult details. However, for the reader who only wishes an understanding of the methodology, the main point is that C programs can be compiled and linked to Smalltalk. Many C routines can be linked to create a very versatile set of routines in the environment. A cautionary note is necessary, however. Although the technique just described appears quite appealing, the portability of the Smalltalk image is lost by adding various C functions. Hence, it is prudent to determine if any desired functionality can be added without having to resort to using the C-language linkages.

## Interfacing with Multiple Applications in Microsoft Windows

Release 4 of Objectworks \ Smalltalk includes classes that can be filed in which provide a simple and direct interface with the Microsoft Windows environment. The fileIn can be found in the standard release in \utils\extfunc.st. Filing in this code will create a category name OS-External-Interface which contains several classes including **MSWindowsInterface**. Contained in this class are a number of examples that can help guide the user in understanding how to interface Smalltalk with other applications in Windows. A simple example illustrates the use of the **MSWindowsInterface** class:

In a workspace, one can type:

MSWindowsAPI

define: 'WinExec'

parameters: #(#string #word)

returns: #word.

MSWindowsAPI at: #WinExec

callWith: 'calendar' with 1.