0% found this document useful (0 votes)
22 views11 pages

Building A MATLAB Graphical User Interface To Solv

Uploaded by

suroor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views11 pages

Building A MATLAB Graphical User Interface To Solv

Uploaded by

suroor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/325079801

Building a MATLAB Graphical User Interface to Solve Ordinary Differential


Equations as a Final Project for an Interdisciplinary Elective Course on
Numerical Computing

Article · May 2018


DOI: 10.22369/issn.2153-4136/9/1/3

CITATION READS

1 3,146

3 authors, including:

Jianan Zhao Ashlee Ford Versypt


Oklahoma State University - Stillwater University at Buffalo, The State University of New York
18 PUBLICATIONS 412 CITATIONS 70 PUBLICATIONS 1,131 CITATIONS

SEE PROFILE SEE PROFILE

All content following this page was uploaded by Jianan Zhao on 05 December 2018.

The user has requested enhancement of the downloaded file.


Journal of Computational Science Education Volume 9, Issue 1

Building a MATLAB Graphical User Interface to Solve Ordinary


Di�erential Equations as a Final Project for an Interdisciplinary
Elective Course on Numerical Computing

Steve M. Ruggiero∗ Jianan Zhao∗ Ashlee N. Ford Versypt†


School of Chemical Engineering School of Chemical Engineering School of Chemical Engineering
Oklahoma State University Oklahoma State University Oklahoma State University
Stillwater, OK Stillwater, OK Stillwater, OK
[email protected]
ABSTRACT following numbers of graduate students by degree program: eight
A �nal project assignment is described for an interdisciplinary ap- in chemical engineering, six in mechanical engineering, two in
plied numerical computing upper division and graduate elective in chemistry, and one each in environmental engineering, mathemat-
which students develop a GUI for de�ning and solving a system of ics, and plant and soil sciences. The �rst and second authors of this
ordinary di�erential equations (ODEs) and the associated explicit paper took the course as �rst year chemical engineering graduate
algebraic equations such as values for parameters. The primary task students in the �rst and second course o�erings, respectively.
is to use the MATLAB built-in graphical user interface development The course is designed to train science and engineering seniors
environment (GUIDE) [16, 17] to develop a graphical user interface and graduate students to use practical software tools for com-
(GUI) that takes a user-speci�ed number of ODEs and explicit alge- putational problem solving and research: Git for version control,
braic equations as input, solves the system of ODEs using ode45, LATEX for mathematical and scienti�c typesetting, and MATLAB
returns the solution vector, and plots the solution vector compo- and Python as high level programming languages with libraries of
nents vs. the independent variable. The code for the GUI must be solvers, visualization tools, and capabilities for designing graphi-
veri�ed by showing that it returns the same results and the same cal user interfaces (GUIs). Throughout the course, the instructor
�gures as a system of ODEs with a known solution. The purpose of emphasizes best practices of open-source code development, veri�-
the �nal project assignment is threefold: (1) to practice GUI design cation, and documentation [2, 3, 8–15, 18, 20–23, 26, 28] and adopts
and construction in MATLAB, (2) to verify code implementation, the Software Carpentry philosophy of providing hands-on training
and (3) to review content covered throughout the course. The manu- in very practical computational skills for scientists and engineers
script �rst introduces the course and the context and motivation for [27]. Rather than covering the basics of computer programming
the project. Then the project assignment is detailed. Two student or details of algorithms for numerical methods, the course focuses
project submissions are described. The veri�cation case study is on applying numerical computing methodologies, primarily ordi-
also provided. nary di�erential equation solvers and optimization routines for
parameter estimation to solve realistic continuum scale problems
KEYWORDS in science and engineering.
The course consists of ten reading assignments worth 2% each
numerical methods, graduate education, computational science
and six computational assignments. The �rst assignment is worth
elective course
5% and introduces the students to using version control in Git and
document typesetting in LATEX, which are required components in
1 INTRODUCTION
all subsequent assignments. The second assignment is worth 5%
The corresponding author of this paper teaches a course titled Ap- and gives student practice with programming in MATLAB while
plied Numerical Computing for Scientists and Engineers that she developing best practices for scienti�c computing. The students are
developed at Oklahoma State University. The course is o�ered as a required to create a function de�ning a system of ordinary di�eren-
chemical engineering upper division and graduate elective designed tial equations (ODEs) and write well-documented code. The third
and advertised to be interdisciplinary. Over the �rst two o�erings, assignment is worth 10% and involves using built-in functions and
�ve chemical engineering seniors took the course along with the library routines for numerical methods (speci�cally ODE solvers)
∗ The �rst two authors contributed equally to this work. in MATLAB and Python to solve the system of ODEs described in
† Corresponding author. Appendix A. The fourth assignment is worth 15% and covers pa-
rameter estimation of dynamic models using MATLAB and Python
Permission to make digital or hard copies of all or part of this work for personal or focusing on a case study from [1]. The �fth assignment is worth 15%
classroom use is granted without fee provided that copies are not made or distributed
for pro�t or commercial advantage and that copies bear this notice and the full and involves creating a relatively straightforward GUI in MATLAB
citation on the �rst page. To copy otherwise, or republish, to post on servers or to to take user inputs and display simulation results from user-de�ned
redistribute to lists, requires prior speci�c permission and/or a fee. Copyright ©JOCSE,
a supported publication of the Shodor Education Foundation Inc.
functions provided by the instructor for di�erent scienti�c applica-
tions. The sixth and �nal computational assignment is worth 30%
© 2018 JOCSE, a supported publication of the Shodor Education Foundation Inc. of the course grade and is described in detail in this paper.
DOI: https://doi.org/10.22369/issn.2153-4136/9/1/4

