You are on page 1of 57

Programming

Compilers

by GIUSEPPE CIABURRO

There was until recently no free full F90 compiler. A free f90 and HPF compiler for linux from Pacific Sierra appeared end of May 1998. Also, some compilers restricted to modern subsets of the language might be free. These are ELF90 and F from Imagine1 for Linux. Compilers for these subsets are also available for other platforms, but presently not for free.
Absoft Pro Fortran v6.0 and Pro FortranMP - for Linux (native/intel), Power

Mac, UNIX and Windows (NT, 95, 3.1) - Both releases include full F90 compilers with most [f77] workstation extensions. Pro FortranMP includes auto parallelizer for dual processor systems. Upgrades to more processors and OpenMP available option. Pro Fortrans also include F77/C/C++ compilers and complete developement toolset. ACE f90 and HPF - for Parsytec PowerPC-based machines. Apogee - highly optimizing Apogee-Fortran 90, C-DAC Fortran 90 (comes with debugger). Both compilers are for SPARC architectures. APR xHPF 2.1 - HPF compiler ([Cray]T3D,[IBM]SP-2,[Intel] Paragon, [Dec Alpha]3000/900 275Mhz,[SGI Power Challenge]MIPS R8000, [Sun SPARC]2000 40Mhz) CRAY CF90 - for Crays YMP and YMP-C90, Superserver 6400 and Sparc Solaris 2.3, plans for HP, SGI DEC Fortran 90 V4.1 - for Digital UNIX Alpha and for OpenVMS Alpha, UNIX version including full HPF support and nearly full F95, Digital Parallel Software Environment (PSE), companion product on UNIX for HPF programming. Digital Visual Fortran - for Windows NT and Windows 95. EPC Fortran 90 - for Sparc Solaris 1.X and 2.X, IBM RS/6000, Intel 3/486 (SVR3&4, Solaris 2.x), SGI, Motorola 88000/100/100 (SVR3&4), MIPS, NT Fujitsu - full compiler for Sparc Solaris 1.1 and 2.x next: Sun Sparc (MP) 3Q/95, HP PA-RISC 4Q/95 MIPS ABI 4Q/95, SGI 4Q/95, Windows 1Q/96 HP HP Fortran 90 - full compiler for HP-UX 10.20, 10.10, 10.01 and SPPUX IBM XLF - full compiler for RS/6000, with HPF extensions + KAP preprocessor - from KAI, for AIX V3.2 and V4.1

Imagine1 F - educational subset (dusty features removed, for inexpensive

F90 learning) - free for Linux. Lahey LF95 - Fortran 95 compiler under several packaging options. Lahey LF90 - for DOS, Windows including Pentium optimizations and Interacter Kit. Lahey ELF90 - educational subset (dusty features removed, for inexpensive F90 learning) - freely downloadable. Microsoft Fortran Powerstation V4.0 - for Windows NT 3.5 and Windows 95. See Digital Visual Fortran, as Microsoft ``handed over'' Fortran to DEC in Spring 97. MicroWay - for DOS, OS/2, Unix, Linux. NA Software F95 FortranPlus - Full F95, native ISO_Varying_String, Fortran2000 extensions, OpenGL graphics compatibility, backwards compatibility extensions. NA Software HPFPlus r2 -HPF for Linux PC PVM, Sun Sparc PVM or MPI, Meiko CS2 PVM or MPI, IBM SP2 (MPI). NAG/ACE Optimizing f90 - release 1.0 for Sparc Solaris 2. NAGWare f90 - uses C as intermediate language, now at rel:2.2, includes HPF extensions and exists in Linux version. NAGWare f95. NEC FORTRAN90/SX - for its supercomputer SX series. Pacific Sierra VAST/f90 - uses F77 as intermediate language, for Unix, VMS and Convex. Pacific Sierra HPF - PSR offers a free HPF compiler for Linux. PGI - f90/HPF compiler, for SGI, IBM SP2, HP/Convex, Linux. Salford FTN90 - PC implementation of NAG f90, direct generation of object code. Salford FTN95 - full Fortran 95 compliant compiler for Extended DOS, Windows 3.1 and Win32 (NT and 95). SGI - under IRIX 6.1 on R8000 machines: Power Challenge, Power Indigo 2, Power Onyx - Cray-compatible compiler (version 7.2 and later). SPARCompiler Fortran 90 - Sun's Cray-compatible compiler. Sun's HPF. Stern C. S. CF90 - Cray-compatible for DEC OSF/1. NOTE: Some vendors offer a number of F90 extensions, for instance array syntax or ALLOCATE instruction. Code re-structurers and converters
Summary of the f95 parser project

F90 code to Laheys free ELF90 A converter provided by Alan Miller for

Numerical Recipes
Pacific-Sierra VAST/77to90 (see article by JKP in Fortran Journal 5/4)

LOFT90, by NA Software (available also under Linux) FORESYS 1.4, GUI based High Performance Global Analysis, F77->F90 conversion, and parallelization. FORGE Explorer 2.0, Distributed and shared memory Parallelizer, Applied Parallel Research, Inc. NAGWare f90 tools, pretty-printer, declarations standardiser, precision standardiser, names changer. CONVERT, conversion to F90 free format, proposed by Mike Metcalf via anonymous ftp on jkr.cc.rl.ac.uk (130.246.8.23), file /pub/MandR/convert.f90. FORTRAN-lint for F77 and F90. ftof90.c, minimal F77 -> F90 conversion. f90ppr, F90 pre-processor similar to cpp. f90aib, Automatic interface bloc generator (beta version). Sun's fpp, Fortran public domain pre-processor. flecs90, FLECS to F90 translator. HPF mapper, for PVM or Parmacs, on Sun clusters: NA software. Libraries and utilities
*Emacs* package free-format f90-mode. Among the options one finds

automatic matching and completion of all end-blocks (for example, indenting a line starting with end, finds the corresponding if/do/module... and checks/fills in the right kind of block and a possible name), it has an automatic fill-function which breaks a line and inserts &-signs (two if inside a string) when a line gets too long, different coloring for different features which is updated with every indent of a line. The most common commands are available via a menu. Fortran-2000.com will host downloadable source code for Unconditional, Unique, and Partial Ranking, Sorting, and Permutation. Some utilities (pre-processor/pretty-printer, automatic interface generation, f90split, PostScript listing of source). OpenGL Fortran 90 bindings interface for OpenGL 1.1 (or Mesa), GLU 1.2, GLUT 3.6 and several OpenGL extensions, supports most Unix workstations and Windows 95/NT. PSPLOT, a Fortran-callable PostScript plotting library which is platform independent, supports color, and produces publication quality graphics.

Performance Library - LAPACK, BLAS, FFTPACK, VFFTPACK et

LINPACK optimized for SPARC (Sun Performance Workshop). INTERACTER - graphics library for Lahey LF90 and Salford FTN90, on 386/486/pentium + DOS Extenders (Int. Soft. Serv.). Lahey has F90 components (manual, array intrinsics, front end,...) that they would like to license to others. f90doc is an easy-to-learn documentation tool that generates pages of HTML documentation from Fortran 90 source. NAG fl90, numerical and statistical library, Sun 4, Sgi, DECstation, and IBM RISC System/6000. NAG tool components (parser, semantic analyser, tree modification library and tree flattener). f90SQL, a library of functions and subroutines that work as an interface between Fortran programs and Microsoft Windows Open Database Connectivity (ODBC) API. Numerical recipes(Others give caveats !) Cray LibSci(tm), numerical library for Crays and Sparc Solaris 2.3 MPFUN (Multiple Precision Floating Point Computation Package) by David W. Bailey, for Cray CF-90. IMSL library (Visual Numerics) Fortran Math and Stat libraries are available from Absoft Syntax verifier extracted from NAG compiler, put into public domain by NAG for Sun 3, Sun 4, Sgi. Interactive checking of user's code over www at http://www.nag.co.uk/0/Forms/f90_interface.html ISAM/VSAM/btree file structure, and Positional Key file structure ISF and PKF modules, shareware from Garnatz and Grovender, Inc XLIB interface, from Garnatz and Grovender also. CADNA, by professeur Vignes from Universite Pierre et Marie Curie, implements stochastic arithmetic in Fortran 90, and enables monitoring of precision loss and/or numerical instabilities during execution. (Control of Accuracy and Debugging for Numerical Aplications in Fortran) More information available from AERO (see also articles by J. Vignes), or Pr. Chesneaux (chesneaux@masi.ibp.fr). ISO/IEC 1539-2 (Auxiliary standard) - Variable length character strings in Fortran (with a demonstration of implementation) LAPACK, (minimaly) translated by myself, successfully passed all its tests with NAg-f90 2.0. I aggressively translated single precision Blas, and intend to do the same with other Blas as soon as I have time. StopWatch, Measurement of execution times by W.F Mitchell FFT module, by Michael Steffens

F90 makedepend, perl script by Kate Hedstrom Automatic differentiation with Fortran programs

Tests and Benchmarks Lahey Test suite - F77 & F90 (license agreement) NAGware Test suite - tests for compilers (same as: Unicomp Test suite - now available as F95 version, marketed by Quetzal Benchmark from John K. Prentice, also with additional CAPACITA benchmarks on http://www.polyhedron.com/. Benchmark of Syracuse University, via anonymous ftp on minerva.npac.syr.edu, in /old_pub. Channel benchmark by John D. McCalpin, via anonymous ftp on perelandra.cms.udel.edu, in bench/channel. Examples and repositories Nag has set up a repository for contributed code: WWW: http://www.nag.co.uk/1/nagware/Examples The Fortran Market has established itself on the World Wide Web. "ONE place to find all information, products, and services related to Fortran" WWW: http://www.fortran.com/fortran/market.html
Lahey Computer Systems downloadable F90 public domain code.

11,000 lines offered by Richard Maine via anonymous ftp on


ftp.dfrf.nasa.govfile is fdas.tar.Z

Many of the example codes and problem solutions from NUMERICAL METHODS FOR DIFFERENTIAL EQUATIONS - A computational approach by John R. Dormand have been coded in F. Alan Miller's home page contains code for converting Numerical Recipes F90 code to make it compatible with Laheys free ELF90 compiler and a variety of other F90 code (quadruple-precision COMPLEX arithmetic, TOMS 768, ...). STEJOI, statistical package for joint occurrence events, on Sun, including source code and everything, via anonymous ftp on ftp.ifremer.fr the file is f90dvl.tar.Z

Module unsigned_32, for definition and use of unsigned 32 bits integers, also on ftp.ifremer.fr the file is unsi32.f90.Z f90split, experimental version, similar to Unix BSD fsplit, but for free source form, also on ftp.ifremer.fr the file is f90split.f90.gz Algorithm 999 by A.G. Buckley for unconstrained nonlinear minimization, on ftp.royalroads.ca Courses and Consultancy IT Independent Training Limited, UK DRIME, France, janninst@drime.fr CTS, Germany Unicomp, USA Pacific-Sierra Research Corp., USA CETech, Inc., USA

A bibliography in French, gathered by Bernard Pichon.

Standards ISO/IEC 1539:1997 International Standard Information technology - Programming langages - Fortran Somewhat expensive (CHF 210 ~ US$ 140 !) for instance, at ISO. Surprisingly enough, the identical, save for foreword and acknowledgements, ANSI standard X3.198-1992 is even more expensive. Walter S. Brainerd, Unicomp., offers: - for 125 US$, an electronic ascii monouser version, - for 125 + 10n US$, an electronic PostScript version, and the right to make n paper copies, - or for 1000 US$, an electronic ditroff monouser version. A version with French glossary is available as European norm NF EN 21539. Glossary

Fortran terminology glossary by Ken Hawick hawick@npac.sys.edu

Journals
Fortran Journal ISSN 1060-0221, Enquiries: Walt Brainerd

walt@fortran.com Subscriptions: Fortran Users Group / P.O. Box 4201 / Fullerton, CA 92634 (From 1997, free access from the Fortran Market) Fortran Forum edited by Loren Meissner meissner@usfca.edu Subscriptions: ACM membership services: acmhelp@acm.org 10$ members, 20$ non members Tutorials and other documents
FORTRAN Performance Tuning co-Guide. European Standards For Writing and Documenting Exchangeable Fortran 90 Code. University of Liverpool on-line tutorial. P. Corde and H. Delouis, ``Support de cours Fortran 90 IDRIS''. This is a very

complete reference (224 pp.), in French, for which the authors have agreed to give free access. Pr. Loren Meissner has written an ELF subset (Essential Lahey Fortran) textbook, from his PWS book, and offers it on a royalty basis of $1.00 per copy, with advance royalty payment for 100 copies (LPMeissner@msn.com). Copyright but freely available course material is available from Manchester Computer Centre. Bo Einarsson and Yurij Shokin have written a tutorial on the transition from Fortran 77 to Fortran 90, with the title "Fortran 90 for the Fortran 77
programmer"

Michel Goossens has now installed a Fortran 90 tutorial on the World Wide Web (WWW) under the URL : F90 Tutorial/Overviewhttp://wwwcn.cern.ch/asdoc/f90.html There is no copyright on this material. There is a Fortran (90) tutorial on the net that might be of some use Tutorial
from University of New Mexico

A discussion about the various aspects of OO Fortran 90 programming, with comparison to C++, can be found at OO Fortran 90 See also:
http://www.nsc.liu.se/~boein/fortran.html http://www.kcl.ac.uk/kis/support/cc/fortran/f90home.html DEC ORNL

ftp://ftp.th-darmstadt.de/pub/thd/fortran/f90/ The University of Liverpool Belfast Univ of New Mexico Syracuse Univ. Pacific-Sierra Research mini-tutorial about converting Fortran 77 programs to

High Performance Fortran


EPCC Writing Data parallel programs with High Performance Fortran Leicester

Books * in English, Adams, Brainerd, Martin, Smith. Fortran Top 90 - Ninety Key Features of Fortran 90, Unicomp, Sept. 1994. Adams, Brainerd, Martin, Smith, Wagener. Fortran 90 Handbook, McGraw-Hill, 1992. ISBN 0-07-000406-4 Adams, Brainerd, Martin, Smith, Wagener. Fortran 95 Handbook, MIT Press, 1997. ISBN 0-262-51096-0 Adams, Brainerd, Martin, Smith. Key Features of F, Unicomp, 1996. ISBN 0-9640135-2-5 Brainerd, W., Goldberg, and Adams. Programmer's guide to Fortran 90, 3rd edition, Unicomp, 1996. ISBN 0-07-000248-7 Brainerd, W., Goldberg, and Adams. Programmer's guide to F, Unicomp, 1996. ISBN 0-9640135-1-7 Brooks. Problem solving with Fortran 90: for scientists and engineers, Springer, 1997. ISBN 0-387-98229-9 Chamberland, Luc. Fortran 90 : A Reference Guide, Prentice Hall. ISBN 0-13-397332-8. Chivers, I. and Sleightholme, J. Introducing Fortran 90, Springer-Verlag, Sept. 1995. ISBN 3-540-19940-3 Counihan, Pitman. Fortran 90, 1991. ISBN 0-273-03073-6 Einarsson, B., Shokins, Y. Fortran 90 for the Fortran 77 programmer HTMLbook. Ellis, T.M.R, Lahey, T. and Philips, I. Fortran 90 Programming, Addison Wesley, 1994, with examples ISBN 0-201-54446-6 Forsythe. Contemporary Computing for Technical Engineers and Scientists: using Fortran 90 and spreadsheets, PWS, 1997 ISBN 0-53493139-1 Gehrke, W. Fortran 95 Language Guide Springer-Verlag, 1996, ISBN 3-54076062-8, Softcover

Gehrke, W. The F Language Guide, Springer-Verlag, 1997, ISBN 3-54076165-9, Softcover Gehrke, W. Fortran 90 Language Guide Springer-Verlag, 1995, ISBN 3-54019926-8, Softcover Hahn, B.D., Arnold, E. Fortran 90 for Scientists and Engineers, 1994. ISBN 0-340-60034-9 Huddleston. Fortran 90, Exchange Publ. Div., Buffalo, NY, 1996, ISBN 0945261-07-1 Kerrigan, J. Migrating to Fortran 90, O'Reilly and Associates, 1993 (2nd ed. Sept.94), with examples ISBN 1-56592-049-X Charles H. Koelbel, David B. Loveman, Robert S. Schreiber, Guy L. Stelle Jr., Mary E. Zosel. High Performance Fortran Handbook, MIT Press, 349 pages, 1994. ISBN 0-262-61094-9 $24.95 in paper back ISBN 0-26211185-3 $45 for hard cover Mayo, W.E. and Cwiakala, M. Schaum's Outline of Theory and Praxis -Programming in Fortran 90, Mc Graw Hill, 1996. ISBN 0-07-041156-5 Meissner, L. Fortran 90, PWS Kent, Boston, 1995. ISBN 0-534-93372-6 Meissner, L. Essential Fortran 90 and 95, Unicomp, 1997. ISBN 09640135-3-3 $40 Metcalf, M. and Reid, J. Fortran 90/95 Explained, Oxford University Press, 1996. ISBN 0-19-851888-9 (2nd edition, 1999, ISBN 0-19-850558-2) Metcalf, M. and Reid, J. The F programming Language, Oxford University Press, 1996. ISBN 0-19-850026-2 Morgan and Schonfelder, Programming in Fortran 90, Alfred Waller Ltd., 1993. ISBN 1-872474-06-3 Nyhoff and Leestma, Fortran 90 for Engineers and Scientists, Prentice Hall, 1996. ISBN 0-13-519729-5 Nyhoff and Leestma, An introduction to Fortran 90 for Engineers and Scientists, Prentice Hall, 1996. ISBN 0-13-505215-7 Ortega, Saunders, Introduction to Fortran 90 for Scientific Computing, Saunders College Publishing, 1994 ISBN 0-030010198-0 Press, Teukolsky, Vetterling and Flannery, Numerical Recipes in Fortran 90: The Art of Parallel Scientific Computing, Volume 2 of Fortran Numerical Recipes, Cambridge U. Press, 1996. ISBN 0-521-57439-0 Redwine, C., Upgrading to Fortran 90, Springer, 1995 ISBN 0-387-979956 Schick W., Silverman Gordon, Fortran90 and engineering computations, John Wiley and sons, 1995 ISBN 0-471-58512-2 Smith, I.M. Programming in Fortran 90, Wiley, examples ISBN 0-47194185-9

Thompson, Atlas for Computing Mathematical Functions ... in Fortran 90 and Mathematica, Wiley, 1997 ISBN 0-471-18171-4 Vowels, R., Introduction to Fortran 90/95, Algorithms and Structured Programming ISBN 0-9596384-8-2 Will, D.R., Advanced Scientific Fortran, John Wiley and sons, 1995 ISBN 0-471-95383-0 * in French, Aberti, C. Fortran 90: Initiation a partir du Fortran 77, S.I. ditions, 1992. ISBN 2-909615-00-6 Ain, M. Savez-vous parler Fortran, Bibliotheque des universites (de Boeck), 1994. ISBN 2-8041-1755-3 Delannoy, C. Programmer en Fortran 90, Eyrolles, 1992. ISBN 2-21208723-3 Dubesset, M. et Vignes, J. Les spcificites du Fortran 90, ditions Technip, 1993. ISBN 2-7108-0652-5 Lignelet, P. Fortran 90: Approche par la Pratique, S.I. ditions, 1993. ISBN 2-909615-01-4
Lignelet, P. Manuel complet du langage Fortran 90 et Fortran 95, Calcul intensif et gnie logiciel, Masson, 1996. ISBN 2-225-85229-4 Lignelet, P. Structures de Donnes (et leurs algorithmes) en Fortran 90 / 95, Masson, 1996. ISBN 2-225-85373-8

Metcalf, M. et Reid, J. (translated by M. Caillat and B. Pichon) Fortran 90: Les concepts fondamentaux, AFNOR Editions, 1993. ISBN 2-12-4865137 Olagnon, M. Traitement de donnes numriques avec Fortran 90, Masson, 1996. ISBN 2-225-85259-6 * in Chinese, He Xingui, Xu Zuyuan, Wu Gingbao and Chen Mingyuan Programming Language FORTRAN 90, China Railway Publishing House, Beijing, 1994. ISBN 7-113-01788-6/TP.187 * in Finnish, Haataja, Rahola and Ruokolainen Fortran 90, Center for Scientific Computing (Finland), 1996. ISBN 952-9821-33-6 * in German,

Brainerd, W.S., Goldberg Ch.H., Adams J.C., translated by Peter Thomas and Klaus G. Paul Fortran 90, Lehr- und Arbeitsbuch fuer das erfolgreiche Programmieren, R. Olbenbourg Verlag, Muenchen, 1994, ISBN 3-48622102-7 Gehrke, W. Die Programmiersprache F Springer-Verlag, geplant fuer Sept/Okt 1997. Gehrke, W. Fortran 90 Referenz-Handbuch, Carl Hansen Verlag, 1991. ISBN 3-446-16321-2 Heisterkamp. Fortran 90: Eine Informelle Einfuehrung, BIWissenschaftsverlag, 1991. ISBN 3-411153-21-0 Langer, E. Programmieren in Fortran, Springer Verlag, 1993. ISBN 0-38782446-4 Michel, T. Fortran 90 Lehr- und Handbuch, BI-Wissenschaftsverlag, 1994. Schobert, Programmierung in Fortran 90, Oldenburg, 1991. Ueberhuber, C., Meditz, P. Software-Entwicklung in Fortran 90, Springer Verlag, 1993. ISBN 3-211-82450-2 Wojcieszynski, B, Wojcieszynski, R. Fortran 90 Programmieren mit dem neuen Standard, Addison-Wesley, 1993. ISBN 3-89319-600-5 * in Dutch, Brainerd, W.S., Goldberg Ch.H., Adams J.C., transl. by J.M. den Haan Fortran 90, Academic Service, 1991. ISBN 90-6233-722-8 * in Swedish, Blom, K. Fortran90 - en introduktion, Studentlitteratur, Lund, 1994. ISN 9144-47881-X Einarsson, B., Shokins, Y. Fortran 90 for the Fortran 77 programmer HTMLbook. * in Russian, Einarsson, B., Shokins, Y. Fortran 90 for the Fortran 77 programmer Printed book. Metcalf, Reid (translated by P.Gorbounov) Fortran 90 Explained. Mir Publishers, Moscow, 1995. ISBN 5-03-001426-8 Russian customers: Mr. A.S.Popov, E-mail asp@mir.msk.su European residents: Petr.Gorbounov@cern.ch * in Japanese

Metcalf, Reid (translated by H.Nisimura, H.Wada, K.Nishimura, M.Takata) Fortran 90 Explained, Kyoritsu Shuppan Co., Ltd., 1993 ISSN 0385-6984.

Barrowes Consulting
Fortran consulting: code modernization, refactoring. Matlab consulting: code development, GUIs, physics/electrical engineering Specializing in fortran => Matlab conversion/translation/porting (see below)
Ben Barrowes has been using fortran and Matlab since beginning graduate school in 1996. During graduate work at MIT, I decided to translate several numerical fortran routines into Matlab as part of my research. Frustrated by the tedious and repetitive conversion process, I decided to modify mymatlab2fmex translator into f2matlab, an automated fortran to Matlab code converter/translator.

f2matlab is the only semiautomatic fortran to Matlab translator in the world. It is usually sufficient for the conversion of small programs when followed by manual cleanup, debugging, and validation. The most recent version of f2matlab can be downloaded here. I specialize in complete translation services for larger, more complex, mission critical fortran programs. Using f2matlab as a starting point, I can complete projects and incorporate revisions rapidly and accurately. Specifically, I provide the following translation consulting services:

inspection and cleanup (refactor) of fortran code including goto

remediation translation of fortran line by line with the help of f2matlab validation of Matlab code using customer supplied tests

optimization of Matlab code (optional and limited to what can be accomplished without major code revision) Fortran/Matlab general services

Translation Examples

example1.f90 and example1.m shows some of the capabilities of f2matlab. Computation of Special Functions - A direct translation of the original

FORTRAN-77 implementation of "Computation of Special Functions." by Zhang and Jin. toms757_prb.f90 and toms757_prb.m Uncommon special functions and testing routines fromJohn Burkardt. ~12k lines of code. slatec library not fully complete, >450k lines of code.

Barrowes Consulting

Fortran consulting: code modernization, refactoring. Matlab consulting: code development, GUIs, physics/electrical engineering Specializing in fortran => Matlab conversion/translation/porting (see below)

The fortran goto statement allows jumps within a fortran program. Most goto's jump to the same or shallower nested if/do/while level. Jumps into a more deeply nested if/do/while were rare. To have any hope of converting or translating fortran code to a more modern language like matlab/octave, python, etc., one has to remove every

goto in the fortran code. I do this using while/break/continue combinations with a tool called remgoto.m I wrote. Remgoto analyzes the fortran code for goto's, then refactors the goto's by replacing them with do/while loops and branch statements. The resulting fortran code is logically and functionally equivalent to the original fortran code, but without the goto's. After this step, the fortran code can now be more readily converted into matlab/octave source code. As an example, consider the following subroutine cbal.f from slatec:
subroutine CBAL (NM, N, AR, AI, LOW, IGH, SCALE) INTEGER I,J,K,L,M,N,JJ,NM,IGH,LOW,IEXC REAL AR(NM,*),AI(NM,*),SCALE(*) REAL C,F,G,R,S,B2,RADIX LOGICAL NOCONV RADIX = 16 B2 = RADIX * RADIX K = 1 L = N go to 100 SCALE(M) = J if (J == M) go to 50 DO 30 I = 1, L F = AR(I,J) AR(I,J) = AR(I,M) AR(I,M) = F F = AI(I,J) AI(I,J) = AI(I,M) AI(I,M) = F CONTINUE DO 40 I = K, N F = AR(J,I) AR(J,I) = AR(M,I) AR(M,I) = F F = AI(J,I) AI(J,I) = AI(M,I) AI(M,I) = F CONTINUE go to (80,130), IEXC if (L == 1) go to 280 L = L - 1 DO 120 JJ = 1, L J = L + 1 - JJ DO 110 I = 1, L if (I == J) go to 110 if (AR(J,I) /= 0.0E0 .OR. AI(J,I) /= 0.0E0) go to 120 CONTINUE M = L IEXC = 1 go to 20 CONTINUE go to 140 K = K + 1 DO 170 J = K, L DO 150 I = K, L if (I == J) go to 150 if (AR(I,J) /= 0.0E0 .OR. AI(I,J) /= 0.0E0) go to 170 CONTINUE M = K IEXC = 2 go to 20 CONTINUE DO 180 I = K, L SCALE(I) = 1.0E0 NOCONV = .FALSE. DO 270 I = K, L C = 0.0E0 R = 0.0E0 DO 200 J = K, L

20

30

40 50 80 100

110

120 130 140

150

170 180 190

200

210

220 230

240

250

260 270 280

if (J == I) go to 200 C = C + ABS(AR(J,I)) + ABS(AI(J,I)) R = R + ABS(AR(I,J)) + ABS(AI(I,J)) CONTINUE if (C == 0.0E0 .OR. R == 0.0E0) go to 270 G = R / RADIX F = 1.0E0 S = C + R if (C >= G) go to 220 F = F * RADIX C = C * B2 go to 210 G = R * RADIX if (C < G) go to 240 F = F / RADIX C = C / B2 go to 230 if ((C + R) / F >= 0.95E0 * S) go to 270 G = 1.0E0 / F SCALE(I) = SCALE(I) * F NOCONV = .TRUE. DO 250 J = K, N AR(I,J) = AR(I,J) * G AI(I,J) = AI(I,J) * G CONTINUE DO 260 J = 1, L AR(J,I) = AR(J,I) * F AI(J,I) = AI(J,I) * F CONTINUE CONTINUE if (NOCONV) go to 190 LOW = K IGH = L return end

This has 19 goto statements along with being older style f77. Even with a program like Polyhedron's spag, we still get the following:
SUBROUTINE CBAL(NM, N, AR, AI, LOW, IGH, SCALE) IMPLICIT NONE INTEGER , INTENT(IN) :: NM INTEGER , INTENT(IN) :: N INTEGER , INTENT(OUT) :: LOW INTEGER , INTENT(OUT) :: IGH REAL , INTENT(INOUT) :: AR(NM,*) REAL , INTENT(INOUT) :: AI(NM,*) REAL , INTENT(INOUT) :: SCALE(*) INTEGER :: I, J, K, L, M, JJ, IEXC REAL :: C, F, G, R, S, B2, RADIX LOGICAL :: NOCONV RADIX = 16 B2 = RADIX*RADIX K = 1 L = N GO TO 100 20 SCALE(M) = J IF (J /= M) THEN DO I = 1, L F = AR(I,J) AR(I,J) = AR(I,M) AR(I,M) = F F = AI(I,J) AI(I,J) = AI(I,M) AI(I,M) = F END DO DO I = K, N F = AR(J,I) AR(J,I) = AR(M,I) AR(M,I) = F F = AI(J,I) AI(J,I) = AI(M,I) AI(M,I) = F

80 100

130 140

190

210

220 230

240

280

END DO ENDIF IF (IEXC == 1) GO TO 80 IF (IEXC == 2) GO TO 130 IF (L == 1) GO TO 280 L = L - 1 L120: DO JJ = 1, L J = L + 1 - JJ DO I = 1, L IF (I == J) CYCLE IF (AR(J,I)==0.0E0 .AND. AI(J,I)==0.0E0) CYCLE CYCLE L120 END DO M = L IEXC = 1 GO TO 20 END DO L120 GO TO 140 K = K + 1 L170: DO J = K, L DO I = K, L IF (I == J) CYCLE IF (AR(I,J)==0.0E0 .AND. AI(I,J)==0.0E0) CYCLE CYCLE L170 END DO M = K IEXC = 2 GO TO 20 END DO L170 SCALE(K:L) = 1.0E0 NOCONV = .FALSE. DO I = K, L C = 0.0E0 R = 0.0E0 DO J = K, L IF (J == I) CYCLE C = C + ABS(AR(J,I)) + ABS(AI(J,I)) R = R + ABS(AR(I,J)) + ABS(AI(I,J)) END DO IF (C==0.0E0 .OR. R==0.0E0) CYCLE G = R/RADIX F = 1.0E0 S = C + R IF (C >= G) GO TO 220 F = F*RADIX C = C*B2 GO TO 210 G = R*RADIX IF (C < G) GO TO 240 F = F/RADIX C = C/B2 GO TO 230 IF ((C + R)/F >= 0.95E0*S) CYCLE G = 1.0E0/F SCALE(I) = SCALE(I)*F NOCONV = .TRUE. AR(I,K:N) = AR(I,K:N)*G AI(I,K:N) = AI(I,K:N)*G AR(:L,I) = AR(:L,I)*F AI(:L,I) = AI(:L,I)*F END DO IF (NOCONV) GO TO 190 LOW = K IGH = L RETURN END SUBROUTINE CBAL

This is more modern and looks better, but the routine still has 12 goto's. Using remgoto, we get the following fortran90 code with no goto's, but instead has do/exit/cycle/if statements:

SUBROUTINE CBAL(NM, N, AR, AI, LOW, IGH, SCALE) IMPLICIT NONE logical :: remg(15)=.true. INTEGER , INTENT(IN) :: NM INTEGER , INTENT(IN) :: N INTEGER , INTENT(OUT) :: LOW INTEGER , INTENT(OUT) :: IGH REAL , INTENT(INOUT) :: AR(NM,*) REAL , INTENT(INOUT) :: AI(NM,*) REAL , INTENT(INOUT) :: SCALE(*) INTEGER :: I, J, K, L, M, JJ, IEXC REAL :: C, F, G, R, S, B2, RADIX LOGICAL :: NOCONV do if (remg(11)) then if (remg(6)) then if (remg(5)) then if (remg(4)) then if (remg(3)) then if (remg(2)) then if (remg(1)) then RADIX = 16 B2 = RADIX*RADIX K = 1 L = N remg(3)=.false.;cycle endif remg(1)=.true. 20 SCALE(M) = J IF (J /= M) THEN DO I = 1, L F = AR(I,J) AR(I,J) = AR(I,M) AR(I,M) = F F = AI(I,J) AI(I,J) = AI(I,M) AI(I,M) = F enddo DO I = K, N F = AR(J,I) AR(J,I) = AR(M,I) AR(M,I) = F F = AI(J,I) AI(J,I) = AI(M,I) AI(M,I) = F enddo ENDIF IF (IEXC == 1) then remg(2)=.false.;cycle endif IF (IEXC == 2) then remg(4)=.false.;cycle endif endif remg(2)=.true. 80 IF (L == 1) then remg(11)=.false.;cycle endif L = L - 1 endif remg(3)=.true. 100 DO JJ = 1, L!L120 J = L + 1 - JJ DO I = 1, L IF (I == J) then cycle endif IF (AR(J,I)==0.0E0 .AND. AI(J,I)==0.0E0) then cycle endif remg(12)=.false.;exit enddo if (.not.(remg(12))) then remg([12])=.true. ; cycle endif M = L

IEXC = 1 remg(1)=.false.;exit enddo !L120 if (.not.(remg(1))) cycle remg(5)=.false.;cycle endif remg(4)=.true. 130 K = K + 1 endif remg(5)=.true. 140 DO J = K, L!L170 DO I = K, L IF (I == J) then cycle endif IF (AR(I,J)==0.0E0 .AND. AI(I,J)==0.0E0) then cycle endif remg(13)=.false.;exit enddo if (.not.(remg(13))) then remg([13])=.true. ; cycle endif M = K IEXC = 2 remg(1)=.false.;exit enddo !L170 if (.not.(remg(1))) cycle SCALE(K:L) = 1.0E0 endif remg(6)=.true. 190 NOCONV = .FALSE. DO I = K, L do if (remg(10)) then if (remg(9)) then if (remg(8)) then if (remg(7)) then C = 0.0E0 R = 0.0E0 DO J = K, L IF (J == I) then cycle endif C = C + ABS(AR(J,I)) + ABS(AI(J,I)) R = R + ABS(AR(I,J)) + ABS(AI(I,J)) enddo IF (C==0.0E0 .OR. R==0.0E0) then remg(14)=.false.;exit endif G = R/RADIX F = 1.0E0 S = C + R endif remg(7)=.true. 210 IF (C >= G) then remg(8)=.false.;cycle endif F = F*RADIX C = C*B2 remg(7)=.false.;cycle endif remg(8)=.true. 220 G = R*RADIX endif remg(9)=.true. 230 IF (C < G) then remg(10)=.false.;cycle endif F = F/RADIX C = C/B2 remg(9)=.false.;cycle endif remg(10)=.true. 240 IF ((C + R)/F >= 0.95E0*S) then remg(15)=.false.;exit

endif G = 1.0E0/F SCALE(I) = SCALE(I)*F NOCONV = .TRUE. AR(I,K:N) = AR(I,K:N)*G AI(I,K:N) = AI(I,K:N)*G AR(:L,I) = AR(:L,I)*F AI(:L,I) = AI(:L,I)*F exit enddo if (.not.(remg(14).and.remg(15))) then remg([14,15])=.true. ; cycle endif enddo IF (NOCONV) then remg(6)=.false.;cycle endif endif remg(11)=.true. 280 LOW = K IGH = L exit enddo RETURN END SUBROUTINE CBAL

This can now be converted into matlab/octave code with f2matlab:


function [nm, n, ar, ai, low, igh, scale_ml]=cbal(nm, n, ar, ai, low, igh, scale_ml); persistent b2 c f g i iexc j jj k l m noconv r radix_ml remg s ; if isempty(remg), remg([1:15])=true; end; ar_shape=size(ar);ar=reshape([ar(:).',zeros(1,ceil(numel(ar)./prod([abs(nm)])).*prod([abs( nm)])-numel(ar))],abs(nm),[]); ai_shape=size(ai);ai=reshape([ai(:).',zeros(1,ceil(numel(ai)./prod([abs(nm)])).*prod([abs( nm)])-numel(ai))],abs(nm),[]); scale_shape=size(scale_ml);scale_ml=reshape(scale_ml,1,[]); if isempty(i), i=0; end; if isempty(j), j=0; end; if isempty(k), k=0; end; if isempty(l), l=0; end; if isempty(m), m=0; end; if isempty(jj), jj=0; end; if isempty(iexc), iexc=0; end; if isempty(c), c=0; end; if isempty(f), f=0; end; if isempty(g), g=0; end; if isempty(r), r=0; end; if isempty(s), s=0; end; if isempty(b2), b2=0; end; if isempty(radix_ml), radix_ml=0; end; if isempty(noconv), noconv=false; end; while (1); if(remg(11)) if(remg(6)) if(remg(5)) if(remg(4)) if(remg(3)) if(remg(2)) if(remg(1)) radix_ml = 16; b2 = radix_ml.*radix_ml; k = 1; l = fix(n); remg(3)=false; continue; end; remg(1)=true; scale_ml(m) = j; if(j ~= m) for i = 1: l;

f = ar(i,j); ar(i,j) = ar(i,m); ar(i,m) = f; f = ai(i,j); ai(i,j) = ai(i,m); ai(i,m) = f; end; i = fix(l+1); for i = k: n; f = ar(j,i); ar(j,i) = ar(m,i); ar(m,i) = f; f = ai(j,i); ai(j,i) = ai(m,i); ai(m,i) = f; end; i = fix(n+1); end; if(iexc == 1) remg(2)=false; continue; end; if(iexc == 2) remg(4)=false; continue; end; end; remg(2)=true; if(l == 1) remg(11)=false; continue; end; l = fix(l - 1); end; remg(3)=true; %L120 for jj = 1: l; j = fix(l + 1 - jj); for i = 1: l; if(i == j) continue; end; if(ar(j,i)==0.0e0 && ai(j,i)==0.0e0) continue; end; remg(12)=false; break; end; if(~(remg(12))) remg([12])=true; continue; end; m = fix(l); iexc = 1; remg(1)=false; break; %L120 end; if(~(remg(1))) continue; end; remg(5)=false; continue; end; remg(4)=true; k = fix(k + 1); end; remg(5)=true; %L170 for j = k: l; for i = k: l; if(i == j) continue; end; if(ar(i,j)==0.0e0 && ai(i,j)==0.0e0) continue; end; remg(13)=false;

break; end; if(~(remg(13))) remg([13])=true; continue; end; m = fix(k); iexc = 2; remg(1)=false; break; %L170 end; if(~(remg(1))) continue; end; scale_ml([k:l]) = 1.0e0; end; remg(6)=true; noconv = false; for i = k: l; while (1); if(remg(10)) if(remg(9)) if(remg(8)) if(remg(7)) c = 0.0e0; r = 0.0e0; for j = k: l; if(j == i) continue; end; c = c + abs(ar(j,i)) + abs(ai(j,i)); r = r + abs(ar(i,j)) + abs(ai(i,j)); end; j = fix(l+1); if(c==0.0e0 || r==0.0e0) remg(14)=false; break; end; g = r./radix_ml; f = 1.0e0; s = c + r; end; remg(7)=true; if(c >= g) remg(8)=false; continue; end; f = f.*radix_ml; c = c.*b2; remg(7)=false; continue; end; remg(8)=true; g = r.*radix_ml; end; remg(9)=true; if(c < g) remg(10)=false; continue; end; f = f./radix_ml; c = c./b2; remg(9)=false; continue; end; remg(10)=true; if((c + r)./f >= 0.95e0.*s) remg(15)=false; break; end; g = 1.0e0./f; scale_ml(i) = scale_ml(i).*f; noconv = true; ar(i,[k:n]) = ar(i,[k:n]).*g; ai(i,[k:n]) = ai(i,[k:n]).*g; ar([1:l],i) = ar([1:l],i).*f;

ai([1:l],i) = ai([1:l],i).*f; break; end; if(~(remg(14)&&remg(15))) remg([14,15])=true; continue; end; end; if(noconv) remg(6)=false; continue; end; end; remg(11)=true; low = fix(k); igh = fix(l); break; end; return; end %subroutine cbal

This converted matlab/octave code can now be optimized and modified as an m-file as desired. Fortran to matlab conversion
Asked by Jessica on 16 Jul 2012

Hi, I am trying to convert a code from Fortran to MATLAB and I am stuck. I basically need to output the results, using write command in Fortran but within a loop. Does anyone know how to do this in MATLAB? Below is the Fortran code. Thanks module WriteResults use globvar implicit none contains subroutine estimates implicit none integer :: t,j,k,s,i CHARACTER(len=40) :: temp1,temp2 real(8) :: P(ntime,nfac,nfac) !Variance of factor real(8) :: rho(ntime,nfac,nfac) !Variance of factor open(1,file='observation.out') do t = 1, ntime do j = 1, nequation(t) k = eqindex(t,j) write(1,'(2I,<nx+nfac+1>f16.8)')t,k, H(t,k,k) write(1,'(2I,<nx+nfac+1>f16.8)')t,k,sdbeta(t,k,:),sdZ(t,k,:),sdH(t,k,k) write(1,*) beta(t,k,:), Z(t,k,:),

end do write(1,*) end do close(1)

2 Comments
James Tursa on 16 Jul 2012 Link

Do you mean that you have some MATLAB m-code with some variables, and you want to have m-code that will output results to a file in the same way that the above Fortran code does? Or something else? Also, please format all of your code above so that it is more readable.
Jan Simon on 16 Jul 2012 Link

@Jessica: Please do not post 2 question about the same problem. See:http://www.mathworks.com/matlabcentral/answers/43720-error-when-using-writeif-statement . And, as far as I remember I ask the 3rd time, please format your code properly. If you are in doubt, follow the "? help" button, which appears when you create or edit a message. Or readhttp://www.mathworks.com/matlabcentral/answers/13205-tutorial-how-to-format-your-question-withmarkup .

0 votes

Tags

fortran conversion
Products

No products are associated with this question.

1 Answer
Answer by Ben Barrowes on 17 Jul 2012

Jessica, This is Ben Barrowes. I see you are making progress converting this. This bracket syntax is meant to be a variable repeat specification as explained here, for example:http://astro.uni-tuebingen.de/software/ftnchek/f77.html What it means is that the f16.8 should be used nx+nfac+1 times. Sorry f2matlab did not convert this for you. This line in fortran: write(1,'(2I,<nx+nfac+1>f16.8)')t,k, beta(t,k,:), Z(t,k,:), H(t,k,k) Should have been converted by f2matlab to be: writef(fid_1,[repmat('%i',1,2),repmat('%16.8f',1,nx+nfac+1)],t,k, beta(t,k,:), z(t,k,:), h(t,k,k)); The other lines with the bracket notation would be similar. Thanks for catching this. bb

2 Comments
Star Strider on 17 Jul 2012 Link

I can't find any documentation for writef in MATLAB. I believe the correct current MATLAB function is fprintf.
Ben Barrowes on 17 Jul 2012 Link

Right, writef is a function supplied by f2matlab when it converts the fortran to matlab code.

Batch Reactor Problem


Example 6: DYNOPT Users Guide version 4.1.0 Batch reactor with reactions: A -> B -> C. M. Cizniar, M. Fikar, M. A. Latifi, MATLAB Dynamic Optimisation Code DYNOPT. Users Guide, Technical Report, KIRP FCHPT STU Bratislava, Slovak Republic, 2006.

13.1 Problem description


Find T over t in [0; 1 ] to maximize
J = x2(tf)

subject to:
dx1 = k1*x12 dt dx2 = k1*x12k2*x2 dt

k1 = 4000*exp 2500

5000 k2 = 620000*exp T

where
x(0) = [1 0] 298 <= T <= 398

Reference: [13]

13.2 Problem setup


toms t p = tomPhase('p', t, 0, 1, 30); setPhase(p); tomStates x1 x2 tomControls T % Initial guess % Note: The guess for t_f must appear in the list before expression involving t. x0 = {icollocate({x1 == 1; x2 == 0}) collocate(T==398-t*100)}; % Box constraints

cbox = {298 <= collocate(T) <= 398}; % Boundary constraints cbnd = initial({x1 == 1; x2 == 0}); % Various constants and expressions k1 = 4000*exp(-2500./T); k2 = 620000*exp(-5000./T); % ODEs and path constraints ceq = collocate({dot(x1) == -k1.*x1.^2 dot(x2) == k1.*x1.^2-k2.*x2}); % Objective objective = -final(x2);

13.3 Solve the problem


options = struct; options.name = 'Batch Reactor'; solution = ezsolve(objective, {cbox, cbnd, ceq}, x0, options); % Extract optimal states and controls from solution t = subs(collocate(t),solution); x1 = subs(collocate(x1),solution); x2 = subs(collocate(x2),solution); T = subs(collocate(T),solution); Problem type appears to be: lpcon Starting numeric solver ===== * * * =================================================================== * * * TOMLAB - Tomlab Optimization Inc. Development license 2011-02-05 999001. Valid to

======================================================================= ============== Problem: --- 1: Batch Reactor 0.610799380695553730 0.000006007956267540 f_k sum(|constr|) -

f(x_k) + sum(|constr|) 0.610793372739286240 f(x_0) 0.000000000000000000 Solver: snopt. EXIT=0. INFORM=1.

SNOPT 7.2-5 NLP code Optimality conditions satisfied FuncEv 1 ConstrEv 26 ConJacEv 26 Iter 23 MinorIter 84

CPU time: 0.093750 sec. Elapsed time: 0.094000 sec.

13.4 Plot result


subplot(2,1,1) plot(t,x1,'*-',t,x2,'*-'); legend('x1','x2'); title('Batch Reactor state variables'); subplot(2,1,2) plot(t,T,'+-'); legend('T'); title('Batch Reactor control');

Previous Start Next

http://tomopt.com/docs/propt/tomlab_propt014.php

first order reversible reaction in batch reactor


John Kitchin

Contents

Problem statement plot the solution

Problem statement

forward rate law:

backward rate law: this example illustrates a set of coupled first order ODES function main clc; clear all; close all; u = cmu.units; %note that using units makes this m-file run pretty slowly tspan = [0 5]*u.min; init = [1 0]*u.mol/u.L; [t,C] = ode45(@myode,tspan,init);

plot the solution


plot(t/u.min,C/(u.mol/u.L)) xlabel('Time (min)') ylabel('Concentration (mol/L)') legend C_A C_B

you need this to make the plot appear in the right place above when published. It appears you need a final cell with an output to avoid having the plot showup at the end of the published document. disp('end') end function dCdt = myode(t,C) % ra = -k1*Ca % rb = -k_1*Cb % net rate for production of A: ra - rb % net rate for production of B: -ra + rb u = cmu.units; k1 = 1/u.min; k_1 = 0.5/u.min; Ca = C(1); Cb = C(2); ra = -k1*Ca; rb = -k_1*Cb; dCadt = ra - rb; dCbdt = -ra + rb; dCdt = [dCadt; dCbdt]; % categories: ODEs % tags: reaction engineering

% post_id = 706; %delete this line to force new post;

Batch Reactor Problem


Example 6: DYNOPT User's Guide version 4.1.0 Batch reactor with reactions: A -> B -> C. M. Cizniar, M. Fikar, M. A. Latifi, MATLAB Dynamic Optimisation Code DYNOPT. User's Guide, Technical Report, KIRP FCHPT STU Bratislava, Slovak Republic, 2006.

Contents

Problem description Problem setup Solve the problem Plot result

Problem description
Find T over t in [0; 1 ] to maximize

subject to:

where

% Copyright (c) 2007-2008 by Tomlab Optimization Inc.

Problem setup
toms t p = tomPhase('p', t, 0, 1, 30); setPhase(p); tomStates x1 x2 tomControls T % Initial guess % Note: The guess for tf must appear in the list before expression involving t. x0 = {icollocate({x1 == 1; x2 == 0}) collocate(T==398-t*100)}; % Box constraints cbox = {298 <= collocate(T) <= 398}; % Boundary constraints cbnd = initial({x1 == 1; x2 == 0}); % Various constants and expressions k1 = 4000*exp(-2500./T); k2 = 620000*exp(-5000./T); % ODEs and path constraints ceq = collocate({dot(x1) == -k1.*x1.^2 dot(x2) == k1.*x1.^2-k2.*x2}); % Objective objective = -final(x2);

Solve the problem


options = struct; options.name = 'Batch Reactor'; solution = ezsolve(objective, {cbox, cbnd, ceq}, x0, options); % Extract optimal states and controls from solution t = subs(collocate(t),solution); x1 = subs(collocate(x1),solution); x2 = subs(collocate(x2),solution); T = subs(collocate(T),solution); Problem type appears to be: lpcon ===== * * * =================================================================== * * * TOMLAB - Tomlab Optimization Inc. Development license 999001. Valid to 2010-02-05 ========================================================================= ============ Problem: --- 1: Batch Reactor f_k 0.610799380695554730 sum(|constr|) 0.000006007956194376 f(x_k) + sum(|constr|) 0.610793372739360410

f(x_0) 0.000000000000000000 Solver: snopt. EXIT=0. INFORM=1. SNOPT 7.2-5 NLP code Optimality conditions satisfied FuncEv 1 ConstrEv 26 ConJacEv 26 Iter 23 MinorIter CPU time: 0.093750 sec. Elapsed time: 0.093000 sec. 70

Plot result
subplot(2,1,1) plot(t,x1,'*-',t,x2,'*-'); legend('x1','x2'); title('Batch Reactor state variables'); subplot(2,1,2) plot(t,T,'+-'); legend('T'); title('Batch Reactor control');

Copyright 2009, Tomlab Optimization Inc.

Mathlab question on Semi-batch, isothermal reactor


Subject: Mathlab question on Semi-batch, isothermal reactor From: Tan Jason Date: 31 Mar, 2008 13:43:02 Message: 1 of 2

Reply to this message Add author to My Watch List View original format Flag as spam

Consider a semi-batch, isothermal reactor where an exothermic reaction A + B -> C takes place. As the engineer responsible for this reactor,you have been tasked with minimizing the time needed to produce a given amount of C(0.6mol). To achieve this objective, you are allowed to freely manipulate (within constraints), the feed rate of B. There are constraints on the maximum volume and on the maximum temperature reached under cooling failure.

The governing equations are:

dotcA = -kcAcB u/V*cA ----- cA(0) = cAo,

dotcB = -kcAcB + u/V*(cBin - cB)----- cB(0) = cBo,

dotV = u ---- V(0)=Vo

The concentration of C is given by:

cC = (cAoVo + cCoVo - cAV)/V

The model parameters, operating bounds and initial conditions for the reaction system are given below.

k = 0.0482L/mol h T = 70 degC DelH = -60000 J/mol density = 900 g/L cp = 4.2 J/gK cBin = 2 mol/L umin = 0 L/h umax = 0.1 L/h Tmax = 80 degC Vmax = 1 L nCdes = 0.6 mol cAo = 2 mol/L cBo = 0.63 mol/L Vo = 0.7 L

In the case of a cooling failure, the system becomes adiabatic. The best strategy is to immediately stop the feed. Yet, due to the presence of unreacted components in the reactor, the reaction goes on. Thus, chemical heat will be released, which causes an increase in temperature. The maximum attainable temperature under cooling failure is given by:

Tcf(t) = T(t)+min(cA(t), cB(t))(-delH/density*cp),

Use Matlab to determine the feed rate profile of B such that 0.6mol of C is produced in the shortest possible time.
Subject: Mathlab question on Semi-batch, isothermal reactor From: David Date: 31 Mar, 2008 15:46:03

Message: 2 of 2

Reply to this message Add author to My Watch List View original format Flag as spam

"Tan Jason" <f_boi@hotmail.com> wrote in message <fsqpp6 $eif$1@fred.mathworks.com>... > Consider a semi-batch, isothermal reactor where an > exothermic reaction A + B -> C takes place. As the > engineer responsible for this reactor,you have been tasked > with minimizing the time needed to produce a given amount > of C(0.6mol). To achieve this objective, you are allowed > to freely manipulate (within constraints), the feed rate > of B. There are constraints on the maximum volume and on > the maximum temperature reached under cooling failure. > > The governing equations are: > > dotcA = -kcAcB u/V*cA ----- cA(0) = cAo, > > dotcB = -kcAcB + u/V*(cBin - cB)----- cB(0) = cBo, > > dotV = u ---- V(0)=Vo > > The concentration of C is given by: > > cC = (cAoVo + cCoVo - cAV)/V > > The model parameters, operating bounds and initial

> conditions for the reaction system are given below. > > k = 0.0482L/mol h > T = 70 degC > DelH = -60000 J/mol > density = 900 g/L > cp = 4.2 J/gK > cBin = 2 mol/L > umin = 0 L/h > umax = 0.1 L/h > Tmax = 80 degC > Vmax = 1 L > nCdes = 0.6 mol > cAo = 2 mol/L > cBo = 0.63 mol/L > Vo = 0.7 L > > In the case of a cooling failure, the system becomes > adiabatic. The best strategy is to immediately stop the > feed. Yet, due to the presence of unreacted components in > the reactor, the reaction goes on. Thus, chemical heat > will be released, which causes an increase in temperature. > The maximum attainable temperature under cooling failure > is given by: > > Tcf(t) = T(t)+min(cA(t), cB(t))(-delH/density*cp), > > Use Matlab to determine the feed rate profile of B such > that 0.6mol of C is produced in the shortest possible > time.

ok, so what is your question?

http://m2matlabdb.ma.tum.de/files.jsp?MC_ID=9&SC_ID=14 http://tomopt.com/docs/propt/tomlab_propt123.php

122 Two-Phase Schwartz


Users Guide for dyn.Opt, Example 4 Schwartz, A. L., Theory and Implementation of Numerical Methods based on Runge-Kutta Integration for Solving Optimal Control Problems. Ph.D. Dissertation, University of California, Berkeley, 1989

122.1 Problem Formulation


Find u over t in [0; 2.9 ] to minimize
J = 5*(x1(tF)2 + x2(tF)2)

subject to:
dx1 = x2 dt dx2 = u 0.1*(1+2*x12)*x2 dt x(0) = [1 1]

and path constraints for t<1:


x20.4 19*(x11) ( 0.3 0.8x2 <= 0 > 0.8 <= x2 1 <= u <= 1, (t<1)
2

)2 <=0

Reference: [16]

122.2 Problem setup


toms t1 p1 = tomPhase('p1', t1, 0, 1, 25); toms t2 p2 = tomPhase('p2', t2, 1, 1.9, 25); setPhase(p1); tomStates x1p1 x2p1 tomControls up1 setPhase(p2); tomStates x1p2 x2p2 tomControls up2 setPhase(p1); % Initial guess x01 = {icollocate({x1p1 == 1; x2p1 == 1}) collocate(up1==0)}; % Box constraints cbox1 = {-0.8 <= icollocate(x2p1) -1 <= collocate(up1) <= 1}; % Boundary constraints

cbnd1 = initial({x1p1 == 1; x2p1 == 1}); % ODEs and path constraints ceq1 = collocate({ dot(x1p1) == x2p1 dot(x2p1) == up1 - 0.1*(1+2*x1p1.^2).*x2p1 1-9*(x1p1-1).^2-((x2p1-0.4)/0.3).^2 <= 0}); setPhase(p2); % Initial guess x02 = {icollocate({x1p2 == 1; x2p2 == 1}) collocate(up2==0)}; % Box constraints cbox2 = {-50 <= collocate(up2) <= 50}; % ODEs and path constraints ceq2 = collocate({ dot(x1p2) == x2p2 dot(x2p2) == up2-0.1*(1+2*x1p2.^2).*x2p2}); % Link phase link = {final(p1,x1p1) == initial(p2,x1p2) final(p1,x2p1) == initial(p2,x2p2)}; % Objective objective = 5*(final(p2,x1p2)^2+final(p2,x2p2)^2);

122.3 Solve the problem


options = struct; options.name = 'Two Phase Schwartz'; constr = {cbox1, cbnd1, ceq1, cbox2, ceq2, link}; solution = ezsolve(objective, constr, {x01, x02}, options); t = subs(collocate(p1,t1),solution); t = [t;subs(collocate(p2,t2),solution)]; x1 = subs(collocate(p1,x1p1),solution);

x1 = [x1;subs(collocate(p2,x1p2),solution)]; x2 = subs(collocate(p1,x2p1),solution); x2 = [x2;subs(collocate(p2,x2p2),solution)]; u = subs(collocate(p1,up1),solution); u = [u;subs(collocate(p2,up2),solution)]; Problem type appears to be: qpcon Starting numeric solver ===== * * * =================================================================== * * * TOMLAB - Tomlab Optimization Inc. Development license 2011-02-05 999001. Valid to

======================================================================= ============== Problem: --- 1: Two Phase Schwartz 0.000000000000002541 0.000000000002833381 f(x_k) + sum(|constr|) 0.000000000002830840 f(x_0) 10.000000000000014000 Solver: snopt. EXIT=0. INFORM=1. f_k sum(|constr|) -

SNOPT 7.2-5 NLP code Optimality conditions satisfied FuncEv 1 ConstrEv 24 ConJacEv 24 Iter 18 MinorIter 361

CPU time: 0.156250 sec. Elapsed time: 0.156000 sec.

122.4 Plot result


subplot(2,1,1) plot(t,x1,'*-',t,x2,'*-'); legend('x1','x2'); title('Two Phase Schwartz state variables'); subplot(2,1,2) plot(t,u,'+-'); legend('u'); title('Two Phase Schwartz control');

Previous Start Next

100 Singular CSTR


ITERATIVE DYNAMIC PROGRAMMING, REIN LUUS 10.4 Nonlinear two-stage CSTR problem CHAPMAN & HALL/CRC Monographs and Surveys in Pure and Applied Mathematics

100.1 Problem Formulation


Find u over t in [0; t_F ] to minimize:
J = x(tF)*x(tF) + tF

(the state variables are moved to bounds)

subject to:
dx1 = 3*x1+g1 dt dx2 = 11.1558*x2+g18.1558*(x2+0.1592)*u1 dt dx3 = 1.5*(0.5*x1x3)+g2 dt dx4 = 0.75*x24.9385*x4+g23.4385*(x4+0.122)*u2 dt

10 g1 = 1.5e7*(0.5251x1)*exp( x2+0.6932 15 1.5e10*(0.4748+x1)*exp( x2+0.6932 10 g2 = 1.5e7*(0.4236x2)*exp( x4+0.6560 15 1.5e10*(0.5764+x3)*exp( x4+0.6560 ) 0.5086 ) ) 1.4280 )

The initial condition are:


x(0) = [0.1962 0.0372 0.0946 0] 1 <= u(1:2) <= 1

Reference: [25]

100.2 Problem setup


toms t t_f p = tomPhase('p', t, 0, t_f, 30); setPhase(p) tomStates x1 x2 x3 x4 tomControls u1 u2 % Initial guess x0 = {t_f == 0.3 icollocate({x1 == 0.1962; x2 == -0.0372 x3 == 0.0946; x4 == 0}) collocate({u1 == 0; u2 == 0})}; % Box constraints cbox = {0.1 <= t_f <= 100 -1 <= collocate(u1) <= 1 -1 <= collocate(u2) <= 1}; % Boundary constraints cbnd = {initial({x1 == 0.1962; x2 == -0.0372 x3 == 0.0946; x4 == 0}) final({x1 == 0; x2 == 0 x3 == 0; x4 == 0})}; % ODEs and path constraints g1 = 1.5e7*(0.5251-x1).*exp(-10./(x2+0.6932)) ...

- 1.5e10*(0.4748+x1).*exp(-15./(x2+0.6932)) - 1.4280; g2 = 1.5e7*(0.4236-x2).*exp(-10./(x4+0.6560)) ... - 1.5e10*(0.5764+x3).*exp(-15./(x4+0.6560)) - 0.5086; ceq = collocate({ dot(x1) == -3*x1+g1 dot(x2) == -11.1558*x2+g1-8.1558*(x2+0.1592).*u1 dot(x3) == 1.5*(0.5*x1-x3)+g2 dot(x4) == 0.75*x2-4.9385*x4+g2-3.4385*(x4+0.122).*u2}); % Objective objective = t_f;

100.3 Solve the problem


options = struct; options.name = 'Singular CSTR'; solution = ezsolve(objective, {cbox, cbnd, ceq}, x0, options); t = subs(collocate(t),solution); x1 = subs(collocate(x1),solution); x2 = subs(collocate(x2),solution); x3 = subs(collocate(x3),solution); x4 = subs(collocate(x4),solution); u1 = subs(collocate(u1),solution); u2 = subs(collocate(u2),solution); Problem type appears to be: lpcon Starting numeric solver ===== * * * =================================================================== * * * TOMLAB - Tomlab Optimization Inc. Development license 2011-02-05 999001. Valid to

======================================================================= ============== Problem: --- 1: Singular CSTR 0.324402684069356410 0.000000010809098017 f(x_k) + sum(|constr|) 0.324402694878454410 f_k sum(|constr|)

f(x_0) 0.299999999999999990 Solver: snopt. EXIT=0. INFORM=1.

SNOPT 7.2-5 NLP code Optimality conditions satisfied FuncEv 1 ConstrEv 75 ConJacEv 75 Iter 42 MinorIter 427

CPU time: 0.562500 sec. Elapsed time: 0.594000 sec.

100.4 Plot result


subplot(2,1,1) plot(t,x1,'*-',t,x2,'*-',t,x3,'*-',t,x4,'*-'); legend('x1','x2','x3','x4'); title('Singular CSTR state variables'); subplot(2,1,2) plot(t,u1,'+-',t,u2,'+-'); legend('u1','u2'); title('Singular CSTR control');

Previous Start Next

3 Nonlinear CSTR
Dynamic optimization of chemical and biochemical processes using restricted second-order information 2001, Eva Balsa-Canto, Julio R. Banga, Antonio A. Alonso Vassilios S. Vassiliadis Case Study III: Nonlinear CSTR

73.1 Problem description


The problem was first introduced by Jensen (1964) and consists of determining the four optimal controls of a chemical reactor in order to obtain maximum economic benefit. The system dynamics describe four simultaneous chemical reactions taking place in an isothermal continuous stirred tank reactor. The controls are the flow rates of three feed streams and an electrical energy input used to promote a photochemical reaction. Luus (1990) and Bojkov, Hansel, and Luus (1993) considered two sub-cases using three and four control variables respectively.

The problem is formulated as follows:Find u1(t), u2(t), u3(t) and u4(t) over t in [t0,t_f] to maximize:
J = x8(tf)

Subject to:
dx1 = u4q*x117.6*x1*x223*x1*x6*u3 dt dx2 = u1q*x217.6*x1*x2146*x2*x3 dt dx3 = u2q*x373*x2*x3 dt dx4 = q*x4+35.2*x1*x251.3*x4*x5 dt dx5 = q*x5+219*x2*x351.3*x4*x5 dt dx6 = q*x6+102.6*x4.*x523*x1*x6*u3 dt dx7 = q*x7+46*x1*x6*u3 dt dx8 = 5.8*(q*x1u4)3.7*u14.1*u2+

dt q*(23*x4+11*x5+28*x6+35*x7)5*u320.099

where:
q = u1+u2+u4;

with the initial conditions:


x(t0) = [0.1883 0.2507 0.0467 0.0899 0.1804 0.1394 0.1046 0.000]

And the following bounds on the control variables:


0 <= u1 <= 20 0 <= u2 <= 6 0 <= u3 <= 4 0 <= u4 <= 20

The final time is considered fixed as t_f = 0.2. Reference: [1]

73.2 Problem setup


toms t

73.3 Solve the problem, using a successively larger number collocation points

for n=[5 20 60] p = tomPhase('p', t, 0, 0.2, n); setPhase(p); tomStates x1 x2 x3 x4 x5 x6 x7 x8 tomControls u1 u2 u3 u4 % Interpolate an initial guess for the n collocation points if n == 5 x0 = {}; else x0 = {icollocate({x1 == x1opt; x2 == x2opt x3 == x3opt; x4 == x4opt; x5 == x5opt x6 == x6opt; x7 == x7opt; x8 == x8opt}) collocate({u1 == u1opt; u2 == u2opt u3 == u3opt; u4 == u4opt})}; end % Box constraints cbox = {icollocate({ 0 <= x1; 0 <= x2; 0 <= x3 0 <= x4; 0 <= x5; 0 <= x6 0 <= x7; 0 <= x8}) collocate({ 0 <= u1 <= 20; 0 <= u2 <= 6 0 <= u3 <= 4; 0 <= u4 <= 20})};

% Boundary constraints cbnd = initial({x1 == 0.1883; x2 == 0.2507 x3 == 0.0467; x4 == 0.0899; x5 == 0.1804 x6 == 0.1394; x7 == 0.1064; x8 == 0}); % ODEs and path constraints % 4.1*u2+(u1+u2.*u4) in another paper, -0.09 instead of -0.099 q = u1+u2+u4; ceq = collocate({ dot(x1) == (u4-q.*x1-17.6*x1.*x2-23*x1.*x6.*u3)

dot(x2) == (u1-q.*x2-17.6*x1.*x2-146*x2.*x3) dot(x3) == (u2-q.*x3-73*x2.*x3) dot(x4) == (-q.*x4+35.2*x1.*x2-51.3*x4.*x5) dot(x5) == (-q.*x5+219*x2.*x3-51.3*x4.*x5) dot(x6) == (-q.*x6+102.6*x4.*x5-23*x1.*x6.*u3) dot(x7) == (-q.*x7+46*x1.*x6.*u3) dot(x8) == (5.8*(q.*x1-u4)-3.7*u1-4.1*u2+q.*... (23*x4+11*x5+28*x6+35*x7)-5*u3.^2-0.099)}); % Objective objective = -final(x8);

73.4 Solve the problem


options = struct; options.name = 'Nonlinear CSTR'; solution = ezsolve(objective, {cbox, cbnd, ceq}, x0, options); % Optimal x and u as starting point x1opt = subs(x1, solution); x2opt = subs(x2, solution); x3opt = subs(x3, solution); x4opt = subs(x4, solution); x5opt = subs(x5, solution); x6opt = subs(x6, solution); x7opt = subs(x7, solution); x8opt = subs(x8, solution); u1opt = subs(u1, solution); u2opt = subs(u2, solution); u3opt = subs(u3, solution); u4opt = subs(u4, solution); Problem type appears to be: lpcon Starting numeric solver ===== * * * =================================================================== * * * TOMLAB - Tomlab Optimization Inc. Development license 2011-02-05 999001. Valid to

======================================================================= ============== Problem: --- 1: Nonlinear CSTR 21.841502289865435000 0.000000000210565355 f(x_k) + sum(|constr|) 21.841502289654869000 f(x_0) 0.000000000000000000 Solver: snopt. EXIT=0. INFORM=1. f_k sum(|constr|) -

SNOPT 7.2-5 NLP code Optimality conditions satisfied FuncEv 1 ConstrEv 53 ConJacEv 53 Iter 41 MinorIter 342

CPU time: 0.453125 sec. Elapsed time: 0.500000 sec. Problem type appears to be: lpcon Starting numeric solver ===== * * * =================================================================== * * * TOMLAB - Tomlab Optimization Inc. Development license 2011-02-05 999001. Valid to

======================================================================= ============== Problem: --- 1: Nonlinear CSTR 21.896802275281718000 0.000000001587400641 f(x_k) + sum(|constr|) 21.896802273694316000 f(x_0) 21.841502289865460000 Solver: snopt. EXIT=0. INFORM=1. f_k sum(|constr|) -

SNOPT 7.2-5 NLP code Optimality conditions satisfied FuncEv 1 ConstrEv 96 ConJacEv 96 Iter 91 MinorIter 380

CPU time: 1.500000 sec. Elapsed time: 1.547000 sec. Problem type appears to be: lpcon

Starting numeric solver ===== * * * =================================================================== * * * TOMLAB - Tomlab Optimization Inc. Development license 2011-02-05 999001. Valid to

======================================================================= ============== Problem: --- 1: Nonlinear CSTR 21.887245712594538000 0.000000000445950436 f(x_k) + sum(|constr|) 21.887245712148587000 f(x_0) 21.896802275281658000 Solver: snopt. EXIT=0. INFORM=1. f_k sum(|constr|) -

SNOPT 7.2-5 NLP code Optimality conditions satisfied FuncEv end t = subs(collocate(t),solution); 1 ConstrEv 277 ConJacEv 277 Iter 258 MinorIter 1045

CPU time: 40.765625 sec. Elapsed time: 42.203000 sec.

x1 = collocate(x1opt); x2 = collocate(x2opt); x3 = collocate(x3opt); x4 = collocate(x4opt); x5 = collocate(x5opt); x6 = collocate(x6opt); x7 = collocate(x7opt); x8 = collocate(x8opt); u1 = collocate(u1opt); u2 = collocate(u2opt); u3 = collocate(u3opt); u4 = collocate(u4opt);

73.5 Plot result

figure(1) plot(t,x1,'*-',t,x2,'*-',t,x3,'*-',t,x4,'*-' ... ,t,x5,'*-',t,x6,'*-',t,x7,'*-',t,x8/10,'*-'); legend('x1','x2','x3','x4','x5','x6','x7','x8/10'); title('Nonlinear CSTR state variables'); figure(2) plot(t,u1,'+-',t,u2,'+-',t,u3,'+-',t,u4,'+-'); legend('u1','u2','u3','u4'); title('Nonlinear CSTR control');

Previo

irst order reversible reaction in batch reactor


John Kitchin

Contents

Problem statement plot the solution

Problem statement

forward rate law: backward rate law: this example illustrates a set of coupled first order ODES
function main

clc; clear all; close all; u = cmu.units; %note that using units makes this m-file run pretty slowly tspan = [0 5]*u.min; init = [1 0]*u.mol/u.L; [t,C] = ode45(@myode,tspan,init);

plot the solution


plot(t/u.min,C/(u.mol/u.L)) xlabel('Time (min)') ylabel('Concentration (mol/L)') legend C_A C_B

you need this to make the plot appear in the right place above when published. It appears you need a final cell with an output to avoid having the plot showup at the end of the published document.
disp('end') end function dCdt = myode(t,C) % ra = -k1*Ca % rb = -k_1*Cb % net rate for production of A: ra - rb % net rate for production of B: -ra + rb u = cmu.units; k1 = 1/u.min; k_1 = 0.5/u.min; Ca = C(1); Cb = C(2); ra = -k1*Ca; rb = -k_1*Cb; dCadt = ra - rb; dCbdt = -ra + rb; dCdt = [dCadt; dCbdt]; % categories: ODEs % tags: reaction engineering % post_id = 706; %delete this line to force new post;

Published with MATLAB 7.10

Solving Bessel's Equation numerically


August 08, 2011 at 01:53 PM | categories: odes | 0 Comments

Solving Bessel's Equation numerically


Reference Ch 5.5 Kreysig, Advanced Engineering Mathematics, 9th ed. Bessel's equation comes up often in engineering problems such as heat transfer. The solutions to this equation are the Bessel functions. To solve this equation numerically, we must convert it to a system of first order ODEs. This can be done by letting and and performing the change of variables:

if we take the case where , the solution is known to be the Bessel function , which is represented in Matlab as besselj(0,x). The initial conditions for this problem are: and .
function bessel_ode clear all; close all; clc; % define the initial conditions y0 = 1; z0 = 0; Y0 = [y0 z0];

There is a problem with our system of ODEs at x=0. Because of the ODEs are not defined at x=0.
fbessel(0,Y0) ans = 0 NaN

term, the

if we start very close to zero instead, we avoid the problem


fbessel(1e-15,Y0)

ans = 0 -1 xspan = [1e-15 10]; [x,Y] = ode45(@fbessel, xspan, Y0); figure hold on plot(x,Y(:,1),'b-'); plot(x,besselj(0,x),'r--') legend 'Numerical solution' 'analytical J_0(x)'

You can see the numerical and analytical solutions overlap, indicating they are the same.
'done' ans = done function dYdx = fbessel(x,Y) % definition of the Bessel equation as a system of first order ODEs nu = 0; y = Y(1); z = Y(2); dydx = z; dzdx = 1/x^2*(-x*z - (x^2 - nu^2)*y); dYdx = [dydx; dzdx]; % categories: ODEs % tags: math % post_id = 763; %delete this line to force new post;

You might also like