You are on page 1of 112

UCH 1712 COMPUTATIONAL PROGRAMMING LAB

FOR CHEMICAL ENGINEERS

DEPARTMENT OF CHEMICAL ENGINEERING


SSN COLLEGE OF ENGINEERING
Kalavakkam – 603 110
Department of Chemical Engineering

UCH 1712 Computational Programming Lab for Chemical Engineers

S. No. Name of the Experiments Page No.

1. Introductory Aspects Of Microsoft Excel 4

2. Plotting Of Graphs In Microsoft Excel 10

Solving Non-Linear Equations Using Goal-Seek And Circular


3. 24
Reference Operations Of Microsoft Excel

Solving And Optimization Of Non-Linear Equations Using Solver


4. 34
Tool Of Microsoft Excel

Solving Nonlinear Equations Using ‘User Defined Function’ (Macros)


5. 44
In Microsoft Excel

6. Matrix Operations And Plotting Graphs In Matlab 58

7. Solving Set Of Linear Equations In Matlab 64

8. Solving Non-Linear Equations In Matlab 67

9. Solving Ordinary Differential Equations With Matlab 74

10. Steady State Simulation Of Heat Exchanger Using Aspen 77

11. Steady State Simulation Of Distillation Column Using Aspen 84

12. Steady State Simulation Of Extraction Column Using Aspen 89

13. Steady State Simulation Of Absorber Using Aspen 94

Beyond Syllabus Experiments


CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

S. No. Name of the Experiments Page No.

1 Plotting of X – Y graphs in Python

2 Solution to Linear and Nonlinear Algebraic Equations with Python 100

3 Solving Ordinary Differential Equations with Python

2
Department of Chemical Engineering

UCH 1712 Computational Programming for Chemical Engineers

S. Date of Name of the Experiment Page Date of Marks Signature


No Expt. No. Submission of Staff

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

UCH 1712 COMPUTATIONAL PROGRAMMING FOR CHEMICAL ENGINEERS


LTPC
0 0 4 2

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

LIST OF EQUIPMENT FOR BATCH OF 30 STUDENTS

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

EXP. INTRODUCTORY ASPECTS OF MICROSOFT EXCEL

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.

1. To Fill Adjacent Cells with Sequential Data:


• Enter one or two terms of a series to be filled as shown below.
• Select the cells with the terms, click on right hand lower corner of cell and drag as per
requirement to fill as shown.

4
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

The output is obtained as shown above.

2. To Use the Built-in Functions:


Excel has lot of built-in functions in various categories such as math, text, logical, information,
financial etc. These functions can be used to any calculation as needed. The function values are
calculated by typing the = symbol followed by the formula as applicable with corresponding
arguments. The argument value may be a number or any reference to a cell. For example, to get log of
a number 12, we shall get it as
= log(12)

Upon pressing enter, we get the calculated value of the cell.

If we want log for a cell value at A2, we shall type as


= log(A2)

(a) Log functions


The input numbers are entered in the cells for which we are to find the logarithm.
In the adjacent cell the first entry is typed: =LOG(cell address)and pressed enter.
The value gets displayed which can be pulled down for the remaining entries using the auto
fill feature.

5
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

(B) TRIGONOMETRIC FUNCTIONS

• 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.

• The formula to calculate Volume is given by: V=(RT)/P.


• Since R is a constant, the “$” sign is inserted before both the row number and column
letter. (Full-absolute referencing)
• For the Pressure and Temperature rows, since the rows remain unchanged the “$” sign is
used before the row number alone. (Row-absolute referencing)
• By using the auto fill feature the same formula is dragged to other cells to get the volume
data for all the cases.

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

• This will display the product matrix.

For a matrix D its inverse can be calculated by using the MINVERSEfunction.


In a random cell the function is typed as: =MINVERSE( matrix D) 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
matrix inverse and pressed F2 followed by pressing ctrl, shift and enter simultaneously.

8
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