May 2018 ISSN 2153-4136 19


Volume 9, Issue 1 Journal of Computational Science Education

The �nal computational assignment is referred to as the “�nal


project” to emphasize its signi�cance in the course grade, its compre-
hensive nature, and the time involved to complete the assignment
satisfactorily. The students are allowed one month to work on this
project, and it serves as a take-home �nal exam. The purpose of this
assignment is threefold: (1) to practice GUI design and construction
in MATLAB, (2) to verify code implementation, and (3) to review
content covered throughout the course. The project builds upon
content from all of the previous assignments. Although it does not
explicitly involve parameter estimation, the systems of ODEs used
for the dynamic models in the fourth assignment from [1] are used
in the �nal project as two of the three veri�cation cases required.
For brevity we only provide the most complicated of the veri�cation
cases here in Appendix A, which is from the third assignment.
In the chemical reaction engineering course that the correspond-
ing author teaches and many other o�erings of the same course
around the U.S., the software POLYMATH [25] is used as recom- Figure 1: Graphical user interface in POLYMATH for enter-
mended by the popular textbook [4], which uses the software ing a di�erential equation.
throughout the book in many examples and homework problems.
POLYMATH is a numerical computation package that can solve data
regressions and systems of simultaneous ODEs, linear algebraic
equations, or nonlinear algebraic equations. These are all of the
types of computational science problems encountered in a typical
chemical reaction engineering course. In POLYMATH, equations
are entered through GUIs in formats that look just like the written
form of the equations, so there is not a coding learning curve (Fig.
1 and Fig. 2). After entering equations via GUIs or in lieu of using
the GUIs, users can edit code directly in a script �le. For details on
how to use POLYMATH to enter and solve a system of ODEs, a
tutorial document is available on the web [5]. A limitation of the
current POLYMATH educational version is that users can enter
only 30 simultaneous ODEs and 40 explicit algebraic equations.
Figure 2: Graphical user interface in POLYMATH for enter-
This is adequate for typical use. However, for the course project
ing an explicit algebraic equation.
in the author’s chemical reaction engineering course [6], the limit
is often reached. Additionally, POLYMATH cannot combine di�er-
ent types of numerical solvers in the same problem unlike other
software programs such as MATLAB and Python. The author origi- use the MATLAB built-in graphical user interface development
nally started programming MATLAB or Python scripts for working environment (GUIDE) to develop a graphical user interface (GUI)
around the equation number limit in POLYMATH but found the that takes a user-speci�ed number of di�erential equations and
codes to be challenging for novice users to modify. The �nal project explicit algebraic equations as input, solves the system of ODEs
discussed here grew out of a need to have a POLYMATH-like GUI- using ode45, returns the solution vector, and plots the solution
based platform built into a more sophisticated software platform vector components vs. the independent variable. The GUI should
when dealing with more than 30 simultaneous ODEs. MATLAB was work in general for any system of ODEs (speci�cally initial value
selected for this �nal project because of its relative ease in creating problems not boundary value problems). The code for the GUI must
GUIs and packaging them as apps, which are very user-friendly for be veri�ed by showing that it returns the same results and the same
download and installation. �gures as the systems of ODEs de�ned in Computational Assign-
The remainder of this paper provides the required tasks in the ments 3 and 4. The more complicated of these veri�cation cases
�nal project assignment in Section 2, gives details of two student is provided in detail in Appendix A. Students are not penalized if
project submissions in Section 3, and o�ers conclusions in Section their code does not work for arbitrary ODEs beyond the veri�cation
4. The veri�cation case study is presented in Appendix A. cases.
The GUI can take a variety of layouts, which may involve use
of multiple .m �les, if desired. A descriptive �le naming system
2 PROJECT ASSIGNMENT should be used. Students should design a GUI that is intuitive to
In the project assignment, students develop a GUI for de�ning use with the following required as buttons:
and solving a system of ODEs and the associated explicit algebraic • de�ne a system of ODEs
equations (e.g., temperature dependence of rate constants or values – The numbers of di�erential equations and algebraic equa-
for parameters) for di�erent applications. The primary task is to tions should be solicited either directly or indirectly.

