Docsity

Petroleum Engineering Numerical Methods Lecture Note and Study Guide | PETE 301, Study notes of Engineering

Partial preview of the text

Download Petroleum Engineering Numerical Methods Lecture Note and Study Guide | PETE 301 and more Study notes Engineering in PDF only on Docsity!

PETE 301 PETROLEUM ENGINEERING

NUMERICAL METHODS LECTURE NOTES AND

STUDY GUIDE

Peter P. Valk´o

August 18, 2004

Contents

  • I Introduction
    • 0.1 Course Objectives
    • 0.2 Resources
    • 0.3 Course structure
  • II Tools
  • 1 Introduction to Excel and VBA
    • 1.1 Starting Excel, saving a file
    • 1.2 Workbook, worksheet, views, printing
      • 1.2.1 Review
    • 1.3 Spreadsheet basics
    • 1.4 Graphing with Excel
    • 1.5 Numerical methods inside Excel
    • 1.6 Database Management with Excel
    • 1.7 Excel and the WWW
    • 1.8 Keyboard macros and what they can’t do
    • 1.9 VBA, variable, sub, function, module
    • 1.10 Structured Programming: Subs, Decisions and Loops
  • 2 Mathematica
  • III Engineering models and numerical methods
  • 3 Mathematical Modeling and Engineering Problem Solving
    • 3.1 Conservation Laws and Engineering
    • 3.2 Accuracy and Precision, Approximations and Round-Off Errors
    • 3.3 Error propagation
    • 3.4 Existence and uniqueness, Convergence criterion
    • 3.5 Order of the method, rate of convergence, stability, sensitivity
    • 3.6 Classification of problems and methods
  • 4 Methods related to single variable problems
    • 4.1 Roots of equations and extrema of functions
      • 4.1.1 Bisection
      • 4.1.2 False position
      • 4.1.3 Newton’s method
      • 4.1.4 Optimization: Golden ratio search for a minimum
    • 4.2 Fixed-point iteration as a general framework for iterative processes
    • 4.3 Representing, manipulating functions - where 4.3.1 Numerical Differentiation of functions that can be evaluated every-
      • 4.3.2 Numerical Integration
      • 4.3.3 Simpson’s 1/3 rule
    • 4.4 Interpolation, Smoothing, Curve fit, Least squares
      • 4.4.1 Least Squares and its Numerical Aspects
    • 4.5 Numerical solution of ordinary differential equations
      • 4.5.1 Basic methods for solving ODE
  • 5 Methods related to multi-variable problems
    • 5.1 Matrices, vectors
    • 5.2 System of linear equations
    • 5.3 LU Decomposition and Backsubstitution
    • 5.4 System of nonlinear equations, Newton-Raphson method
    • 5.5 Multivariable extrema
    • 5.6 Solution of system of ordinary differential equations: RK4
    • 5.7 Partial differential equations and reservoir simulation
      • 5.7.1 Reservoir Simulation
    • form 6 Integral Transforms, Spectral methods, inversion of the Laplace trans-
    • 6.1 Transformations
    • 6.2 Laplace transform
      • 6.2.1 Numerical inversion of the Laplace transform
  • IV Appendix
  • 7 Study guide
    • 7.1 Be able to
  • 8 Assignments, test problems
    • 8.1 Error propagation: borehole volume
    • 8.2 Error propagation: one-gallon cube
    • 8.3 Error propagation: barrel
    • 8.4 Error propagation: hydrocarbon volume
    • 8.5 Root finding; Newton iteration: z factor
    • 8.6 Root finding: solution of the PR equation of state
    • 8.7 Root finding: heat balance
    • 8.8 Root finding: friction factor
    • 8.9 Root finding: Well deliverability
    • 8.10 Root finding: isoterm flash
    • 8.11 Optimization: Maximizing Net Present Value
    • 8.12 Integration of a function: PV
    • 8.13 Numerical integration of discrete data: pore volume
    • 8.14 Straight-line: formation volume factor model
    • 8.15 Straight-line: formation volume factor model
    • 8.16 Straight-line: gas in place
    • 8.17 Straight-line: Flow-After-Flow Test (IPR)
      • ature 8.18 Nonlinear least squares: oil viscosity as a function of pressure and temper-
    • 8.19 ODE: Production rate decline from a differential equation
    • 8.20 ODE: pressure versus depth in a shut-in well
    • 8.21 Meaning of matrices and vectors: chemical component balance
    • 8.22 System of linear equations: mixing
    • 8.23 System of linear equations with many right-hand-sides: log interpretation
      • tion 8.24 Nonlinear System of Equations: Chemical Equilibrium of Methan Combus-
    • 8.25 Units: Darcy’s law
  • 9 Tables

