|Column Tag:||Fortran's World
Fractuals in Fortran 2.1
By Chuck Bouldin, Physicist, National Bureau of Standards
A Look at MacFortran 2.1
Last month's issue contained a first look at Macfortran, an implementation of FORTRAN on the Macintosh. This article is intended to continue that discussiion, and specifically to look at the new features in the 2.1 release of Macfortran and to begin to explore the Macfortran interface to the Toolbox routines. This article will describe the new Toolbox capabilities in the 2.1 release, the extensions and improvements to FORTRAN in 2.1 and give a couple of short examples which begin to show how Macfortran interacts with the Macintosh environment. It will discuss the strengths (and weaknesses) of this implementation of FORTRAN, and show what this language can accomplish on the Macintosh.
One of the first things to determine about any computer language is the class of problems for which it is best suited. There are lots of languages now available for the Macintosh; we need to determine where FORTRAN fits into the hierarchy of tools available for programming the Mac. Please note that this is not intended to continue the meaningless debate about the 'best' computer language, rather this intended to be a (reasonably) realistic assesment of FORTRAN as a tool on the Mac.
First of all, there exists a very clear definition of the language. The American National Standards Institute (ANSI) has published a document which completely defines the FORTRAN 77 language. Any implementation of the language must meet the standards defined by ANSI, or it really isn't FORTRAN. In the past, the main problem with microcomputer implementations of FORTRAN has been that they were incomplete, including only a part of the ANSI standard. MacFortran is a refreshing break from the past; it implements the full ANSI definition of the language. Since the language is so clearly defined, this makes for a remarkable degree of software portability. Code written in FORTRAN on any other machine, micro or mainframe, ports easily to the Macintosh. Obviously, Macintosh extensions such as Toolbox calls will not be of much use on other machines, but the other parts of the code are standard. Details on the Toolbox interface and porting FORTAN from other machines to the Mac are given later.
Second, MacFortran is the only fully compiled language for the Macintosh other than C. This means that when an application must run fast, then the high level language possibilities are C or FORTRAN. In some ways FORTRAN represents a natural upgrade from Basic when speed is a concern, since Basic was first derived as a subset of FORTRAN. Basic programmers who find they need faster running programs will probably find it easier to convert to FORTRAN than to learn C.
Third, if you crunch numbers, this is your language. MacFortran does not use SANE, the 80 bit software floating point built into the Mac. MacFortran has its own floating point; 32 bit single precision and 64 bit double precision. This floating point is fast, easily the fastest available on the Macintosh. Specific benchmarks are given below.
The language does has limitations, which show up mostly in the ancient lineage of FORTRAN. The most glaring limitation is the inability to create data types which correspond to Pascal records or C structures. The closest that MacFortran comes to this is simple arrays. This means that when dealing with complex data structures, the programmer, rather than the compiler, is forced to do some of the bookkeeping about where various data elements are located.
Of course the crucial element of a language for the Macintosh is how well it can interface to the Toolbox routines provided in the Mac ROMS. MacFortran provides direct access to almost all of the Toolbox routines, including Quickdraw, access to serial ports, Window and Menu creation, the font manager, the standard file package, Text edit, use of Desk accesories from inside FORTRAN programs, and more. Missing so far are access to the control and memory manager. Although not all of the Toolbox is directly supported from FORTRAN, MacFortran allows calls to assembly language subroutines which can obviously access any routine.
MacFortran calls Macintosh routines through a single subroutine, TOOLBX. The first parameter passed to this subroutine is an upper case character string which is the name of the Mac routine being called. The parameters which follow are the arguments that the Mac routine needs. TOOLBX is a 'glue' routine which takes care of putting the arguments onto the stack or into the cpu registers.
There is one main complication in using MacFortran to access Mac Toolbox routines. As mentioned earlier, FORTRAN does not support data types such as Pascal records or C structures. Since such data structures are used by many of the Toolbox routines, how can these routines be supported from MacFortran? The answer is simple, the data structures are just mapped onto a MacFortran array, and the array is then passed to TOOLBX, which handles the mapping from array elements onto stack locations or 68000 registers. With this type of approach, MacFortran can handle all of the Mac Toolbox with equal facility.
The MacFortran system comes with compiler, linker, librarian, and source code debugger. Apple's Edit and Rmaker programs are also included. The compiler and debugger have full Mac-style interfaces with pull-down menus and the usual dialogue boxes for file selection and compiler options. Suprisingly, the linker and librarian retain Unix type interfaces.
The compiler is organized into 3 overlays: (1) parsing and preliminary reduction of tokens into object code, (2) resolution of backwards jumps and some final code generation (3) setting up pointers for a runtime linkage. The overall compilation speed for large programs is 500-1000 lines/minute. Due to disc overhead swapping the compiler overlays, small programs (under 100 lines) will seem much slower, perhaps 50-200 lines/minute.
As mentioned above, the third compiler pass actually sets up pointers for a runtime link. In a program which does not call previously compiled subroutines this justs sets a pointer to load the MacFortran runtime library. At runtime, the library and any other needed subroutines, will be autoloaded when called. At runtime, first the default disc and then the internal disc are searched for needed subroutines. During development, this saves having to crank up the linker every time a change is made in the code. On the down side, subroutines are not locked in memory after they are called once; they are reloaded at each call. Clearly, you don't want runtime linking for subroutines which are called more than a few times. Also, the search path can lead to some confusion. If an application program is executed from the internal drive and the runtime library is in the external drive, the runtime library is not found, since the internal drive is now also the default drive. The internal drive is first searched as the internal drive and then as the default drive, missing the runtime library. [Isn't this a bug? -Ed.]
Easily the most impressive component of the package is the source code Debugger. This utility brings up a window of the MacFortran source code being debugged, a window to display variables and a 5 line MacFortran output window. The source code can be single stepped, breakpoints can be set and changed, and variables can be continuously monitored. This is almost like having a FORTRAN interpreter! Getting code working is very greatly simplified by this debugger.
The linker and librarian are certainly functional, but do not have a Macintosh type interface. The worst part of this is having to remember file names. On the plus side, the linker supports creation of 'scripts', files which contain canned linker 'programs'. This simplifies linking since many of the same libraries and subroutines are linked to different programs. According to Absoft there are two reasons for the non-Mac interface: (1) to provide the large table space that the linker needs and still fit into a 128K machine it was necessary to use a primitive interface, and (2) the interface remained unchanged in 2.1 since the programming effort was put into changing the linker to support linking on an entry point, rather than a filename basis. In 2.0, the ENTRY statement in FORTRAN was effectively disenfranchised since linking was done on only a filename basis. I still don't like the user interface, but the functionality of supporting the ENTRY statement is certainly more important. [In otherwords, the linker isn't finished yet! -Ed.]
The linker also makes no discrimination about what parts of the runtime library are actually used by a program; the entire library is linked in regardless. This means that the smallest MacFortran program will be about 18K, a real detriment to writing desk accessories in this language. On the other hand, several programs can be completely linked except for the runtime libary and share a single copy of the runtime library through runtime linking. Also, applications that do anything more involved than "hello, world" are likely to bring in large fractions of the Runtime library anyway. Runtime linking is certainly not required. The linker and librarian manage pre-compiled object code and standalone applications are easily created.
As mentioned earlier, one of the main attractions of FORTRAN is the portability of the language. I have ported several large applications down from a VAX 11/780 and have learned some of the pitfalls to watch out for when porting code down to the Mac. Since the use of existing code, particularly mathematical software, is a major incentive for using Macfortran, it is worth describing the portability considerations in detail. All of the non-portable code that I have downloaded to the Mac has turned out to be due to the use of non-standard features in VAX FORTRAN.
First, it is essential to use the SAVE statement in order to preserve variables between calls to a subroutine. This was mentioned in last months column, but the impression was given that this is a quirk of Macfortran. It is not. It is standard FORTRAN, although VAX and most mainframes do not require it. On a small machine such as the Macintosh, the use of the SAVE statement allows you to write larger programs by disposing of unneeded variable space. The main caution is that COMMON blocks must be SAVE-d between calls to a subroutine. This is conterintuitive, but it is standard FORTRAN.
Second, DATA statements must follow all declarations (REAL, COMPLEX, etc.). Again, this is standard FORTRAN, but is relaxed on most large machines. The main place to look out for this is when using INCLUDE statements to enter the COMMON variables in a group of subroutines that share COMMON blocks.
Third, watch out for READ/WRITE statements that use system dependent logical units. The way to avoid this problem is to use PARAMETER statements to assign logical units. For instance, to avoid the problems described last month with units 5 and 6 in Macfortran I use on the Macintosh:
On the VAX I use the same code, but set:
It is also possible to use the compiler option which maps READ* and PRINT* statements to unit 9 to resolve all the problems associated with list directed READ and WRITE statements.
Extensions and Enhancements in 2.1
The major news for the 2.1 revision is that the compiler has been licensed to Microsoft. This should mean that there will now develop a much larger user community for this language. In evaluating the 2.1 revision I have been working from a (slightly) modified version of the 2.0 documentation. According to Absoft, the new manual has been completely rewritten by Microsoft, and is much more Mac specific than the old documentation. The manual is 400 pages, organized into a Users guide and a Reference manual. It also reflects an orientation towards a less sophisticated user with less prior knowledge of FORTRAN.
In addition to Macintosh specific enhancements, there are some extensions in the Absoft FORTRAN which are very nice. Probably the most powerful is the addition of recursion to the language. Some programs are very difficult to write without recursion and are very natural when recursion is used. As an example of recursion, and to illustrate the drawing speed of Macfortran a short example which draws fractals is given below.
Other extensions include a CASE statement for multi-way branches, DO loops that are terminated with a REPEAT statement, and a generalized looping statement, WHILE(condition)....REPEAT. The WHILE statement is especially useful, since it gives much more flexible looping to FORTRAN; one no longer has to map all loops onto arithmetic progressions.
The compiler still operates in the same way as before. The user selects a file from the standard file box and then chooses among options such as Compile, Compile and Execute, Compile and Debug, etc. A nice human engineering change is that the compiler options can now be saved so that they do not need to be reset after every compile. The user still has to explicitly choose an option before anything happens. I do not find this flexibility confining.
The standard file package, Text edit utilities, and Desk accessory support (Systemclick and Systemtask) are now accessible from Fortran. The glaring things still missing are access to the Control and memory managers. By using the compile to assembly source to observe what code is generated for, say, the Window Manager it should be possible to figure out what to do for the Control Manager. It is aggravating to have to do this; hopefully we will soon get full documentation on all the Toolbox.
There is now a compiler option to map lower case onto upper case. This is very useful since only upper case characters are recognized by an ANSI standard compiler. Differences betwen VAX and Macfortran about character case have caused problems porting code. This option switch solves those problems.
There are several new demo programs, including a Fortran version of the Edit program from Inside Macintosh. On the subject of Edit, it is not Absoft's fault that the MDS Editor contains hardwired references to its transfer points. This is not even a resource that can be changed with the resource editor! Instead, references to EXEC, etc. are embedded in the code in the MDS Editor. The simple (but not elegant) solution is to rename Fortran as EXEC on the desktop. This allows transfers back and forth between Macfortran and Edit.
There is now access to the A5 register and Quickdraw globals via a call to GETGLOBALS.
As mentioned earlier, one reason for using this language is speed. The code is fully translated into 68000 object code for fast execution. For instance, the Sieve of Eratosthenes runs in 6.8 seconds, about as fast as Mac C compilers (without register variables). It is harder to find such universal benchmarks for floating point, but MacFortran executes single precision floating point 5-10 times faster than Mac languages that use the 80 bit SANE package. Some of the Mac C compilers also have their own floating point packages, but MacFortran is 2 times faster than the fastest of these.
To give some idea of floating point speed I ran two benchmarks that have had some runs on other machines (mostly IBM and clones). I ran Jerry Pournelle's benchmark which fills and multiplies two 20x20 matrices, with an execution time of 2.9 seconds. This is very fast, since an 8 Mhz 8088 with 8087 runs the same benchmark in 3.9 seconds using Pascal MT+. In addition, I ran the benchmark 'float' from the Aug, 85 issue of Byte magazine, page 133. Here, an IBM XT with 8087 recorded a time of 11.7 seconds using Microsoft Fortran and an IBM AT with an 80287 and Digital Research Fortran came in at 17.7 seconds. Using MacFortran, the Macintosh comes in at 7.7 seconds. When compared to a VAX 11/780 for large application programs such as matrix inversion, Fourier transforms, and optical ray tracing Macfortran delivers about 4-7% of the 780 performance. Of course, what a user cares about is how long he waits for the results. On a moderately loaded VAX I find that the difference in execution time drops to a factor of 2-5 between the Mac and the VAX.
I won't belabor the comparisons any more since the conclusion is clear; MacFortran is very, very fast for floating point operations. For a reasonable mix of floating and fixed point operations, MacFortran is at least as fast as any other language on the Mac. It is also faster than the main microcomputer competitor even when compared with hardware floating point. For crunching numbers, this language is unbeatable.
There are some caveats. The above benchmarks compare the default precision of each language. In MacFortran this is 32 bit single precision, providing only 5-6 decimal digits of accuracy, so is it 'fair' to compare this with the 80 bit software floating point of SANE or the 80 bit hardware floating point of the 8087? Yes, it is. Languages which do all floating point as 80 bit calculations give the user no choice, frequently providing more precision than is needed. In MacFortran you choose; if you need more accuracy, use double precision (64 bit), while if speed is the main concern, stay with single precision. Usually single precision is fine.
A Pair of Examples
The examples below are intended to illustrate a small part of the Macfortran interface to the Mac Toolbox routines. These show about the simplest level at which a FORTRAN program can interface with the Macintosh. The 'user interface' in these examples is not via Menus and dialogue boxes, but these routines do show off the graphics capability available from Macfortran and illustrate the use of recursion for drawing fractals (see Aug, 85 Macworld for the same example in MacPascal).
* This illustrates the use of some Quickdraw routines for
* plotting on the screen and erasing areas of the screen. This
* routine is intended to show the drawing speed on the screen
* and to illustrate the use of the internal random number
* generator, TOOLBX(RANDOM). Since the coordinate arrays
* are filled before plotting starts, this routine gives a measure
* of the raw plotting speed from inside Macfortran. Toolbox
* routines used are:
* Storage for the starting position
* For random coordinates
INTEGER*4 IXRAND(3000), IYRAND(3000)
* Declarations for calculating elapsed time for plot
INTEGER TIME1, TIME2
* Include the Toolbox Call Parameter file.
* Rectangle stuff for erasing the screen
INTEGER*2 BIGRECT(4), SMLRECT(4)
DATA BIGRECT /0,0,512,512/
DATA SMLRECT /0,0,60,100/
*Stuff default values for NSTEPS and ISCALE
NSTEPS = 1000
ISCALE = 6
* Set up number of steps and stepsize
PRINT*, 'Number of steps ? (3000 maximum, 1000 default)'
PRINT*,'Approximate step size in pixels ? (5 default)'
ISCALE = 32000 / ISCALE
* Clear the screen
* Get the starting time (in ticks)
* Note that this is a system global!
* Stuff the random coordinate arrays
* TOOLBX(RANDOM) returns a random integer between
* -32768 and 32767, inclusive
DO ( I=1,NSTEPS )
IXRAND(I) = TOOLBX(RANDOM) / ISCALE
IYRAND(I) = TOOLBX(RANDOM) / ISCALE
* Move to center of screen
XSTART = ( BIGRECT(1) + BIGRECT(3) ) / 2
YSTART = ( BIGRECT(2) + BIGRECT(4) ) / 2
CALL TOOLBX (MOVETO,XSTART,YSTART)
* Draw the next line.
DO ( I=1, NSTEPS )
CALL TOOLBX (LINE,IXRAND(I),IYRAND(I) )
* Get the ending time and print deltat
* Ending time in ticks
TIME2 = LONG(362)
DELTAT = (TIME2 - TIME1) / 60.
PRINT*,'ELAPSED TIME = ',DELTAT
* Draws a fractal pattern using Toolbox calls and recursion.
xorig = 250
yorig = 230
scaling = 100
rect(1)=0; rect(2)=0; rect(3)=340; rect(4)=510
type "order= (0 to quit)"; accept n
go to 20
x1 = xorig - scaling
y1 = yorig
x2 = xorig + scaling
y2 = yorig
s = 0.5573
x(12) = x12
y(12) = y12
xdiff = x12 - x1
ydiff = y12 - y1
x(10) = x1 + xdiff/3
y(10) = y1 + ydiff/3
x(11) = x1 + xdiff*2/3
y(11) = y1 + ydiff*2/3
x(3) = x(10) + ydiff*s
y(3) = y(10) - xdiff*s
x(9) = x(10) + ydiff*s/3.0
y(9) = y(10) - xdiff*s/3.0
x(8) = x(10) + ydiff*s*2.0/3.0
y(8) = y(10) - xdiff*s*2.0/3.0
x(2) = (x1+x(3))/2
y(2) = (y1+y(3))/2
x(4) = x(11) + ydiff*s
y(4) = y(11) - xdiff*s
x(6) = x(11) + ydiff*s*2.0/3.0
y(6) = y(11) - xdiff*s*2.0/3.0
x(5) = (x12+x(4))/2
y(5) = (y12+y(4))/2
x(7) = (x(8)+x(4))/2
y(7) = (y(8)+y(4))/2
if (n=1) then