Вы находитесь на странице: 1из 28
PE 3013, Computer Applications in Petroleum Engineering Spring 2009 Introduction + Computer programming is simi ‘mathematics or playing a musical instrument in the sense that you must practice in order to lear People who consistently work through the ‘examples and assignments and come for help ‘people who don", get i i 5 & Ee i z z ‘3 i é What You Need to Know + How to open Excel and save files + How to enter mathematical formulas in Excel + How to copy formulas to new cells or ranges + How to use worksheet functions (e.9., cos, sin, log, etc.) Excel Version ‘Lam assuming that you all have access to Excel 2007. This version is very different to previous versions, s0 use of older books that refer to Excel 2003 may not be helpful In this class you wil learn to develop programs that solve common Petroleum Engineering tasks. The programming language is the same in all versions of Excel Class Format + Class time willbe spit into two parts: aya. fatal of clas vl be on eo. presentation or solution a an example problem. : ene oe Ee coment ‘orintomet accase willbe allowed during exams! Class Format large percentage of your learning willbe done outside of class. Its absolutely important that you clarify any ‘doubts you have about any topic in this course as they arise, Small doubts at the beginning will lead to huge obstacles as the course progresses. (Knowledge is cumulative.) + Please come by and ask for help when you ‘need it! Most people who do are successful at the course. Approach + Leaming to program is similar to laming a foreign Luge, cal bevy ostating ab bofoning + My approach isto get you programming as quickly 38, possible, (before you completely understand what you re ing) + nial | wiglos over essential theory to get you Started then we wl renfore te theory lar as You Become more profoentin programming and tings begin fo meke more sense. + The only way you will lear to program is by practicing. Approach + There are two separate aspects to programming in VBA (Visual Basic for Applications) = Engineering programming, where we create procedures fo perform engineering computations; we ‘il spend the frst 6-8 weeks excusively on ths, spect of cwaing programs. This isthe heart of the ~ Graphical User interface (GUN) programming, where ‘we assis the user Io run the program by using Buttons, drop down boxes, fists, et to make nput and execution ofthe background engineering programs easy. We wil begin ooking at is inthe Secand haf othe semester. Text + Unfortunately, | have been unable to find any suitable text. Most VBA programming books spend one to two chapters glossing over the language ~ They tend to concentrate on the GUI aspects. + | will continue to look at texts throughout the semester, and | will try to get you some recommendations later on. Grading + Biweekly Exams: 90% (based on 6 exams) + Project: 10% (Due 4/27) Preliminary exam schedule: +123, 26,2720, 318,327, 4/10, 4724 +The last two exams willbe compuisory “tke home” exams. There wil be 8 fra (dosed Book) uz 0n 4/27. The ial grades forthe take home {xara athe project wil be determined by ‘mutiplyng the obtained grades bythe uz grade. Notes on the Project The project will be split into two parts: A fluid properties project. A pipeline project or a project related to teservoir engineering. There are lots of old projects around, and ‘you may be tempted to copy; each time | give the project, I vary the requirements slightly; if you copy someone else's project and do not meet my exact requirements, t Excel 2007 Interface + We will be writing (developing) code in VBA, and Excel 2007 provides a new interface and file format for creating and saving Excel files with built in programs. + First we will enable the “developer” tab Developer Tab Developer Tab Developer tab Other Useful Settings under Excel options R1C1 Style evar vane egg a ‘inn Trust Center (Gyo ca vata on Macro Settings Macros Introduction + A macro sa set of instructions used to automate a task ™ Simple macros maybe created using he Excel Macro Recorder ~ Can create sophisticated procedures ha ar similar {Srnacrn vnta VBR" Vioul Bai fr Appabons {Gis be te main at of te couse) + Macros can be stored in = The cunt workbook ~ Area workbook = "Personal Maco Workbook” Macro Recorder + The simplest approach to creating procedures is to use the Macro Recorder. (We will see that itis limited in its utility for more complicated applications). + The Macro Recorder records every action you perform = Plan your steps careful before recording + Before we start, we need to talk about security. Start Macro Recorder Macro Security (Developer Tab) + By default, Excel will not allow you to run ‘Macros from a workbook - the security setting is high to prevent malicious programs (Viruses) + You must change the security settings (using Excel Options->Trust Center- >Macro Settings) to make macros work + (Ifyou have not done this, go back to slides 20 and 21 before you go on.) Example Step 1 + We will record a Macro to add two + Open Excel and numbers, the first in the current selected set up two cells * cell and the second in the cell to the right with some of the current cell and place the result in arbitrary numbers the cell 3 cells fo the right of the current, += Select the 2 * cell Tefimostcel SF Step 2 Step 2 (Continued) + Be sure to select “Use relative References” + Start the Macro Recorder (with the starting cell selected) + Choose Macro Name and Location / Step 4 + Select the destination cell and type in the formula. In this example, the destination cell is and the formula is" = D4 + E4” —Press enter, and stop the macro recorder + Personal Macro Workbook — Avaliable to ern al S ‘workbooks on current machine ~ "hidden sheet” - + New Workbook must be opened to acess mac 5 eal + The Workbook — ony avaiable in current workbook i a f Step 5 How It Works + Test the Macro: Choose any other cell and type in a number and a number in the cell to the right. ~ Select the first cell ~ Click on Macros (Developer Tab) ~ Select the Macro we just recorded and run, + Save the file as an "Excel Macro-Enabled ‘Workbook’. ‘+ When the Macro recorder is on, Excel records ‘ever move we make on the sheet and every {formula we type, and stores itin a "Module" + Too see the module, choose the Visual Basic button Macro Code Macro Record Modes + "Relative" reference — Macro performed based on the location of the starting cell (the cell that is selected when we start the macro) + *Absloute” Reference ~ Macro performed on a fixed set of cells. (Calculations ALWAYS performed on Cells D4 and D5.) Note + The Maco recorder is also available under the View Tab (Macros) Personal Macro Workbook + The Personal Macro Workbook is normally hidden and is associated with a particular machine. + To make macros or programs that are portable (and that I can read and grade), ALWAYS work with the current workbook. Deleting Macros + Simply choose Macros (Developer Tab); select the macro you want to delete and hit delete. + This works UNLESS the macro is recorded in the Personal xis file. In that case you must first unhide Personal.xis by clicking Unhide under the View tab. Exercise 1 + Use the Macro Recorder to Create a Macro to convert the temperature in the current cell from °F to °C and place the answer in the cell below. + The formuta is Visual Basic Editor Access the Visual Basic Editor + You can access the Visual Basic Editor using the “Visual Basic” Button in the developer Tab, ‘or by pressing function key combination All-F11 VBE Components + Top left - Project Explorer Window ~ Displays open projects, modules, forms + Bottom left ~ Properties window ~ Displays user definable properties of the ‘object selected in the Project Explorer Window + Top right - Code Window — User editable VBA code + Other (Debugging) Windows — (not shown) VBE Components Project Security + You can prevent others from viewing your project code if you plan to redistribute the ‘worksheet = Protection tab ~ Lock project = Provide Password = Close and save Project Security + On reopening the project, the user must supply the password to view the code Useful Editor Options + For building VBA programs, the folowing settings in the VBA editor must be employed ~ Access options via Too's->Options in the VB editor Introduction to VBA Introduction + VBA (Visual Basic for Applications) is a ‘computer programming language that allows us ‘to develop code that can solve engineering problems quickly + Ineffect, we write a sequence of instructions that tell the computer how to solve the probiem. + VBA\is very similar to the more powerful VB.NET which can be used for all sorts of problems. (Designing windows programs, games, etc.) Comparison of VB (VB.NET) and VBA + VBA provides a large portion ofthe language that VB ~ Code forthe languages is almost identical + VBA runs within the host application (Excel) ~ Always need Excel asa host; can never run as a “stand alone" application ~ Interpreted language; code can never be as fast as. for compled language + (You wi be asked to program in VB forthe Ding | course.) + Microsoft seems to be moving more to VB.NET ints (ce applications Introduction to Data Types + A ‘data type" refers to how VBA stores data in memory + Excel does not require you to specify the data type of a “variable”; VBA can automatically ‘determine it for you, but this slows down the ‘program execution — For his cass we wil aways declare data types of "Variables" explicit ~ (we actualy tok car ofthis on slide 48), ~ (A*vatiable”is ikea box wth a label that contains data) Data Size + The size of a data type refers to the number of bytes it takes to store it A byte is a group of bits A bitis the smallest storage unit either zero or one) + Keeping the number of bytes required to store data in memory low wil allow you to maximize computer memory resources Common Data Types caer tage om ee Epnaaree aa : viaite = 8 * png. Integer witha range of values from “2147483648 to 2147483647 Example: Dim visits as Long Note: Assignment Operator “=" + In VBA (an all programming tnguages), the mesning of {he assignment operator) is ferent rom the ‘mathematical equal sign. + The statement visite = 6 i inerpreted as “assign the value 6 othe integer variable sits” wate enng tft en a? Common Data Types ¥ Single ~ floating point number with values in the range -3.402823E38 to -1.401298E-45 for negative numbers and 1.401298E-45 to 3,402823E38 for positive numbers Example: Dim pressure as Single Y Double ~ floating point number with values in the range -1,79769313486232E308 to -4.94065645841247E-324 for negative numbers ‘and 4,94065645841247e-324 to 1.79769313486232E308 for positive numbers Example: Dim pressure as Double Common Data Types ¥ Boolean - variable can be either True or False ~ Example: Dim stressed as Boolean * ~ Example: stressed = true = Note: do not put quotes around True or False + Variant ~ Excel “catch all data type. ifa variable is not declared beforehand, Excel will ‘automatically create the variable as Variant. ~ This is inficent since the actual datatype must be determined at run time = Inthis class, ALL variables must be explcity typed before being used. Common Data Types ¥ String — variable that stores a sequence of characters. Can be fixed or variable in length ~Fixed: Dim Fixedstring as String = 25 + Can oy store 25 characters Variable: Dim Variablestring as string * Canhold up to2 bition characters sVariablestring = "This is a test” More on Variables + Avariable is a user-defined storage space + Variable names can be any combination of characters and numbers as long as the first letter is alphabetic, = You cannot use spaces as pat ofthe name ~ YBA is case ingensive, so the variables ONE, “One and “one are ena! *+ You should make your variable names descriptive so that you can easy folow your ie = E.g: use “pressure” instead of fora variable Variable Declaration + Use mae sig pomanmicg ngage Se slave Yuluevarabeowa aang en ee meen iyi enna ty ~The atta elect at ase : Rechunecenemcecetomneite - gigi moines = Uae prion Sep ots ase etna each noc. (Sheuisos erat wine stings we have cose) Variable Declaration + When we “declare vaabe, we tll VBA tat we are going to-stor some value in hie named leeaton + Format fr variable declaration is = Din Vartabletane As Type = Where the acta nar and type are subettes + You can deciare tpl variable ina sng statement such osm at As intes Integer = Noe: Dim AL, A2, A3 As Integer wit not work conty AS willbe an Iioger. At and A2 wile of ype Varant = nVBoin Ai, A2, AB As Integer wilereate at Intogers. * A As Integer, AS As Procedures * rept ttt ene att cont at pero Tt acenin sonra yore Stee, em “ree ees Sea + Apocadgeic a conerare th you go Eset pean some + Aneto but Excl prooadires z20) Fis al ens atta unter 1234 + Wiewabe wing vst poesars compete common Petoiun iow ao Procedures + Two types of procedure: = Function = Subroutine + The only difference is that Functions return a value, while subroutines do not. (We wil focus ‘on Functions first) + Areva of bul in Exe fncon opt) logy in Goa we ae cana the Beta Macon ig withthe contents ofc "Ai the function operates on the contents of cell A1, and retums the answer to the cell where ‘we began typing, Procedures + All procedures consist of a name (e.9., "log", followed by brackets that may contain one or more values (separated by commas) that are passed to the procedure. These values are called “arguments”. Arguments pass information to (and/or from) the procedure. + Some procedures take no arguments; e.g the excel procedure pi() takes no arguments and returns the value of n. Functions General form “newest Taste i Poy} + Example + Function to add two floating point numbers. conn Pcmtane_wt_yp sou taacatarin Procedures + Procedures can have any name as long as it ‘begins with a letler and does not conflict with Excel naming —E.g. A function named A3 is not alowed, since A3 refers fo an Excel cell (Variables can be named A3, but not procedures) + Subroutines cannot be called directly from a Work sheet, We wil tak more about them later. + Note: Aways wie engineering functions in a User Procedures User Procedures User Procedures Arithmetic Operators 7 Rae Be RE BASS Fe ORS PRESTR fexoonert Foressrsie, 3 6 eges « rib 7] ideo rarer vasa i i ama Forexamgle, SUGD 2+ [ds tro roel were = [biterenees ws rote sxprearane Exercises + Wfite a function *CircleArea” that takes the diameter as a single argument and returns the area, + Write a function “RectanglePerimeter’ that takes. the lengths of the short and long sides of a rectangle and returns the perimeter. + Wie a function “Hypotenuse” that computes the length ofthe long side ofa right angled triangle, given the lengths of the other two sides using Pythagoras’ theorem Constants + Constants have defined values that cannot be changed during the running of a program. - Example: ‘const £t2_per_bbl As Double = 5.6146 — Use the above constant fo convert a number Comparison Operators arin prea sa 5 itermines tet expression gral an S00ond =| Beharmines @ ea expression sos han he scan supesson Deters expose aera eau SS [Deterines ffs expressions ret an or ual in barrels to cubic feet P=] Bene het Opa Ran oo Conn fp th Bae = S46 second excision Logical Operators Comments aut we abe orca wae reba nasa an Tae’ ba opencn Fubar (| itoreerenis te mad onentnNematie + You can add comments to your code by inserting an apostrophe; everything from the apostrophe to the end of the line will be ignored. Exercise + The folowing expressions a polynomial approximations to cos(x), where the angle xis in radians and 0 < xs 2. ofa) = 1 - 04967022 + 0.037054 + Wit a function to evaluate the appraximation (note: you Cannot name your function “cos" because tis isthe ‘name of the bul in function ) + White @ second function that retums the difference Setwaen he approxaton andthe bitin Excel Exercise + Amore accurate approximation to cos(s is siven by: cen) = 1 = 0499999996312 + 0.0165655418<4 = 000138883971 + 00002476084 - 000000260521 + White function to compute this approximation + Write a second function to return the difference ‘between this approximation and the Excel function More on Excel Programming Control Structures + VBA provides several structures for conditionally controlling the flow of a procedure. + In this section we will explore the more ‘common flow controls, Conditional Execution + Yatenamnaoray cana pp tenet ag ef Thee Example + The mathematical statement ity <2 Sity=2 sity>2 + ts programmed as: Example - Vazquez correlation for Solution GOR, R, and B, + The Vazquez correlation starts by calculating a “standardized” gas gravity, which isthe gravity of the gas occuring at 114.7 psia given by, aft tavosmntenirg ued 2a, 1s gravity measured at separator conltons erator pressure, pia Tap Separator temperature, °F Vasquez correlation, API < 30° * Solution gas-oil ratio and bubble point pressure a ra apna Vasquez correlation, API > 30° + Solution gas-oil ratio and bubble point pressure peleene gw afin Vasquez correlation, API < 30° * Oil formation volume factor below bubble point A=1064677 Rxl0*s0R7St«10" D-L 8106x104", D Vasquez correlation, API > 30° + Oil formation volume factor below bubble point 2.100461 Rxt0*40.1010* DoBEITs10*R,D + Correct bubble point B, to values above bubble point using oil compressibility Example (Hand Calculation) + Estimate R, and B, using the Vasquez correlation for a 40.7 °API stock-tank oil at 2685 psia and 220 °F. The actual solution gas-oil ratio is 768 scl/STB, and the gas gravity is 0.786. Assume that separator pressure is 100 psig. Solution + Standardized gas gravity Ye 21.94 Ta «104039120407 7, Yyaey = 0.786 + Solution gas-oil ratio APL___ 40.7 “+460” 220+ 460 Solution * Solution gas-oll ratio (0.786}2685)"™ usmss - 601 st a CET 0 91500578 + Oil formation volume factor Solution Oil formation volume factor — Using estimated R, 1.06467 (61)<10* +0111» 10~ (24s) 0.133710 (691) (283 = 1anisbousTe Using actual R, 191.0467 (68)s10" +0,11s10~ (285) 0.133710" (68) (285 14585 BOLSTB Exercise + Complete programming of the Vazquez and Beggs Correlations + (See Word Document on Vazquez-Beggs) Debugging Error Types + Inwriting code, you will inevitably make errors. Errors can be of four basic types: Design: caused by mistyping code — e.g. leaving out a parenthesis; these are detected immediately in the VBE if"Auto Syntax Check’ is enabled under VBE Tools->Options Compile: before each ine of code is ‘executed it must be compiled; any compilation errors will be highlighted and described at this stage Error Types Runtime: Occur during execution of a program; e.g, division by zero, Excel issues {an error message which either must be handled or causes the program to stop Logical: errors in the logic of implementing the procedure, These are usually the most difficult to find. Here the debugger is most useful Inserting Breakpoints + With the cursor at the line in the VBE where you want to halt code execution, right click ‘and select ‘toggle breakpoint” + Repeat at as many lines as you want + To see the values of Viewing Variables the variables in the Debug Toolbar + Make the debug toolbar visible (itis module while the ‘not by selecting code is executing, View->Toolbars- choose View-> Locals >Debug Window ~ You can use tis to cenit he execution of your program Watch Expressions Adding a Watch ‘You can use watch expressions to ‘monitor the values of expressions as you tep through the code “This is good for tracing through a program to find where the unexpected value occurs + Right click in the watch window to add a watch Insert the Watch expression Execute in Steps + You can step through the code using the “step cover” or ‘step into” debugging buttons Execute a task while a condition is true + The Do While Loop structure provides a way of repeating a procedure until a condition is no longer valid. + Format nam D2 WBiLE Condition sae Yeiweon —- Instructions ‘ise = (Exit Do) veers oop ™ Pre on ed Perform multiple tasks until a condition is met + The Do Until Loop structure provides another way of repeating a procedure until a condition is met. + Format o Untii Condition , Instructions a (exit Do) Loop Execute Tasks a specific number of times + The For ... Next structure provides a way of repeating a procedure a fixed number of times + Format Notes on Loops + In engineering programming, loops are found in the following situations: + Computation of Sums + Computation of products + Iterative solutions + In association with arrays Sums + Sums can be finite or infinite. For example, the finite sum Hen) = De VBA as follows. Example Code te incager) aa Downe a hs Sums ‘Similarly, the infinite sum S2)=De, forzet is truncated when tee ‘where «is a small tolerance. (Note that this only works ifx <1) ‘We will do this together as an example in class Using the MsgBox function + This is actually a GUI function, but | wil allow its use in Engineering code. + The MsgBox function is used to pop up message boxes when a VBA procedure executes. (See \VBA help on MsgBox Function) + Has 2 functions: = It displays a dialog box to provide the user with information Itreturns a value that provides the user response MsgBox return values [weox [ok ttn press Fwecancat | Cane! bts reed fwenbort [Abort bt reed fbRetey | Rery buon peed Products + Products are similar to sums. An example is the computation of, Note velo ndeatogt . fwotgnors | soe bats rose + which we can implement as follows: joven | Yerbtor esl [ste —[Notaton sd Example Code Exercises + Evaluate a1 ly For x > 1 (For x = 5, n = 20, result = 1.25) + Evaluate: 21 ly + Forx> 1 (Forx= 7, result = 1.166666) Exercises + Evaluate . IL x + Forx= 1.2, n= 10, resultis 22644,80225 + (Note: this function grows rapidly, so keep x and n small or Excel will overflow!) Debugging Example + One way of computing the value of x is by ‘computing it from the following formula: bes + Use the debugger to find the error(s) in the code Code stapes detente Fatt Arrays + An array is a collection of related variables that are denoted by a single variable name and an index + For example, consider the polynomial: 2x 45x? —3x! +2x° + The numbers 2, 5, -3 and 2 are all coefficients of descending powers of x + Itis convenient to represent them as a single subscripted variable Arrays + In Mathematics we might write the polynomial as ax +a? +43! +ax"= Sax! + With ap = 2, a = 3,45, a,=2 + In VBA we can declare an ARRAY “a” containing 4 elements as Dina ose Arrays + We could assign values to the array “a” using subscripted variables as + We could then use the values in a procedure; for example Arrays + Unfortunately, we cannot call functions that take arrays as arguments directly from a worksheet. ‘We will discuss how to use arrays and functions that take arrays as arguments more later. (We need to talk a little about GUI's first.) Exercise + The value of canbe called using the formula + Wit a function MyPi that sums a fed number of terms Inthe senes to return an approximate value of Le. he Prope sou amo ag + Wie a secon function MyPi2 that computes the sum nut jl where is 2 User provided tolerance; eg. Exercise + fava onen cmon er 660) sorsaievasmeinitagr oo Sera ara ett es ae = (ies re oncay mar canetwnet Eimecaeare emery _qiiahnserbananre dopa ape + Fai oco anny cso: 1 frci isig feoemars Exercise simple way of numerically integrating a function in ‘one dimension is the trapezoidal rl, which spits the integration region into ‘sips. The sum of he areas of ‘he strips ves an approximation to the integra, Le. free =f A320 Ee + wt pogam eae faire + ing apr ie, Subroutines and Functions Subroutines ‘+ Subroutines get information from an external ‘source and returns other information through the argument list. + For example, a subroutine to compute gas Critical properties might look lke + Here SG = Gas Specie Gravity (an input) ‘Te= Gas Pseudocrtcal Temperature (an output) c= gas Pseudocrtcal Pressure (an ouput) + Note: There ie no retum value, Soubroutines + The call to the subroutine might be + Note: the names of the arguments in the call do not have to match the names in the subroutine. + The variables are identified by their positions in the arqument list Subroutines + The variables in the argument ist must be defined for our example, the caling Foutne should have the folowing variables declared before te subroutine call, + Any additional variables that must be used in the body of the subroutine for calculating the factor must be Function ftom the ments Iterative solutions This s the most common type of problem that we will encounter. In general takes the frm (eau) ‘and we stop when we ~ Al < © Iterative Solutions + For this type of problem, we must have a first estimate of the solution; + Sometimes this is provided by the user, other times, we have a good method of estimating a frst guess. (For example, in the 2factor routines, 2 good first guess of z-factoris 1) Iterative Solutions ‘The ypeal cp wlekias Application — z factor determination using Newton's Method Tart nie conn wh ease ne, we Newton's Method Examples + Iterative method for 5 as a guess to find the root determining the zero 1 (0F root) of a function . ~ Sart yexe'-1 reasonable guess of hesalsionsy + Use x = 10 as a guess to find the root some = Alfa) of ® 215 sce fix)e0 y=in(2)-3 Hall-Yarborough z-Factor + Z factor determined from 20051257 rex9{-120-1 = 0ostasrsent 126-7)” ~T,= reduced temperature = 1/7, ~P, = reduced pressure = pp, —y solves fy) =0 Hall-Yarborough z-Factor function Soy=atbeetde 0.06125 P,# exg-12 (1.07) Goth) 41) y+ Lily? c= (458 1-9.76) 14 14.76) 097 dm (and 1—2422)r49021 y 28 Hall-Yarborough z-Factor function + Solve using Newton's Method = n= n-POO/F'O0 + Derivative function Poynarbre a=((Q-4) yt A)yeA)y+ LML= Vt == (.161~1952)122952)19 o> (218+ 2429 (424 4-2022)14907) nyimne Hall-Yarborough z-Factor function solution + Need 1* guess of the value of y + Setz=1 in 06125 Frexpl-1.26. ay y Project + Write a function HallYarboroughZ that ‘computes z-factor given values of 7,and P, PseudoCritical Properties + The most common correlation for ‘computing natural gas pseudocritical properties is due to Sutton: = T.= 1092 + (3495-74 1) 7 = P,=756.8-(131 +36) + Write a subroutine SuttonTcPc to compute and return values of pseudocritical pressure and temperature = Public Sub SuttonfcPc(Gamma as Single, Pe as Single, Te as Singie) Acid Gas Correction + The Wichert and Aziz acid gas correction to the pseudocritical properties to account for the presence of HS and CO, is based ‘on the mole fractions of these gases in the micture. + The procedure for computing the correction is given in the following slide Acid Correction Equations ‘co, + Yas D= Pus ~ Veo) = 120(8"-S'*)+15D; Project + Write a subroutine AcidGasCorrection that computes the corrected pseudocritical properties, Project + Putitall together Create a worksheet called GasPropertes ~ Aad ool or input of temperature, pressure, cas wy, moe Fractons of #5 and CO, | Coks for output of gas gravity and density — Add a button to compute the properties = On eckng the btn: ‘Comput tal ropes + Comput ac gas comacton(recessey) 1 Campus focor * Compute densty « Dranchuk and Abu-Kassem z- Implicit Equation + The equation is implicit in z and must be solved using Newton's method 2wAalel —Avet ihreok aul) Jeo factor correlation + o am ae abate ” “0 “ The Derivative Definitions + The derivative function for use in Newton's + Reduced density method is 027 Pa reve Ty abe Zed sa tas + Derivative of reduced density Me Pe Coefficients Project + Program the Dranchuk and Abu Kassem z-factor correlation + For the moment, use a button to calculate this z-factor; ie., your spreadsheet will now have 1 ‘botton for the Hall-Yarborough z-factor and another for the Dranchuk and ‘Abu Kassem z-factor correlation = Later we will use a “ComboBox’ to select the Correlation we wish to use, Gas Viscosity + The most common correlation for natural . gas viscosity in the petroleum industry is due to Lee et al + Uses the following formulas 10° *K exp(Xpy] y= 2.4- 0.2K (94+ 0.0za4) ri 986 TerwsT | X=35+286+001M Lee et al Correlation + Tis temperature in °R, Mis molecular weight of gas (= gas Specific gravity x My: Molecular weight of air = 28.97); and p, is the gas density in gmicm®. - P Pg = 0.08337 Fr Lucas Gas Viscosity + An alternative correlation for computing gas viscosity is due to Lucas. + Formulas: seone{ivsl) Lucas Viscosity __000124seaps. 1767; a 7 0.4489 ex9(3.05767,7™ a= a(.65537,-1.273) = F _ 1. T368exp(2.2317,7**" T, sHasemf-0.8sar) Lucas Viscosity Gig. = 080772" -0.35Texp(-0.449T,)+ O.34exp(-4.0587,)+0018 ¢=9490 a Fe) Project + Complete your basic gas property sheet by including ~Gas Viscosites ~ Gas density (bmicu. f) Gas formation volume factor (bbv/scf) ~ Gas gravitational gradient (psi) Execute Code on Opening Sheet + Code can be executed automatically on ‘opening a workbook by placing a subroutine called — Private Sub Workbook_Open() + In the "ThisWorkbook” module. + This is valuable for initializing a worksheet; e4g., setting up items in a "ComboBox". + Acomboboxis a drop down list that offers. the user a choice of atemative tems + You can chose a cae cea ‘ComboBox from the a i design toolbar, and ==" | drop it onto your worksheet parang Initialize the ComboBox Example + You can initialize items in the ComboBox list using the ComboBox's Additem Property when the sheet is first opened. + See CombotoxExample xs + Initialize the ComboBox Gn This WorkBook) + Option Expat ~ Pate sun wonaeok Open) “inti the Comboton shea Hetobox Adder le Gveyone”stnden =O Shes Hetobox Adem visto Daly” stndox= 1 Shea! Hetobax Adam elo Lesle™ etn = Shea HelnGoe ister =2 The CommandButton \Wiite the following code for the Command Button = Privale Sub CommandButtont_Cick) if Sheett Helloox Listindex= 0 Then ‘MsgBox (Helio Everyone?) Eset Sheett Helloox Listindex= 1 Then MsgBox (Hello Doi Eee Sheett HelloBoxListindex = 2 Then MsgBox (Hello Leslie") End if End Sub Project + You now have two routines for calculating the z-factor and viscosity: Add ‘ComboBoxes for the user to choose which correlations he would lke to use. + Aliso include the possibilty of assuming an ideal gas (where z = 1)

Вам также может понравиться