Part I

Introduction

0.2 Resources

The concepts and methods of technical computing are summarized in the excellent book of Chapra and Canale: Numerical Methods for Engineers (CC). In order to make efficient use of our time, we request you to read the material before the lecture. Any similar book can be used, however. The Visual Basic for Applications (Excel) program development environment will be available in the lab. Whenever you are asked to solve a problem by computer, we request an Excel Workbook with Visual Basic source code and results. Excel and VBA for Excel has a vast literature. We will give you the opportunity to experiment with many of the numerical methods using a Living Textbook, developed particularly for this course. To make full use of the Living Textbook you will need a software system called Mathematica. This course, however, does not require you to learn how to program in Mathematica. In fact, to run any portion of the Living Textbook you will need minimum knowledge which can be acquired in 5 minutes. Many of the specific petroleum engineering problems also will be provided in the form of Living Textbook. You may experiment with them and may use the results for checking your Visual Basic for Applications (VBA) program results.

Basic References

  1. S.C. Chapra and R. P. Canale : Numerical Methods for Engineers, McGraw Hill, any edition, any year (or any similar title)

  2. Either of the following (or any similar title) a) Larsen: Engineering with Excel, Prentice Hall, 2002 b) Liengme: A guide to Microsoft Excel 2002 for scientists and engineers, Butterworth Heinemann, 2002 c) Bloch : Excel for Engineers and Scientists, 2002

  3. All of your Petroleum Engineering Books

Special thanks go to L. Piper, B. Maggard, R. Archer, R. Wattenbarger.

0.3 Course structure

  1. Engineering problem solving tools and programming

(a) Engineering problem solving approaches, software tools (b) Excel (c) VBA (d) Structured and Modular Programming

  1. Basics of numerical methods

(a) Taylor polynomial, Numerical errors, Error propagation (b) Iteration, Convergence, Order, Stability, Sensitivity (c) Classification of problems and methods

  1. Methods related to single variable problems

(a) Roots of equations and extrema of functions Bisection; False position; Newton; golden ratio search (b) Numerical differentiation and integration Finite difference; Trapezoid rule; Simpson’s rule (c) Interpolation, Smoothing, Curve fit, Least squares (d) Numerical solution of ordinary differential equations

  1. Methods related to multi-variable problems

(a) Matrices, vectors (b) System of linear equations (c) Gauss, Gauss-Jordan, LU decomposition Special cases, Iterative methods (d) Multivariable nonlinear equations: Newton-Raphson (e) Multivariable extrema: Nelder-Mead simplex, Fully nonlinear least squares

  1. Partial differential equations and reservoir simulation

(a) Classification and Numerical Solution of PDEs (b) Transient solution of the diffusivity equation (c) Reservoir simulation

  1. Transformation methods

(a) Spectral methods (b) Laplace transform inversion

Chapter 1

Introduction to Excel and VBA

1.1 Starting Excel, saving a file

To create a new workbook: On the File menu, click New, and then click Blank Workbook on the New Workbook task pane.

To save a workbook: On the File menu, click Save As. In the File name box, type a new name for the workbook. In the Save as type list, click a file format (if you want other than .xls) (In general, it is useful to click the right mouse button. Most of the time it will offer a menu item you really want.)

1.2 Workbook, worksheet, views, printing

1.2.1 Review

A Microsoft Excel workbook is a file that contains one or more worksheets, which you can use to organize various kinds of related information. You can enter and edit data on several worksheets simultaneously and perform calculations based on data from more than one worksheet. When you create a chart, you can place the chart on the same worksheet as its related data or on a separate chart sheet. To view and scroll independently in different parts of a worksheet, you can split a worksheet horizontally and vertically into separate panes. Splitting a worksheet into panes allows you to view different parts of the same worksheet side by side and is useful, for example, when you want to paste data between different areas of a large worksheet. To see how it will look like in print: On the View menu, click Page Break Preview. Before you do any work, make sure that you macros are allowed (security level is low) and you can save an excel spreadsheet to your own disk.

