Manual - Computer LAB UCH 1712-Merged
Manual - Computer LAB UCH 1712-Merged
2
Department of Chemical Engineering
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Syllabus
OBJECTIVE:
To develop computational skills for chemical engineers by solving the computationally involved
problems of chemical engineering with softwares such as MS EXCEL, MATLAB, ASPEN
PLUS/HYSYS / CHEMCAD.
LIST OF EXPERIMENTS
1. Programming With FOR Loop (e.g.: to find terminal velocity at various Re) - Excel/Matlab
2. Solving Linear Equations Using MATRIX Methods - Excel/Matlab
3. Solving Non-Linear Equations (e.g.: cubic equation of state) - Excel/Matlab
4. Regression And Statistical Analysis (fitting linear and non-linear equations) - Excel/Matlab
5. Thermodynamic Properties Generation (VLE data at constant P / T) - Aspen
6. Steady State Simulation of Heat Exchanger - Aspen
7. Steady State Simulation of Distillation Column - Aspen
8. Steady State Simulation of Absorber - Aspen
9. Solving differential equation (e.g.: Tank Level Dynamics) - Matlab
10. Open loop Response: effect of various types of inputs - Matlab
11. Closed Loop Response (stable and unstable operation of loops) - Matlab
12. Complete Process Flow Sheet Simulation of Simple Chemical Process Plants. - Aspen
TOTAL : 45 PERIODS
Minimum 10 experiments to be offered
1. Computers
2. Software tools such, Microsoft Excel, MATLAB, ASPENTECH.
2
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
GENERAL INSTRUCTIONS
• Before coming to the laboratory, understand the theory behind the reaction you are going to
carry out.
• Keep the work - bench and sink neat and clean
• Save the work file in a designated folder with proper name and after the lab over you need to
shutdown the computer.
• Precautions should be taken to avoid fire accidents.
• Students are requested to get the results attested within a week of the respective
experiment date, and in the subsequent laboratory class completed record is to be
submitted.
3
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
NO.: 1.1
Date:
AIM:
kTo use basic functions of Excel to perform operations such as:
• to fill sequential data
• to use the built-in functions such as trignometric, logarithemic functions
• copying formulas annd to understand concept of relative and absolute reference
• to do matrix calculations such as matrix multiplication, inverse of matrix and to find
the determinant of matrix.
4
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
5
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
• By using the formula tab, we can access trigonometric values for various angles. The
angle magnitudes are first converted to radians from degrees.
• For the degree value which is given as an input, the corresponding radian is calculated by
inserting the formula: = RADIAN(cell address).
• Following this the various trigonometric functions are calculated by simple application of
formulas like SIN, COS, TANaccompanied by the cell address.
• By selecting the output and dragging down will result in computation of the remaining
cells.
6
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
3. Copying Formulas:
ABSOLUTE REFERENCING
An absolute reference is the one with the dollar sign ($) in the row or column coordinates, like
$A$1 or $A$1:$B$10.
An absolute cell reference remains unchanged when filling other cells with the same formula.
Absolute addresses are especially useful when you want to perform multiple calculations with a
value in a specific cell or when you need to copy a formula to other cells without changing
references.
In this example of determination of work, we use absolute reference of cells containing Pressure and
Temperature data. The Gas Constant value is also introduced. The “$” sign refers to the condition
that keeps corresponding row or column constant as the operation proceeds through the cells that are
containing the Volume data.
4. MATRIX FUNCTIONS:
The matrix elements are given as input in the cells.
Excel processes the multiplication according to matrix multiplication rules.
In a random cell the function is typed as: =MMULT(matrix A: matrix B)by selecting the
cell groups that represent the matrix and pressed enter.
A single element will get displayed which should be selected along with the outline of the
product matrix and pressed F2 followed by pressing ctrl, shift and enter simultaneously.
7
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
8
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
RESULT
9
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
AIM:
• To plot graphs between two sets of data points in Excel namely the linear and log-log plots, and
to explore various formatting options for the purposes of customization.
• To get the equation of a plotted curve.
PROCEDURE:
• The given data is entered in the form of two columns as shown below.
• The columns are highlighted, and the required graph is searched for under the Scatter group under
the Charts section in the Insert tab.
10
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
11
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
OUTPUT I:
Various types of formatting can be applied to the graph such as titles to the axes, modification of the
scale and the initial point, displaying X and Y values on the plot and insertion of grid lines into the
plot.
• Select the graph with the mouse, causing the chart tools tab to appear containing the Design,
Layout and Format tabs.
• Here, go to Chart Elements and select Axis Title from the drop-down lists, which leads to yet
another drop-down menu, where the axis can be selected.
12
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
13
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
OUTPUT II:
• Under the chart tools tab, select the design tab from the drop-down list.
• Choose the appropriate grid layout from the chart layouts section, as shown below.
14
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
OUTPUT III:
• Data Labels can also be added to the plot. These data labels can be used to provide a clear idea
of each data point without having to reference the data table.
• Click on the Plot to activate the Chart Tools Tab. Go to Chart Elements and select Data
Labels from the drop-down lists, which leads to yet another drop-down menu where more Data
Table options can be chosen.
15
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
• In the Format Data Table dialog box, make sure that the X-Values and Y-Values are marked.
16
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
17
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
OUTPUT IV:
• To Format Chart Axis, right click on the Plot and select Format Axis
• In the Format Axis dialog box, modify the minimum and maximum values as per the
requirements.
18
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
• After selecting Format Axis, under Axis options, check the Logarithmic box.
19
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
OUTPUT V:
20
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
21
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
• The trendline may be formatted to have different colours in order to enhance visibility. Here, the
selected colour is red. Selection is performed by going to Format Chart Area and then selecting
“Trendline”.
• The equation of the trendline and the R2-value (which estimates accuracy of the fit) can be
displayed by selecting the options under the “Trendline Options” tab.
22
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
• The same can be repeated for creating a trendline of 2nd order polynomial type.
OUTPUT VI:
Linear fit
OUTPUT VII:
Related Problems:
• Equilibrium Diagram
• Friction Factor vs. Reynolds number plot
• Phase Angle vs. Frequency plot
• PV diagrams
23
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
AIM:
To solve the nonlinear equation using “Goal-Seek” and “Circular-Reference” operations of Microsoft
Excel.
PROCEDURE:
Nonlinear equations give multiple solutions. Solving such equations is not straight-forward. It requires
trial-and-error procedure, or an iterative procedure starting with an initial guess value for the solution.
The numerical technique of “Newton-Raphson technique” is often used.
For solving such nonlinear equations, the operations such as Goal-Seek, Circular-Reference, and
Solver are very useful.
The nonlinear equation is written in a form such that f(x) = 0. The objective is to obtain one of the
value of x that satisfies this f(x).
As an example to this nonlinear equation, we have taken virial equation of state, to solve for the value
of volume.
Calculate the molar volume of N2 at 300 K and 50 Bar using Virial equation with B = -200 cm3/mol
and C = 20000 cm6/mol2.
Virial equation is given by:
V = (RT/P)*(1 + B/V + C/V2)
Solution by Goal-Seek Operation:
The given equation is written in the form such that f(V) = 0.
f(V) = V - (RT/P)*(1 + B/V + C/V2) = 0
The given data of B, C, and the variables T, P along with the universal gas constant R are made
available in separate cells of Excel, as below:
24
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
In a cell, the function f(V) = V - (RT/P)*(1 + B/V + C/V2) is written, connecting the cells for R, T, P,
B, C, with a guess value of V available in a cell.
Let us take the guess value of V = 1. For this the f(V) calculated by Excel is found to be non-zero. To
make this f(V) to zero, Excel’s Goal-Seek operation is invoked as below:
1) In the Data tab, select the What-if analysis. In the What-if analysis, select the Goal Seek
option.
2) There is a new tab opened which contains 3 different cells namely (i) Set cell:, (ii) To value:,
(iii) By changing cell:.
25
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
3) In the Set cell, the value to be solved i.e., f(V) is selected. In the To value, the goal or the value
to be achieved is to be set. In this case, it is 0, as we want f(V) to be zero. In the By changing
cell, the address of cell which is expected to have the value of V is given.
4) Then click OK.
.
5) Using the initial guess value of V, Excel calculates the final converged value of V, so as to meet
the target value of f(V) closer to zero.
26
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
It can be seen that the GoalSeek tool is making the f(V) closer to zero, by keep on changing the
value of V.
It is important that the “Set cell” should not contain any formula. It should be connected
with the “Target value”. The “Set cell” should be allowed to be changed by Excel.
The formula: V = (RT/P)*(1 + B/V + C/V2) contains V on both the sides. We are asked to find
the value of V that satisfies this equation. To do that, we can allocate one cell for the value of V
(i.e., LHS) and another cell having the formula {(RT/P)*(1 + B/V + C/V2) i.e., RHS}
connecting the cell with V. These two cells are in circular reference now.
The circular reference is a series of references where a last object references the first,
resulting in a closed loop.
Let us start with some guess value of 1 to the cell of V (i.e., LHS). The RHS is connected with this
LHS cell, by the formula.
27
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Then the LHS is made equal to RHS, by typing a formula to the cell of V.
28
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Upon connecting LHS and RHS by formulas for both the cells, we get the following window:
“Circular Reference Warning”, followed by connecting the two cells which are in circular
reference.
29
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
30
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
The cells C16 and C18 are in “Circular Reference” now, as indicated by blue arrow bars.
This “Circular Reference” warning can be overcome by selecting the “Enable Iterative
Calculation” in the “Excel Options” menu of Excel.
There is a new tab opened. In the formula tab, a box named “Enable iterative calculations” is
there. By clicking it, we can change the number of iterations the programme has to run. Then
click OK.
31
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Upon enabling iterative calculation of “Formulas” menu bar of Excel-Options, we could see
the calculation of LHS = RHS is done automatically, and we get the result as below:
32
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
RESULT:
Thus, the usage of GoalSeek and Circular Reference operations of Microsoft Excel are understood with
the example of solution to virial equation of state.
Related Problems:
1. Solution to cubic equations of state.
2. Solving for temperature of bubble point, dew point calculations of binary VLE.
3. Solving for interest rate of “internal rate of return” in Economics problems.
33
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
AIM:
Problem Statement-1:
PROCEDURE:
• Create a table with the required values input into the cells.
• The objective of this problem is to maximize the profit by changing the number of units sold.
• Hence, to determine the number of units sold is solved using solver tool.
• Calculate the profit and net profit values using the required formulae.
Formulae used:
PROFIT = Sale34price – Cost price
Total profit = profit * number of
units
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
35
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
36
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
5) Click solve and once the ‘Solver results’ prompt appears click on the ‘Keep Solver
Solution’ option and click the ‘Answer’ in the reports section.
37
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
38
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Problem Statement-2:
Water flows in the parallel horizontal pipe system as shown in figure, for which
the following data are available:
Length
Pipe Diameter(m) (m) f
AaB 0.10 300 0.0060
AbB 0.15 250 0.0055
AcB 0.20 500 0.0050
The supply pipe to point A is of 0.30 m diameter and the mean velocity of water
in it is 3 m/s. What is the discharge in each pipe? Neglect all minor losses.
Solution:
Equation of Continuity:
QA = Qa + Qb + Qc
40
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
The problem statement with the given data is represented in Excel as below:
We have to solve for the values of velocities in pipe a, b, c. i.e., va, v, vc:
To start with we shall have assumed values of 1 m/s.
Using this the values of Q of every pipeline is calculated using
Qa = /4 Da2 va
41
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
The cells for Qa, Qb, and Qc are calculated by connecting the values of va, vb, vc.
The Sum of this Q’s is calculated.
Qsum = Qa + Qb + Qc
42
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
RESULT:
Thus, the usage of Solver-Addin of Excel for (i) optimizing a multivariable
problem, and (ii) solving set of nonlinear equations is studied.
43
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
AIM:
To study the various conditional statement (IF and COUNTIF), Conditional formatting and
User defined functions in Excel.
INTRODUCTION:
3. Logic functions
44
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
e_if_true],[value_if_false])
4 OR Logical Used when evaluating =OR(D8="admin",E8="ca
multiple conditions. Returns shier") N.B. the above
true if any or all of the function returns true if
conditions are true. Returns either or both D8 and E8
false if all of the conditions admin or cashier
are false
5 TRUE Logical Returns the logical value TRUE()
TRUE. It is used to compare
the results of a condition or
function that either returns
true or false
IF Function:
The IF function can perform a logical test and return one value for a TRUE result, and
another for a FALSE result. For example, to "pass" scores above 70:
=IF(A1>70,"Pass","Fail"). More than one condition can be tested by nesting IF functions.
The IF function can be combined with logical functions like AND / OR. It is hence used to
test for a specific condition. Use the IF function to test for or evaluate certain conditions, and
then react differently depending on whether the test was TRUE or FALSE.
Syntax for IF:-
=IF (logical_test, [value_if_true], [value_if_false])
Arguments :-
logical_test - A value or logical expression that can be evaluated as TRUE or FALSE.
value_if_true - [optional] The value to return when logical_test evaluates to TRUE.
value_if_false - [optional] The value to return when logical_test evaluates to FALSE.
COUNTIF Function:
The COUNTIF function is used to count cell that meet a single criterion. COUNTIF can be
used to count cells with dates, numbers, and text that meet specific criteria. The COUNTIF
function supports logical operators (>, <, <>, =) and wildcards (*, ?) for partial matching.
The COUNTIF function in Excel counts the number of cells in a range that match one
supplied condition. Criteria can include logical operators (>,<,<>,=) and wildcards (*,?) for
partial matching. Criteria can also be based on a value from another cell, as explained below.
Syntax for COUNTIF:-
= COUNTIF (range, criteria)
Arguments :-
range - The range of cells to count.
criteria - The criteria that controls which cells should be counted.
CONDITIONAL FORMATTING:
Conditional formatting in Excel enables you to highlight cells with a certain color, depending
on the cell's value.
45
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
5. Click OK.
Result. Excel highlights the cells that are greater than 80.
46
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Note: you can also use this category (see step 3) to highlight cells that are less than a value,
between two values, equal to a value, cells that contain specific text, dates (today, last week,
next month, etc.), duplicates or unique values.
❖ Clear Rules:
To clear a conditional formatting rule, execute the following steps.
1. Select the range A1:A10.
47
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
❖ Top/Bottom Rules
To highlight cells that are above average, execute the following steps.
1. Select the range A1:A10.
48
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
5. Click OK.
Result. Excel calculates the average (42.5) and formats the cells that are above this average.
Note: you can also use this category (see step 3) to highlight the top n items, the top n
percent, the bottom n items, the bottom n percent or cells that are below average.
49
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Explanation: always write the formula for the upper-left cell in the selected range. Excel
automatically copies the formula to the other cells. Thus, cell A2 contains the formula
=ISODD(A2), cell A3 contains the formula =ISODD(A3), etc.
Here's another example.
7. Select the range A2:D7.
50
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Explanation: we fixed the reference to column C by placing a $ symbol in front of the column
letter ($C2). As a result, cell B2, C2 and cell D2 also contain the formula =$C2="USA", cell
A3, B3, C3 and D3 contain the formula =$C3="USA", etc.
51
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Question
1. Generate table
52
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
53
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
54
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Excel allows you to create custom functions using VBA (Visual Basics for Applications),
called "User Defined Functions" (UDFs) that can be used the same way you would use
SUM() or other built-in Excel functions. They can be especially useful for advanced
mathematics or special text manipulation. Many Excel add-ins provide large collections of
specialized functions.
6. Use the functions - They will appear in the Paste Function dialog box (Shift+F3) under
the "User Defined" category
• Press ALT+F11
• A dialog box will appear like this. Click insert and select module.
55
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Then open the excel sheet as the name you saved and type = in the cell and then the
function name
56
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Here Diameter as 2,
Velocity as 4,
Density as 1000,
Viscosity as 1
The result is obtained as below
After finding reynolds number, to find friction factor write a program what is showed in the
above figure.
And then save the program in the same file.
Then open the excel workbook and select the cell and then type (=functionname(Reynum
saved value)) as shown in the below fig.
RESULT:
The various conditional statements (IF and COUNTIF), conditional formatting and User
defined functions in Excel were studied, executed and understood.
57
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
AIM:
PROCEDURE:
1. Open MATLAB and go to command window.
2. Type the codes as shown below. The cursor is waiting next to >>
3. The output will be displayed in the command window.
4. Understand the variants of the codes, with altered codes.
CODE:
1. Array Creation
To create an array with four elements in a single row, separate the elements with either a
comma (,) or a space.
>> a = [1 2 3 4]
a=1 2 3 4
2. Matrix Creation
To create a matrix that has multiple rows, separate the rows with semicolons.
>> a = [1 2 3; 4 5 6; 7 8 10]
a= 1 2 3
4 5 6
7 8 10
3. Matrix and Array Operations
MATLAB allows you to process all of the values in a matrix using a single arithmetic
operator or function
i). To display the first row of a matrix
>> a(1,:)
ans = 1 2 3
a(:,:) is the equivalent two-dimensional array. For matrices this is the same as
‘a’.
58
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
vii). You can perform standard matrix multiplication, which computes the inner
products between rows and columns, using the ‘*‘ operator. For example, confirm
that a matrix times its inverse returns the identity matrix:
>> p = a*inv(a)
p= 1.0000 0 0
0.0000 1.0000 0
0.0000 -0.0000 1.0000
Other matrix functions include det(a),eig(a),diag(a),rank(a),size(a)
>> p = a.*a
p= 1 4 9
16 25 36
49 64 100
ix). The matrix operators for multiplication, division, and power each have a
corresponding array operator that operates element-wise. For example, raise each
element of a to the third power:
>> a.^3
ans = 1 8 27
64 125 216
343 512 1000
x). To can carry out operations on a range of numbers.
>> x = 1:10;
>> y = sin(x);
>> y(1:5)
ans = 0.8415 0.9093 0.1411 -0.7568 -0.9589
59
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
4. Concatenation
Concatenation is the process of joining arrays to make larger ones. In fact, you made your
first array by concatenating its individual elements. The pair of square brackets [] is the
concatenation operator.
>> A = [a, a]
A= 1 2 3 1 2 3
4 5 6 4 5 6
7 8 10 7 8 10
Concatenating arrays next to one another using commas is called horizontal concatenation.
Each array must have the same number of rows. Similarly, when the arrays have the same
number of columns, you can concatenate vertically using semicolons
>> A = [a; a]
A= 1 2 3
4 5 6
7 8 10
1 2 3
4 5 6
7 8 10
5. Complex Numbers
Complex numbers have both real and imaginary parts, where the imaginary unit is the square
root of -1.
>> sqrt(-1)
ans = 0.0000 + 1.0000i
To represent the imaginary part of complex numbers, use either i or j.
>> c = [3+4i, 4+3j; -i, 10j]
c= 3.0000 + 4.0000i 4.0000 + 3.0000i
0.0000 - 1.0000i 0.0000 +10.0000i
RESULT:
The basic concepts of MATLAB were understood and executed successfully.
60
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
AIM:
To plot a linear, and loglog plots in MATLAB.
PROCEDURE:
All kinds of graphs – linear, log-log, semilog can be plotted using MATLAB. The procedure
is given below:
● Open a new window in MATLAB
● Type the source-code as mentioned below for various different plots in the command
window of MATLAB.
● The appropriate plot functions are:
♦ plot(X,Y); for linear plot
♦ loglog(X,Y); for loglog plot
♦ semilogx(X,Y); for semilog plot, also semilogy.
➢ LINEAR PLOT:
SOURCE CODE:
% Conversion versus rate plot for a second order reaction
global c;
X=0:0.01:1 ; %Conversion ranges from 0-1, with increments of 0.1
c=input('Enter the initial concentration of the reactant');
% Let c = 1 mol/lit
display=['Rate constant for the reaction is : 2 lit/mol-min'];
disp(display);
rate =2*c.^2*(1-X);
Y=rate.^ (-1);
plot(X, Y,'-*');
title ('Conversion vs. Rate plot (2nd Order reaction)');
xlabel('Conversion');
ylabel('1/r');
OUTPUT:
61
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
LOG-LOG PLOT:
To cover a wider range of variables, say 0.001 to 10,000 with every data to be shown with
precision, log-log scales are better.
SOURCE CODE:
x =logspace(-1,2);
%% logspace creates equidistant points ranging from
%% 10^(-1) to 10^2
y =exp(x);
loglog(x,y,'-*');
xlabel('x');
ylabel('y=exp(x)'); grid on
OUTPUT:
62
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
TASK: Try plotting multiple graphs on a single figure, take the same example of second
order reaction and plot the (rate)-1 vs. conversion for three rate constant values (k = [1 2
3] mol. (lit-min)-1).
ENGINEERING APPLICATIONS:
➢ Linear plot can be used to solve graphical problems in chemical reaction engineering.
Plots between Conversion and Rate ( XA vs -rA), temperature vs. conversion ( T vs.
XA) etc can be plotted.
➢ Log-log plot can be used to show the relation between friction factor and Reynolds
number.
➢ Semi log plot can be used to show the relationship between the phase angle and
amplitude ratio in process dynamics and control system.
RESULT:
➢ Linear, semi log and loglog plot have been plotted using MATLAB software for
single as well as multiple plots on the same graph.
RELATED PROBLEMS:
1. Generation of BODE plots.
2. Creating root-locus diagrams.
3. Simulation of response of a system to different inputs(step, ramp, sinusoidal, etc).
63
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
AIM:
To solve set of linear equations using MATLAB by (a) inverse matrix, (b) inbuilt
slash operator ‘ \ ’, and (c) Gauss elimination numerical method.
PROCEDURE:
It is desired to develop the steady-state tray compositions for a six-plate absorption column. It
can be assumed that a linear equilibrium relation holds between liquid (xm) and vapor (ym) on
each plate: ym = axm + b
The inlet composition to the column x0 and y7 are specified along with the liquid (L) and gas
(G) phase flow rates (moles/time). The system is shown schematically in below Figure. To
solve the problem, a material balance is written on a representative tray, n.
64
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
−( L + Ga ) x1 + Gax2 = − Lx0
Lx1 − ( L + Ga ) x2 + Gax3 = 0
Lx2 − ( L + Ga ) x3 + Gax4 = 0
Lx3 − ( L + Ga ) x4 + Gax5 = 0
Lx4 − ( L + Ga ) x5 + Gax6 = 0
y7 − b
Lx5 − ( L + Ga ) x6 = −Ga
a
Matrix_A(1,1) = -product1;
Matrix_A(1,2) = product2;
Matrix_A(2,1) = Liquid_flow;
Matrix_A(2,2) = -(product1);
Matrix_A(2,3) = product2;
Matrix_A(3,2) = Liquid_flow;
Matrix_A(3,3) = -(product1);
Matrix_A(3,4) = product2;
Matrix_A(4,3) = Liquid_flow;
Matrix_A(4,4) = -(product1);
Matrix_A(4,5) = product2;
Matrix_A(5,4) = Liquid_flow;
Matrix_A(5,5) = -(product1);
Matrix_A(5,6) = product2;
65
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Matrix_A(6,5) = Liquid_flow;
Matrix_A(6,6) = -(product1);
Vector_B1 = zeros(6,1);
Vector_B1(1,1) = -Liquid_flow*x_0;
Vector_B1(6,1) = -Gas_flow*(y_7-b);
Assignment: Solve the same set of equation by Gauss elimination method. (Use its algorithm
and write a code for solving equations)
RESULT:
Different ways of solving set of linear equations using different ways vis. Matric inverse,
inbuilt slash operator and Gauss elimination method.
Related Problems:
• Calculation of molar flow rates and composition in array of distillation columns to
separate components (E.g. Xylene, styrene, toluene, and benzene)
• Estimation of temperature profile in heat rods, such structures used to manage heat in
radiators, refrigerators, computer chips, fins, etc.
66
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
AIM:
To solve non-linear equations using MATLAB.
PROCEDURE:
Solving non linear equations using fzero function:
fzero is an inbuilt function in MATLAB which is used to calculate the roots of a non-linear
equation.
The syntax of the function is as follows:
x = fzero(fun, x0)
x = fzero(fun, x0, options)
x = fzero(problem)
[x, fval, exitflag, output] = fzero(___)
The function returns a scalar which is close to the value of the initial guess x0. This scalar is a
solution of the entered non-linear equation. MATLAB treats the points at which the curve of
the non-linear equation crosses (not touches) the x-axis, as the roots of the equation. The
value returned by fzero is a root of the given non-linear equation near x0.
Example 1:
Code:
fzero(@(x) x^2-1,5)
Output:
In the above example fzero is used to calculate the root of a non-linear equation (x2-1) near
an initial guess point (5). Notice that the whole operation is carried out in the command
window.
Example 2:
Code:
% fzeroexample.m
f=@(x) x.^2-4;
67
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
zero=fzero(f,-5)
Output:
In the above example, the same function is carried out on a different non-linear equation but
the code is executed as a script.
Example 3:
Code:
% RKeqn.m
%Finding volume occupied by 1 mol of gas and saturated liquid at the given conditions using
R-K equation
R=8.314 ;%(Pa-m^3)/(mol-K)
T=input('Enter Temperature in K: ');
P=input('Enter Pressure in Pa: ');
Tc=input('Enter critical temperature in K: ');
Pc=input('Enter critical pressure in Pa:');
a=((0.42748*(R.^2)*(Tc.^2.5)/(Pc*(Tc.^0.5))));
b=(0.08664*R*Tc)/Pc;
V_initial=(R*T)/P;
f=@(v) ((R*T)/(P+(a/(v*(v+b)))))+b-v;
zero=fzero(f,V_initial);
disp('The volume occupied by gas is');
disp(zero)
Run the file by typing the filename at the command prompt of MATLAB.
Output:
68
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
In the final example, the application of fzero in solving engineering problems is illustrated
with the help of a thermodynamic problem involving calculating the volume of a gas and its
saturated liquid using Redlich-Kwong equation of state.
S = solve(eqn(s), var(s))
where s is the variable in which the solution(s) of the equation(s) will be stored.
An illustration of using solve function is given below.
Example 4:
Code:
>> syms x y;
>> soln=solve([x^2+y^2==20,y==x^2],[x,y])
Output:
69
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Once the line containing solve function is executed, the sizes of the variables (x and y, here)
are displayed. In order to access the values of the variables (i.e. solutions of the equations),
S.var (soln.x or soln.y) is typed in the command window. The values (of x and y) will be
displayed.
Another interesting privilege that solve offers the users is to impose conditions on the
solution(s) to be displayed. In the example considered below, there exist 4 pairs of solutions
(x, y) and supposedly, the solution pair with positive values of either variable is required, the
condition is given as shown below.
Example 5:
Code:
>> syms x y;
>> soln = solve([x^2+y^2==20,y==x^2,x>0,y>0],[x,y])
Output:
70
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
fsolve is an inbuilt function in MATLAB used to solve a system of non-linear equations. This
function works similar to that of fzero function but differs in the way that the former can
solve multiple non-linear equations simultaneously. fsolve is more advantageous than solve
because a complex set of equations can be solved without any ambiguity or difficulty with
fsolve.
The function returns a vector (instead of a scalar as in the case of fzero function) containing
the solution of the system of equations entered. The solution is calculated in a manner similar
to that of fzero function i.e., the solution of the system of equations near the initial guess
values is calculated and returned. Also, the initial guess variable is a vector with dimensions
corresponding to the number of variables involved.
Example 5:
Code:
% fsolveexample.m
zero=fsolve(@funcarray,[0,0])
% funcarray.m
function f = funcarray(x)
f(1)=x(1).^2+x(2).^2-10;
f(2)=x(1)-3*x(2)+10;
Output:
71
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
In the above example, a system of non-linear equations is solved by using a function array
funcarray containing the two functions as elements and invoking the function funcarray
using fsolve. The solution of the given system is displayed as shown above. The solution of
each variable can also be individually displayed by typing solution_variable(index) (here,
zero (1) or zero (2)).
Example 6:
Code:
% fsolveex2.m
x1=input('Enter x1:');%mole fraction of component 1
x2=1-x1; %mole fraction of component 2
a1=input('Enter a1:');%activity coefficient of component 1
a2=input('Enter a2:');%activity coefficient of component 2
zero=fsolve(@vanlaar,[-5,-5],[],a1,a2,x1,x2);
disp('A')
disp(zero(1))
disp('B')
disp(zero(2))
% vanlaar.m
function f = vanlaar(A,a1,a2,x1,x2)
f(1)=log(a1)-(A(1)*(x2.^2))*(((A(1)/A(2))*x1)+x2).^-2;
f(2)=log(a2)-(A(2)*(x1.^2))*(((A(2)/A(1))*x2)+x1).^-2;
Output:
72
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
RESULT:
Different ways of solving non-linear equations especially with fzero, solve and fsolve
functions were explored and analysed for their suitability in different cases.
Related Problems:
• Calculation of HTU and NTU of a packed bed absorption column.
• Calculation of the length of shell and tube heat exchangers.
• Calculation of the volume of reactor required for carrying out chemical reactions
under specified conditions.
73
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
AIM:
To understand the solution to ordinary differential equations (ODE) using the ODE solvers of
MATALB, with two examples.
PROCEDURE:
1. To solve for x, for various values of t, for the differential equation:
dx/dt = f(x)
with x(to) = xo is specified, where x is a vector.
2. To do so, we shall make use of ODE solvers available in MATLAB. Some of the
solvers of MATLAB are: ode23, ode45, oder23s.
4. The output [t,x] shall be stored for further processing, or shall be plotted.
CODE:
The following two files PFRsolnCvsV.m, and pfrfun.m are written in a text editor or with
Script-editor of MATLAB.
% PFRsolnCvsV.m
% The file PFRsolnCvsV.m is having the contents below
% to solve for C
C0 = 1;
Vspan = 0:0.1:12;
[VSol,CSol] = ode45('pfrfun', Vspan, C0);
%to plot
plot(VSol, CSol)
%%---
%pfrfun.m
The file pfrfun.m is having the contents below
function dC = pfrfun(V,C)
dC = -0.5*C^(1.25);
%%----
74
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
OUTPUT:
i.e.,
CODE:
%%--
%twotnk.m
function hdot = twotnk(t,h)
% To solve
75
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
% dh1/dt = 1 - 0.5*sqrt(h1-h2)
% dh2/dt = 0.25*sqrt(h1-h2) - 0.25*sqrt(h2)
hdot = zeros(2,1); % a column vector
hdot(1) = 1- 0.5*sqrt(h(1)-h(2));
hdot(2) = 0.25*sqrt(h(1) - h(2)) - 0.25*sqrt(h(2));
%%---
OUTPUT:
RESULT:
Using the above two problems we could understand the solution of ODEs using the ODE
solvers of MATLAB.
Related Problems:
• Reaction Engineering - Concentration vs. time (dC/dt),
• Heat Transfer -Temperature vs. time (dT/dt) of lumped system analysis, Temperature
vs. distance (dT/dx) of heat exchanger.
76
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
Aim:
To simulate steady state heat exchanger using aspen plus software.
Simulation Procedure:
STEP 1: Open Aspen Plus
STEP 2: Enter component ID, Name, type and alias in the component specification.
Example: Benzene, styrene, Ethylbenzene, water.
77
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
78
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
STEP 9: In Steams
✓ HOT-IN
✓ Input
Enter Temperature ‘T’ Example: 200°C
Enter Pressure ‘P’ Example: 4 bar
Total Flow basis: Mass
Total Flow rate: 10,000 kg/hr
In composition: Mass Fraction
Benzene: 0.5
Styrene: 0.2
Ethylbenzene: 0.2
Water: 0.1
80
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
✓ In Specifications
o Model fidelity: Shortcut
o Shortcut flow direction: Countercurrent
o Calculate mode: Design
o Specifications: Hot stream outlet vapor fraction
o Minimum Temperature approach: 1°C
81
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Results:
The summary of results page for the heat exchanger is shown below.
82
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
83
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
Aim:
To simulate steady state distillation column using aspen plus software.
Simulation Procedure:
STEP 2: Enter component ID, Name, type and alias in the component specification.
Example: Water and Methanol
84
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
85
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
✓ Go to Streams
o Click on Feed: 15 stages
86
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
✓ Go to Pressure
o Click on condenser pressure
o Enter 1 atm
Results:
The summary of results page for the distillation is shown below.
87
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
88
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
Aim:
To simulate steady state extraction column using aspen plus software.
Simulation Procedure:
STEP 2: Enter component ID, Name, type and alias in the component specification.
Example: Ethyl acetate and Acetone
89
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
90
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
91
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
STEP 8: In Steams
✓ Steam 2
✓ Input
Enter Temperature ‘T’ Example: 25°C
Enter Pressure ‘P’ Example: 1 atm
Total Flow basis: Mass
Total Flow rate: 1 kg/hr
In composition: Mass Fraction
Ethyl acetate: 0
Acetone: 0.5
Results:
The summary of results page for the distillation is shown below.
92
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
93
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
Date:
Aim:
To simulate steady state absorber using aspen plus software.
Simulation Procedure:
STEP 1: Open Aspen Plus
STEP 2: Enter component ID, Name, type and alias in the component specification.
Example: water, Nitrogen (N2), Carbon dioxide (CO2), Acetic acid
94
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
95
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
✓ Input
Enter Temperature ‘T’ Example: 40°C
Enter Pressure ‘P’ Example: 10 bar
Total Flow basis: Mass
Total Flow rate: 100 kg/hr.
In composition: Mass Fraction
N2: 0.012
CO2: 0.982
Acetic acid: 0.006
STEP 8: In Steams
✓ FRESH-SO
✓ Input
Enter Temperature ‘T’ Example: 25°C
Enter Pressure ‘P’ Example: 10 bar
Total Flow basis: Mass
Total Flow rate: 150 kg/hr
In composition,
Enter Mass fraction of each components. So, enter water as ‘1’.
96
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
✓ Go to Streams
o Click on Fresh-SO: 1 (Above Stage)
o Feed-Gas: 6 (on Stage)
97
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
✓ Go to Pressure
o Click on condenser pressure
o Enter 1.01 bar
Results:
98
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
99
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers
100
Plotting of X – Y graphs in Python
Exp No:
Date:
AIM:
To plot a typical linear and log-log x – y plots in python.
Problem I
Data for equilibrium distillation has been given. It is required to plot the given data as a curve.
Code:
# importing the required module. VERY IMPORTANT.
import matplotlib.pyplot as plt
# x and y axis values
x1 = [0,0.1,0.16,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]
y1 = [0,0.22,0.38,0.52,0.63,0.71,0.79,0.85,0.91,0.96,1]
# y = x line
x2 = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]
y2 = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]
# plotting the points
plt.plot(x1, y1, label = "equilibrium curve")
plt.plot(x2, y2, label = "x = y line")
# naming the x and y axes
plt.xlabel('x - mole fraction in liquid phase')
plt.ylabel('y - mole fraction in vapour phase')
# giving a title to graph
plt.title('equilibrium curve - distillation')
# to show legend
plt.legend()
# function to show the plot
plt.show()
Explanation:
OUTPUT I:
Code:
# importing the required module
import matplotlib.pyplot as plt
# x axis values
x = [8000, 10000, 15000, 20000, 25000, 30000, 35000, 40000,
50000, 75000, 100000, 500000, 1000000, 5000000, 10000000]
# corresponding y axis values
y = [0.009844, 0.008169, 0.007716, 0.006981, 0.006521, 0.006195,
0.005947, 0.00575, 0.005587, 0.005332, 0.004917, 0.004657,
0.003642, 0.003392, 0.003102]
plt.loglog(x,y, label = "Nre vs f")
plt.xlabel('Reynolds number - NRe')
plt.ylabel('Frictional factor - f')
plt.title('Reynolds number vs frictional factor')
plt.legend()
plt.show()
Explanation:
plt.loglog is used instead of plt.plot in order to get log-log axes. Other steps are similar to those
used in the previous example.
RESULT:
The various commands related to linear and loglog plots creation with Python software, are
studied. Similarity of the Python commands with MATLAB is understood.
Solution to Linear and Nonlinear Algebraic Equations with Python
Exp No:
Date:
AIM:
To write programs in python:
• to find the inverse of a matrix.
• to solve equations using f solve.
PROCEDURE:
Linear set of equations can be solved by writing the coefficients of the equations in matrix
form, and inverting the matrix. Nonlinear equations can be solved as like linear equation, by
linearising the equation around an initial point.
The following are examples to solve the liner and nonlinear equations, with Python codes.
CODE:
OUTPUT:
Rows 2
Columns 2
x3 + y2 – 3x = 0
exp(y) + xy – 3 = 0
# NonLinearSoln.py
import scipy.optimize as opt
from numpy import exp
def f(variables) :
(x,y) = variables
soln=opt.fsolve(f,(10,1))
print ("The solution is\n", soln)
OUTPUT:
The solution is
[1.65625145 0.65220927]
RESULT:
The codes have been successfully executed: 1) to get matrix inversion using inv of
python. 2) to solve nonlinear equations using fsolve of python.
Solving Ordinary Differential Equations with Python
Exp No:
Date:
AIM:
To write a program in python, to solve ordinary differential equations.
PROCEDURE:
CODE:
Differential equations are solved in Python with the scipy.integrate package using
odeint function. Another Python package that solves differential equations is GEKKO.
An example of using odeint is with the following differential equation with parameter
k=0.3, the initial condition y0=5 and the following differential equation.
def model(y,t):
k = 0.3
dydt = -k * y
return dydt
y0 = 5
t = np.linspace(0,20)
y = odeint(model,y0,t)
plt.plot(t,y)
plt.xlabel('time')
plt.ylabel('y(t)')
plt.show()
OUTPUT:
RESULT:
A program has been written to solve ordinary differential equations in python, and the
roles of various modules are understood.
Related Problems:
1) Solving differential Bernoulli equation
y’ + p(t)y = q(t) yn