bachelor

40
Media Engineering and Technology Faculty German University in Cairo Algorithm Visualization VISA Bachelor Thesis Author: Ahmed Ashmawy Supervisor: Prof. Dr. Slim Abdennadher Submission Date: 1 June, 2008

Upload: 3ashmawy

Post on 07-Aug-2015

23 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: bachelor

Media Engineering and Technology FacultyGerman University in Cairo

Algorithm Visualization

VISA

Bachelor Thesis

Author: Ahmed Ashmawy

Supervisor: Prof. Dr. Slim Abdennadher

Submission Date: 1 June, 2008

Page 2: bachelor

Media Engineering and Technology FacultyGerman University in Cairo

Algorithm Visualization

VISA

Bachelor Thesis

Author: Ahmed Ashmawy

Supervisor: Prof. Dr. Slim Abdennadher

Submission Date: 1 June, 2008

Page 3: bachelor

This is to certify that:

(i) the thesis comprises only my original work toward the Bachelor De-gree

(ii) due acknowlegement has been made in the text to all other materialused

Ahmed Ashmawy1 June, 2008

Page 4: bachelor

Abstract

The main purpose of VISA is to visualize arbitrary algorithms. It capturesthe process of algorithm execution and reflects the information processedinto visual representations. The system relies on Java Debugger Interface(JDI) to dynamically extract information from the virtual machine. Thesoftware is aimed for students that need to understand the behavior ofexisting algorithms. It could also be used by programmers to visualizenew algorithms.

IV

Page 5: bachelor

Contents

1 Introduction 21.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.2 Aim of VISA . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.3 Thesis Overview . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 VISA 52.1 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 System Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.3 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

3 System Functionalities 83.1 User/Viewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

3.1.1 Installing VISA . . . . . . . . . . . . . . . . . . . . . . 83.1.2 Algorithm selection area . . . . . . . . . . . . . . . . . 83.1.3 Algorithm view area . . . . . . . . . . . . . . . . . . . 93.1.4 Trace table . . . . . . . . . . . . . . . . . . . . . . . . . 93.1.5 Input area . . . . . . . . . . . . . . . . . . . . . . . . . 103.1.6 Visualization area . . . . . . . . . . . . . . . . . . . . . 103.1.7 Control panel . . . . . . . . . . . . . . . . . . . . . . . 113.1.8 Console panel . . . . . . . . . . . . . . . . . . . . . . . 113.1.9 Options . . . . . . . . . . . . . . . . . . . . . . . . . . 123.1.10 Status Bar . . . . . . . . . . . . . . . . . . . . . . . . . 12

3.2 Programmer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123.2.1 Input of new Algorithms . . . . . . . . . . . . . . . . 123.2.2 Pseudo code file . . . . . . . . . . . . . . . . . . . . . . 133.2.3 Algorithm class . . . . . . . . . . . . . . . . . . . . . . 143.2.4 Map file . . . . . . . . . . . . . . . . . . . . . . . . . . 183.2.5 Visual class . . . . . . . . . . . . . . . . . . . . . . . . 19

V

Page 6: bachelor

CONTENTS VI

4 Implementation 224.1 Design Overview . . . . . . . . . . . . . . . . . . . . . . . . . 224.2 Debugging Engine . . . . . . . . . . . . . . . . . . . . . . . . 23

4.2.1 Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244.2.2 Local Variables . . . . . . . . . . . . . . . . . . . . . . 24

4.3 Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244.4 Console Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

4.4.1 Input Stream . . . . . . . . . . . . . . . . . . . . . . . 254.4.2 Output and Error Streams . . . . . . . . . . . . . . . . 25

4.5 Trace table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.6 Annotation Processor . . . . . . . . . . . . . . . . . . . . . . . 254.7 Visualization System . . . . . . . . . . . . . . . . . . . . . . . 264.8 Code Control . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

4.8.1 Code View . . . . . . . . . . . . . . . . . . . . . . . . . 274.8.2 Code Mapping . . . . . . . . . . . . . . . . . . . . . . 274.8.3 Code Highlighting . . . . . . . . . . . . . . . . . . . . 27

4.9 Input graphical interface . . . . . . . . . . . . . . . . . . . . . 28

5 Conclusion and Future Work 295.1 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295.2 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

References 31

Page 7: bachelor

List of Figures

3.1 VISA Screen-shot . . . . . . . . . . . . . . . . . . . . . . . . . 83.2 Directory node . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.3 File node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.4 Algorithm view area showing binary search algorithm . . . 93.5 Binary search algorithm trace table . . . . . . . . . . . . . . . 103.6 Input area of binary search algorithm . . . . . . . . . . . . . 103.7 Visualizing fibonacci recursive algorithm . . . . . . . . . . . 113.8 Control Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . 113.9 Console panel . . . . . . . . . . . . . . . . . . . . . . . . . . . 113.10 Status Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