20 ISSN 2153-4136 May 2018


Journal of Computational Science Education Volume 9, Issue 1

⇤ In the direct method, when this button is clicked, a


window should appear asking the user how many equa- 1 % Executes on button press in saveplot_button
tions of both types that they want to de�ne. After that 2 function saveplot_button_Callback(hObject, ...
eventdata, handles)
windows should appear recursively for the user to en- 3 % hObject handle to saveplot_button
ter the speci�ed numbers of corresponding di�erential 4 % eventdata reserved
equations and algebraic equations. 5 % handles structure with handles and user data
6 if exist('plotName.png', 'file') == 2
⇤ In the indirect method, when this button is clicked, win- 7 beep
dows should be opened for de�ning di�erential or alge- 8 h = msgbox(...
braic equations one at a time (or in bulk for algebraic 9 'plotName.png already exists. Please rename ...
or delete the existing plotName.png file ...
equations). At the end of each input, the user chooses before trying to save again.',...
done or continue to enter another equation of the same 10 'Plot NOT Saved');
11 else
type. The number of equations of that type is then in- 12 ax = handles.plotAxes;
cremented. 13 figure_handle = isolate_axes(ax);
– The interfaces for entering the equations should be sim- 14 export_fig plotName.png
15 h = msgbox(...
ilar to those used in POLYMATH (Figs. 1 and 2), which 16 'The plot was successfully saved as ...
can be implemented using one or more windows that are plotName.png. Be careful to rename it if ...
themselves GUIs and/or dialog boxes. you want to save multiple versions of ...
the plot.',...
– The user must be able to enter initial values and limits of 17 'Plot Saved');
integration. 18 end
– The comment section and the buttons labeled Clear and
Cancel shown in the POLYMATH examples (Figs. 1 and 2) Figure 3: saveplot_button_Callback function example.
are optional.
– After input is provided by the user, it should be visible to
them as a static textbox, editable textbox, or listbox with
windows; however, other ways are acceptable. Another useful but-
options to edit the input.
ton could allow users to edit the axes labels, particularly to include
• calculate results
units. The GUI must be packaged as a MATLAB app and submitted
– This button should calculate results in preparation for
electronically via the course website.
either exporting to Excel or plotting.
Students must create a .tex �le to document testing that their
– Something should be output to indicate that the results
GUI works for the veri�cation test cases. A screenshot of the GUI
were calculated; command window output is acceptable.
when all equations have been entered must be included as well as
• plot results
the output plot with all of the dependent variables plotted together
The plot routine should have options for displaying all or
vs. the independent variable. A veri�cation case is described further
a subset of the output vectors (dependent variables vs. the
in Appendix A.
independent variable).
String manipulation is not the primary purpose of the �nal
• save plot
project, but it is necessary to take input from di�erent windows
– The save plot button should call export_fig.m [19] to
and compose strings into equations. To aid students less familiar
create a .png �le of a reasonable size for the output plot
with string manipulation, the following tips are provided. If the
that currently appears on the screen.
code can accept the proper input arranged as cell arrays, the func-
– The user should be prompted to specify a �lename and
tion shown in Fig. 4 connects the input to the ODE solver. In test
target directory for the plot.
cases, it is clear that the numerator and denominator are not ex-
– A sample callback function for a button that saves a plot
actly the strings that are needed for ode45(@(t,y)ODE...) and
with a prescribed name via export_fig.m is shown in
that the explicit equations and the right hand sides of the ODEs
Fig. 3.
are not in terms of and t as desired. It is strongly advised NOT
• export results as Excel �le
to use strrep in MATLAB or other �nd and replace algorithms.
The export results button should export all the independent
Instead, let MATLAB do that automatically by parsing the strings.
and dependent variable output from the ODE solver to a
Fig. 4 is a working version of a function ODE that properly reads
.csv or .xls or .xlsx �le (label the type of output on your
cell array inputs stored as variables in handles and converts them
GUI) so that the user could view the results in Excel for
to the equations that de�ne the system of ODEs. ODE is called by
creating more elaborate plots.
ode45. The only requirement to the user is that they cannot name
a constant parameter or t. This requirement is not necessary for
Additional buttons or other GUI objects may be useful. For ex- independent or dependent variables.
ample, a .mat �le is recommended for saving selected variables
from a subsidiary GUI window for de�ning the ODEs or the explicit 3 STUDENT PROJECT SUBMISSIONS
equations. Then this can be loaded in the main GUI �le to read
The top student submissions for the �nal project from each of
the values after the temporary GUI window closes. A cell array is
the �rst two course o�erings are presented here as examples. We
a natural way to save the values generated from each of the GUI
have prepared a private Bitbucket version control repository for

May 2018 ISSN 2153-4136 21


Volume 9, Issue 1 Journal of Computational Science Education

(Fig. 5 shows only the �rst dependent variable selected). Multiple


