ERTH2020 Introduction to Geophysics

Similar documents
ERTH3021 Exploration and Mining Geophysics

1 Introduction. 2 Useful linear algebra (reprise) Introduction to MATLAB Reading. Spencer and Ware (2008), secs. 1-7, 9-9.3,

Scientific Computing: Lecture 1

3 Introduction to MATLAB

Geophysics 224 B2. Gravity anomalies of some simple shapes. B2.1 Buried sphere

Scientific Computing using Python

Getting Started with MATLAB

Computational Programming with Python

MATLAB INTRODUCTION. Matlab can be used interactively as a super hand calculator, or, more powerfully, run using scripts (i.e., programs).

MATH STUDENT BOOK. 12th Grade Unit 4

Introduction to MATLAB Practical 1

(Ca...

Introduction to Python Practical 1

CITS2401 Computer Analysis & Visualisation

An Introduction to Maple and Maplets for Calculus

MEI Desmos Tasks for AS Pure

A quick Matlab tutorial

Dr Richard Greenaway

Working Environment : Python #1

Name: Dr. Fritz Wilhelm Lab 1, Presentation of lab reports Page # 1 of 7 5/17/2012 Physics 120 Section: ####

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Lab 1 Intro to MATLAB and FreeMat

0 Graphical Analysis Use of Excel

Laboratory 1 Octave Tutorial

CSI Lab 02. Tuesday, January 21st

Lab1: Use of Word and Excel

The value of f(t) at t = 0 is the first element of the vector and is obtained by

Get It Interpreter Scripts Arrays. Basic Python. K. Cooper 1. 1 Department of Mathematics. Washington State University. Basics

Math 2250 Lab #3: Landing on Target

Computer Lab 1: Introduction to Python

MS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing

Matlab Tutorial and Exercises for COMP61021

How to learn MATLAB? Some predefined variables

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

Computer Science 102. Into to Computational Modeling Special Topics: Programming in Matlab

COSC 490 Computational Topology

Lecture 1. Course Overview, Python Basics

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

f( x ), or a solution to the equation f( x) 0. You are already familiar with ways of solving

A/D Converter. Sampling. Figure 1.1: Block Diagram of a DSP System

AMS 27L LAB #2 Winter 2009

Pre-Lab Excel Problem

Introduction to Scientific Computing with Matlab

Lab1: Communicating science

ENCM 339 Fall 2017 Lecture Section 01 Lab 9 for the Week of November 20

New Mexico Tech Hyd 510

Goals: Course Unit: Describing Moving Objects Different Ways of Representing Functions Vector-valued Functions, or Parametric Curves

Physics 251 Laboratory Introduction to Spreadsheets

Lecture 1. Course Overview, Python Basics

Introduction to MATLAB

Laboratory 1 Introduction to MATLAB for Signals and Systems

MATLAB TUTORIAL WORKSHEET

The Bisection Method versus Newton s Method in Maple (Classic Version for Windows)

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.

Research Computing with Python, Lecture 1

MATLAB Tutorial III Variables, Files, Advanced Plotting

MAT 275 Laboratory 1 Introduction to MATLAB

Molecular Statistics Exercise 1. As was shown to you this morning, the interactive python shell can add, subtract, multiply and divide numbers.

Symbols. Anscombe s quartet, antiderivative, 200. bar charts for exercise, for expenses, Barnsley fern, drawing,

1 Introduction to Matlab

Dynamics and Vibrations Mupad tutorial

Models for Nurses: Quadratic Model ( ) Linear Model Dx ( ) x Models for Doctors:

Introduction to Python Part 2

User-Defined Function

Introduction to Python for Scientific Computing

Introduction to Finite Element Modelling in Geosciences: Introduction to MATLAB

FIND RECTANGULAR COORDINATES FROM POLAR COORDINATES CALCULATOR

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

Week - 01 Lecture - 04 Downloading and installing Python

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Writing MATLAB Programs

Here is the data collected.

Handout: Handy Computer Tools

3.4 System Dynamics Tool: Nova Tutorial 2. Introduction to Computational Science: Modeling and Simulation for the Sciences

Programming with Python

Class #15: Experiment Introduction to Matlab

Introduction to MATLAB

Introduction to Matlab

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

Python Programming. Hans-Petter Halvorsen.

LAB 2: DATA FILTERING AND NOISE REDUCTION

Output Primitives Lecture: 4. Lecture 4

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

Administrivia. Next Monday is Thanksgiving holiday. Tuesday and Wednesday the lab will be open for make-up labs. Lecture as usual on Thursday.

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

Week Two. Arrays, packages, and writing programs

MEI GeoGebra Tasks for AS Pure

Choose the file menu, and select Open. Input to be typed at the Maple prompt. Output from Maple. An important tip.

Math Day 2 Programming: How to make computers do math for you

Introduction to Python and NumPy I

Chapter P Preparation for Calculus

Lagrange Multipliers and Problem Formulation

You are currently enrolled in IB Math SL for the Fall of This course will prepare you for the IB Math SL Exam in May of 2019.

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:

CITS2401 Computer Analysis & Visualisation

Introduction. What is Maple? How to use this tutorial. Where can I find Maple?

GG450 4/5/2010. Today s material comes from p and in the text book. Please read and understand all of this material!

Dr. Del's Tiers 1 6 Syllabus

Use Geometry Expressions to create and graph functions, and constrain points to functions.

Transcription:

ERTH2020 Practical:: Introduction to Python Page 1 ERTH2020 Introduction to Geophysics 2018 Practical 1: Introduction to scientific programming using Python, and revision of basic mathematics Purposes To introduce simple programming skills using the popular Python language. To provide analysis tools for use in subsequent practicals. To encourage revision of basic mathematical ideas (algebra, trig, calculus) Report Required Exercises 1-7 are intended to guide you through introductory Python concepts. It is assumed that you are reasonably familiar with this material from the prerequisites for this course. No reporting is required for these parts. Your submitted report will concisely cover Exercises 8,9,10. Include your worked answers to mathematical elements, python code and output plots. Mathematical answers can be hand written. Mathematical Revision This practical provides a computational partner to ERTH2020 Tutorial 1 Basic Maths Revision. Two of the questions from that tutorial are repeated here and are to be included in this practical report.

ERTH2020 Practical:: Introduction to Python Page 2 Programming languages Most students will have had some experience with the concept of programming, via programmable calculators, or using the formula tool in Excel. These are useful for very simple tasks, but for realworld data handling more complete tools are needed. In geophysical modelling and data handling, several languages are currently being used, including: Fortran: Excellent for mathematical algorithms, easy to write and understand, produces 'fastest' code, huge archive of freely available code. Excellent open source versions available. C: Very powerful for low-level instrumental control, also widely used for algorithmic work, slightly more difficult to write, excellent general purpose language. Open Source available. C++ An update of 'C'. More powerful, but more difficult to learn, write and maintain. Matlab: Higher-level, hence excellent for rapid prototyping, but arguably less flexible and lower performance. Generally not used for production systems. Proprietary. Python: A modern, easy-to-use language with a rapidly growing support base. More detail below. Why use Python Very easy to learn, use and maintain Open-source Concise (fewer lines of code to do tasks) - economical to write and maintain High-level, very rapid development Good tools to link in existing Fortran or C code Excellent for User Interfaces and graphics. Python Versions As of 2018 there are two main version of Python in widespread use (Python 2.7 and Python 3.6). The differences are fairly minor, but code is not generally interchangeable. Some of the plotting tools we use are not yet stable in Python 3.6. Hence in this course we will use Python 2.7 Python Download URLs (if you want to install on your computer) The core Python language is freely available from http://www.python.org/downloads/ This is the core distribution supporting most general purpose programming needs. However, there are three add-ons which are needed for our more specialised work. These are matplotlib, numpy and scipy, which are all freely available. As of 2018, one of the most convenient distributions which includes all these packages appears to be Anaconda, which is freely available at: https://www.anaconda.com/download/ You can download for Windows, MAC, or Linux. You can install either Python 2.7 or Python 3.x (or both.)

ERTH2020 Practical:: Introduction to Python Page 3 Python Tutorials We will outline all that we need in class. However, there are several good tutorials on the web if you want to go further. http://www.sthurlow.com/python/ A good intro for beginners https://docs.python.org/2/tutorial/ Python. the definitive tutorial by Guido van Rossum, the inventor of Note that in this course we adopt a programming approach which is relatively simple, but which allows you to do most of what is commonly needed in scientific computing. As you gain more experience Python allows you to explore more advanced approaches if you want to (e.g. NUMPY vector programming, object orientation etc.) Note on subtle differences between different python installs You may find differences between the interface on the UQ lab computers and other Python distributions. For uniformity we will use the standard IDLE interface, which is available on lab computers and also in Anaconda. Note on File Extensions In serious computational work, it is very useful to use the file extension to identify files of a particular type. For example, we will use the extension.py to signify a file which holds python code. Before proceeding ensure that your PC is configured so that it does NOT hide file extensions. This is important. Getting up and running in UQ Labs (Room 221/222) (Instructions for 2018) Log into windows Click on the window symbol at bottom left of the screen Type idle to search for the required program Select idle (Python GUI) You will get the Python interpreter prompt >>> You will also see confirmation that it is Version 2.7.12

ERTH2020 Practical:: Introduction to Python Page 4 Exercise 1: Using the Python Interpreter as a calculator As a starting point, we will work directly with the Python Interpreter. This is very useful for understanding how individual Python statements are interpreted. Start up the Python IDLE interpreter as described at bottom of Page 3 On IDLE, you will see the Python interpreter prompt >>> In the following, italics are used to indicate what you should type in after the prompt (>>>) (a) Try typing some simple mathematical expressions, such as: 4 + 5 3.7 * 1.2 23.4 * 17 + 19.5 23.4 * (17 + 19.5) 3 / 2 (what is going on here!). Note that this convention has changed in Python 3. 3.0 /2 (b) Experiment with spaces, brackets, minus signs etc. Does the interpreter behave as expected? (c) Experiment with some simple algebra, such as: a = 10.0 b = 20.0 a + b c= a+b c d=a**2+b**2+c**2 D what happens and why?

ERTH2020 Practical:: Introduction to Python Page 5 Exercise 2: Importing modules into the Interpreter - mathematical functions (a) Experiment with some mathematical functions. sin (0) log (100.0) x=pi/2 what happens and why? (b) Now tell the interpreter to load the maths module and experiment further. from math import sin, pi, log sin (0) sin 0 note that you need the brackets in a function sin (90) what happens and why? sin(pi/2) python needs angles in radians. Python knows about pi log(100) assumes natural log log10(100) special function for base 10 log(100,e) more general usage. See what happens when you stop typing after the '(' log(100,10) dir() shows you what names and functions you currently have available Exercise 3: Experimenting with useful control functions (a) Experiment with the range function, noting in particular, the behaviour of the 'end' point. range(1,10) range(1,10,2) produces a list of integers, but excludes the 'end' point increment other than 1 is allowed. (b) Experiment with the multi-line 'for' statement. for i in range(0,5): print i, 'squared is', i**2 note the colon note the indentation - very important note quotes and commas in print statement (c) Experiment with the multi-line 'if' statement. x=5 if x>0: print 'x is greater than zero' note the indentation. Try again but with x = -3

ERTH2020 Practical:: Introduction to Python Page 6 Exercise 4: Python Program sinwave1.py Now that we understand how the interpreter works, we can try some more interesting exercises. We will want to save our efforts, and the way we do this is to put all our commands into a file. From the IDLE Shell, click on file, new window. Immediately Save as sinwave1.py, in a sensible directory of your own. Note that the.py extension tells the editor that we are typing a python program, and we will immediately get nice colours etc. (Note as discussed previously we are assuming you are NOT hiding file extensions if you are you'll get into serious confusion about now.) Then enter the following code and save. program sinwave1.py compute a sinwave for i in range(0,91,1): theta = i * pi / 180.0 print 'sin', i, 'is ', sin (theta) step through angle in degrees convert to radians Click on Run, Run Module and see what happens. Fix your program by adding an import command and rerun. Exercise 5: Python Program sinwave2.py- Introducing Arrays Start with your sinwave1.py program, and do a save as sinwave2.py This will do exactly the same thing, but now we are using arrays, which will make it easier when we come to plotting. program sinwave2.py compute sin wave using arrays from math import pi, sin from numpy import zeros sinwave = zeros (1000, float) for i in range(0,91,1): theta = i * pi / 180.0 sinwave[i] = sin(theta) print 'sin', i, 'is ', sinwave[i] load general maths tools load array tools set up a numpy array for answers step through angle in degrees convert to radians

ERTH2020 Practical:: Introduction to Python Page 7 Exercise 6: Python Program sincos.py - Introducing Plotting Do a save-as on your previous code, and modify it to make a new program We ll call it sincos.py program sincos.py compute and plot sin and cos waves using arrays from math import sin, cos, pi load general maths tools from numpy import zeros load array tools from pylab import plot, title, xlabel, ylabel, legend, show plotting tools sinwave = zeros (91, float) set up arrays for answers coswave = zeros (91,float) for i in range(0,91,1): step through angle in degrees theta = i * pi / 180.0 convert to radians sinwave[i] = sin(theta) coswave[i]=cos(theta) print 'Angle:', i, 'Sin:', sinwave[i], 'Cos:', coswave[i] plot (sinwave, label='sin') Now plot the functions plot (coswave, label='cos') title('trig Function Plot') xlabel('angle (deg)') ylabel('function') legend() show() Note: The following four exercises are to be submitted. They will be due on Tuesday in Week 3. To ensure maximum marks, make sure you answer everything that is asked. By the end of Exercise 10 you'll be a competent Python programmer. Exercise 7: The plotting mechanism in Exercise 6 is limited in that the 'degrees axis' can only handle positive latitudes, and unit increments. Improve the program to plot from -90.0 to 90.0 degrees at an increment of 0.1 degrees. One way to achieve this is to introduce a new array for the latitude. This then requires a slightly different plot command of the form: plot(latitude, sinwave, label='sin') One mechanism to handle this type of double sided plotting (-90.0 to 90.0) is given in Exercise 10. From now on we will normally use two arrays whenever we do xy type plots. This allows us to handle increments other than 1 on the x axis.

ERTH2020 Practical:: Introduction to Python Page 8 Exercise 8: Beach Problem A Note: This question and the following one are repeated from Tutorial 1. They provide good revision of several mathematical ideas, as well as practice in Python. We will do the programming elements in our practical class. In your report include all elements. Maths can be hand written. I have arrived at the gate to the beach (Point G on the accompanying plan-view diagram) and I want to walk to Point S, 100m along the beach, where the surf looks good. On the soft sand I can walk at 2.5 km/hr. On the hard sand (right at the waters edge) I can walk at 5 km/hr. I want to get to the surf as quickly as possible! 100 m Water S P x Hard sand (vh=5km/hr) 50m Soft sand (vs=2.5km/hr) Fence G (i) Use calculus to show that the take-off direction ( ) which will give the shortest possible time is approximately 30 degrees, and that the time taken is then approximately 134.4 seconds. [Method 1: Express the total time as a function of x, minimise with respect to x, and finally find (ii) Repeat Part (i) but now derive your time equation directly as a function of and then differentiate with respect to (iii) Use a numerical approach to confirm your optimum value. [ Method: Using Python plot the total time from G to P to S as a function of Read off the optimum value, and the corresponding travel time.] (iv) Which approach (analytical or numerical) do you prefer and why?

ERTH2020 Practical:: Introduction to Python Page 9 Exercise 9: Beach Problem B The following weekend, I visit the same location at low tide, such that the water is now 50m further out. I now have to walk obliquely across the hard sand to get to the surf. Surf S 100 m Hard sand (vh=5km/hr) 50m P x Soft sand (vs=2.5 km/hr) Fence G 50m (i) Use a numerical approach to show that the take-off direction ( ) which will give the shortest time along the path GPS is approximately 24.8 degrees. Show that the corresponding shortest time is about 145.4s. (ii) Using calculus (method from 8(i)) show that the x value corresponding to this optimum path satisfies the following 4th order equation. 18.75 x 4 3750 x 3 + 234375 x 2 + 3125000 x 156250000 = 0 (Depending on how you handle the problem you may get an equation which is just a multiple of this one. That is OK since the RHS is zero.) (iii) Plot the polynomial in (ii) as a function of x (use Python). Show that the polynomial has a root at x = 23.09m. Hence show that the corresponding travel time and takeoff direction agree with your numerical solution in Part (i) (iv) Use the Wolfram Alpha website to confirm the root of your polynomial in (ii) (v) The increased complexity of Exercise 9 compared to Exercise 8 means that the numerical approach is probably easier for most people. However the analytical solution also has a very important role. What might this be?

ERTH2020 Practical:: Introduction to Python Page 10 Exercise 10: Vertical gravity anomaly due to a buried spherical body This final exercise is intended to provide additional practice in python programming. It is designed to include the same programming constructs as in Exercises 8-9, applied to a different geophysical problem. The results from this exercise will be used in Practical 2. This exercise is intended to be completed outside of class. Background theory The required theory can be easily understood with reference to several basic concepts. The following outline essentially summarises upcoming lecture material from ERTH2020. If a buried body can be approximated as a sphere, then we can calculate the gravity anomaly using an analytical approach. That is, we use a theoretical formula derived by the volume-integration approach. When the integration process is carried through, we find that a spherical body behaves as if it were a particle-sized body with its mass at the centre of the sphere. Suppose the spherical body has a radius R and density contrast (relative to the country rock) The anomalous mass will therefore be M = 4 R 3 / 3 (Volume x density contrast) (1) The gravity anomaly at a distance r from the centre of the sphere is then dg = G M / r 2 (2) Suppose that the centre of the sphere is at a depth Z. Consider a surface observation point at a horizontal distance x from the centre of the sphere. That is, the distance from centre of sphere to observation point, by Pythagoras theorem is given by Hence r 2 = x 2 + Z 2 dg = G M / ( x 2 + Z 2 ) (3) Normally we are interested in the vertical component of gravity. dg Z = G M cos / ( x 2 + Z 2 ) = G M (Z / r) / ( x 2 + Z 2 ) dg Z = G M Z / (x 2 + Z 2 ) 3/2 (4)

ERTH2020 Practical:: Introduction to Python Page 11 Exercise 10 - Instructions Assume a spherical body of radius R= 50m, depth to centre Z=100m, and density contrast =1000 kg m -3. Using Equations 1 and 4, calculate and plot the gravity anomaly (i.e. the excess gravitational acceleration in m s -2 ) along a surface profile extending from x =- 300m to x = 300m at an interval of 1m. The basic code here will be similar to that used in Exercises 8,9. Some coding ideas to get you started are given below. Demonstrate the concept of non-uniqueness, by choosing new values of R and which yield the same gravity anomaly curve. Hint: look at Equation 1. How do you need to change R and, so as to keep the same anomalous mass M. In Practical 2, you will check your Python curves using the Berkeley web modeller. Coding Ideas for Ex 10 (Note that the following code is incomplete) : sphere.py gravity anomaly due to a buried spherical body from math import... from numpy import. from pylab import... define the model parameters G =. Big G in SI units R =50.0 radius of sphere in m Z =100.0 depth to centre in m sigma = 1000.0 density contrast in SI units N= 601 number of points on the profile (from -300m to 300m at 1m intervals) dx=1.0 x increment in m initialise arrays x= zeros(n, float) array to hold x coordinate for the plot dgz= zeros(... array to hold the computed gravity anomaly calculate excess mass M =... use Equation 1 loop along the profile at 1m interval for i in range(0,n): x[i] = - 300.0+ i*dx the x coordinate dgz[i] =... use Eqn 4 here plot(x,dgz) now plot the gravity anomaly title(... xlabel(... ylabel(... show()