4.1 Design Overview . . . . . . . . . . . . . . . . . . . . . . . . . 224.2 Code Control . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.3 Map Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

VII

Page 8: bachelor

List of Tables

3.1 LocalVariableEvent methods . . . . . . . . . . . . . . . . . . . 203.2 MyLocalVariable methods . . . . . . . . . . . . . . . . . . . . 203.3 FieldEvent methods . . . . . . . . . . . . . . . . . . . . . . . . 21

1

Page 9: bachelor

Chapter 1

Introduction

1.1 Overview

As the saying goes, ”A picture is worth a thousand words”. Algorithmvisualization tools implement this concept to facilitate the process of un-derstanding computer programs. Authors in the field have come up withalot of different definitions for software visualization. One of these def-initions is that software visualization is the use of crafts of typography,graphic design, animation, interaction, and cinematography to facilitatecomputer programs understanding [4]. Software visualization is furthercategorized to algorithm and data visualization. Visualizing data refersto visualizing the data structures and variables in the program. While al-gorithm visualization means visualizing the higher level abstraction thatdescribes the behavior of programs [4]. Use of visual aids in teaching hasalways been an added skill to the instructor because they form a mentalimage in the student’s brain that helps form relationships between ideas.Now with the use of algorithm visualization tools, instructors could inte-grate their explanations with images and animations. Teaching algorithmsfor computer science students has always been done using drawings andtrace tables to describe how the algorithm works. Software visualizationtools generate such animations so that the instructor could present themwith a click of a button. Programmers also use software visualization toolsto discover bugs in their systems, ease the design process, generate UMLdiagrams, and maintenance.

In the past decades visualization tools have evolved tremendously toprovide a better visualization experience. Algorithm visualization toolshave improved from visualizing only a fixed set of algorithms to visu-

2

Page 10: bachelor

CHAPTER 1. INTRODUCTION 3

alizing arbitrary ones. Current state-of-art visualization tools are able tovisualize large-scale programs at run time. This means that live informa-tion is gathered from the executing program and reflected via images andanimations. Even sounds are added to the visualization to create yet abetter experience. Software visualization tools are now able to provideboth data and algorithm visualization to the user. Let alone, the systemsthat are able to visualize concurrent programs and multiple programs. Vi-sualizing concurrent programs display concurrent tasks executing in theprogram so that the user is able to watch the behavior of each thread in aseparate view. While systems that visualize multiple programs are able toshow the behavior of different algorithms solving the same problem to theuser.

Unfortunately, most current systems are bounded by different restric-tions that introduce boundaries to the visualization process. Most of thesoftware visualization tools restrict the programmer to use a new customvisualization scripting language to produce the animation. The scriptinglanguage then uses a visual library that is implemented by the systemdeveloper to draw the various graphic elements that form the visualiza-tion. Therefore the produced visualization is bounded by the power ofthe scripting language and the visual library implemented by the systemdeveloper.

1.2 Aim of VISA

VISA aims to produce a dynamic image that reflects the executing pro-gram state at both data and algorithm levels. The system could be used toteach students how existing algorithms work or it could be used to visual-ize new algorithms. One of the important goals VISA tries to accomplishis to keep an open mind about how the programmer produces the visual-ization. So not only it does provide an interface for the user to watch thevisualization, but it also provides the programmer with an interface thatcould be used to acquire live information about the executing program.The programmer will not be bound to use a scripting language to producethe visualization. The programmer will be able to write Java code thathandles the incoming run-time information. VISA also does not restrictthe programmer to use a specific visual library to produce the animation.The programmer is free to choose whatever library they want.

Page 11: bachelor

CHAPTER 1. INTRODUCTION 4

1.3 Thesis Overview

The thesis is formed of 5 chapters including the introduction and the con-clusion. In Chapter 2 we introduce VISA and discuss the features it pro-vides. In Chapter 3 we will describe how the system could be used. Fi-nally, in Chapter 4 we discuss the implementation details of VISA.

Page 12: bachelor

Chapter 2

VISA

This chapter introduces VISA and discusses the main features provided.We will also point out who are the system users and what are their roles.

2.1 Requirements

VISA is implemented in Java, so its portable and cross-platform. The sys-tem could be used on any machine that has Java virtual machine installed.

2.2 System Users

• User/Viewer

The user/viewer is the person that will use the system to select froman algorithm collection an algorithm to run and then watch the visu-alization to understand how the algorithm behaves.

• Programmer

The programmer is the person that should write the algorithm andvisualization code that will be executed by the user/viewer.

2.3 Features

• Algorithm and Data Visualization

We differentiated between algorithm and data visualization and con-structed separate view areas for each. Algorithm visualization is thehigh level abstraction that describes the behavior of a program [4].

5

Page 13: bachelor

CHAPTER 2. VISA 6