1 function dydt = ODE(t, y, denominators, ... GUI windows are used for this program.
numerators, RHSs, explicitEqns) All the push buttons, except Reset and Help, were separated
2 % Input: t and y are the independent and
3 % dependent variable values, into three groups based on the objectives of the program. Within the
4 % denominators, numerators, RHSs, and panel labeled Define/Edit Equations/Parameters, the Define
5 % explicitEqns are cell arrays with Equations push button �rst allows the user to specify the num-
6 % the first three terms defining the
7 % ODEs of the formă ber of ODEs and gives the user an option to choose whether or
8 % d(numerators) / d(denominators) = RHSs not to de�ne any explicit equations after the system of ODEs is
9
10
%
%
and the fourth term defining the associated
explicit equations
de�ned (Fig. 6). If the radio button Add explicit equations is
11 % Output: the derivative vector dy/dt for activated (Fig. 6), a GUI window appears that allows user to enter
12 % y(1):y(numODEs) where the explicit equations in bulk (Fig. 7) after the system of ODEs has
13 % numODEs = length(numerators) = length(RHSs) =
14 length(denominators) been successfully de�ned. All the ODEs must have explicit form
d
15 % To be called by ode45(@(t,y)... of dt = f (t, ). Based on the input number of ODEs, a for loop
16 % ODE(t,y,denominators,numerators,RHSs,...
17 % explicitEqns), tspan, y0) is used to repeatedly pop up the window for de�ning each ODE
18 separately along with its initial value (Fig. 8). When the loop is
19 % independent variable �nished, a new GUI window lets the user de�ne the upper and
20 str0=cell2mat(denominators(1));
21 eval(strcat(str0,'=t;')); lower limits of the integration, with both having default values of
22 % dependent variables 0 (Fig. 9). The speci�ed values and equations all appear in the main
23
24
for i = 1:length(numerators)
str1 = cell2mat(numerators(i));
GUI window either in listboxes or as static text (Fig. 5).
25 eval(strcat(str1,'=y(i);')); The remaining buttons in the �rst panel in Fig. 5 are used for
26 end editing. The Edit Selected ODE push button enables the user to
27 % explicit equations provided in MATLAB
28 % acceptable order; can be a edit speci�c ODE expressions and the corresponding initial value
29 % semicolon separated list according to selected line in the ODE(s)Entered list box (Fig. 5).
30 for i = 1:length(explicitEqns) By clicking the Integration Limits push button, the user can
31 str2 = cell2mat(explicitEqns(i));
32 eval(str2); modify the integration limits via the dialog box (Fig. 9). Through
33 end the Edit Explicit Eqs push button, the user opens a new GUI
34
35
% Right-hand sides of ODE definitions
for i = 1:length(RHSs)
window (Fig. 7) to de�ne the explicit equations if they have not
36 str3 = cell2mat(RHSs(i)); been de�ned yet or to edit existing explicit equations.
37 dydt(i) = eval(str3); In the Calculate/Plot panel, clicking the push button Calculate
38 end
39 % output formatting opens a dialog window to require the user to enter the step size for
40 dydt = dydt'; the numerical integration. The default value is 10 4 . Then ode45
is called to solve the system of ODEs. When the Plot Results
button is pushed, the window titled Select Variables Shown
Figure 4: Example ODE function that properly reads cell ar-
on Plot appears to allow the user to select single or multiple de-
ray inputs stored as variables in handles and converts them
pendent variables to be shown on the axes of the main GUI (Fig. 10).
to the equations that de�ne the system of ODEs.
The user can modify the labels of the independent and dependent
axes via the push button Edit Plot Axes. The default axes labels
archiving the code for these submissions along with the instructor are shown in Fig. 11.
documents related to the project assignment. The link is not shared The Save Plot push button enables the user to specify a �le
publicly here to prevent future students from simply downloading name and target local directory for saving the plot currently shown
the solution without doing the project. Interested educators may in the axes area of the main GUI. Similarly, the Save Data to
contact the corresponding author by email to request access to the .csv push button prompts the user to provide a �le name and
private repository. local directory for saving all the results for the independent and
dependent variable output from the ODE solver to a .csv �le.
3.1 Submission 1 The program is capable to some extent of checking for the legality
3.1.1 Overview. The program of Submission 1 is mainly com- of user inputs. In the window to de�ne a di�erential equation
posed of three parts: collecting user inputs to de�ne the system (Fig. 8), the numerator and denominator positions are checked for
of ODEs and the explicit equations, solving the system of ODEs the presence of characters and the initial condition blank is checked
coupled to the explicit equations, and saving simulation results by for a numerical value. The upper limit of integration is required to
exporting calculated values and �gures of plots. be larger than the lower limit. When the user decides to edit the
notation of the independent variable, the program can only change
3.1.2 GUI Description. The main GUI is composed of ten push the left hand side of every ODE; therefore, the user needs to make
buttons, three listboxes, and one axes (plot) object (Fig. 5). The user sure the notation is also modi�ed on the right hand side of each
can provide inputs through the push buttons. List boxes are used to ODE to avoid any errors during the calculation.
display the ODEs, corresponding initial conditions, and the explicit
equations. The axes object is used to display plots of some or all of 3.1.3 Program Verification. We entered the system of equations
the dependent variables as functions of the independent variable from Appendix A into the program, calculated the results, and

