Refinery Blending Problems by Engr. Adefami Olusegun

72
1 CHAPTER ONE INTRODUCTION 1.1 Background Linear programming is the most often used method for solving optimization problems. Since the development of the simplex algorithm for solving linear programming by George Dantzig, Linear programming has been used to solve optimization problems in fields as diverse as petroleum, banking, education, Product Constraints, Raw Material The problem of solving a system of linear inequalities dates back at least as far as Fourier, after whom the method of Fourier-Motzkin elimination is named. Linear programming arose as a mathematical model developed during the secondworld war to plan expenditures and returns in order to reduce costs to the army and increase losses to the enemy. It was kept secret until 1947. Postwar, many industries found its use in their daily planning. Limitations, Safety Restrictions, Product Specifications and Material and Energy Balances, and many others. It has a great importance in operation research methods. A useful tool for solving linear programming problems is WHAT’S BEST! Software. This software employs powerful optimization algorithms leading to dramatically reduced solution time of the optimization procedure when the problem contains a large numbers of variables and constraints.

Transcript of Refinery Blending Problems by Engr. Adefami Olusegun

Page 1: Refinery Blending Problems by Engr. Adefami Olusegun

1

CHAPTER ONE

INTRODUCTION

1.1 Background

Linear programming is the most often used method for solving optimization problems.

Since the development of the simplex algorithm for solving linear programming by George

Dantzig, Linear programming has been used to solve optimization problems in fields as

diverse as petroleum, banking, education, Product Constraints, Raw Material

The problem of solving a system of linear inequalities dates back at least as far as Fourier,

after whom the method of Fourier-Motzkin elimination is named. Linear programming

arose as a mathematical model developed during the secondworld war to plan expenditures

and returns in order to reduce costs to the army and increase losses to the enemy. It was

kept secret until 1947. Postwar, many industries found its use in their daily planning.

Limitations, Safety Restrictions, Product Specifications and Material and Energy Balances,

and many others. It has a great importance in operation research methods. A useful tool for

solving linear programming problems is WHAT’S BEST! Software. This software

employs powerful optimization algorithms leading to dramatically reduced solution time

of the optimization procedure when the problem contains a large numbers of variables and

constraints.

Page 2: Refinery Blending Problems by Engr. Adefami Olusegun

2

1.2 Objective of Study

(1) To develop a software to solve linear programming problems using Visual Studio

2005.

(2) Formulation and Solving Problems in linear programming.

(3) To determine application of linear programming

(4) To compare the program with other software e.g. Excel Solver

1.3 Scope of Work

This study is relevant to process data as well as enterprise data, consisting of commercial

and financial information, are used with the methodologies shown to make decisions in a

timely fashion. This model can be optimized to obtain target levels and price for inter-

refinery transfers, crude oil and product allocations to each refinery, inventory targets,

optimal operating conditions, stream allocations, and blends for each refinery.

1.4 Statement of the problem

(1) Linear programming is applicable only to problems where the constraints

and objective function are linear i.e., where they can be expressed as

equations which represent straight lines. In real life situations, when

constraints or objective functions are not linear, this technique cannot be

used.

(2) Factors such as uncertainty, weather conditions etc. are not taken into

consideration

Page 3: Refinery Blending Problems by Engr. Adefami Olusegun

3

(3) There may not be an integer as the solution, e.g., the number of men

required may be a fraction and the nearest integer may not be the optimal

solution i.e., Linear programming technique may give practical valued

answer which is not desirable

(4) Only one single objective is dealt with while in real life situations, problems

come with multi-objectives.

(5) Parameters are assumed to be constants but in reality they may not be so.

Page 4: Refinery Blending Problems by Engr. Adefami Olusegun

4

CHAPTER TWO

2 RESEARCH METHODOLOGY

2.1 Introduction

Revised simplex method was programmed into Visual Studio 2005 software

through Visual basic application to solve a Linear Programming problem where

optimal solution is determined. This program enables us to solve different problems

in Refinery Blending and in Process chemical industry. The Computer uses linear

Programming models to optimize blending at lowest cost.

2.2 Visual Basic Tools In the Program

The tools used in the program are:

1. TextBox

2. ComboBox

3. Button

4. ListBox

5. Rich TextBox

TEXTBOX -: We used the textbox to display some text that can be edited.

COMBOBOX -: Combox was used to select the type of optimization (either MAXIMIZE

or MINIMIZE).We also used the ComboBox to select the number of variables the objective

function to optimize.

BUTTON-: We used Button to raises an event when clicked. In the program, three buttons

were used which are “EXECUTE”, “CLEAR” & “EXIT”. Any button pressed responds

based on the Click Event code.

Page 5: Refinery Blending Problems by Engr. Adefami Olusegun

5

LISTBOX-: We used it in the program to accept each constrain and display them.

RICH TEXTBOX-: We used rich textbox to display the result of the computation.

Page 6: Refinery Blending Problems by Engr. Adefami Olusegun

6

CHAPTER THREE

3.1 Program Design Strategy:

Every computer program has to follow some strategies before they can be effectively

written. The strategies used in designing this program consist of three stages which are:

1. Planning stage;

2. Interface stage; and

3. Coding stage

Planning Stage

The stage involves the use of flowchart in order to determine the flow and order the

program will follow so as to write the program effectively. One other tool that was used is

algorithm.

The flowchart for this program is as shown in figure 3.1 while the algorithms follow

immediately.

Page 7: Refinery Blending Problems by Engr. Adefami Olusegun

7

Figure 3.1 Program Flow Chart for Design

3.3.1 The Revised Simplex Program Algorithm.

1. Start

2. Choose the number of variable of the objective function

3. Select to either maximize or minimize the function

4. Supply the objective function

5. Supply each of the constrains

Yes

No

Start

Supply the objective function

and constrains and validate

them

Do the Constrains

validates?

Select the No of

objective function

variable

Do the revised simplex computation

Display the output:

Optimal solution

Stop

Page 8: Refinery Blending Problems by Engr. Adefami Olusegun

8

6. Check if the objective function and constrains are correct (validation). If not

correct, go to step 9.

7. Do the revised simplex computation.

8. Display the result.

9. Stop.

The Revised Simplex Algorithm

1. Start with some basic index set B1 = {i(1), i(2), … ,i(m)}.

2. Compute a coefficient of the relative cost coefficient

rj = cj - cBAB-1aj

for B1 until some index j with rj > 0 is found.

(i).If all rj ≤ 0, termination phase has been reached.

(ii).Only those j M N1 are candidates

3. Find AB-1aj = aj and AB-1b = b and compute the allowable ratios of the jth column , viz.,

bi/aij for those I with aij > 0.

(i). If there are no allowable ratios, then a termination phase has been reached.

4. Find an index k where the minimum ratio is attained.

5. Add j to the basic index set and delete i(k) to get a new basic index set B2.

6. Go back to step 2.

Interface Design Stage

This stage involves the designing of the forms used in the program. The forms were first

designed effectively before the code for the action is written. It suffice us here to explain

the program components used in the design of the forms

Page 9: Refinery Blending Problems by Engr. Adefami Olusegun

9

3.2 Program Component

In this program, components used are two window forms (frmSiimplex and frmRetrieve)

and a module (Rsimplex).

3.2.1 A Brief Description:

The “frmSimplex” is the startup form. It allows the user to enter the objective function and

constrains, validate and execute the function. It also allows the user to save the executed

objective function and retrieve the saved equation. The executed function can also be

printed. All these can be achieved by pressing different buttons (Execute, Save, Validate,

Retrieve and Print buttons). It also has “Exit” button which is used to close the program.

The “frmRetrieve” serves as the form that loads when the “Retrieve” button is being

pressed on the “frmSimplex” form. It provide the user the opportunity of choosing from

the formerly saved functions and execute it and get the answer being displayed on the

“frmSimplex” form. It has “Execute” and “Exit” buttons.

The “RSimplex” module contains public variables, many functions and a structure. The

functions are “Determinant”, “FormLU”, “Revised Simplex

The Screen Shot of the following Buttons where display below Execute, Save, Print,

Validate, Retrieve, Clear and Exit.

Page 10: Refinery Blending Problems by Engr. Adefami Olusegun

10

Figure 3.2 Showing “Execute Button”

Figure 3.3 Showing the “Save Button”

Page 11: Refinery Blending Problems by Engr. Adefami Olusegun

11

Figure 3.4 showing “Print Button”

Page 12: Refinery Blending Problems by Engr. Adefami Olusegun

12

Figure 3.5 Showing “Validate Button”

Page 13: Refinery Blending Problems by Engr. Adefami Olusegun

13

Figure 3.6 Showing “Retrieve button” of Revised Simplex

Figure. 3.7 “Clear Button”

Page 14: Refinery Blending Problems by Engr. Adefami Olusegun

14

Figure 3.8 showing the “Exist” button display.

3.3.2. Step by Step Procedure Used to Design The Interface:

For any work to be done effective, orders had to be followed. Consequently, there are

procedures that are followed in the course of writing this program. They are as follows:

1. The program was first planned using flowchart. This was to make writing the

program fast and effective with little bugs.

2. After this, the database used was designed . This is necessary to know the structure

of the database and program accordingly to avoid unnecessary wasting of effort in

adjusting both the program and database in the course of writing the codes.

3. The “frmSimplex” form was later created after the paper work concerning the

program interface had been made.

Page 15: Refinery Blending Problems by Engr. Adefami Olusegun

15

4. The code for the form was written and the bugs (errors) were removed through

testing and debugging the codes.

5. It was later viewed to create allowance for users to have the objective function

saved after the execution. This lead the designing “RSimplex” module and

“frmRetrieve” form.

6. The “RSimplex” module was necessary to store public variables and create public

functions which were used by the two forms.

7. The “frmRetrieve” was then designed and the code was written.

8. The overall program was tested using different examples from textbooks, internet,

and formulated ones.

Coding Stage

This is the stage where the code for the program was written for the form objects designed

in “Interface Design Stage”. These codes are shown below.

CHAPTER FOUR

4 Results and Discussion

Page 16: Refinery Blending Problems by Engr. Adefami Olusegun

16

4.1 Introduction

The software is written in Visual Studio 2005 through Visual basic (VB). Code Visual to

Flowchart is a program Flow chart generator for code flowcharting and visualization. It

can perform automated reverse engineering of program code into programming flowcharts,

help programmers to document, visualize and understand source code.

4.2 DATA USED FOR THE PROJECT

Data for the Refinery Feeds and Products were formulated and analyzed in Problem 4.1

and optimum value was determined. Both Problem 4.2 and Problem 4.3 are Production

Planning problems and they were formulated and the raw data was input into visual studio

to obtain optimal solution.

4.3 PROGRAM OUTPUT

4.3.1 Correct Data Input:

Correct data was input in the problems below

Problem 4.1 (Guy, Krik R, Nelson J.J Cole E. 2004)

Looking at the chemical process industries in the 1950’s, the information pertaining to the

expected yields of the fifteen types of crude oils when processed by the refinery is as shown

Page 17: Refinery Blending Problems by Engr. Adefami Olusegun

17

in page 67. Note that the product distribution from the refinery is quite different for the

fifteen crude oils. The limitations on the established markets for the various products in

terms of the allowed maximum daily production were given.

To set up the linear programming problem, formulate an objective function and constraints

for the refinery operation.

Solution

Let the variable be: X1 = bbl/day of crude #1

X2 = bbl/day of crude #2

X3 = bbl/day of crude #3

X4 = bbl/day of crude #4

X5 = bbl/day of crude #5

X6 = bbl/day of crude #6

X7 = bbl/day of crude #7

X8 = bbl/day of crude #8

X9 = bbl/day of crude #9

X10 = bbl/day of crude #10

X11 = bbl/day of crude #11

X12 = bbl/day of crude #12

X13 = bbl/day of crude #13

X14 = bbl/day of crude #14

X15 = bbl/day of crude #15

X16 = bbl/day of propane

Page 18: Refinery Blending Problems by Engr. Adefami Olusegun

18

X17 = bbl/day of butane

X18 = bbl/day of LPG

X19 = bbl/day of Petroleum ether

X20 = bbl/day of ligroin

X21 = bbl/day of straight-run gasoline

X22 = bbl/day of kerosene

X23 = bbl/day of heating oil

X24 = bbl/day of gas oil

X25 = bbl/day of diesel fuel

X26 = bbl/day of lubricating oil

X27 = bbl/day of waxes

X28 = bbl/day of residual oil

X29 = bbl/day of asphalt

X30 = bbl/day of tar

The linear objective function Z (to be maximized).

Other constraints that exist or are implied in this problem are given below. These can be

formulated as inequality constraints:

Propane: X16 48

Butane: X17 51

LPG: X18 46

Petroleum ether: X19 41

Ligroin: X20 47

Page 19: Refinery Blending Problems by Engr. Adefami Olusegun

19

Straight-run gasoline: X21 44

Kerosene: X22 43

Heating oil: X23 43

Gas oil: X24 41

Diesel fuel: X25 49

Lubricating oil: X26 64

Waxes: X27 54

Residual oil: X28 56

Asphalt: X29 59

Tar: X30 45

Maximize Z =

151413121110987654321 54243242

Subject to

Page 20: Refinery Blending Problems by Engr. Adefami Olusegun

20

4523222233

5925242224

56232322344

5422332223233

6425233232223

4932223232

412222222

43222222223

432223322

4422222423

474222222

4122223222

4632215223

513222223223

48222322222

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

151413121110987654321

X

X

Page 21: Refinery Blending Problems by Engr. Adefami Olusegun

21

Figure 4.1 Formulation of Revised Simplex Method.

Figure 4.2 Optimal Solution Revised Simplex Method Using Visual Studio 2005

Page 22: Refinery Blending Problems by Engr. Adefami Olusegun

22

4.3.2 Excel Solver Solution:

Microsoft Excel Provides tool called Solver that handles this problem in a manner that is

transparent to the user. The dynamic display of the iterative search process enables the user

to monitor location of the optimum solution by the search algorithm

Figure 4.3 Showing Solver Parameters

Page 23: Refinery Blending Problems by Engr. Adefami Olusegun

23

Figure 4.4 Solver Options

Figure 4.5 9(a) Solver Results

Page 24: Refinery Blending Problems by Engr. Adefami Olusegun

24

Figure. 4.6 Solver Results Solution

Page 25: Refinery Blending Problems by Engr. Adefami Olusegun

25

Table 4.1 COMPARISONS BETWEEN REVISED SIMPLEX METHOD AND

EXCEL SOLVER

No of

Variables

Revised Simplex

Method

Excel Solver

Solution

Observation

X2 0.59091 0.5909091 X2 in Rsimplex method

solution is the same in Excel

solver Solution

X4 6.27273 6.2727273 X4 in Rsimplex method

solution is the same in Excel

solver Solution

X7 4.64773 4.647727 X7 in Rsimplex method

solution is the same in Excel

solver Solution

X12 3.12500 3.125000 X12 in Rsimplex method

solution is the same in Excel

solver Solution

X14 6.52273 6.522727 X2 in Rsimplex method

solution is the same in Excel

solver Solution

z 85.32955 85.32955 Optimal Solution is the same

in Rsimplex and Excel Solver

Solution.

Page 26: Refinery Blending Problems by Engr. Adefami Olusegun

26

4.3.3 Analysis of Problem 4.1

The objective function and constraints for the refinery operation was formulated using

visual studio 2005 and the optimal solution was determined in Problem 4.1 This problem

was compared with Excel Solver Solution. The Optimal Solution for both applications is

the same.

Problem 4.2: Production Planning (Vasant P.M, 2003)

Eleven products are processed through different operations. The times (in minutes)

required per unit of each product, the daily capacity of the operations (in minutes per day)

and the profit per unit sold of each product (in dollars) are as shown below.

The zero times indicate that the product does not require the given operation. It is assumed

that all units produced are sold. Moreover, the given profits per unit are net values that

result after all pertinent expenses are deducted. The goal of the model is to determine the

optimum daily production for the eleven products that maximizes profit.

Page 27: Refinery Blending Problems by Engr. Adefami Olusegun

27

Max Z= 1110987654321 2323432

Subject to

512353

643424222

85234244336

7943346523

7532642323

442342

644422332

77434424233

593233244

582324232

47222332

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

X

X

Page 28: Refinery Blending Problems by Engr. Adefami Olusegun

28

Figure 4.7 Formulation of Revised Simplex Method.

Figure 4.8 Optimal Solution in Revised Simplex Method Using Visual Studio 2005

Page 29: Refinery Blending Problems by Engr. Adefami Olusegun

29

Problem 4.3 (Textile Technology Spinning, 2008).

The Concrete Products Corporation has the capability of producing eleven types of

concrete blocks. The plant manager desires to maximize the profit during the next month.

Max Z= 1110987654321 532423

Subject to

512353

643424222

85234244336

7943346523

7532642323

442342

644422332

77434424233

593233244

582324232

47222332

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

1110987654321

X

X

Page 30: Refinery Blending Problems by Engr. Adefami Olusegun

30

Figure 4.9 Formulation of Revised Simplex Method.

Figure 4.10 Optimal Solution Revised Simplex Method Using Visual Studio 2005

Page 31: Refinery Blending Problems by Engr. Adefami Olusegun

31

Problem 4.4 (James H. Gary and Glenn E. handwork, 2001)

Reid Vapor Pressure

The desired RVP of a gasoline is obtained by blending n-butane with C5-38oF (C5-193oC)

naphtha. The amount on n-butane required to give the needed RVP is calculated by:

iRVPMRVPN

I

ITt

1

Where

t total moles blended product

iRVP Specification RVP for product, psi

i moles of component i

iRVP RVP of component i, psi or Kpa

Base Stock BPD lb/hr MW mol/hr mol% RVP PVP

Page 32: Refinery Blending Problems by Engr. Adefami Olusegun

32

LSR gasoline 4,000 39,320 86 457 21.0 11.1 2.32

Reformate 6,000 69,900 115 617 28.4 2.8 0.80

Alkylate 3,000 30,690 104 295 13.4 4.6 0.62

FCC gasoline 8,000 87,520 108 810 37.2 4.4 1.64

Total 21,000 2,179 100.0

Blend for a 10 psi RVP (n-butane: MW=58, RVP=52).

Butane requirement:

(2,179)(5.38) + M(52.0) = (2,179 + M)(10)

11,723 + 52.0M = 21,790 + 10.0M

42.0M = 10,067

M = 240 Moles 4nC required

BPD lb/hr MW mol/hr

n-butane 1,640 13,920 58 240

Total 10 psi RVP gasoline = 21,000 + 1,640 = 22,640 BPD

4.3.4. Incorrect Data Input

Page 33: Refinery Blending Problems by Engr. Adefami Olusegun

33

Incorrect data was input into the cell of visual studio 2005 to test how efficient the program

is compare to excel solver. Fig 4.3.4 showing “you must supply at least one constrain”,

“The constrain must contain ‘<=’ or ‘>=’ or ‘=’, “you must supply number of variable”.

Problem 4.4

Max Z = 321 335

333

22

31

321

Figure 4.11 Incorrect Data Input Showing (“you must supply at least one constrain”)

Page 34: Refinery Blending Problems by Engr. Adefami Olusegun

34

Figure 4.12 Incorrect Data Input showing The constrain must contain ‘<=’ or ‘>=’ or

‘=’.

Page 35: Refinery Blending Problems by Engr. Adefami Olusegun

35

Figure 4.13 Incorrect Data Input.

4.3.5 Discussion of Results:

The difference between visual studio 2005 software and excel solver is that visual studio

shows incorrect inputs and gives directions of what to do at every point in time why excel

solver does not show any incorrect input data.

4.4 Special Challenges Encountered

The main challenge I encountered was manipulation of matrices especially the inverse

function. I first used LU method but it did not work properly. Later I used Gaussian

elimination method. The other challenge is getting the equation of 10 or more variables

that can be used to test the application because it was not even available on the

internet as at this time. The cost for the research on this project is expensive.

Page 36: Refinery Blending Problems by Engr. Adefami Olusegun

36

4.5 DISCUSSION OF RESULTS

We present a computation method for solving quadratic programming problems which

reduces to the revised simplex for linear programming when the objective function is

linear. The basis matrix which is maintained is symmetric and may vary in size from

iteration to iteration. Comparison on test problems below indicates that the method is more

efficient than the other available methods. We used the active set algorithm in chapter 3

i.e. the revised simplex method Eqs (1) to Eqs (12), to solve the resulting optimization

problem.

Using Visual Studio 2005 software in a design of optimization application is equivalent to

considering the results of many virtual experiments, each of which is run using different

configurations, including geometrical, material or constraints. The design of optimum

codes in visual basic is a very difficult task but the application is friendly when compared

to Excel Solver and Matlab 7.0 softwares in solving large problems.

In the problem formulated and analysed below Excel Solver Software was compared with

Visual Studio software which is the aim and objective of this project and we discovered

the solutions of both problems were the same. The major difference between Excel Solver

Spreadsheet and Visual basic in Visual Studio 2005 is that Visual Basic shows the incorrect

data input while excel solver does not show it.

Finally, we can deduce that application of visual studio 2005 in Linear Programming is

friendly to the end user and it is useful in refinery blending, Production Planning,

Chemical Processing Industry and Financial Distribution.

Page 37: Refinery Blending Problems by Engr. Adefami Olusegun

37

CHAPTER FIVE

5.0 CONCLUSION AND RECOMMENDATON

Based on the results achieved on chapter four, the following conclusions were drawn.

The results generated through Revised Simplex method (data used for the project) was

compared with Excel Solver Solution and results were the same.

Revised Simplex method is the main function for linear programming with the most

flexibility for specifying the methods used, and it is the most efficient for large-scale

problems.

In the Revised Simplex Method there is an improvement in the objective function in

each step as the algorithm converges to the optimum. However, a situation can arise

where there is no improvement in the objective function from an application of the

algorithm.

In solving Problems in Revised simplex method Visual Studio Software application is

better than Excel solver and Mat Lab 7.0 .

Page 38: Refinery Blending Problems by Engr. Adefami Olusegun

38

REFERENCES

Alfredo M, (2005): “Formulating and solving splittable capacitated multiple

allocation hub location problems” Computer and Operation Research, Vol. 32, pp

3093- 3109.

Aspen Technology, Inc. (1996), Ten Canal Park, Cambridge, MA 02141-2200. Tel:

617-949-1000. Fax: 617-949-1030.

Beasley J.E, (2006): “OR – Linear Programming Formulation Notes”, Field of

Operation Research.

Billy E, and others, (2005), “Professional VB 2005” , Wiley Publishing,Inc.

Bazaraa, M. S., and J. J. Jarris, Linear Programming and Network Flows, John

Wiley and Sons, Inc., New York (1977).

Computing in Science and Engineering, (2000), Vol. 2,

James H.Gary and Glenn E. Handwerk, (2001), “Petroleum Refining” Mercel

Dekker, Inc. 270 Madison Avenue, New York, New York 10016.

Cai P. and Cai J.Y, (1997): On the 100% Rule of Sensitivity Analysis in Linear

Programming” Annual international Computing and Combinatorics Conference,

Vol. 1276, pp. 460-469.

Page 39: Refinery Blending Problems by Engr. Adefami Olusegun

39

Charnes, A., and W. W. Cooper, Management Models and Industrial Applications

of Linear Programming, Vols. 1 and 2, John Wiley and Sons, Inc., New York

(1967)

Delson, J.K and Shahidehpour S.M (1992): “Linear programming applications to

power system economics, planning and operations”, Power System, IEEE

Transaction on, Vol. 7, pp 1155-1163..

Edward J.M (1972):” The Application of Linear Programming to a Distribution

System Orientated Toward Service”, International Journal of Physical Distribution

& Logistics Management, Vol. 3, pp 191-204.

Gass, S. I., Linear Programming: Methods and Applications, 5th Ed., McGraw-Hill

Book Co., New York (1985).

Greenberg, cites: V. Klee and G.J. Minty. "How Good is the Simplex Algorithm?"

In O. Shisha, editor, Inequalities, III, pp 159–175. Academic Press, New York,

NY, 1972

Kallrath J.F, (2005): “Solving Planning and Design Problems in the Process

Industry Using Mixed Integral and Global Optimization” Annals of Operations

Research, Vol. 140, pp.339-373.

Optmalon Software, (2007): “GIPALS32” - Linear Programming Library

Page 40: Refinery Blending Problems by Engr. Adefami Olusegun

40

OR/MS, (1992): “Linear Programming Software” 49 packages, pp 44-45.

Psacharopoulous G. (2006): “Synthetic Approaches in Manpower Planning”, De

Economist”, Vol. 127, pp 287-297.

Ravichandran N, (1989): “Models in Management Science” A Journal of

Management Research, Vol. 4, pp 1

Smith, C. L., R. W. Pike, P. W. Murrill, Formulation and Optimization of

Mathematical Models, International Textbook Co., Scranton, Pa. (1970)

Trkman, Peter & Gradisar, Miro, 2008. "One-dimensional cutting stock

optimization in consecutive time periods," European Journal of Operational

Research, Elsevier, vol. 179(2), pp. 291-301.

Taiwo, F (2004), “Chemical Engineering Operations and Management” Ladoke

Akintola University of Technology” Vo1.3, pp. 1-23(3), Press, Ile-Ife

Tibor F., (1967): “Blast Furnace Production Planning-A Linear Programming

Example”, JSTOR System, European Journal Research, Vol. 14, pp B1-B27.

Vasant P.M, (2003): “Application of Fuzzy Linear Programming in Production

Planning, Fuzzy optimization and Decision making, Vol. 2, pp 229-241(13).

Wayne L.W, “Operation Research: Application and Algorithms, Wayne L.

Winston.-3rd ed., pp554-605, Wadsworth Publishing Company Belmont,

California, 1994.

Page 41: Refinery Blending Problems by Engr. Adefami Olusegun

41

William T.M (1960): “Application of Linear Programming To Financial Budgeting

and The Costing Of Funds”, The Engineering Economist Vol. 5, pp 55-56.

Zhenhua S, (1994): “Sensitivity Analysis for Optimization Linear Programming ,

American Control Conference, Vol. 2, pp 1911-1912

Page 42: Refinery Blending Problems by Engr. Adefami Olusegun

42

APPENDIX

Appendix 1

Definition of terms

BV Matrix for set of basic Variable

b = Right-hand side vector of the original tableau’s constraints

ja = Column of jx in the constraints of the original problem

B = m x m matrix whose jth column is the column for BVj in the original constraints

jC = Coefficient of jx in the objective function

BVC 1 x m row vector whose jth elements is the objective function coefficient for BVj

ix = m x 1 column vector with ith element 1 and all other elements equals to zero

ajB 1 Column for jx in BV tableau

jjBV CaBC `1 Coefficient of jx in row 0 (Price out)

bB 1 = Right-hand side of constraints in BV tableau

iBV xBC 1 Coefficient of slack variable iS in BV in row 0

iBV xBC 1 Coefficient of excess variable ie in BV row 0

bBCBV

1 Right-hand side of BV row 0.

Page 43: Refinery Blending Problems by Engr. Adefami Olusegun

43

Appendix 2

Execute Button Code rtbDisplay.Text = ""

Dim result As MsgBoxResult

bttnExecute.ForeColor = Color.Red

result = MsgBox("Do you want to execute",

MsgBoxStyle.YesNo, My.Application.Info.Title & "-Execute")

If result = MsgBoxResult.No Then

bttnExecute.ForeColor = Color.Black

Exit Sub

End If

Dim blnValidate As Boolean = False

Try

Validation(False)

Catch ex As Exception

MsgBox(ex.Message, MsgBoxStyle.Critical)

bttnExecute.ForeColor = Color.Black

Exit Sub

End Try

If cboContrains.Items.Count > 0 Then

blnValidate = True

Else

MsgBox("You must supply at least one constrain",

MsgBoxStyle.Critical, My.Application.Info.Title)

cboContrains.Focus()

Exit Sub

End If

Me.Enabled = False

Try

If blnValidate = True Then

NC = cboContrains.Items.Count - 1

NV = Convert.ToInt32(cboVariable.Text)

Dim blnOptimum As Boolean = False

Dim dblBConstants(NC) As Double

Dim dblZConstants(NV - 1) As Double

Dim dblXConsArray(NC, NV + NC) As Double

For i As Int32 = 0 To

cboContrains.Items.Count - 1

Dim strConstrain As String =

cboContrains.Items(i)

If strConstrain.IndexOf(">=") <> -1 Then

dblBConstants(i) = -1 *

Microsoft.VisualBasic.Right(strConstrain,

strConstrain.Length - (strConstrain.IndexOf("=") + 1))

Page 44: Refinery Blending Problems by Engr. Adefami Olusegun

44

Else

dblBConstants(i) =

Microsoft.VisualBasic.Right(strConstrain,

strConstrain.Length - (strConstrain.IndexOf("=") + 1))

End If

Next

dblZConstants =

GetMatrixZ(UCase(Trim(txtObjFxn.Text)))

If cboOptimal.SelectedIndex = 0 Then

blnOptimum = True

ElseIf cboOptimal.SelectedIndex = 1 Then

blnOptimum = False

End If

For i As Int32 = 0 To NC

Dim myXConstant() As Double =

GetMatrix(cboContrains.Items(i))

For j As Int32 = 0 To NV - 1

dblXConsArray(i, j) = myXConstant(j)

Next

Next

For i As Int32 = 0 To NC

For j As Int32 = NV To

dblXConsArray.GetUpperBound(1)

Dim myJ As Int32 = j - NV

If i = myJ Then

dblXConsArray(i, j) = 1

Else

dblXConsArray(i, j) = 0

End If

Next

Next

Dim dblAnswer() As Variable =

MatrixHelper.RevisedSimplex(dblZConstants, dblXConsArray,

dblBConstants, blnOptimum)

Call Display(dblZConstants, dblAnswer)

bttnSave.Enabled = True

End If

Catch ex As Exception

MsgBox(ex.Message)

bttnExecute.ForeColor = Color.Black

Me.Enabled = True

End Try

Me.Enabled = True

End Sub

Page 45: Refinery Blending Problems by Engr. Adefami Olusegun

45

Appendix 3

Save Button Code

Dim blnDuplicate As Boolean = False 'To make sure equation of

the same type does not exist in the database

Dim result As MsgBoxResult

bttnSave.ForeColor = Color.Red

result = MsgBox("Do you want to Save",

MsgBoxStyle.YesNo, My.Application.Info.Title & "-Save")

If result = MsgBoxResult.No Then

bttnSave.ForeColor = Color.Black

Exit Sub

End If

If rtbDisplay.Text = "" Then

MsgBox("Cannot save this equation",

MsgBoxStyle.Critical, My.Application.Info.Title & "-Save")

bttnSave.ForeColor = Color.Black

Exit Sub

End If

Try

Validation(False)

Catch ex As Exception

MsgBox(ex.Message & " Cannot save this equation",

MsgBoxStyle.Critical)

bttnSave.ForeColor = Color.Black

Exit Sub

End Try

If myCon.State = ConnectionState.Open Then

myCon.Close()

End If

myCon.Open(strCon)

'Submit equation to database

Dim myData As New ADODB.Recordset

strQry = "SELECT * FROM Equation"

myData.Open(strQry, myCon,

ADODB.CursorTypeEnum.adOpenStatic,

ADODB.LockTypeEnum.adLockOptimistic)

For i As Int32 = 0 To myData.RecordCount - 1

If myData.Fields("strEquation").Value =

txtObjFxn.Text.Trim.ToUpper Then

blnDuplicate = True

End If

myData.MoveNext()

Next

If blnDuplicate = False Then

Page 46: Refinery Blending Problems by Engr. Adefami Olusegun

46

myData.AddNew()

myData.Fields("strEquation").Value =

txtObjFxn.Text.Trim.ToUpper

myData.Fields("strOptimal").Value =

cboOptimal.Text.Trim

myData.Fields("intVarNo").Value =

cboVariable.Text.Trim

myData.Update()

Else

MsgBox("Cannot save this equation. The equation

already exist. ", MsgBoxStyle.Critical,

My.Application.Info.Title)

txtObjFxn.Focus()

bttnSave.ForeColor = Color.Black

Exit Sub

End If

myData.Close()

'Submit the constrains

strQry = "SELECT * FROM Constrains"

myData.Open(strQry, myCon,

ADODB.CursorTypeEnum.adOpenStatic,

ADODB.LockTypeEnum.adLockOptimistic)

For i As Int32 = 0 To cboContrains.Items.Count - 1

myData.AddNew()

myData.Fields("strEquation").Value =

txtObjFxn.Text.Trim.ToUpper

myData.Fields("strOptimal").Value =

cboOptimal.Text.Trim

myData.Fields("strConstrain").Value =

cboContrains.Items(i).ToString

myData.Update()

Next

myData.Close()

'Submit the answers

strQry = "SELECT * FROM Answer"

myData.Open(strQry, myCon,

ADODB.CursorTypeEnum.adOpenStatic,

ADODB.LockTypeEnum.adLockOptimistic)

For i As Int32 = 0 To DataArray.GetUpperBound(0)

myData.AddNew()

myData.Fields("strEquation").Value =

txtObjFxn.Text.Trim.ToUpper

myData.Fields("strOptimal").Value =

cboOptimal.Text.Trim

Page 47: Refinery Blending Problems by Engr. Adefami Olusegun

47

myData.Fields("strVariable").Value =

DataArray(i).strVariable

myData.Fields("dblAnswer").Value =

DataArray(i).dblValue

myData.Update()

Next

myData.Close()

myCon.Close()

MsgBox("The equation is saved",

MsgBoxStyle.Information, My.Application.Info.Title)

bttnSave.ForeColor = Color.Black

End Sub

Appendix 4A

Retrieve Button Code

Private Sub bttnRetrieve_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles bttnRetrieve.Click

frmRetrieve.Show()

End Sub

Appendix 4B

Print Button Code

Private Sub bttnPrint_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles bttnPrint.Click

Dim PS As New System.Drawing.Printing.PageSettings

PS.Margins.Left = 300

PS.Margins.Right = 175

PS.Margins.Top = 200

PS.Margins.Bottom = 200

PrintDialog1.PrinterSettings =

PrintDocument1.PrinterSettings

If PrintDialog1.ShowDialog() =

Windows.Forms.DialogResult.OK Then

PrintDocument1.DefaultPageSettings = PS

PrintDocument1.PrinterSettings =

PrintDialog1.PrinterSettings

PrintDocument1.Print()

End If

End Sub

Page 48: Refinery Blending Problems by Engr. Adefami Olusegun

48

Appendix 4C

Clear Button Code

Dim result As MsgBoxResult

bttnClear.ForeColor = Color.Red

result = MsgBox("Do you want to Clear",

MsgBoxStyle.YesNo, My.Application.Info.Title & "-Clear")

If result = MsgBoxResult.No Then

bttnClear.ForeColor = Color.Black

Exit Sub

End If

txtObjFxn.Text = ""

txtObjFxn.Focus()

cboOptimal.SelectedIndex = 0

cboVariable.SelectedIndex = -1

cboContrains.Text = ""

cboContrains.Items.Clear()

rtbDisplay.Text = ""

bttnSave.Enabled = False

bttnClear.ForeColor = Color.Black

End Sub

Appendix 4D

Validate Button Code

bttnValidate.ForeColor = Color.Red

Dim result As MsgBoxResult

result = MsgBox("Do you want to Validate",

MsgBoxStyle.YesNo, My.Application.Info.Title & "-Validate")

If result = MsgBoxResult.No Then

bttnValidate.ForeColor = Color.Black

Exit Sub

End If

Try

Validation(True)

Catch ex As Exception

MsgBox(ex.Message)

End Try

bttnValidate.ForeColor = Color.Black

End Sub

Appendix 4E

Page 49: Refinery Blending Problems by Engr. Adefami Olusegun

49

Exit Button Code

Private Sub bttnExit_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles bttnExit.Click

Dim result As MsgBoxResult

bttnExit.ForeColor = Color.Red

result = MsgBox("Are you sure you want to Exit",

MsgBoxStyle.YesNo, My.Application.Info.Title & "-Exit")

If result = MsgBoxResult.No Then

bttnExit.ForeColor = Color.Black

Exit Sub

End If

Me.Close()

End Sub

Appendix 5

Inverse Function Code

Public Function Inverse(ByVal sourceMatrix(,) As Double) As

Double(,)

Dim eachCol As Integer

Dim eachRow As Integer

Dim rowsAndCols As Integer

If (UBound(sourceMatrix, 1) <> UBound(sourceMatrix,

2)) Then

Throw New Exception("Matrix must be square.")

End If

Dim rank As Integer = UBound(sourceMatrix, 1)

' ----- Clone a copy of the matrix (not just a new

reference).

Dim workMatrix(,) As Double = _

CType(sourceMatrix.Clone, Double(,))

' ----- Variables used for backsolving.

Dim destMatrix(rank, rank) As Double

Dim rightHandSide(rank) As Double

Dim solutions(rank) As Double

Dim rowPivots(rank) As Integer

Dim colPivots(rank) As Integer

Page 50: Refinery Blending Problems by Engr. Adefami Olusegun

50

' ----- Use LU decomposition to form a triangular

matrix.

workMatrix = FormLU(workMatrix, rowPivots,

colPivots, rowsAndCols)

' ----- Backsolve the triangular matrix to get the

inverted

' value for each position in the final matrix.

For eachCol = 0 To rank

rightHandSide(eachCol) = 1

BackSolve(workMatrix, rightHandSide, solutions,

rowPivots, colPivots)

For eachRow = 0 To rank

destMatrix(eachRow, eachCol) =

solutions(eachRow)

rightHandSide(eachRow) = 0

Next eachRow

Next eachCol

' ----- Return the inverted matrix result.

Return destMatrix

End Function

Appendix 6

Revised Simplex Code

Public Function RevisedSimplex(ByVal objFunc() As Double,

ByVal constFunc(,) As Double, ByVal dblB() As Double, ByVal

blnOptimal As Boolean) As Variable()

Dim m, t As Int32

Dim zolution(,) As Double

Dim strBasis(NC) As String

Dim intBasis(NC) As Int32

Dim strNBasis(NV - 1) As String

Dim intNBasis(NV - 1) As Int32

Dim Xb(objFunc.GetUpperBound(0), 0) As Double

Dim Xa(objFunc.GetUpperBound(0), 0) As Double

Dim Ratio(NC) As Double

Dim matrixA(constFunc.GetUpperBound(0),

constFunc.GetUpperBound(1)) As Double

Dim objFuncWork(objFunc.GetUpperBound(0)) As Double

Dim dblBWork(dblB.GetUpperBound(0)) As Double

Dim dblBWorkUse(dblB.GetUpperBound(0), 0) As Double

Dim B(matrixA.GetUpperBound(0), NC) As Double

Dim P(NC, 0) As Double

Dim Y(,) As Double

Page 51: Refinery Blending Problems by Engr. Adefami Olusegun

51

Dim Z(intNBasis.GetUpperBound(0)) As Double

Dim intIterationCounter As Int32 = 0

Dim Cb(0, intBasis.GetUpperBound(0)) As Double

Dim invB(matrixA.GetUpperBound(0), NC) As Double

Dim RepeatLoop As Boolean = True

Array.Copy(constFunc, matrixA, constFunc.Length)

Array.Copy(objFunc, objFuncWork, objFunc.Length)

Array.Copy(dblB, dblBWork, dblB.Length)

'Note: based strbasis on the no of varIABLE e.g

variable strbasis(0)="X" & 5

For count As Int32 = 1 To NV

intNBasis(count - 1) = count

Next

For count As Int32 = NV + 1 To

matrixA.GetUpperBound(1) + 1

intBasis(count - (NV + 1)) = count

Next

For j As Int32 = 0 To dblBWorkUse.GetUpperBound(0)

dblBWorkUse(j, 0) = dblBWork(j)

Next

While RepeatLoop

For k As Int32 = 0 To intBasis.GetUpperBound(0)

Try

Cb(0, k) = objFuncWork(intBasis(k) - 1)

Catch

Cb(0, k) = 0

End Try

Next

For i As Int32 = 0 To matrixA.GetUpperBound(0)

For j As Int32 = 0 To

intBasis.GetUpperBound(0)

B(i, j) = matrixA(i, intBasis(j) - 1)

Next

Next

invB = Inverse(B)

Xb = Multiply(invB, dblBWorkUse)

zolution = Multiply(Cb, Xb)

Y = Multiply(Cb, invB)

Dim a As Int32 = 0

Do While a <= intNBasis.GetUpperBound(0)

For i As Int32 = 0 To

matrixA.GetUpperBound(0)

P(i, 0) = matrixA(i, intNBasis(a) - 1)

Page 52: Refinery Blending Problems by Engr. Adefami Olusegun

52

Next

Dim Zme(0, 0) As Double

Zme = Multiply(Y, P)

Try

Z(a) = Zme(0, 0) -

objFuncWork(intNBasis(a) - 1)

Catch

Z(a) = Zme(0, 0) - 0

End Try

a += 1

Loop

'to choose to either maximise or minimise

If blnOptimal = True Then 'maximize

m = Minimum(Z, intNBasis)

Else

m = Maximum(Z, intNBasis)

End If

If m < 0 Then

'write out Xb and Z

Dim var(Xb.GetUpperBound(0) + 1) As Variable

For i As Int32 = 0 To Xb.GetUpperBound(0)

var(i).dblValue = Xb(i, 0)

var(i).strVariable = "X" & intBasis(i)

Next

var(Xb.GetUpperBound(0) + 1).strVariable =

"Z"

var(Xb.GetUpperBound(0) + 1).dblValue =

zolution(0, 0)

intCounter = intIterationCounter

Return var

RepeatLoop = False

Exit Function

End If

For i As Int32 = 0 To matrixA.GetUpperBound(0)

P(i, 0) = matrixA(i, m) ' Note in case of

error

Next

Xb = Multiply(invB, dblBWorkUse)

Xa = Multiply(invB, P)

For i As Int32 = 0 To Xb.GetUpperBound(0)

Dim x As Double = Xb(i, 0) / Xa(i, 0)

If Double.IsInfinity(x) Then

Ratio(i) = 0

Else

Ratio(i) = x

End If

Next

Page 53: Refinery Blending Problems by Engr. Adefami Olusegun

53

If LessEqualZero(Ratio) Then

Dim var(Xb.GetUpperBound(0) + 1) As Variable

For i As Int32 = 0 To Xb.GetUpperBound(0)

var(i).dblValue = Xb(i, 0)

var(i).strVariable = "X" & intBasis(i)

Next

var(Xb.GetUpperBound(0) + 1).strVariable =

"Z"

var(Xb.GetUpperBound(0) + 1).dblValue =

zolution(0, 0)

intCounter = intIterationCounter

Return var

RepeatLoop = False

Throw New Exception("The Problem has no

bounded solution")

Exit Function 'write: the problem has no

bounded solution

Else

t = MinRatio(Ratio)

End If

'to avoid double entry of each value

Dim blnDoubleEntry As Boolean = False

For i As Int32 = 0 To intBasis.GetUpperBound(0)

If intBasis(i) = m + 1 Then

blnDoubleEntry = True

End If

Next

If blnDoubleEntry = False Then

For i As Int32 = 0 To

intBasis.GetUpperBound(0)

If intBasis(i) = t + NV + 1 Then

intBasis(i) = m + 1

End If

Next

For i As Int32 = 0 To

intNBasis.GetUpperBound(0)

If intNBasis(i) = m + 1 Then

intNBasis(i) = t + NV + 1

End If

Next

Else

Dim var(Xb.GetUpperBound(0) + 1) As Variable

For i As Int32 = 0 To Xb.GetUpperBound(0)

var(i).dblValue = Xb(i, 0)

var(i).strVariable = "X" & intBasis(i)

Next

Page 54: Refinery Blending Problems by Engr. Adefami Olusegun

54

var(Xb.GetUpperBound(0) + 1).strVariable =

"Z"

var(Xb.GetUpperBound(0) + 1).dblValue =

zolution(0, 0)

intCounter = intIterationCounter

Return var

RepeatLoop = False

End If

Array.Sort(intNBasis)

For i As Int32 = 0 To intNBasis.GetUpperBound(0)

strNBasis(i) = "X" & intNBasis(i)

Next

'Array.Sort(intBasis)

For i As Int32 = 0 To intBasis.GetUpperBound(0)

strBasis(i) = "X" & intBasis(i)

Next

intIterationCounter += 1

If intIterationCounter = 1000 Then

Dim var(0) As Variable

var(0).strVariable = "No solution is found"

var(0).dblValue = 0

intCounter = intIterationCounter

Return var

Exit Function

End If

End While

End Function

Appendix 7

VISUAL BASIC CODE FOR THE COMPUTER AIDED DESIGNED

'Start: Thursday

'Stop:

'Programmer: Adefami olusegun A. (08034988098)

[email protected]

Public myCon As New ADODB.Connection

Public myData As ADODB.Recordset

Public strCon As String =

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &

Page 55: Refinery Blending Problems by Engr. Adefami Olusegun

55

My.Application.Info.DirectoryPath & "\RevisedSimplex.mdb"

';Jet OLEDB:Database Password=adtaxymac"

Public strQry As String

Public intCounter As Int32

Public NV, NC As Int32

Public Solution_Problem As Boolean

Public Function MakeDisplayable(ByVal sourceMatrix(,) As

Double) As String

' ----- Prepare a multi-line string that shows the

contents

' of a matrix, a 2D array.

Dim rows As Integer

Dim cols As Integer

Dim eachRow As Integer

Dim eachCol As Integer

Dim result As New System.Text.StringBuilder

' ----- Process all rows of the matrix, generating

one

' output line per row.

rows = UBound(sourceMatrix, 1) + 1

cols = UBound(sourceMatrix, 2) + 1

For eachRow = 0 To rows - 1

' ----- Process each column of the matrix on a

single

' row, separating values by commas.

If (eachRow > 0) Then result.AppendLine()

For eachCol = 0 To cols - 1

' ----- Add a single matrix element to the

output.

If (eachCol > 0) Then result.Append(",")

result.Append(sourceMatrix(eachRow,

eachCol).ToString)

Next eachCol

Next eachRow

' ----- Finished.

Return result.ToString

End Function

Public Function MakeDisplayable(ByVal sourceArray() As

Double) As String

' ----- Present an array as multiple lines of output.

Dim result As New System.Text.StringBuilder

Dim scanValue As Double

Page 56: Refinery Blending Problems by Engr. Adefami Olusegun

56

For Each scanValue In sourceArray

result.AppendLine(scanValue.ToString)

Next scanValue

Return result.ToString

End Function

Public Function Inverse(ByVal sourceMatrix(,) As Double)

As Double(,)

' ----- Build a new matrix that is the mathematical

inverse

' of the supplied matrix. Multiplying a matrix

and its

' inverse together will give the identity

matrix.

Dim eachCol As Integer

Dim eachRow As Integer

Dim rowsAndCols As Integer

' ----- Determine the size of each dimension of the

matrix.

' Only square matrices can be inverted.

If (UBound(sourceMatrix, 1) <> UBound(sourceMatrix,

2)) Then

Throw New Exception("Matrix must be square.")

End If

Dim rank As Integer = UBound(sourceMatrix, 1)

' ----- Clone a copy of the matrix (not just a new

reference).

Dim workMatrix(,) As Double = _

CType(sourceMatrix.Clone, Double(,))

' ----- Variables used for backsolving.

Dim destMatrix(rank, rank) As Double

Dim rightHandSide(rank) As Double

Dim solutions(rank) As Double

Dim rowPivots(rank) As Integer

Dim colPivots(rank) As Integer

' ----- Use LU decomposition to form a triangular

matrix.

workMatrix = FormLU(workMatrix, rowPivots,

colPivots, rowsAndCols)

' ----- Backsolve the triangular matrix to get the

inverted

Page 57: Refinery Blending Problems by Engr. Adefami Olusegun

57

' value for each position in the final matrix.

For eachCol = 0 To rank

rightHandSide(eachCol) = 1

BackSolve(workMatrix, rightHandSide, solutions,

rowPivots, colPivots)

For eachRow = 0 To rank

destMatrix(eachRow, eachCol) =

solutions(eachRow)

rightHandSide(eachRow) = 0

Next eachRow

Next eachCol

' ----- Return the inverted matrix result.

Return destMatrix

End Function

Public Function Determinant(ByVal sourceMatrix(,) As

Double) As Double

' ----- Calculate the determinant of a matrix.

Dim result As Double

Dim pivots As Integer

Dim count As Integer

' ----- Only calculate the determinants of square

matrices.

If (UBound(sourceMatrix, 1) <> UBound(sourceMatrix,

2)) Then

Throw New Exception( _

"Determinant only calculated for square

matrices.")

End If

Dim rank As Integer = UBound(sourceMatrix, 1)

' ----- Make a copy of the matrix so we can work

inside of it.

Dim workMatrix(rank, rank) As Double

Array.Copy(sourceMatrix, workMatrix,

sourceMatrix.Length)

' ----- Use LU decomposition to form a triangular

matrix.

Dim rowPivots(rank) As Integer

Dim colPivots(rank) As Integer

workMatrix = FormLU(workMatrix, rowPivots,

colPivots, count)

' ----- Get the product at each of the pivot points.

Page 58: Refinery Blending Problems by Engr. Adefami Olusegun

58

result = 1

For pivots = 0 To rank

result *= workMatrix(rowPivots(pivots),

colPivots(pivots))

Next pivots

' ----- Determine the sign of the result using

LaPlace's formula.

result = (-1) ^ count * result

Return result

End Function

Private Function FormLU(ByVal sourceMatrix(,) As Double,

_

ByRef rowPivots() As Integer, ByRef colPivots()

As Integer, _

ByRef rowsAndCols As Integer) As Double(,)

' ----- Perform an LU (lower and upper) decomposition

of a matrix,

' a modified form of Gaussian elimination.

Dim eachRow As Integer

Dim eachCol As Integer

Dim pivot As Integer

Dim rowIndex As Integer

Dim colIndex As Integer

Dim bestRow As Integer

Dim bestCol As Integer

Dim rowToPivot As Integer

Dim colToPivot As Integer

Dim maxValue As Double

Dim testValue As Double

Dim oldMax As Double

Const Deps As Double = 0.0000000000000001

' ----- Determine the size of the array.

Dim rank As Integer = UBound(sourceMatrix, 1)

Dim destMatrix(rank, rank) As Double

Dim rowNorm(rank) As Double

ReDim rowPivots(rank)

ReDim colPivots(rank)

' ----- Make a copy of the array so we don't mess it

up.

Array.Copy(sourceMatrix, destMatrix,

sourceMatrix.Length)

Page 59: Refinery Blending Problems by Engr. Adefami Olusegun

59

' ----- Initialize row and column pivot arrays.

For eachRow = 0 To rank

rowPivots(eachRow) = eachRow

colPivots(eachRow) = eachRow

For eachCol = 0 To rank

rowNorm(eachRow) +=

Math.Abs(destMatrix(eachRow, eachCol))

Next eachCol

If (rowNorm(eachRow) = 0) Then

Throw New Exception("Cannot invert a singular

matrix.")

End If

Next eachRow

' ----- Use Gauss-Jordan elimination on the matrix

rows.

For pivot = 0 To rank - 1

maxValue = 0

For eachRow = pivot To rank

rowIndex = rowPivots(eachRow)

For eachCol = pivot To rank

colIndex = colPivots(eachCol)

testValue =

Math.Abs(destMatrix(rowIndex, colIndex)) _

/ rowNorm(rowIndex)

If (testValue > maxValue) Then

maxValue = testValue

bestRow = eachRow

bestCol = eachCol

End If

Next eachCol

Next eachRow

' ----- Detect a singular, or very nearly

singular, matrix.

If (maxValue = 0) Then

Throw New Exception("Singular matrix used for

LU.")

ElseIf (pivot > 1) Then

If (maxValue < (Deps * oldMax)) Then

Throw New Exception("Non-invertible

matrix used for LU.")

End If

End If

oldMax = maxValue

' ----- Swap row pivot values for the best row.

Page 60: Refinery Blending Problems by Engr. Adefami Olusegun

60

If (rowPivots(pivot) <> rowPivots(bestRow)) Then

rowsAndCols += 1

Swap(rowPivots(pivot), rowPivots(bestRow))

End If

' ----- Swap column pivot values for the best

column.

If (colPivots(pivot) <> colPivots(bestCol)) Then

rowsAndCols += 1

Swap(colPivots(pivot), colPivots(bestCol))

End If

' ----- Work with the current pivot points.

rowToPivot = rowPivots(pivot)

colToPivot = colPivots(pivot)

' ----- Modify the remaining rows from the pivot

points.

For eachRow = (pivot + 1) To rank

rowIndex = rowPivots(eachRow)

destMatrix(rowIndex, colToPivot) = _

-destMatrix(rowIndex, colToPivot) / _

destMatrix(rowToPivot, colToPivot)

For eachCol = (pivot + 1) To rank

colIndex = colPivots(eachCol)

destMatrix(rowIndex, colIndex) += _

destMatrix(rowIndex, colToPivot) * _

destMatrix(rowToPivot, colIndex)

Next eachCol

Next eachRow

Next pivot

' ----- Detect a non-invertible matrix.

If (destMatrix(rowPivots(rank), colPivots(rank)) =

0) Then

Throw New Exception("Non-invertible matrix used

for LU.")

ElseIf (Math.Abs(destMatrix(rowPivots(rank),

colPivots(rank))) / _

rowNorm(rowPivots(rank))) < (Deps * oldMax)

Then

Throw New Exception("Non-invertible matrix used

for LU.")

End If

' ----- Success. Return the LU triangular matrix.

Return destMatrix

Page 61: Refinery Blending Problems by Engr. Adefami Olusegun

61

End Function

Private Function Calculate_Inverse(ByVal MatrixA(,) As

Double) As Double(,)

Dim multiplier_1 As Double

Dim elem1 As Double

Dim temporary_1 As Double

Dim line_1 As Double

Dim k As Int32

Dim m As Int32

Dim N As Int32

Dim System_DIM As Int32 = MatrixA.GetUpperBound(0) +

1

Dim MAX_DIM As Int32 = MatrixA.GetUpperBound(0)

Dim Operations_Matrix(MAX_DIM, (2 * MAX_DIM) + 1) As

Double 'Matrix where the calculations are done

Dim Inverse_Matrix(MAX_DIM, MAX_DIM) As Double

'Matrix with the Inverse of [A]

'Uses Gauss elimination method in order to calculate

the inverse matrix [A]-1

'Method: Puts matrix [A] at the left and the singular

matrix [I] at the right:

'[ a11 a12 a13 | 1 0 0 ]

'[ a21 a22 a23 | 0 1 0 ]

'[ a31 a32 a33 | 0 0 1 ]

'Then using line operations, we try to build the

singular matrix [I] at the left.

'After we have finished, the inverse matrix [A]-1

(bij) will be at the right:

'[ 1 0 0 | b11 b12 b13 ]

'[ 0 1 0 | b21 b22 b23 ]

'[ 0 0 1 | b31 b32 b33 ]

'On Error GoTo errhandler 'In case the inverse cannot

be found (Determinant = 0)

Solution_Problem = False

'Assign values from matrix [A] at the left

For N = 0 To System_DIM - 1

For m = 0 To System_DIM - 1

Operations_Matrix(m, N) = MatrixA(m, N)

Next

Next

'Assign values from singular matrix [I] at the right

For N = 0 To System_DIM - 1

For m = 0 To System_DIM - 1

Page 62: Refinery Blending Problems by Engr. Adefami Olusegun

62

If N = m Then

Operations_Matrix(m, N + System_DIM) = 1

Else

Operations_Matrix(m, N + System_DIM) = 0

End If

Next

Next

'Build the Singular matrix [I] at the left

For k = 0 To System_DIM - 1

'Bring a non-zero element first by changes lines

if necessary

If Operations_Matrix(k, k) = 0 Then

For N = k To System_DIM - 1

If Operations_Matrix(N, k) <> 0 Then

line_1 = N : Exit For

End If 'Finds line_1 with non-zero

element

Next N

'Change line k with line_1

For m = k To (System_DIM - 1) * 2

temporary_1 = Operations_Matrix(k, m)

Operations_Matrix(k, m) =

Operations_Matrix(line_1, m)

Operations_Matrix(line_1, m) =

temporary_1

Next m

End If

elem1 = Operations_Matrix(k, k)

For N = k To 2 * (System_DIM - 1)

Operations_Matrix(k, N) =

Operations_Matrix(k, N) / elem1

Next N

'For other lines, make a zero element by using:

'Ai1=Aij-A11*(Aij/A11)

'and change all the line using the same formula

for other elements

For N = 0 To System_DIM - 1

If N = k And N = MAX_DIM Then Exit For

'Finished

If N = k And N < MAX_DIM Then N = N + 1 'Do

not change that element (already equals to 1), go for next

one

If Operations_Matrix(N, k) <> 0 Then 'if it

is zero, stays as it is

Page 63: Refinery Blending Problems by Engr. Adefami Olusegun

63

'

multiplier_1 = Operations_Matrix(N, k) /

Operations_Matrix(k, k)

For m = k To 2 * (System_DIM - 1)

Operations_Matrix(N, m) =

Operations_Matrix(N, m) - Operations_Matrix(k, m) *

multiplier_1

Next m

End If

Next N

Next k

'Assign the right part to the Inverse_Matrix

For N = 0 To System_DIM - 1

For k = 0 To System_DIM - 1

Inverse_Matrix(N, k) = Operations_Matrix(N,

System_DIM + k)

Next k

Next N

Return Inverse_Matrix

Exit Function

errhandler:

Throw New Exception("An error occured during the

calculation process. Determinant of Matrix [A] is probably

equal to zero.")

Solution_Problem = True

End Function

Private Sub Swap(ByRef firstValue As Integer, ByRef

secondValue As Integer)

' ----- Reverse the values of two reference integers.

Dim holdValue As Integer

holdValue = firstValue

firstValue = secondValue

secondValue = holdValue

End Sub

Private Sub BackSolve(ByVal sourceMatrix(,) As Double, _

ByVal rightHandSide() As Double, ByVal

solutions() As Double, _

ByRef rowPivots() As Integer, ByRef colPivots()

As Integer)

' ----- Solve an upper-right-triangle matrix.

Dim pivot As Integer

Dim rowToPivot As Integer

Dim colToPivot As Integer

Dim eachRow As Integer

Page 64: Refinery Blending Problems by Engr. Adefami Olusegun

64

Dim eachCol As Integer

Dim rank As Integer = UBound(sourceMatrix, 1)

' ----- Work through all pivot points. This section

builds

' the "B" in the AX=B formula.

For pivot = 0 To (rank - 1)

colToPivot = colPivots(pivot)

For eachRow = (pivot + 1) To rank

rowToPivot = rowPivots(eachRow)

rightHandSide(rowToPivot) += _

sourceMatrix(rowToPivot, colToPivot) _

* rightHandSide(rowPivots(pivot))

Next eachRow

Next pivot

' ----- Now solve for each X using the general formula

' x(i) = (b(i) - summation(a(i,j)x(j)))/a(i,i)

For eachRow = rank To 0 Step -1

colToPivot = colPivots(eachRow)

rowToPivot = rowPivots(eachRow)

solutions(colToPivot) =

rightHandSide(rowToPivot)

For eachCol = (eachRow + 1) To rank

solutions(colToPivot) -= _

sourceMatrix(rowToPivot,

colPivots(eachCol)) _

* solutions(colPivots(eachCol))

Next eachCol

solutions(colToPivot) /=

sourceMatrix(rowToPivot, colToPivot)

Next eachRow

End Sub

Public Function RevisedSimplex(ByVal objFunc() As Double,

ByVal constFunc(,) As Double, ByVal dblB() As Double, ByVal

blnOptimal As Boolean) As Variable()

Dim m, t As Int32

Dim zolution(,) As Double

Dim strBasis(NC) As String

Dim intBasis(NC) As Int32

Dim strNBasis(NV - 1) As String

Dim intNBasis(NV - 1) As Int32

Dim Xb(objFunc.GetUpperBound(0), 0) As Double

Dim Xa(objFunc.GetUpperBound(0), 0) As Double

Dim Ratio(NC) As Double

Dim matrixA(constFunc.GetUpperBound(0),

constFunc.GetUpperBound(1)) As Double

Page 65: Refinery Blending Problems by Engr. Adefami Olusegun

65

Dim objFuncWork(objFunc.GetUpperBound(0)) As Double

Dim dblBWork(dblB.GetUpperBound(0)) As Double

Dim dblBWorkUse(dblB.GetUpperBound(0), 0) As Double

Dim B(matrixA.GetUpperBound(0), NC) As Double

Dim P(NC, 0) As Double

Dim Y(,) As Double

Dim Z(intNBasis.GetUpperBound(0)) As Double

Dim intIterationCounter As Int32 = 0

Dim Cb(0, intBasis.GetUpperBound(0)) As Double

Dim invB(matrixA.GetUpperBound(0), NC) As Double

Dim RepeatLoop As Boolean = True

Array.Copy(constFunc, matrixA, constFunc.Length)

Array.Copy(objFunc, objFuncWork, objFunc.Length)

Array.Copy(dblB, dblBWork, dblB.Length)

'Note: based strbasis on the no of varIABLE e.g

variable strbasis(0)="X" & 5

For count As Int32 = 1 To NV

intNBasis(count - 1) = count

Next

For count As Int32 = NV + 1 To

matrixA.GetUpperBound(1) + 1

intBasis(count - (NV + 1)) = count

Next

For j As Int32 = 0 To dblBWorkUse.GetUpperBound(0)

dblBWorkUse(j, 0) = dblBWork(j)

Next

While RepeatLoop

For k As Int32 = 0 To intBasis.GetUpperBound(0)

Try

Cb(0, k) = objFuncWork(intBasis(k) - 1)

Catch

Cb(0, k) = 0

End Try

Next

For i As Int32 = 0 To matrixA.GetUpperBound(0)

For j As Int32 = 0 To

intBasis.GetUpperBound(0)

B(i, j) = matrixA(i, intBasis(j) - 1)

Next

Next

invB = Inverse(B)

Xb = Multiply(invB, dblBWorkUse)

zolution = Multiply(Cb, Xb)

Page 66: Refinery Blending Problems by Engr. Adefami Olusegun

66

Y = Multiply(Cb, invB)

Dim a As Int32 = 0

Do While a <= intNBasis.GetUpperBound(0)

For i As Int32 = 0 To

matrixA.GetUpperBound(0)

P(i, 0) = matrixA(i, intNBasis(a) - 1)

Next

Dim Zme(0, 0) As Double

Zme = Multiply(Y, P)

Try

Z(a) = Zme(0, 0) -

objFuncWork(intNBasis(a) - 1)

Catch

Z(a) = Zme(0, 0) - 0

End Try

a += 1

Loop

'to choose to either maximise or minimise

If blnOptimal = True Then 'maximize

m = Minimum(Z, intNBasis)

Else

m = Maximum(Z, intNBasis)

End If

If m < 0 Then

'write out Xb and Z

Dim var(Xb.GetUpperBound(0) + 1) As Variable

For i As Int32 = 0 To Xb.GetUpperBound(0)

var(i).dblValue = Xb(i, 0)

var(i).strVariable = "X" & intBasis(i)

Next

var(Xb.GetUpperBound(0) + 1).strVariable =

"Z"

var(Xb.GetUpperBound(0) + 1).dblValue =

zolution(0, 0)

intCounter = intIterationCounter

Return var

RepeatLoop = False

Exit Function

End If

For i As Int32 = 0 To matrixA.GetUpperBound(0)

P(i, 0) = matrixA(i, m) ' Note in case of

error

Next

Xb = Multiply(invB, dblBWorkUse)

Xa = Multiply(invB, P)

For i As Int32 = 0 To Xb.GetUpperBound(0)

Dim x As Double = Xb(i, 0) / Xa(i, 0)

Page 67: Refinery Blending Problems by Engr. Adefami Olusegun

67

If Double.IsInfinity(x) Then

Ratio(i) = 0

Else

Ratio(i) = x

End If

Next

If LessEqualZero(Ratio) Then

Dim var(Xb.GetUpperBound(0) + 1) As Variable

For i As Int32 = 0 To Xb.GetUpperBound(0)

var(i).dblValue = Xb(i, 0)

var(i).strVariable = "X" & intBasis(i)

Next

var(Xb.GetUpperBound(0) + 1).strVariable =

"Z"

var(Xb.GetUpperBound(0) + 1).dblValue =

zolution(0, 0)

intCounter = intIterationCounter

Return var

RepeatLoop = False

Throw New Exception("The Problem has no

bounded solution")

Exit Function 'write: the problem has no

bounded solution

Else

t = MinRatio(Ratio)

End If

'to avoid double entry of each value

Dim blnDoubleEntry As Boolean = False

For i As Int32 = 0 To intBasis.GetUpperBound(0)

If intBasis(i) = m + 1 Then

blnDoubleEntry = True

End If

Next

If blnDoubleEntry = False Then

For i As Int32 = 0 To

intBasis.GetUpperBound(0)

If intBasis(i) = t + NV + 1 Then

intBasis(i) = m + 1

End If

Next

For i As Int32 = 0 To

intNBasis.GetUpperBound(0)

If intNBasis(i) = m + 1 Then

intNBasis(i) = t + NV + 1

End If

Next

Page 68: Refinery Blending Problems by Engr. Adefami Olusegun

68

Else

Dim var(Xb.GetUpperBound(0) + 1) As Variable

For i As Int32 = 0 To Xb.GetUpperBound(0)

var(i).dblValue = Xb(i, 0)

var(i).strVariable = "X" & intBasis(i)

Next

var(Xb.GetUpperBound(0) + 1).strVariable =

"Z"

var(Xb.GetUpperBound(0) + 1).dblValue =

zolution(0, 0)

intCounter = intIterationCounter

Return var

RepeatLoop = False

End If

Array.Sort(intNBasis)

For i As Int32 = 0 To intNBasis.GetUpperBound(0)

strNBasis(i) = "X" & intNBasis(i)

Next

'Array.Sort(intBasis)

For i As Int32 = 0 To intBasis.GetUpperBound(0)

strBasis(i) = "X" & intBasis(i)

Next

intIterationCounter += 1

If intIterationCounter = 1000 Then

Dim var(0) As Variable

var(0).strVariable = "No solution is found"

var(0).dblValue = 0

intCounter = intIterationCounter

Return var

Exit Function

End If

End While

End Function

Public Function Multiply(ByVal A1(,) As Double, ByVal

B1(,) As Double) As Double(,)

Dim m As Int32 = A1.GetUpperBound(0)

Dim k As Int32 = A1.GetUpperBound(1)

Dim n As Int32 = B1.GetUpperBound(1)

Dim C(m, n) As Double

'Multiply

For i As Int32 = 0 To m

For j As Int32 = 0 To n

C(i, j) = 0 'Initialise to zero

For p As Int32 = 0 To k

C(i, j) += A1(i, p) * B1(p, j)

Next

Page 69: Refinery Blending Problems by Engr. Adefami Olusegun

69

Next

Next

Return C

End Function

Public Function Minimum(ByVal minA() As Double, ByVal

minValues() As Int32) As Int32

Dim minimal As Double

Dim blnFound As Boolean = False

Dim minB(minA.GetUpperBound(0)) As Double

Dim myMinLoc As Int32 = -1

For min As Int32 = 0 To minA.GetUpperBound(0)

If minA(min) < 0 Then

myMinLoc = -1

blnFound = True

End If

Next

If Not (blnFound) Then

Return myMinLoc

Exit Function

End If

For min As Int32 = 0 To minA.GetUpperBound(0)

If minA(min) < 0 Then

minB(min) = -1 * minA(min)

Else

minB(min) = 0

End If

Next

minimal = minB(0)

myMinLoc = 0

For min As Int32 = 1 To minA.GetUpperBound(0)

If minimal < minB(min) Then

minimal = minB(min)

myMinLoc = min

End If

Next

If minimal = 0 Then

myMinLoc = -1

Else

myMinLoc = minValues(myMinLoc) - 1

End If

Return myMinLoc

End Function

Page 70: Refinery Blending Problems by Engr. Adefami Olusegun

70

Public Function Maximum(ByVal maxA() As Double, ByVal

maxValues() As Int32) As Int32

Dim maximal As Double

Dim blnFound As Boolean = False

Dim maxB(maxA.GetUpperBound(0)) As Double

Dim myMaxLoc As Int32 = -1

For min As Int32 = 0 To maxA.GetUpperBound(0)

If maxA(min) > 0 Then

myMaxLoc = -1

blnFound = True

End If

Next

If Not (blnFound) Then

Return myMaxLoc

Exit Function

End If

For max As Int32 = 0 To maxA.GetUpperBound(0)

If maxA(max) < 0 Then

maxB(max) = 0

Else

maxB(max) = maxA(max)

End If

Next

maximal = maxB(0)

myMaxLoc = 0

For min As Int32 = 1 To maxA.GetUpperBound(0)

If maximal < maxB(min) Then

maximal = maxB(min)

myMaxLoc = min

End If

Next

If maximal = 0 Then

myMaxLoc = -1

Else

myMaxLoc = maxValues(myMaxLoc) - 1

End If

Return myMaxLoc

End Function

Public Function MinRatio(ByVal minA() As Double) As Int32

Dim minimal As Double

Dim blnFound As Boolean = False

Dim minB(minA.GetUpperBound(0)) As Double

Dim myMinLoc As Int32 = -1

For min As Int32 = 0 To minA.GetUpperBound(0)

If minA(min) > 0 Then

Page 71: Refinery Blending Problems by Engr. Adefami Olusegun

71

blnFound = True

End If

Next

If blnFound = False Then

Return myMinLoc

Exit Function

End If

For min As Int32 = 0 To minA.GetUpperBound(0)

If minA(min) < 0 Then

minB(min) = 0

Else

minB(min) = minA(min)

End If

Next

If minB(0) <> 0 Then

minimal = minB(0)

myMinLoc = 0

Else

minimal = 1000000

End If

For min As Int32 = 1 To minA.GetUpperBound(0)

If minimal > minB(min) And minB(min) <> 0 Then

minimal = minB(min)

myMinLoc = min

Else

minimal = minimal

myMinLoc = myMinLoc

End If

Next

Return myMinLoc

End Function

Public Function LessEqualZero(ByVal Zero() As Double) As

Boolean

Dim blnFound As Boolean = True

For myCount As Int32 = 0 To Zero.GetUpperBound(0)

If Zero(myCount) > 0 Then

blnFound = False

End If

Next

End Function

Structure Variable

Dim strVariable As String

Page 72: Refinery Blending Problems by Engr. Adefami Olusegun

72

Dim dblValue As Double

End Structure

End Module