The user will be able to watch the algorithm visualization in the vi-sualization area. On the other hand, data visualization is the visu-alization of the program variables and data structures and it is dis-played in the trace table. Visualization information for both typesis gathered dynamically as the program is executing. The trace ta-ble is automatically generated by the system and organized so thateach variable is displayed as an entry in the table. Each variable en-try contains the name, type and value of that variable. The systemgrabs the user’s attention to the entry currently being processed byhighlighting that entry. The trace table will only show variable val-ues of primitive types, more complex types is up to the programmerto visualize in the visualization area. The trace table is able to dis-play local variables, fields and even variables passed as argumentsto methods. While the data visualization is automatically generatedand displayed in the trace table, algorithm visualization is not. Theprogrammer has to write the code that produces the algorithm visu-alization and then the system will execute that code and output itsresults in the visualization area.

• Code View

The system will display the pseudo code of the program running sothat the user is able to relate the visualization to the source code. Thepseudo code is displayed in the algorithm view area and current lineexecuting will be highlighted to the user.

• User Control

The user will be able to run the program, sit back and relax and justwatch the visualization or they can run the program step by step.Since the program execution is so fast that the user may miss it, thesystem provides the user the ability to set a delay time between eachstep.

• User interaction with executing program

The system provides a console panel so that the user could interactwith the executing program. Also it provides a graphical interfacethat the user could use to set values of variables needed as inputby the algorithm. The input graphical interface recognizes primitivevariables and arrays. This feature works with single threaded pro-grams only, it cannot handle concurrent programs.

• Visualized Program

Page 14: bachelor

CHAPTER 2. VISA 7

The system is able to execute and visualize any Java compiled class.Since the visualized program is a compiled Java class the systemis able to handle sequential, iterative, conditional, recursive, multi-threaded . . . etc programs. For multi-threaded programs, the systemwill be able to execute them but it will not create separate views foreach thread. Separate views however could be done by the program-mer and viewed in the visualization area.

• Input of new algorithms

The system is designed so that it can accept new algorithm inputfrom the user. The code of the algorithm and its visualization how-ever must be written by the programmer in Java. The system willthen be able to execute the algorithm provided by the programmerand extract live information from it as it is running. Also it will sendinformation about the running algorithm in the form of events to theclasses written by the programmer so that the programmer would beable to draw the required visualization based on what is happeningin the executing program. The programmer is free to choose fromany graphic library to draw the algorithm visualization as long as itis written in Java.

Page 15: bachelor

Chapter 3

System Functionalities

In this chapter we will discuss how the user and the programmer woulduse the system. The chapter will be divided into two sections, one for theuser/viewer and the other for the programmer.

3.1 User/Viewer

Figure 3.1: VISA Screen-shot

This section discusses how the user/viewer could use VISA. Figure 3.1

8

Page 16: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 9

shows the various components VISA provide to the user. More detailsabout each component will be discussed in this section.

3.1.1 Installing VISA

• Unzip the file downloaded

• After unzipping, the directory algorithms and the jar file of VISAwill be created

• Run the executable jar file

3.1.2 Algorithm selection area

Figure 3.2: Directory node

Figure 3.3: File node

The algorithm selection area appears on the top left corner. It providesthe user the ability to select from a collection of algorithms that are savedunder the algorithm directory. Directories will be given the icon shownin Figure 3.2 while algorithm files will be given the icon shown in Figure3.3. Names of the directories and algorithm files will be displayed besidethe icons. When the user clicks on an algorithm file, the algorithm pseudocode will appear in the algorithm view area. Also the run button and thestep button will be enabled in the control panel.

3.1.3 Algorithm view area

The pseudo code of the algorithm selected will appear in the algorithmview area. As the system executes the algorithm, the system will highlightfor the user the current line being executed. The user could scroll the codeto be able to view different parts of the code. Figure 3.4 shows a snap shotof the view area displaying the binary search algorithm.

Page 17: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 10

Figure 3.4: Algorithm view area showing binary search algorithm

3.1.4 Trace table

Figure 3.5: Binary search algorithm trace table

The trace table is where the user views the data modifications happeningin the program. Each entry in the table corresponds to a variable in theprogram. Three columns appear in the table, which are the name, valueand type of the variable. Data modifications will be shown to the userby highlighting the corresponding entry in the table. The user will havethe ability to scroll the trace table up and down if the number of entries istoo large. Figure 3.5 shows a screen shot of the trace table while VISA isexecuting the binary search algorithm.

3.1.5 Input area

As an alternative for getting input from the console panel, VISA provides agraphical interface that the user could use to enter the values of variables.Figure 3.6 shows a screen shot of the graphical input interface at the startof binary search algorithm execution. Each variable will appear as an entryin that area. Each entry will contain the name, type and a text field the usercan enter in the value of the variable. Also each entry contains a randombutton that will randomize the value of the variable. If the user enters avalue that is not complying with the type of the variable an error messagewill appear to the user requesting entry of an appropriate value.