22 ISSN 2153-4136 May 2018


Journal of Computational Science Education Volume 9, Issue 1

Figure 5: Submission 1 main GUI screenshot with plot of the dependent variable T for the veri�cation case in Appendix A.

Figure 6: Submission 1 dialog box for setup of the number


of equations.

Figure 7: Submission 1 dialog box to enter the explicit equa-


plotted two di�erent sets of the dependent variables in Figs. 5 and tions.
12 to see the curves clearly on their di�erent scales.

3.1.4 Program Shortcomings. One major defect of this program


is that after the number of ODEs is de�ned at the very beginning, could be restructured to utilize the handles, in which case an
it cannot be changed unless the user rede�nes the whole system of update to the number of ODEs would not be as tricky to implement.
equations. This program did not utilize the MATLAB GUI handles Another defect is that the program is not capable of accepting
structure for passing arguments between functions. The de�ciency explicit equations in arbitrary order as in POLYMATH, meaning
related to not being able to edit the number of equations could that a parameter in an explicit equation must be de�ned before it
be compensated by adding another function to manipulate the is used. This requires extra work from the users as all the explicit
master ode_eqs.mat �le, which stores the expressions for all the equations have to be listed in a certain order. This is how MATLAB
equations. This could be modi�ed carefully by adding another ODE reads codes, so this is not a serious problem. For possible solutions
or deleting one or several existing ODEs. Alternatively, the program to this problem, see Submission 2 presented in Section 3.2.

May 2018 ISSN 2153-4136 23


Volume 9, Issue 1 Journal of Computational Science Education

Figure 11: Submission 1 dialog box to edit axes labels start-


ing from default axes labels.

Figure 8: Submission 1 dialog box to enter a di�erential equa-


tion.

Figure 9: Submission 1 dialog box to de�ne limits of integra-


tion.

Figure 12: Submission 1 plots of the dependent variables F A ,


F B , and FC for the veri�cation case in Appendix A.

When the user modi�es an ODE, only one ODE from the list box
can be selected at one time. Also, items in the Initial Value(s)
list box can be selected; however, they are not related to any push
buttons. In a future version, a new GUI could be added to al-
low the user to edit initial values based on the selected line in
the Initial Value(s) list box independent of editing the corre-
sponding ODE.

3.2 Submission 2
3.2.1 Overview. Submission 2 goes beyond the scope of the
project requirements by allowing the user the capability to freely
edit equations in the GUI and to enter equations in any order
(Fig. 13). Allowing the text to be edited enables the user to wholesale
Figure 10: Submission 1 dialog box to select which variables copy text in order to share, save, and enter equations. Additionally,
to display on the plot. if an error is made in entering the equations into the dialog boxes,
the user can quickly �x it by editing the text directly. Furthermore,
if the user is comfortable, they can type their equations directly
without using the dialog boxes. This is very consistent with the
capabilities of POLYMATH.

24 ISSN 2153-4136 May 2018


Journal of Computational Science Education Volume 9, Issue 1

Figure 13: Submission 2 main GUI screenshot.

Figure 15: Submission 2 dialog box for entering algebraic


equations.
Figure 14: Submission 2 dialog box for entering ODEs.

a structured format. The second step is to reorder the equations


3.2.2 GUI Description. The main GUI is composed of one ed-
so that each equation is only dependent on either no equations or
itable textbox, six push buttons, and one axes (plot) object (Fig. 13).
only previously de�ned equations. This is a requirement because
The user can provide inputs through the push buttons in much
MATLAB requires a variable to be de�ned before it can be used.
the same manner as in Section 3.1 through a GUI for de�ning a
The GUI does have dialog boxes that can be used to enter equations
di�erential equation (Fig. 14) and a GUI for de�ning a single explicit
(Figs. 14–15); however, these dialog boxes do little more than for-
algebraic equation (Fig. 15). The axes object is used to display plots
matting and inserting the appropriate text into the editable textbox
of some or all of the dependent variables as functions of the indepen-
as a template for the user to see how to edit the text.
dent variable (Fig. 13 shows all of the dependent variables selected).
To parse the text entered into the textbox of the GUI, a custom
The editable textbox is described in detail in the remainder of this
function ParseEq.m accepts a string as an argument and returns a
section.
cell array that contains 4 elements. The four elements are the name
3.2.3 Equation Parsing. Properly supporting an editable textbox of the variable the equation solves for, the independent variable
for equation entry presents some key issues. If the text displayed associated with the equation if the equation is an ODE, a structure
in the app cannot be edited, then input can be gathered solely from containing the results of parsing the right hand side of the equation,
dialog boxes in a very structured manner such as in Section 3.1. and the type of equation. The right hand side of the equation is
Since an editable textbox is a much less structured form of input, returned in two parts: a string of code that can be executed to solve
interpreting the input becomes a major challenge. The �rst step for the dependent variable and a list of variables that need to be
in handling the input is to parse the text and convert the text into de�ned before the code can be evaluated.