The inverse of the matrix D will get displayed.

• For calculating the Determinant of a matrix the MDETERM function is used.


• In a random cell the function is typed as: =MDETERM( matrix A)by selecting the cell groups
that represent the matrix and pressed enter.
• Since the result is not an array simply pressing the ENTERdisplays the value.

RESULT

Basic functions of Microsoft Excel were understood and executed successfully.

9
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

Exp. Plotting of Graphs in Microsoft Excel


No: 1.2

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.

Adding Axis Titles:

• 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:

Adding Grid Lines to the Graph:

• 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:

Adding Data Labels to X and Y Plot:

• 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

Plotting a Log-log Graph:


• After entering the data in two columns, plot the scatter diagram along with the data labels.
• In the scatter diagram, right click on the axis. In the options provided, select “Format Axis”.

• After selecting Format Axis, under Axis options, check the Logarithmic box.

19
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

• Repeat for the other axis.

OUTPUT V:

20
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

Addition of Trendline to Graph:


• This “Trendline” option of Excel helps to get the equation of a curve.
• To add trendlines to an Excel graph, go to the Chart Elements section of the Layout tab under Chart
Tools.
• Here, choose the option labelled “trendlines”. Two specific cases will be demonstrated below: A
linear plot fit and a polynomial fit of order 2.

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:

Trendline of polynomial order 2


RESULT:
The required graphs have been plotted in Microsoft Excel 2007 on ordinary and log-log scales, and
various formatting options and features such as gridlines, trendlines, data labels, and axis labels have
been explored and implemented.

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

Exp. Solving Non-Linear Equations Using Goal-Seek and Circular Reference


No: 2 Operations of Microsoft Excel

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.

Solving by Circular Reference Operation:


1. Create the table with required input values in the cells.

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.

We can solve this LHS = RHS problem, by making use of Circular-Reference.

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

EXP SOLVING AND OPTIMIZATION OF NON-LINEAR EQUATIONS


NO.: 3 USING SOLVER TOOL OF MICROSOFT EXCEL

Date:

AIM:

To understand the usage of “Solver” tool of Microsoft Excel for:

1. optimizing a multiple variables problem.

2. to solve a set of nonlinear equations.

Problem Statement-1:

IT IS REQUIRED TO ESTIMATE THE NUMBER OF UNITS TO BE PRODUCED IN A


MULTIPLE ITEM PRODUCTION FACILITY, SO AS TO OPTIMIZE THE PROFIT. THE
UNIT SALE PRICE AND COST PRICE OF EVERY ITEM IS GIVING IN THE TABLE.
YOU ARE ASKED TO ESTIMATE THE UNITS TO BE PRODUCED IN EVERY ITEM
(FROM A, B, AND C). THE MAXIMUM QUANTITY THAT CAN BE PRODUCED IN A
SINGLE ITEM CANNOT EXCEED 300.

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

1) Add the solver tool into the data toolbar.

35
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

2) Set the target cell.

3) Set the changing variable cells.

36
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

4) Set the constraints cells.

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

6) The Solver solution is as follows :

7) The Answer Report is as follows:

38
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

Problem Statement-2:

The below given problem is an example of non-linear equations.

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

Equality of Pressure Drops:


P due to friction in Pipe AaB = P due to friction in Pipe AbB
P due to friction in Pipe AaB = P due to friction in Pipe AcB

where pressure drop in a pipeline due to friction is given by

For equality of pressure drop, we get


(fLv2/D)AaB = (fLv2/D)AbB = (fLv2/D)AcB

40
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

The above gives two equations.


Now, we have three equations: 1 from equation of continuity; 2 from equality of
pressure drop. These three equations have 3 unknowns: va, vb, vc.

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

This Qsum has to be equal to QA

i.e., at the correct values of velocities, the difference DelQ = Qsum – QA = 0

WE CAN SET THIS DELQ TO ZERO IN THE TARGET CELL VALUE.