Page 18: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 11

Figure 3.6: Input area of binary search algorithm

To input values for arrays the user will have to input the value of thevariable that determine the size of the array first. Then the array panelwill automatically be generated and will include entries for all the arrayelements.

The user could randomize all values in the input area by clicking onthe Random all button at the bottom of the input area. After finishingentering all values the user should click the OK all button at the bottomof the input area to be able to continue execution. If the user clicked theOK all button without entering all values, an error message will appearrequesting from the user to enter all values.

3.1.6 Visualization area

Figure 3.7: Visualizing fibonacci recursive algorithm

The visualization area is where the user will be able to watch the algorithm

Page 19: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 12

animation provided by the programmer. The visualization area is locatedin the visualization tab. Figure 3.7 shows a screen shot taken from thevisualization area while VISA is executing Fibonacci recursive algorithm

3.1.7 Control panel

Figure 3.8: Control Panel

The user will be shown a control panel at the center that controls the exe-cution of the program. Figure 3.8 shows a snap shot of the control panel.The run button executes the program continuously so that the user couldjust sit back and watch the visualization. The stop button stops the exe-cution process and the continue button should be used if the user stoppedthe program execution and decided to continue execution continuouslyagain. The step button executes the program one step at a time. Finallythe restart button resets the execution, clears the trace table, input areaand the visualization area.

3.1.8 Console panel

Figure 3.9: Console panel

The console panel is where the user could interact with the executing pro-gram. If the program is printing messages it will appear in the consolepanel. It will also receive input from the user if the algorithm is waitingfor input from the user. The user will not be able to write anything in theconsole unless an input is needed by the program. Figure 3.9 shows ascreen shot of the console panel.

3.1.9 Options

The options tab provides the user the ability to modify the delay time andwhether to watch function arguments. The delay time is the delay time

Page 20: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 13

between each step the program executes. The delay time field accepts itsvalue in milliseconds. To apply new values of delay time, the user shouldenter the delay time value in its field and click on the save button at thebottom of the options panel. If the user enters characters and not numbers,an error message will appear to the user after clicking the save buttonrequesting appropriate input. The watch arguments switch when enabledwill make VISA be able to recognize function arguments in the program.For example if the function testFunction(testVariable) is called.Then testVariable will be shown to the user in the trace table area andin the visualization area (if the programmer is visualizing anything thatincludes the testVariable).

3.1.10 Status Bar

Figure 3.10: Status Bar

Figure 3.10 shows the status bar. The status bar displays informationabout the user’s actions, number of operations, and a progress bar thatdisplays an animation indicating the program execution.

3.2 Programmer

This section discusses how the programmer could write new algorithmsand plug them into the system. Each algorithm is composed of a pseudocode file, algorithm class, map file and a visual class. This section willdiscuss each one of them in details.

3.2.1 Input of new Algorithms

To introduce new algorithms into VISA, the programmer has to write analgorithm class, pseudo code file, map file and visual class. VISA can ac-cept an algorithm if it doesn’t have a map file or a visual class but whenexecuting the program VISA will not be able to highlight the pseudo codein the algorithm view area neither will it be able to draw an animation inthe visualization area. We will first start by explaining the algorithmsdirectory created after unzipping. Under the directory algorithms re-side the directories code, Analysis & Design of Algorithms, and

Page 21: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 14

CS102. The directory code contains all classes needed by the algorithms,this involves the algorithm classes and the visual classes and that is wherethe programmer should insert the needed classes. Analysis & Design-of Algorithms, and CS102 directories contain the pseudo code filesand the map files of the algorithms under different directories. For exam-ple the directory CS102 contains the directories Conditional, Iterati-ve, More Algorithms, and Sequential. Each one of these directoriescontains the pseudo code and map files of the algorithms belonging tothem. Now when VISA starts, it will display the algorithms in a tree hi-erarchy similar to the directory hierarchy. The following is the steps theprogrammer need to follow to insert a new algorithm into VISA:

1. Create a directory under algorithms directory that will include theprogrammer’s algorithm

2. Place the pseudo text file and the map file in that directory

3. Place the algorithm class and the visual class in the code directory

3.2.2 Pseudo code file

The pseudo code file should be named as the algorithm class name with.txt extension. For example if the algorithm class name is generalAlgor-ithm.class then the pseudo code file should be generalAlgorithm.t-xt . When VISA starts executing a certain algorithm it will display the textof the pseudo code file. The following is an example of the binary searchalgorithm pseudo code file.

int[] S;int x;

boolean BSearch(index low, index high) {index mid;if (low > high) then

return False;else

{mid = (low + high)/2 ;if (x == S[mid]) then

return True;else

if (x < S[mid]) then

Page 22: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 15

return BSearch(low, mid+1);else

return BSearch(mid+1, high);}

}