May 2018 ISSN 2153-4136 25


Volume 9, Issue 1 Journal of Computational Science Education

At the heart of parsing the entered text is the use of regular is put at the bottom of the list of equations, and the column associ-
expressions. Regular expressions are useful for �nding speci�c se- ated with the variable is zeroed out. This process repeats until no
quences of text. Regular expressions make use of wildcards, white- changes occur in the matrix after an iteration.
space characters, alphanumeric ranges, and more to create a very If the matrix is not completely zeroed out, then any rows that are
powerful and �exible syntax for matching text. For example, in the not entirely zeros represent variables that are not properly de�ned,
GUI the left hand side of an ODE is in the form of d(y)/d(t), where and an error is returned to the user containing the variables that are
and t can be any variables. The regular expression ‘d\(\w*\)\/d\( improperly de�ned. If the entire matrix is zeroed out, then the list
\w*\)’ will match the left hand side of any correctly entered ODE. of equations recorded while zeroing out the matrix is the correct
The �rst step in parsing the equations is to break the equation order for the equations so that each equation is only dependent on
into two parts for the left- and right-hand sides. This is done by the previous equation.
searching for the ‘=’ character and taking either side as separate
strings. Of the two sides, the left-hand side is evaluated �rst. The 4 CONCLUSIONS
left-hand side of each equations has a speci�c structure–the exact The project assignment has been used for 21 total students across
form depends on if the equation is an algebraic equation, ODE, an two o�erings of the Applied Numerical Computing elective course
initial value, or the range of an independent variable. The structured at Oklahoma State University. The project has been challenging
left-hand side of each equation lends itself to being easily parsed and thought provoking for the students in the course without being
through regular expressions. unreasonable and overly time-consuming. Each student has typi-
The main concept used in parsing the right-hand side of an cally visited the instructor’s o�ce hours more than once over the
equation is to build a line of code by following order of operations one month time period allotted for the project. The instructor has
to identify the calculation to be done �rst, producing the code to o�ered assistance with debugging and brainstorming and imple-
evaluate the operation, and then abstracting the evaluated term menting approaches. The most challenging aspect of the project for
from the rest of the equation using a token. For example, the string most students is connecting the input from a subsidiary GUI win-
`x + y * z' becomes `x + #1', where #1 is placeholder for a dow back to the main GUI window. The submissions described here
structure containing the results of parsing `y * z'. Parsing the provide two di�erent methods for doing this, and the instructions
right-hand side becomes more complex when handling parentheses. and tips from the instructor in the assignment and in Fig. 4 suggest
The approach to handling parentheses is to replace the portion another alternative using .mat �les and cell arrays. Students are
of the equation inside of the parenthesis with a token and then encouraged to discuss ideas with their classmates, but the project
recursively calling theParseEq.m function with the replaced text. must be an individual e�ort. The vast majority of the students
The result is that for each nested level of parentheses, the function have earned an A on the project (all who started early enough to
is recursively called until the innermost level of parentheses is complete all of the required components, including the veri�cation
reached and evaluated normally. cases). The students have given the project a positive reception
as they can clearly see how it connects the prior course content
3.2.4 Equation Reordering. The problem of ordering the equa-
related to numerical solution of systems of ODEs and development
tions is reduced to a problem similar to Gaussian elimination. A
of GUIs for scienti�c applications. The project detailed in this paper
matrix is constructed where each row represents a dependent vari-
can be easily integrated into a variety of computational science and
able, and each column represents a unique variable needed to de�ne
engineering elective or required courses. The content is approach-
a variable. For each dependent variable, the element in the column
able for both senior undergraduates and graduate students from
of each variable needed to de�ne the dependent variable is set to 1.
a variety of disciplines given su�cient background in MATLAB
For example, the equations
programming and GUI design.
x =2 (1) Additional cases studies could be used to adapt the project to
other disciplines such as numerical methods, computational physics
= 3⇤x (2) or chemistry, mathematical biology, and other �elds of engineering.
These case studies could readily be developed from textbook ex-
z = 4⇤ +x (3) amples in these �elds or published modeling studies such as [1] in
yield the matrix (with columns and rows labeled for clarity) petrochemical manufacturing, [7] in computational pharmacology,
and [24] in mathematical biology.
x y
x 0 0
A VERIFICATION CASE
y 1 0
z 1 1 For the veri�cation case study, a system of ODEs is used as de�ned
and solved in an example in a chemical reaction engineering text-
Each dependent variable that is de�ned by an ODE has an asso-
book [4]. The equations describe the mass and energy balances for
ciated initial value previously de�ned. Therefore, all of the columns
a pair of gas-phase reactions that occur in a plug �ow reactor that
associated with variables de�ned in ODEs are zeroed out right
is operated non-isothermally:
after creating the matrix, representing the fact that the variable
is de�ned. Each dependent variable has exactly one equation in k1
A !B r 1A = k 1AC A (4)
which the variable will show up on the left hand side. When a row
k2 2
corresponding to a variable is zeroed out, the associated equation 2A !C r 2A = k 2AC A (5)

26 ISSN 2153-4136 May 2018


Journal of Computational Science Education Volume 9, Issue 1

where A, B, and C are chemical species, r i j is the reaction rate of Table 1: Values of parameters for the veri�cation case study.
the ith reaction with respect to the jth species, and ki j is the kinetic
rate constant for the ith reaction with respect to the jth species. Variable Value Units
Pure A is fed at a rate of 100 mol/s, a temperature of 423 K, and a
E 1 /R 4000 K
concentration of 0.1 mol/L. The molar �ow rates of each species,
E 2 /R 9000 K
F A , F B , and FC , and the temperature, T , as functions of the reactor
CT (0) 0.1 mol/L
volume, V , are the quantities of interest. Mole balances on each
H Rx 1A -20,000 J/(mol of A reacted in reaction 1)
species A, B, and C give the ODEs
H Rx 2A -60,000 J/(mol of A reacted in reaction 2)
dF A 90 J/mol· K
= rA (6) C PA
dV CPB 90 J/mol· K
dF B
= rB (7) C PC 180 J/mol· K
dV Ua 4000 J/m3 · s· K
dFC Ta 373 K
= rC (8)
dV
where r i is the net reaction rate of species i. The initial conditions
are F A (0) = 100 mol/s, F B (0) = 0 mol/s, FC (0) = 0 mol/s, and
T (0) = 423 K. are at steady-state but vary spatially along the volume of the re-
The corresponding elementary rate laws that describe reactions actor, hence V is the independent variable. The explicit equations
1 and 2 from (4) and (5), respectively, are needed to complete the system of equations are given in (9)–(19)
and Table 1.
r 1A = k 1AC A (9)
2
r 2A = k 2AC A (10) REFERENCES
where C A is the concentration of species A. The relative rates are [1] J. Ancheyta-Juarez and J. A. Murillo-Hernandez. 2000. A simple method for
estimating gasoline, gas, and coke yields in FCC processes. Energy and Fuels 14
r 1B = r 1A = k 1AC A (11) (2000), 373–379.
[2] J. Carver and G. K. Thiruvathukal. 2013. Software engineering need not be
1 k 2A 2 di�cult. Workshop on Sustainable Software for Science: Practice and Experiences,
r 2C = r 2A = C (12)
2 2 A SuperComputing Conference (2013). http://dx.doi.org/10.6084/m9.�gshare.830442.
Equations (9)–(12) are combined to yield the net rates, [3] B. Ekmekci, C. E. McAnany, and C. Mura. 2016. An introduction to programming
for bioscientists: A Python-based primer. PLOS Computational Biology 12 (2016),
2 e1004867.
r A = r 1A + r 2A = k 1AC A k 2AC A (13)
[4] H. S. Fogler. 2011. Essentials of Chemical Reaction Engineering (1st. ed.). Prentice
r B = r 1B = k 1AC A (14) Hall, Boston, MA.
[5] H. S. Fogler and M. Tikmani. [n. d.]. Polymath tutorial on Ordinary Di�erential
k 2A 2 Equation Solver. ([n. d.]). Retrieved January 4, 2018 from http://umich.edu/
rC = r 2C = C (15)
2 A ~elements/5e/tutorials/ODE_Equation_Tutorial.pdf
The gas-phase stoichiometry without pressure drop is used to [6] A. N. Ford Versypt. 2017. Choose Your Own Kinetics Adventure: Student-
Designed Case Studies for Chemical Reaction Engineering Course Projects. Trans-
de�ne the concentration of species A as actions and Techniques in STEM Education In Press (2017).
[7] A. N. Ford Versypt, G. K. Harrell, and A. N. McPeak. 2017. A pharmacokinet-
F A T (0)
C A = CT (0) (16) ic/pharmacodynamic model of ACE inhibition of the renin-angiotensin system
FT T for normal and impaired renal function. Computers and Chemical Engineering
104 (2017), 311–322.
where the total �ow rate is de�ned by [8] T. Hall and J-P Stacey. 2009. Chapter 2: Designing Software. In Python 3 for
Absolute Beginners. Springer, New York.
FT = F A + F B + FC (17) [9] D. M. Hamby. 1994. Review of techniques for parameter sensitivity analysis
of environmental models. Environmental Monitoring and Assessment 32 (1994),
The rate constants depend on the temperature through the fol- 135–154.
lowing Arrhenius functions: [10] A. K. Hartmann. 2015. Big Practical Guide to Computer Simulations (2nd ed.).
 ✓ ◆ World Scienti�c, Hackensack, NJ.
E1 1 1
k 1A = 10 exp s 1 (18) [11] F. M. Hemez and J. R. Kamm. 2008. A brief overview of the state-of-the-practice
R T (0) T and current challenges in solution veri�cation. In Computational Methods in
 ✓ ◆ Transport: Veri�cation and Validation, F. Graziani (Ed.). Springer-Verlag, Berlin,
E2 1 1 L 229–250.
k 2A = 0.09 exp (19) [12] D. J. Higham and N. J. Higham. 2005. MATLAB Guide (2nd ed.). Society for
R T (0) T mol · s Industrial and Applied Mathematics, Philadelphia.
The energy balance for the reactor is [13] J. M. Kinder and P. Nelson. 2015. A Student’s Guide to Python for Physical Modeling.
Princeton University Press, Princeton, NJ.
dT U a(Ta T ) + r 1A H Rx 1A + r 2A H Rx 2A [14] J. Kiusalaas. 2005. Numerical Methods in Engineering with Python. Cambridge
= (20) University Press, New York.
dV F AC P A + F B C P B + F C C P C
[15] C. S. Lent. 2013. Learning to Program with MATLAB: Building GUI Tools. Wiley,
The values for the remaining parameters representing physical Hoboken, NJ.
[16] MathWorks. [n. d.]. App Building. ([n. d.]). Retrieved February 15, 2018 from
constants are listed in Table 1. https://www.mathworks.com/help/matlab/gui-development.html
To summarize, the system of ODEs for the veri�cation case is [17] MathWorks. [n. d.]. Create a Simple App Using GUIDE. ([n. d.]). Retrieved
given by (6)–(8) and (20) for ddVF A d F B d FC
, dV , dV , and dV
dT , describing February 15, 2018 from https://www.mathworks.com/help/matlab/creating_guis/
about-the-simple-guide-gui-example.html
the molar �ow rates of species, A, B, and C, in mol/s and tempera- [18] C. B. Moler. 2004. Numerical Computing with MATLAB. Society for Industrial
ture, T , in K in a non-isothermal plug �ow reactor. The reactions and Applied Mathematics, Philadelphia.

May 2018 ISSN 2153-4136 27


Volume 9, Issue 1 Journal of Computational Science Education

[19] Oliver Woodford. 2013 (accessed November 12, 2016). export_�g: A MATLAB
toolbox for exporting publication quality �gures. https://github.com/altmany/
export_�g.
[20] J. M. Osborne, M. O. Bernabeu, M. Bruna, B. Calderhead, J. Cooper, N. Dalchau,
S.-J. Dunn, A. G. Fletcher, R. Freeman, D. Groen, B. Knapp, G. J. McInerny, G. R.
Mirams, J. Pitt-Francis, B. Sengupta, D. W. Wright, C. A. Yates, D. J. Gavaghan,
S. Emmott, and C. Deane. 2014. Ten Simple Rules for E�ective Computational
Research. PLOS Computational Biology 10 (2014), e1003506.
[21] A. Prlic and J. B. Procter. 2012. Ten simple rules for the open development of
scienti�c software. PLOS Computational Biology 8 (2012), e1002802.
[22] P. J. Roache. 1998. Veri�cation of codes and calculations. AIAA Journal 36, 5
(1998), 696–702.
[23] K. Rother, W. Potrzebowski, T. Puton, M. Rother, E. Wywial, and J. M. Bujnicki.
2011. A toolbox for developing bioinformatics software. Brie�ngs in Bioinformat-
ics 13, 2 (2011), 244–257.
[24] S. M. Ruggiero, M. R. Pilvankar, and A. N. Ford Versypt. 2017. Computational
modeling of tuberculosis granuloma activation. Processes 5 (2017), 79.
[25] M. Shacham, M. B. Cutlip, and M. Elly. [n. d.]. POLYMATH Software. ([n. d.]).
Retrieved January 4, 2018 from http://www.polymath-software.com/
[26] V. Stodden and S. Miguez. 2013. Best practices for computational science: software
infrastructure and environments for reproducible and extensible research. (2013).
http://dx.doi.org/10.2139/ssrn.2322276.
[27] G. Wilson. 2016. Software Carpentry: lessons learned [version 2]. F1000Research
3 (2016), 62. https://doi.org/10.12688/f1000research.3-62.v2
[28] G. Wilson, D. A. Aruliah, C. T. Brown, N. P. C. Hong, M. Davis, R. T. Guy, S. H. D.
Haddock, K. D. Hu�, I. M. Mitchell, M. D. Plumbley, B. Waugh, E. P. White, and
P. Wilson. 2014. Best Practices for Scienti�c Computing. PLOS Biology 12 (2014),
e1001745.

28 ISSN 2153-4136 May 2018

View publication stats

You might also like