1.3 Spreadsheet basics

The difference between relative and absolute references is the key concept to understand:

Relative references A relative cell reference in a formula, such as A1, is based on the relative position of the cell that contains the formula and the cell the reference refers to. If the position of the cell that contains the formula changes, the reference is changed. If you copy the formula across rows or down columns, the reference automatically adjusts. By default, new formulas use relative references. For example, if you copy a relative reference in cell B2 to cell B3, it automatically adjusts from =A1 to =A2.

Absolute references An absolute cell reference in a formula, such as $A$1, always refer to a cell in a specific location. If the position of the cell that contains the formula changes, the absolute reference remains the same. If you copy the formula across rows or down columns, the absolute reference does not adjust. By default, new formulas use relative references, and you need to switch them to absolute references. For example, if you copy a absolute reference in cell B2 to cell B3, it stays the same in both cells $A$1.

1.4 Graphing with Excel

Import a text file Click the cell where you want to put the data from the text file. To ensure that the external data does not replace existing data, make sure that the worksheet has no data below or to the right of the cell you click. On the Data menu, point to Import External Data, and then click Import Data. In the Files of type box, click Text Files. Check out also: On the Data menu: Text to Columns.

Creating an XY (Scatter) Plot You can create a chart on its own sheet or as an embedded object on a worksheet. You can also publish a chart on a Web page. To create a chart, you must first enter the data for the chart on the worksheet. Arrange your data in columns, with x values in the first column and corresponding y values and/or bubble size values in adjacent columns. Then select that data and use the Chart Wizard to step through the process of choosing the chart type XY and the various chart options, or use the Chart toolbar to create a basic chart that you can format later. Best-fit equations may be calculated for chart data via the Add Trendline dialog. Trendline equations are displayed by checking the correct box under the Options tab Errors bars can be added to a chart by left clicking on a data series, and accessing the Format Data Series dialog box

Editing an Existing Graph Check out.

Creating Graphs with Multiple Curves Check out.

More graphs types Check out.

1.5 Numerical methods inside Excel

Goal Seek The Goal Seek dialog box can be used to solve for roots of a single equation. An initial guess is needed. Goal Seek performs calculations which improve the solution accuracy.

(c) String manipulation (d) File system

  1. Ability to control all of Excel’s features through the Microsoft Excel Objects, in- cluding

(a) Data management (b) Graphics (c) Solver (for optimization and root finding)

  1. Ability to add custom functions which can be used like ”built-in” Excel functions
  2. Capabilities allowing the development of event driven, user friendly programs through a variety of interface tools

(a) Dialog and input boxes (b) Custom user forms with spinners,checkboxes, etc. (c) Custom menus and toolbars

  1. The ability to extend the language through object oriented programming with the use of Class Modules

Example: VBA011 program (After Hahn): If a stone is thrown vertically upward with an initial speed u, its vertical displacement s after a time t has elapsed is given by a simple formula. In this formula, g is the acceleration due to gravity. Air resistance has been ignored. We would like to compute the value of s, given u and t. Note that we are not concerned here with how to derive the formula, rather we want to compute its value. The logical preparation of this program is as follows:

  1. Place the values of g, u and t into variables which can be used for calculations
  2. Compute the value of s according to the formula.
  3. Output the value of s which is the result
  4. Stop

This plan may seem trivial to you, and a waste of time writing down. Yet you would be surprised how many beginners, preferring to rush straight to the computer, try to program step 2 before step 1. It is well worth developing the mental discipline of planning your program first-if pen and paper turns you off why not use your word processor? You could even enter the plan as comment lines in the program.

Option Explicit Const g As Double = 9.81 ’ gravitational acceleration, m/s^

Sub VBA011() ’vertical motion under gravity Dim s As Double ’ vertical displacement, m Dim t As Double ’ time, s Dim u As Double ’ initial velocity, m/s

u = 30 t = 6 s = u * t - (g / 2) * t ^ 2 MsgBox "s = " & CStr(s) &" meters." ’ s is converted to a string End Sub