void BSearchCall(){

boolean found = BSearch(1,S.length);if(found) then

print "Found x"else

print "Sorry didnt Find"}

3.2.3 Algorithm class

The algorithm class is the compiled Java class of the algorithm. The classshould be compiled with -g parameter so that it generates all debugginginformation that will be needed[3]. VISA defined annotations that willbe explained later on in this chapter could be used to annotate elementsin the algorithm class to enable some functionalities that could be useful.The following is an example showing the binary search algorithm class.

@VisualizationClass(fileName="BinarySearchVisual")public class BinarySearch {

@GetInput(field = "null")private int n;

@GetInput(field = "n")private int[] S;

@GetInput(field = "null")private int x;

public BinarySearch() {n = 0;S = new int[n];x = 0;

Page 23: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 16

}

public boolean BSearch(int low, int high) {int mid = 0;if (low > high)

return false;else{

mid=(new Double(Math.floor((low+high)/2.0))).intValue();if (x == S[mid])

return true;else {

if (x < S[mid])return BSearch(low, mid - 1);

elsereturn BSearch(mid + 1, high);

}}

}

public void BSearchCall(){

boolean found = BSearch(0, S.length-1);if (found)

System.out.println("Found: " + x);else

System.out.println("Sorry didnt find:"+x);}

public static void main(String[] args) {BinarySearch b = new BinarySearch();b.BSearchCall();

}

}

Page 24: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 17

@GetInput annotation

@GetInput annotation is used to make the user able to input field valuesvia the graphical user interface. The @GetInput annotation could only beused on fields. The annotation contains an attribute field that declaresthe field as a dependent or an independent one. A field should be declaredas a dependent field if it’s an array, and its size will be the value of anotherindependent field. An independent field is a field that will not depend onvalues of any other field. The attribute field in the annotation shouldbe null if the field is independent. If the field is to be declared as de-pendent then the field attribute should contain the name of the field itsdepending on. The following is an example declaring independent fields.

@GetInput(field = "null")private int n;

@GetInput(field = "null")private int x;

Now when the user starts executing the program, the user will be showna panel to input the value of n and x in it. The following is an example ofdeclaring a dependent field S that is depending on the field n.

@GetInput(field = "n")private int[] S;

For this example, the user will be shown the panel to enter in it the valuesof S elements. But the panel will only appear after the user enters the valueof n. For example if the user entered 4 as the value of n then 4 elementswill appear in the input area.

After setting the annotation, the programmer has to initialize the anno-tated fields in the algorithm class constructor. The following is an exampleto show how this is done.

public BinarySearch() {n = 0;S = new int[n];x = 0;

}

The initialization step has to be done because the system sets the values ofthe fields when they are found in the constructor.

Page 25: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 18

@RandomFile annotation

This annotation could be used only with fields to specify a file that con-tains strings of possible input to that field. This annotation will only beenabled if the field was also annotated by @GetInput annotation. Theannotation should only be used with string fields. When pressing the ran-dom button for that field in the input area, the system will get strings ran-domly from the file specified by the @RandomFile annotation. We willdemonstrate how annotation will work with the following example. Let’ssay that the algorithm class contains the field testField of type string.And the possible input to that field is either ”bla bla” or ”not bla bla”. If theprogrammer wants one of these values to be displayed when the randombutton for that field is clicked in the input area then the @RandomFileannotation should be used here to accomplish that. Now the programmerneeds to create a file (say theBlaBlaFile.random), write ”bla bla” inone line and ”not bla bla” in another line and then annotate the field asfollows:

@RandomFile(file="theBlaBlaFile.random")String testField;

@VisualizationClass annotation

The @VisualizationClass annotation could be used only to annotatethe algorithm class. Its purpose is to link the algorithm class with a visualclass. We will demonstrate how this annotation could be used with thefollowing example.

@VisualizationClass(fileName="BinarySearchVisual")public class BinarySearch {....}

The above example made a link between the algorithm class BinarySearchand the visual class BinarySearchVisual. Now when VISA executesthis algorithm class it will draw whatever the programmer wrote in thevisual class in the visualization panel.

3.2.4 Map file

The map file is where the mapping between the pseudo code and the Javacode is defined. The map file should be named as the algorithm class with

Page 26: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 19

.map extension. Each line in the map file contains the pseudo code linenumber and the corresponding Java code line numbers. The programmercould map one line of pseudo code to multiple lines of Java code but notthe other way around. The syntax of each line is as follows

pseudo Line number:Java line numbers;

The following is an example of the binary search map file:

1:13,14;2:15;4:18;5:19;6:20;7:21;8:22;9:23;10:24;11:25;12:26;13:27;14:28;15:29;16:30;17:31;18:33;19:34;21:36;22:37;23:38;24:39;25:40;26:41;27:42;28:43;