THE AVAILABLE THREE EQUATIONS CAN BE SET AS THE CONSTRAINTS TO


THE SOLVER.

42
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

BY SETTING THE “SOLVER PARAMETERS” AS ABOVE, WE GET THE VALUES OF


VA, VB, VC ARE OBTAINED AS BELOW:

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

Exp. Solving Nonlinear Equations Using ‘User Defined Function’ (MACROS) In


No.: 4 Microsoft Excel

Date:

AIM:

To study the various conditional statement (IF and COUNTIF), Conditional formatting and
User defined functions in Excel.

INTRODUCTION:

1. What is a Logical Function?


It is a feature that allows us to introduce decision-making when executing formulas
and functions. Functions are used to:

• Check if a condition is true or false


• Combine multiple conditions together

2. What is a condition and why does it matter?


• A condition is an expression that either evaluates to true or false. The
expression could be a function that determines if the value entered in a cell is
of numeric or text data type, if a value is greater than, equal to or less than a
specified value, etc.

3. Logic functions

The following table shows all the logical functions in Excel.

S/N Function Category Description Usage


1 AND Logical Checks multiple conditions =AND(1>0,ISNUMBER(1
and returns true if they all )) The above function
the conditions evaluate to returns TRUE because
true. both Condition is True.
2 FALSE Logical Returns the logical value FALSE()
FALSE. It is used to
compare the results of a
condition or function that
either returns true or false
3 IF Logical Verifies whether a condition =IF(ISNUMBER(22),"Yes

is met or not. If the ","No")


condition is met, it returns 22 is Number so that it
true. If the condition is not return Yes.
met, it returns
false. =IF(logical_test,[valu

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.

❖ Highlight Cells Rules:


To highlight cells that are greater than a value, execute the following steps.
1. Select the range A1:A10.

45
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

2. On the Home tab, in the Styles group, click Conditional Formatting.

3. Click Highlight Cells Rules, Greater Than.

4. Enter the value 80 and select a formatting style.

5. Click OK.
Result. Excel highlights the cells that are greater than 80.

46
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

6. Change the value of cell A1 to 81.


Result. Excel changes the format of cell A1 automatically.

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.

2. On the Home tab, in the Styles group, click Conditional Formatting.

47
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

3. Click Clear Rules, Clear Rules from Selected Cells.

❖ Top/Bottom Rules
To highlight cells that are above average, execute the following steps.
1. Select the range A1:A10.

2. On the Home tab, in the Styles group, click Conditional Formatting.

48
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

3. Click Top/Bottom Rules, Above Average.

4. Select a formatting style.

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.

❖ Conditional Formatting with Formulas


Take your Excel skills to the next level and use a formula to determine which cells to format.
Formulas that apply conditional formatting must evaluate to TRUE or FALSE.
1. Select the range A1:E5.

49
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

2. On the Home tab, in the Styles group, click Conditional Formatting.

3. Click New Rule.

4. Select 'Use a formula to determine which cells to format'.


5. Enter the formula =ISODD(A1)
6. Select a formatting style and click OK.

Result. Excel highlights all odd numbers.

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

8. Repeat steps 2-4 above.


9. Enter the formula =$C2="USA"
10. Select a formatting style and click OK.

Result. Excel highlights all USA orders.

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

Example Problem involving IF, COUNTIF, and Conditional Formatting

Question

1. Generate table

2. Give condition using Insert Function option

52
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

3. Enter the necessary details as shown

4. Drag for all the boxes

5. Apply conditional formatting using “Text that contains .”

53
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

6. Apply COUNTIF condition

54
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

Custom User-Defined Functions in Excel

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.

How to create a custom user defined function?

1. Open a new Excel workbook.

2. Get into VBA (Press Alt+F11)

3. Insert a new module (Insert > Module)

4. Copy and Paste the Excel user defined function examples

5. Get out of VBA (Press Alt+Q)

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.

• Write a function like this in the dialog box

55
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

Then save this file type as macro enabled workbook

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

Then type the required parameters as shown below

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.

Finally, the result is obtained as below…

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

EXP MATRIX OPERATIONS AND PLOTTING GRAPHS IN


NO.: 5 MATLAB

Exp No: 5.1

Date:

AIM:

To study the basic operations and functions in MATLAB.

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

ii). To display specific columns of a matrix


>> a(:,2:end)
ans = 2 3
5 6
8 10

Similar functions using ‘:’ include:

a(:,:) is the equivalent two-dimensional array. For matrices this is the same as
‘a’.

a(:) is all the elements of ‘a’, regarded as a single column.

58
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

iii). To extract specific element of a matrix


>> a(3,3)
ans = 10
iv). Adding a number to all elements of a matrix
>> a + 10
ans = 11 12 13
14 15 16
17 18 20
Here the number ‘10’ is actually meaning 10s matrix matching the size of ‘a’.
v). Sin of a matrix
>> sin(a)
ans = 0.8415 0.9093 0.1411
0.7568 -0.9589 -0.2794
0.6570 0.9894 -0.5440
vi). To transpose a matrix, use a single quote ('):
>> a'
ans = 1 4 7
2 5 8
3 6 10

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)

viii). To perform element-wise multiplication rather than matrix multiplication, use


the ‘.* ‘operator:

>> 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

Exp No: 5.2


Date:

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

EXP SOLVING SET OF LINEAR EQUATIONS IN MATLAB


NO.: 6

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.

Applying the macroscopic mass balance yields,

Lxn−1 − ( L + Ga) xn + Gaxn+1 = 0

The entire set of equations for the six-plate column is

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

The simultaneous solution can be expressed in matrix notation as, Ax = b


The solution i.e. composition on each can be found by
(a) Simple matrix operation: x = A−1b
(b) Slash operator ‘\’: x = A \ b

Matlab Code as follows:


% This is MATLAB programming for solving set of linear equations
close all;
% Define initial parameters
a = 0.72; % paramater a in linear realation i.e. slope
b = 0; % parameter b in linear relation i.e. intercept
Gas_flow = 66.7; % in Kg mol/min
Liquid_flow = 40.8; % in Kg mol/min
%read initial conditions
x_0 = 0; % mole fraction of component in inlet liquid stream
y_7 = 0.2; % mole fraction of component in inlet vapor stream
product1 = Liquid_flow+Gas_flow*a;
product2 = Gas_flow*a;
%read in matrices A and B
Matrix_A = zeros(6); %initialization

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);

% using inverse matrix


InvSolnMatrix_x_1 = inv(Matrix_A)*Vector_B1; % for case 1 y7 = 0.2

sprintf("Results with Gauss elimination operator \.")


InvSolnMatrix_x_1
GuassInbuiltSolnMatrix_x_1 = Matrix_A \ Vector_B1;

sprintf("Results with inbuilt Gauss elimination")


GuassInbuiltSolnMatrix_x_1'
------------------End of code

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

EXP SOLVING NON-LINEAR EQUATIONS IN MATLAB


NO.: 7

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.

The usage of fzero function is illustrated through some examples as below.

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;

%Finding Volume occupied by gas using R-K equation

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)

%Finding volume occupied by saturated liquid using R-K equation


V_initial=b;
zero=fzero(f,V_initial);
disp('The volume occupied by saturated liquid 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.

Solving a System of Non-linear Equations using solve Function:


Solve function is used to solve a system of non-linear equations instantly. The syntax of
solve() function is as below:

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

Solving a system of non-linear equations using fsolve function:

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 syntax of fsolve is as follows:


x = fsolve(fun, x0)
x = fsolve(fun, x0, options)
x = fsolve(problem)
[x, fval] = fsolve(___)
[x, fval, exitflag, output] = fsolve(___)
[x, fval, exitflag, output, jacobian] = 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.

The method of using fsolve is illustrated through a series of examples:

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

In this example, the application of fsolve in solving problems in engineering disciplines is


illustrated. In the above code, a thermodynamic problem involving finding the van Laar
coefficients of a solution is solved using fsolve function, when the activity coefficients and
the mole fractions of the components in the solution are given.

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

EXP SOLVING ORDINARY DIFFERENTIAL EQUATIONS


NO.: 8 WITH MATLAB

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.

3. The code is given by:


[t,x] = ode45(ODEFUN,TSPAN,x0,OPTIONS, PARAMETERS)
Where: (i) ODEFUN is the file containing the differential equations.
(ii) TSPAN is the range of independent variables, and x0 is the initial values
if x.
(iii) OPTIONS is set of lines solver options. (iv) PARAMETERS are values
of . parameters passed to the function.

4. The output [t,x] shall be stored for further processing, or shall be plotted.

(a) Problem Statement-1:


To find concentration (C) along a PFR given by dC/dV = -0.5 C1.25 with C(0) = 1 for
reactor volumes (V) raging from 0 to 12.

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

From the MATLAB command prompt, the following is executed:


>> PFRsolnCvsV

The following plot is generated from MATLAB.

OUTPUT:

(b) Problem Statement-2:


To plot the variation in tank levels (h) for two interacting tanks, for change in q0.

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));
%%---

The following codes are written in the MATLAB command prompt.


» [t, h] = ode45(@twotnk, [0 100], [12 7]');
» plot(t, h)
%%---

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

EXP STEADY STATE SIMULATION OF HEAT EXCHANGER


NO.: 9 USING ASPEN

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.

STEP 3: Click on Methods;


In methods, click on specifications and Enter

77
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

1. Method filter: ALL


2. Base method: NRTL-RK
3. Free water method: Steam-TA
4. Water Solubility: 3

STEP 4: Click on Parameters in methods,


✓ Click Binary interaction
✓ Then. Click NRTL-1

STEP 5: Move to Simulation


✓ Go to Main Flowsheet
STEP 6: Draw a Heat Exchanger (Heat X)

78
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

STEP 7: Click on Materials

STEP 8: Click on Steams


✓ COLD-IN
✓ Input
Enter Temperature ‘T’ Example: 25°C
Enter Pressure ‘P’ Example: 10 bar
Total Flow basis: Mass
Total Flow rate: 60,000 kg/hr
In composition,
Enter Mass fraction of each components. So, enter water as ‘1’.
79
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

STEP 10: Click on Blocks


✓ Go to Heat X
o Click on setup

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

STEP 11: Run simulation


✓ Heat exchanger simulating

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

EXP STEADY STATE SIMULATION OF DISTILLATION


NO.: 10 COLUMN USING ASPEN

Date:

Aim:
To simulate steady state distillation column 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 and Methanol

STEP 3: Click on Methods;

84
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

In methods, click on specifications and Enter


5. Method filter: COMMON
6. Base method: SRK

STEP 4: Go to simulation environment

STEP 5: Draw a Distillation Column

STEP 6: Click on Steams


✓ COLD-IN
✓ Input
Enter Temperature ‘T’ Example: 25°C

85
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

Enter Pressure ‘P’ Example: 1 atm


Total Flow basis: Mole
Total Flow rate: 100 kmol/hr
In composition: mole Fraction
Water: 0.5
Methanol: 0.5

STEP 7: Click on Blocks


✓ Go to COL
o Click on setup
✓ In Configuration
o Click on Equilibrium
o Number of Stages = 30
o Condenser: Total
o Distillate to feed ratio: 0.1 Mole
o Reflux ratio: 0.1 Mole

✓ 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

STEP 8: Run simulation


✓ Process simulating

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

EXP STEADY STATE SIMULATION OF EXTRACTION


NO.:11 COLUMN USING ASPEN

Date:

Aim:
To simulate steady state extraction column 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: Ethyl acetate and Acetone

STEP 3: Click on Methods;


In methods, click on specifications and Enter

89
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

7. Method filter: COMMON


8. Base method: NRTL

STEP 4: Click on Parameters in methods,


✓ Click Binary interaction
✓ Then. Click NRTL-1

STEP 5: Move to Simulation


✓ Go to Main Flowsheet

90
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

STEP 6: Click on Materials

STEP 7: Click on Steams


✓ Steam 1
✓ 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.5
Acetone: 0

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

EXP STEADY STATE SIMULATION OF ABSORBER USING


NO.: 12 ASPEN

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

STEP 3: Click on Methods;


In methods, click on specifications and Enter

94
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

9. Method filter: ALL


10. Base method: NRTL

STEP 4: Move to Simulation


✓ Go to Main Flowsheet

STEP 6: Click on Materials

STEP 7: Click on Steams


✓ FEED-GAS

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

STEP 9: Click on Blocks


✓ Go to Configuration
o Click on Equilibrium
o Number of Stages = 6
o Condenser: None
o Reboiler: None

✓ 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

STEP 10: RUN SIMULATION


✓ Process simulating

Results:

98
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

The summary of results page for the absorber is shown below.

99
CHEMICAL ENGINEERING, SSNCE UCH 1712 Computational Programming for Chemical Engineers

Content Beyond Syllabus

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:

• It is mandatory to import the module matplotlib.pyplot in order to plot graphs.


• The name “plt” has been assigned in order to call the module in later steps.
• Define the x-axis and corresponding y-axis values as lists.
• Plot them on canvas using plot function.
• Give a name to x-axis and y-axis using xlabel and ylabel functions.
• Give a title to the plot using title function.
• Show legend using legend function.
• Finally, to view the plot, use show function.

OUTPUT I:

An x – y curve on linear scales has been successfully plotted.


Problem II
Reynold’s number and friction factor data has been given. It is required to plot the given data as
a curve on a log – log graph.

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.

Typical input and output with Anaconda software is given below:


OUTPUT II:

An x- y curve on logarithmic scales has been successfully plotted.

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:

1) To find the inverse of a matrix:


# MatrixSoln.py
import numpy as np
n=int(input("Rows\t"))
m=int(input("Columns\t"))
if(m==n):
a=[]
for i in range(n):
a.append([])
for j in range(m):
num=float(input("Enter the element\t"))
a[i].append(num)
print ("The matrix is\n", a)
DetA=np.linalg.det(a)
if(DetA!=0):
A_inv = np.linalg.inv(a)
print ("The inverse of the matrix is\n", A_inv)
else:
print("Singular matrices do not have an inverse")
else:
print("Only square matrices have an inverse")
Code Execution using Anaconda’s Spyder:

OUTPUT:

Rows 2

Columns 2

Enter the element 2

Enter the element 2.5

Enter the element 4

Enter the element 3


The matrix is
[[2.0, 2.5], [4.0, 3.0]]
The inverse of the matrix is
[[-0.75 0.625]
[ 1. -0.5 ]]
2) To solve nonlinear equations using fsolve:

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

first_eq = x**3 + y**2 -3*x


second_eq = exp(y) + x*y - 3
return [first_eq, second_eq]

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:

1) In the python software menu bar click on file option.


2) Save it with .py extension.
3) Type the code as given below and execute it by clicking the run option.
4) Take a screenshot of the output screen and report it in record.

CODE:

Differential equations are solved in Python with the scipy.integrate package using
odeint function. Another Python package that solves differential equations is GEKKO.

1. model: Function name that returns derivative values at requested y and t


values as dydt = model(y,t)

2. y0: Initial conditions of the differential states

3. t: Time points at which the solution should be reported. Additional internal


points are often calculated to maintain accuracy of the solution but are not
reported.

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.

dy/dt =-k y(t)


# OdeSoln.py
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def model(y,t):
k = 0.3
dydt = -k * y
return dydt

# Note the indentation of block in the block defn


# This is important

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

2) Dynamic simulation of CSTR

You might also like