To make this program run do the following:

  1. From a new Excel workbook, use the Tools, Macros, Visual Basic Editor menu choice to start the VBA integrated development environment (includes editor, compiler, help and debugger).
  2. In ”Project” window of VBA, right click on your new Excel workbook (usually ”VBAProject (Book1)”) and insert a new module.
  3. Cut and paste the text of VBA011, shown in the above text box into the newly created module. Note that the ”Option Explicit” is not part of the program, but is a module option. Note the colors of comments (green), language elements (blue), and names (black).
  4. Left click to place the cursor anywhere inside the subroutine, and use the menu to choose Run, Run Sub/User Form.
  5. If you have questions on the language elements, shown in blue, place the cursor on the word and hit the F1 key.

Some remarks:

  1. VBA performs automatic syntax checking and formatting of code.
  2. The single quote character (’) denotes the beginning of a comment.
  3. In PETE 301 every module should require explicit variable typing by using ”Option Explicit” module option.
  4. The strange way of declaring g makes it a named constant, (its value cannot be changed). The fact that it is placed outside the subroutine makes it valid in the whole module (scope: module).
  5. There is no input. All needed data are hard wired into this simple subroutine. (Later we will learn how to read from the worksheets.)
  6. Output is done using a message box. Later we learn how to put results into the worksheets.
  7. This module contains only one subroutine (macro). In fact many of them can be placed into one module.

Built-in (or intrinsic) functions Visual Basic has many built-in functions. You will often need the math functions: Abs, Atn, Cos, Exp, Fix, Int, Rnd, Sgn, Sin, Sqr, Tan. Log is natural-log. If you wish ten-based logarithm, use Log(x)/Log(10).

if you wish to declare both as integer.

Numerics VBA makes a clear distinction between integer and real. Integers are used for counting things. Real numbers include a fractional part. Real numbers stored as integers are rounded to the nearest integer.

Dim n As Integer, m As Double n = 4/3 !result is 1 n = 5/3 !result is 2 n = 7/2 !result is 2 n = 5/2 !result is 4 m = 5/2 !result is 2.

You should be aware of rules regarding priorities. For instance a frequent error is to write

z = pv/RT

instead of the correct:

z = pv/(RT)

Strings To convert any other value to a string, use the Cstr intrinsic function.

Objects,input and output The structure ”With/End With” and the ”operator” point can be understood if you are familiar with the concept of object. ”ThisWorkbook” is a hierarchical object. It has several Workseets (a whole collection of them). One of them is called ”Sheet2”. The following example shows how to read a number into variable ”a” from cell ”A4” of Sheet2:

With ThisWorkbook.Worksheets("Sheet2") a =.Cells(1, 4) End With

This will output date and time into cells ”A4” and ”A5” of ”Sheet2”:

Sub VBA014() Dim d As String, t As String d = Date() ’ Intrinsic function t = Time() ’ Intrinsic function ’ Display the result With ThisWorkbook.Worksheets("Sheet2") .Cells(1, 4)= d .Cells(1, 5)= t End With End Sub

(Objects have properties and methods associated with them. For instance, when you are formatting a cell, you change some of its properties using some methods available.)

Advanced topics: Variable scope, lifetime, visibility The following key words are important: Static, Public, Private. The scope of a variable is from where it can be reached/altered. Variables declared in a procedure can be used only within the procedure (local variable for the procedure).

Variables declared on the module level can be used in the entire modul in any of the procedures within the module (global variable for the module). Static variables keep their value between two occasions of entering into their scope. In other words, their lifetime is not limited to one call. In general, a procedure-level variable looses its value between two calls, unless it is declared Static. Both module-level variables and all procedures are Public, by default, meaning that they are visible even from other modules (or even other applications.) You can make them Private, and then they are visible only within the module. We will often use module level variables (globals) to simplify engineering problem solving, when some data are needed in various parts of the program.

Advanced topics: Argument passing by Value or by Reference All arguments are passed to procedures by reference, unless you specify otherwise. This is efficient because all arguments passed by reference take the same amount of time to pass and the same amount of space (4 bytes) within a procedure regardless of the argument’s data type. (You can pass an argument by value if you include the ByVal keyword in the pro- cedure’s declaration. Arguments passed by value consume from 2 16 bytes within the procedure, depending on the argument’s data type. Larger data types take slightly longer to pass by value than smaller ones.)