The above example specifies that the pseudo code line number 1 will mapto Java lines 13 and 14 and so on. The end of the map file must contain anempty line.

Page 27: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 20

3.2.5 Visual class

The visual class is the class that should be written by the programmer todefine how the algorithm animation will be produced. This section willdiscuss how the programmer should write the visual class. The visualclass must extend the class Component or any other child of that class (ex-ample: JPanel). It also must implement the interface VisualInterfaceand its constructor shouldn’t have any arguments. Since the visual classshould implement the VisualInterface, the following methods shouldalso be implemented.

void LocalVariableCreated(LocalVariableEvent event)void localVariableModified(LocalVariableEvent event)void fieldAction(FieldEvent event)void threadDied(ThreadDeathEvent event)void threadStarted(ThreadStartEvent event)void methodEntry(MethodEntryEvent event)void methodExit(MethodExitEvent event)

threadStarted() / threadDied() methods

The method threadStarted() is invoked when a thread starts in thealgorithm class. While the method threadDied() is invoked when athread dies in the algorithm class. For more information about the classesThreadStartEvent and ThreadDeathEvent, please refer to the JDIdocument.

methodEntry() / methodExit() methods

The method methodEntry() is invoked when a method is invoked inthe algorithm class. While the method methodExit() is invoked when amethod exits in the algorithm class.

localVariableCreated() / localVariableModified() methods

The method localVariableCreated() is invoked when the algorithmclass creates a new local variable. While the method localVariableMod-ified() is invoked when an existing local variable value changes. Tables3.1 and 3.2 provide information about the class LocalVariableE- ventand other classes it uses.

Page 28: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 21

Table 3.1: LocalVariableEvent methodsReturn value Method name Method descriptionMyLocalVariable getVariable() Returns JDI LocalVariable instance

wrapped in MyLocalVariable class

Table 3.2: MyLocalVariable methodsReturn value Method name Method descriptionString getName() Returns the local variable

nameValue getValue() Returns the value of the

local variable. For moreinformation about theclass Value, please referto the JDI document.

Type getType() Returns the type of the lo-cal variable. For more in-formation about the classType, please refer to theJDI document.

LocalVariable getLocalVariableInstance() Returns the JDI Local-Variable instance. Formore information aboutthe LocalVariable class,please refer to the JDIdocument.

fieldAction() method

The method fieldAction() is invoked when a field declared in the al-gorithm class is modified. Table 3.3 provides information about the classFieldEvent.

Page 29: bachelor

CHAPTER 3. SYSTEM FUNCTIONALITIES 22

Table 3.3: FieldEvent methodsReturn value Method name Method descriptionString getFieldName() Returns the field name.Value getFieldValue() Returns the field value. For more

information about the class Value,please refer to the JDI document.

Type getFieldType() Returns the field type. For moreinformation about the class Type,please refer to the JDI document.

Field getField() Returns JDI Field instance. For moreinformation about the class Field,please refer to the JDI document.

boolean isArray() Checks if the field is an array. Themethod will return true if it’s an ar-ray and false otherwise.

List 〈Value〉 getArrayValues() The method returns a list contain-ing the values of the array elementsif the field is an array. It will re-turn null if the field is not an array.For more information about the classValue, please refer to the JDI docu-ment.

Page 30: bachelor

Chapter 4

Implementation

In this chapter we will discuss the implementation details of VISA. Beforereading this chapter, the reader should have finished reading the systemfunctionalities chapter to be able to understand.

4.1 Design Overview

Figure 4.1: Design Overview

Before entering into details of the implementation, first we will discuss anoverview of the system design. Figure 4.1 shows the design of VISA andhow the components communicate with each other. The core of VISA isthe debugging engine, which is responsible for executing and extracting

23

Page 31: bachelor

CHAPTER 4. IMPLEMENTATION 24

information from the program running the algorithm. The feature com-ponents surrounding the controller communicate with the debugging en-gine through the controller. Finally, the controller is the communicationmedium between the feature components and the debugging engine. Eachof these components will be discussed in details throughout the chapter.

4.2 Debugging Engine

The debugging engine is considered the core of VISA. This componentprovides VISA the ability to control the virtual machine running the algo-rithm the user chose to execute. Also it dynamically extracts informationabout the class loaded by the virtual machine.

The debugging engine starts by launching a virtual machine and con-necting to it. The virtual machine is launched with parameters to beginexecute the algorithm class corresponding to the algorithm the user choseto visualize. The debugging engine will deal with a mirror representingthe virtual machine. The mirror represents the composite state of the tar-get virtual machine [1]. The debugging engine then start creating requestsfrom the virtual machine to be notified if the following events are received

1. Method entry event

2. Method exit event

3. Class prepare event

4. Step event

5. Thread start event

6. Thread death event

When a method is invoked a method entry event is fired and when themethod exits a method exit event is fired. Class prepare events are re-ceived when the virtual machine prepares the class. Class preparation in-volves creating the static fields for a class or interface and initializing suchfields to the standard default values [2]. Step events are received whenthe virtual machine steps into a different line. Thread start events are fired

Page 32: bachelor

CHAPTER 4. IMPLEMENTATION 25

when threads are started from the algorithm class and thread death eventsare fired when threads die.

After setting up requests the debugging engine now is ready to be no-tified for these events and handle them as needed. The engine acquiresthe event queue from the virtual machine. The Event queue is a JDI objectand it’s defined as the manager of incoming debugger events for a targetvirtual machine [1]. The event queue will contain all the events fired thatwere created by the requests discussed above. The engine then resumesthe virtual machine execution and starts iterating through the queue topop the events and handle them.

4.2.1 Fields

When class prepare events are fired, the debugging engine starts creatingmodification watch requests for all fields declared in that class. Modifica-tion watch events are fired later on if field values are modified.

4.2.2 Local Variables

Local variables are discovered when the method holding them is invoked.Whenever a method is invoked a new frame is created that holds localvariable information. A frame is used to store data and partial results, aswell as to perform dynamic linking , return values for methods, and dis-patch exceptions [2]. Only one frame, the frame for the executing method,is active at any point[2]. This frame is referred to as the current frame [2].

When Step events are fired the current frame is acquired and visiblelocal variables at the current line location are processed. The debuggingengine fire events indicating that a local variable was created or modified.

4.3 Controller

The controller can be thought of as the communication medium betweenthe debugging engine and the feature components. It encapsulates debug-ging information received from the debugging engine and provides higherlevel information that could be directly used by the feature components.

Page 33: bachelor

CHAPTER 4. IMPLEMENTATION 26

4.4 Console Panel

The console panel is where the user interacts with the virtual machine. Theconsole panel is basically a text-area that receives input from the user andprint messages sent from the virtual machine. The controller acquires in-put, output and error streams from the virtual machine process and sendsthem to the console panel object. Each time the virtual machine starts thisprocess repeats.

4.4.1 Input Stream

The console panel object listens for input from the user and each characterthe user enters is concatenated into a string. When the user presses theenter key the string is converted into bytes and written to the input streamacquired from the virtual machine.

4.4.2 Output and Error Streams

Output and error streams are handled in the same manner. Each streamis handled by a separate thread that listens for input on its stream (out-put/error) as long as the virtual machine is still running. When new datais sent on the stream, the thread prints the data to the text area and keepschecking for new data.

4.5 Trace table

The trace table is where the user can watch data modification that happensin the executing class. The trace table is basically a table that listens forlocal variable and field events. When local variables or fields are createdor modified the controller sends events to notify the trace table object. Thetrace table object extracts field name, type and value from the sent eventand prints it in the table.

4.6 Annotation Processor

The annotation processor is where all VISA defined annotations are han-dled. The processor is invoked by the debugging engine after the virtualmachine prepares the algorithm class. The debugging engine stops exe-cution and the processor use Java reflection to look for fields annotated

Page 34: bachelor

CHAPTER 4. IMPLEMENTATION 27

by @GetInput or @RandomFile and checks if the algorithm class wasannotated by @VisualizationClass. After it finishes analyzing the al-gorithm class, it sends events to the input handler and the visualizationsystem to notify and provide them with needed information. The inputhandler is the object responsible for the graphical input interface. Thevisualization system and the graphical input interface will be discussedlater in this chapter. After the graphical input interface and the visualiza-tion systems have been notified, the annotation processor job finishes andthe debugging engine continue.

4.7 Visualization System

The visualization system is responsible for plugging in the visual classthe programmer wrote into VISA. The visualization system receives anevent from the annotation processor to be able to identify if the algorithmclass was annotated by @VisualizationClass. The event includes thevisual class name so that the visualization system will be able to load itlater. The system will check that the visual class is an instance of the objectComponent and that it implements the class VisualInterface. If thechecks passed, the visualization system will then use Java reflection todynamically load the visual class and invoke its constructor. After loadingthe visual class, the visualization system will notify the controller that thevisual class needs to receive events about the algorithm class. So the Visualclass will be added as a listener for the following events.

1. Local variable created event

2. Local variable modified event

3. Field event

4. Thread start event

5. Thread death event

4.8 Code Control

This section discusses how code control is implemented, this involvescode view, highlighting, and mapping. Figure 4.2 shows the flow ofevents between the different components involved in the process.

Page 35: bachelor

CHAPTER 4. IMPLEMENTATION 28

Figure 4.2: Code Control

4.8.1 Code View

The code that will be viewed will be the pseudo code the programmerwrote in the pseudo code file. If the pseudo code file is present the file willbe opened and a scanner will go through the file line by line to display itin the algorithm view area.

4.8.2 Code Mapping

Figure 4.3: Map Vector

This section discusses how the Java code of the algorithm class is mappedto the pseudo code the programmer wrote. The mapping information will

Page 36: bachelor

CHAPTER 4. IMPLEMENTATION 29

be acquired from the map file. If the map file is present, the file is openedand a scanner will go through the file line by line to construct a map vectorthat will contain the mapping information. As Figure 4.3 shows, the map-ping vector will contain entries that hold the mapping information of eachpseudo code line and its equivalent Java lines. Each entry will contain thepseudo code line number and Vector that contains its equivalent Java linenumbers. The constructed map vector will then be used to highlight thecorrect line in the algorithm view area.

4.8.3 Code Highlighting

When the algorithm class is compiled, line numbers and source file infor-mation will be saved in the algorithm class [3]. From this information, thedebugging engine will identify whether the map vector contains an entrythat maps the Java line currently executing to a pseudo code line. If theJava line maps to a corresponding pseudo code line, the debugging en-gine will send an event to the controller to notify it. When the controllerreceives the event, it will highlight the pseudo code line number in the al-gorithm view area. If the Java line doesn’t map to a corresponding pseudocode line, the debugging engine will continue execution normally and willnot send any events to the controller.

4.9 Input graphical interface

Fields that need to get input from the user via the graphical interface areannotated by @GetInput annotation in the algorithm class. As for allVISA defined annotations, @GetInput annotation is searched for by theannotation processor after the class is prepared by the virtual machine.The input graphical interface is managed by the input handler which re-ceives events from the annotation processor about the fields that were an-notated by @GetInput. When the input handler receives these eventsfrom the annotation processor, it checks whether the field is dependent orindependent. The input handler then behaves in one of two ways accord-ing to the field dependency.

If the input handler found that the field was independent then it will im-mediately draw a panel for the user in the input area. The panel includesthe field name, type and a text area that the user could enter in the valueof the field. A random button will also appear in the panel that random-izes the value of the field if clicked. But if the input handler found that

Page 37: bachelor

CHAPTER 4. IMPLEMENTATION 30

the field was dependent (An array), it will put it in a waiting list until thefield it’s depending on receives its value. A key listener will be added tothe text area corresponding to the field the dependent field is dependingon. Once the user enters a value in that text area, the input handler willreceive notification to draw the dependent field panel.

As for the fields that were annotated by @RandomFile, the input han-dler changes the behavior of the random button to get random values fromthe random file (declared by the programmer) instead of generating ran-dom numbers. The input handler will be informed by an event about thefields annotated by @RandomFile from the annotation processor. Whenthe input handler receives the event from the annotation processor, it willopen the random file and build a list of the random strings (each line in thefile will be an entry in the list). The random button of the correspondingfield when clicked will randomly select one of the strings in the list anddisplay it the text area.

Page 38: bachelor

Chapter 5

Conclusion and Future Work

5.1 Conclusion

The use of algorithm visualization facilitates the process of understand-ing algorithm behavior via pictorial representations as opposed to readingsource code. This paper presented VISA system and the functionalities itprovides to accomplish the task of visualizing algorithms. We explainedhow the user could use the system to view visualization of algorithms andhow the programmer could use the system to write and insert new algo-rithms. We pointed out whom the work is targeted for and discussed thegeneral benefits of using algorithm visualization tools.

5.2 Future Work

Concerning future work, the system could include new features that en-hance the visualization process and provide a better overall image of theprogram execution. The following is a list of features we intend to add inthe future

• Pretty-printing for the pseudo code appearing in the algorithm viewarea. Pretty printing involves the use of colors to differentiate key-words from the rest of the code

• More support to visualize concurrent programs, this involves sepa-rate views for each thread running

• Ability to visualize multiple programs simultaneously, this way theuser would be able to watch the behaviour of different algorithmsracing to solve the same problem

31

Page 39: bachelor

CHAPTER 5. CONCLUSION AND FUTURE WORK 32

• Adding support for concurrent programs to be able to use the graph-ical input interface

• Automatic visualization of data structures (for example: Trees, LinkedLists, Stacks,. . . etc)

• Automatic generation of UML diagrams

• Adding a plugin system so that programmers would be able to addnew visualization plugins

• Adding functionality that enables VISA to remember preferred op-tions for each algorithm

Page 40: bachelor

Bibliography

[1] Java Debugger Interface API Reference http://java.sun.com/javase/6/docs/jdk/api/jpda/jdi/index.html

[2] Java Virtual Machine Specification http://java.sun.com/docs/books/jvms/second_edition/html/VMSpecTOC.doc.html

[3] Java Compiler Manual http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javac.html

[4] B. Price , I. Small, and R.Baecker. A Taxonomy of Software Visu-alization. http://citeseer.ist.psu.edu/price92taxonomy.html

33