Errors, Debugging and Testing Compilation errors are errors in syntax and construc- tion, like spelling mistakes, that are picked up by the compiler during compilation, the process whereby your program is translated into machine code. They are the most fre- quent type of error. The compiler prints messages, which may or may not be helpful, when it encounters such an error. Generally, there are three sorts of compiler errors:

  1. Ordinary errors-the compiler will attempt to continue compilation after one or more of these errors has occurred, e.g. ”missing End If statement”
  2. Fatal errors-the compiler will not attempt further compilation after detecting a fatal error, e.g. Program too complicated-too many strings
  3. Warnings-these are not strictly errors, but are intended to inform you that you have done something unusual which might cause problems later, e.g. ”Expression in If construct is constant” or ”variable has not been assigned a value but used”, or ”variable has not been declared” (if implicit typing is used) Some typical errors:

g = 9,81 ’ comma instead of decimal point x = 1 + (2 * 3 ’ unpaired parentheses .Cell(2,1)=5 ’ Wrong function name: Cell instead of Cells If (a=b) ’ Missing then x= Else x= End If

If a program compiles successfully, it will run. Errors occurring at this stage are called run-time errors, and are invariably fatal, i.e. the program ”crashes”. An error message, such as

  1. Floating point division by zero

Example Let in your Excel workbook, ”Sheet3” contain the following: Cells A1 and B should contain the X and Y coordinates of a point. Cells A2 and B2 should contain the X and Y coordinates of a second point. This program will read the coordinates of the two points and calculate the slope and intercept of the unique straight line defined by the two points, and output the results in a message box. These two subroutines should be contained in a brand new module within your VBA project. Because the My Line subroutine has arguments, it cannot be executed directly, like the previously discussed subroutines, by using the VBA Run menu.

Option Explicit Private Intercept As Double

Sub VBA015() Dim X1 As Double, X2 As Double, Y1 As Double, Y2 As Double Dim Slope As Double ’ Get the two points from the worksheet, "Sheet3": With ThisWorkbook.Worksheets("Sheet3") X1 = .Cells(1, 1) Y1 = .Cells(1, 2) X2 = .Cells(2, 1) Y2 = .Cells(2, 2) End With ’ Calculate the Slope and Intercept Call My_Line(X1, Y1, X2, Y2, Slope)

’ Display the result With ThisWorkbook.Worksheets("Sheet3") .Cells(3, 1)=" Slope:" .Cells(3, 2)= Slope .Cells(4, 1)= "Intercept:" .Cells(4, 2)= Intercept End With End Sub

’A subroutine used inside:

Sub My_Line(x As Double,y As Double,xx As Double,yy As Double,m As Double) m = (yy - y) / (xx - x) Intercept = y - m * x End Sub

Note: Watch for scope of the various variables! Intercept is a module level variable, but Slope is not. Intercept cannot be seen from other modules.

The If/Then/Else Decision Structure Example (after Hahn) Most banks offer differential interest rates-more for the rich, less for the poor. (The Else part may be missing and you may create more complex structure with Else If.)

If balance < 3000 Then apr = 0. Else apr = 0. End If

Loops: the heart of programming math

Countable: Do the block for i = 1, then i = 2 , etc.:

For i = 1 To 10 "block..." Next i

Count down: Do it for j = 100, then j = 90 etc.:

For i = 100 To 50 Step - block Next i

Forever: Loop forever unless ”If” stops it:

Do If "logical_expression..." Then Exit Do "block..." Loop

Condition controlled: Do while logical expression is true:

While "logical_expression..." "block..." Wend

”Select Case” structure makes your code readable Use the Select Case statement as an alternative to using ElseIf in If...Then...Else statements when comparing one expres- sion to several different values. While If...Then...Else statements can evaluate a different expression for each ElseIf statement, the Select Case statement evaluates an expression only once, at the top of the control structure.

Select Case performance Case 1 bonus = salary * 0. Case 2, 3 bonus = salary * 0. Case Is > 3 bonus = 100 Case Else bonus = 0 End Select

Arrays Arrays are declared the same way as other variables, using the Dim, Static, Private, or Public statements. The difference between scalar variables (those that aren’t arrays) and array variables is that you generally must specify the size of the array. An array whose size is specified is a fixed-size array. An array whose size can be changed while a program is running is a dynamic array. Whether an array is indexed from 0 or 1 depends on the setting of the Option Base statement. If Option Base 1 is not specified, all array indexes begin at zero.

Declaring a fixed array In the following line of code, a fixed-size array is declared as an Integer array having 10 rows and 10 columns: