Scientific Computing (w2) An Introduction to Scientific Computing workshop 2.

Slides:



Advertisements
Similar presentations
Introduction to R Brody Sandel. Topics Approaching your analysis Basic structure of R Basic programming Plotting Spatial data.
Advertisements

Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
MATLAB – A Computational Methods By Rohit Khokher Department of Computer Science, Sharda University, Greater Noida, India MATLAB – A Computational Methods.
Introduction to Matlab
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Scripts and Flow Control. Scripts So far we have been entering commands directly into the command line But there is a better way Script files (and functions)
By Hrishikesh Gadre Session II Department of Mechanical Engineering Louisiana State University Engineering Equation Solver Tutorials.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 03.
EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character arrays.
EGR 106 – Week 2 – Arrays & Scripts Brief review of last week Arrays: – Concept – Construction – Addressing Scripts and the editor Audio arrays Textbook.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Prof. R. Willingale Department of Physics and Astronomy 2nd Year C+R 2 nd Year C and R Workshop Part of module PA2930 – 2.5 credits Venue: Computer terminal.
Introduction to MATLAB ENGR 1187 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
Mathcad Variable Names A string of characters (including numbers and some “special” characters (e.g. #, %, _, and a few more) Cannot start with a number.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
Basic R Programming for Life Science Undergraduate Students Introductory Workshop (Session 1) 1.
Introduction to MATLAB
Data, graphics, and programming in R 28.1, 30.1, Daily:10:00-12:45 & 13:45-16:30 EXCEPT WED 4 th 9:00-11:45 & 12:45-15:30 Teacher: Anna Kuparinen.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Objectives Understand what MATLAB is and why it is widely used in engineering and science Start the MATLAB program and solve simple problems in the command.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
Introduction to MATLAB ENGR 1181 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
Piotr Wolski Introduction to R. Topics What is R? Sample session How to install R? Minimum you have to know to work in R Data objects in R and how to.
Numerical Computation Lecture 2: Introduction to Matlab Programming United International College.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
Variables and Functions. Open your Encoder program Let’s begin by opening the “Labyrinth Auto Straight” code. Save this file as Labyrinth with variables.
Introduction to Programming with RAPTOR
Outline Comparison of Excel and R R Coding Example – RStudio Environment – Getting Help – Enter Data – Calculate Mean – Basic Plots – Save a Coding Script.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Scientific Computing Introduction to Matlab Programming.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
STAT 251 Lab 1. Outline Lab Accounts Introduction to R.
>> x = [ ]; y = 2*x y = Arrays x and y are one dimensional arrays called vectors. In MATLAB all variables are arrays. They allow functions.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Scientific Computing (w1) R Computing Workshops An Introduction to Scientific Computing workshop 1.
A (VERY) SHORT INTRODUCTION TO MATLAB J.A. MARR George Mason University School of Physics, Astronomy and Computational Sciences.
Trinity College Dublin, The University of Dublin GE3M25: Computer Programming for Biologists Python Karsten Hokamp, PhD Genetics TCD, 03/11/2015.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
1 Lecture 5 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
MA/CS 375 Fall 2002 Lecture 2. Motivation for Suffering All This Math and Stuff Try the Actor demo from
Introduction to Computer Programming - Project 2 Intro to Digital Technology.
1 An Introduction to R © 2009 Dan Nettleton. 2 Preliminaries Throughout these slides, red text indicates text that is typed at the R prompt or text that.
Python Lesson 1 1. Starter Create the following Excel spreadsheet and complete the calculations using formulae: 2 Add A1 and B1 A2 minus B2 A3 times B3.
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
Python programming Introduction to the JES environment and basics of Python.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Control Structures Hara URL:
Lecture 2 Functions Trevor A. Branch FISH 553 Advanced R School of Aquatic and Fishery Sciences University of Washington.
Matlab Training Session 4: Control, Flow and Functions
Introduction to the JES environment and basics of Python
Stats Lab #1 TA: Kyle Davis
Variables, Expressions, and IO
MATLAB DENC 2533 ECADD LAB 9.
Code is on the Website Outline Comparison of Excel and R
Introduction to TouchDevelop
Introduction to Matlab
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
R Course 1st Lecture.
Data analysis with R and the tidyverse
Presentation transcript:

Scientific Computing (w2) An Introduction to Scientific Computing workshop 2

Scientific Computing (w2) R Programming Workshop 2 An introduction to computer programming using the R computing environment Solving problems using a computer Using computers as a tool for: –Plotting graphs and pictures –Analysis of data –Learning maths and physics…

Scientific Computing (w2) Getting started with R Logon to a UoL computer. Start  All Programs  RStudio [click] Type commands at the ‘prompt’ in the R ‘console’.

Scientific Computing (w2) Getting Help From Rstudio – click “Help” menu (top) – select “R Help” From the console – type ?plot for help with the “plot” command From the web - Or

Scientific Computing (w2) Refresher: variables and objects

Scientific Computing (w2) Variables, Objects and Assignment > x <- 1.2 [1] 1.2 in R, the things you manipulate and store are objects. There are different classes of object and R has methods for treating an object in a manner appropriate to its class. “1.2” is just a number, a scalar. In fact, it’s a floating point number (not an integer). When we assign an object this value, the object instantly takes the right form. In this case ‘x’ becomes an object storing our single floating point number.

Scientific Computing (w2) Variables, Objects and Assignment > x <- c(1.2, 1.3, 1.4, 2.0) [1] in R, the things you manipulate and store are objects. There are different classes of object and R has methods for treating an object in a manner appropriate to its class. We use the c(…) function to combine several elements (in this case numbers) into one object, often called a vector (a 1D list) or more generally an array (which can have more than 1 dimension). The old ‘x’ has been replaced with a new one, which is now an array storing 5 values.

Scientific Computing (w2) Variables, Objects and Assignment > my.name <- “spider man” [1] “spider man” in R, the things you manipulate and store are objects. There are different classes of object and R has methods for treating an object in a manner appropriate to its class. “spider man” is a string of characters. There are 10 characters (including space) stored as a single string. The object ‘my.name’ is created as a string object and assigned this value.

Scientific Computing (w2) Variables, Objects and Assignment > my.name <- c(“spider man”, “cat woman”) [1] “spider man” “cat woman” in R, the things you manipulate and store are objects. There are different classes of object and R has methods for treating an object in a manner appropriate to its class. You can have an array of strings too…

Scientific Computing (w2) Variables, Objects and Assignment > x <- array(1:20, dim=c(4,5)) Here we define a 2 dimensional array, with size 4x5 (4 rows, 5 columns). There are 20 elements. This produces the numbers 1, 2, …, 20 (20 of them) Create an array. We need to define the values going in to it, and its dimensions.

Scientific Computing (w2) Variables, Objects and Assignment > x <- array(1:20, dim=c(4,5)) > x [,1] [,2] [,3] [,4] [,5] [1,] [2,] [3,] [4,] > x[2,3] Here is the 4x5 array. Notice the order the values are placed. What does this do?

Scientific Computing (w2) Variables, Objects and Assignment > 4 > 3 [1] TRUE Evaluate whether 4 is greater than 3. The answer is TRUE This is a logical object. Possible values are TRUE and FALSE.

Scientific Computing (w2) Variables, Objects and Assignment > 4 >= 3 [1] TRUE Evaluate whether 4 is greater than or equal to 3. The answer is still TRUE This is a logical object. Possible values are TRUE and FALSE.

Scientific Computing (w2) Variables, Objects and Assignment > 4 <= 3 [1] FALSE Evaluate whether 4 is less than or equal to 3. The answer is FALSE This is a logical object. Possible values are TRUE and FALSE.

Scientific Computing (w2) Variables, Objects and Assignment > x <- c(1.0, 2.3, 4.5, 10.0) > x > 4.0 [1] FALSE FALSE TRUE TRUE For each element in the array ‘x’ evaluate whether it is greater than 4 This is an array of logical values. The array has the same size/shape as ‘x’. This is an example of an ‘element-wise’ operation. The operation is simply repeated for each an every element of the arrays involved.

Scientific Computing (w2) Some simple data analysis

Scientific Computing (w2) Means, variance & all that > print(morley) Expt Run Speed The morley data have100 measurements in three columns: Exp = experiment no. (1-5) Run = run no (1-20) Speed = measured speed km/s R has several datasets built-in and ready to play with, to help you practice data analysis at the computer. Here we use 100 speed of light measurements.

Scientific Computing (w2) Means, variance & all that > print(morley$Speed) If we consider just the ‘Speed’ column of the morley array we have 100 numbers in the form of a 1d array (a “vector”) R has several datasets built-in and ready to play with, to help you practice data analysis at the computer. Here we use 100 speed of light measurements.

Scientific Computing (w2) Means, variance & all that > print(morley$Speed) > mean(morley$Speed) [1] The mean(…) function will compute the mean value of whatever you feed it. In this case it uses the 100 values stored in morley$Speed R has several datasets built-in and ready to play with, to help you practice data analysis at the computer. Here we use 100 speed of light measurements. The output (or returned value) is just one number, the mean. As usual, R treats this as a 1  1 array.

Scientific Computing (w2) Means, variance & all that  y <- c(3.4,4.5,2.3,-0.01) > mean(y) Try entering your own list of values. Remember to combine them into a single object – using c(…) – which can be processed by the mean(…) function R comes with a lot of functions for data analysis and manipulation. And you can add more by installing packages. There are packages you can install to add new commands, some packages add dozens of new commands.

Scientific Computing (w2) Means, variance & all that > var(y) > length(y) > sqrt(var(y)) > sd(y) The sd(…) function returns the standard deviation (sqrt of variance). This is a ready-made function that does the same calculation as the previous line. Work from the inside out. The var(…) function returns the number of elements in ‘y’. This is then used as input to the sqrt(…) function. The length(…) function returns the number of elements in ‘y’. The var(…) function will compute the variance value of whatever you feed it. In this case it uses the values you assigned to ‘y’.

Scientific Computing (w2) Means, variance & all that > var(y) > length(y) > sqrt(var(y)) > sd(y) > sd(y)/sqrt(length(y)) This computes the “standard error” on the mean of y

Scientific Computing (w2) Means, variance & all that > mean(morley$Speed) [1] > sd(morley$Speed) [1] > sd(morley$Speed) / sqrt(length(morley$Speed)) > [1] This computes the “standard error” on the mean of the speed

Scientific Computing (w2) Plot the speed of light data > plot(morley$Speed) > hist(morley$Speed) The hist(…) function will generate a histogram (and plot it). Try plotting the data

Scientific Computing (w2) Plot the speed of light data > plot(morley$Speed) > hist(morley$Speed) > hist(morley$Speed, col=“steelblue”, border=“white”, main=“my histogram”) > hist(morley$Speed, col="steelblue",border="white", breaks=seq(500,1200,by=100)) Define exactly where you want the breaks (between histogram bins) to go.

Scientific Computing (w2) Extracting subsets of an array

Scientific Computing (w2) Variables, Objects and Assignment > morley$Speed > 900 [1] FALSE FALSE FALSE TRUE...

Scientific Computing (w2) Variables, Objects and Assignment > morley$Speed > 900 [1] FALSE FALSE FALSE TRUE... > mask 900) > print(morley$Speed[mask]) store the result of the test in the (logical) array ‘mask’ only keeps elements of morley$Speed for which the corresponding element of mask=TRUE I.e. this is the subset of speeds > 900

Scientific Computing (w2) Variables, Objects and Assignment > morley$Speed > 900 [1] FALSE FALSE FALSE TRUE... > mask 900) > print(morley$Speed[mask]) > mean(mask) the logical value TRUE is treated as a numerical value 1, and FALSE is treated as 0. So mean(mask) gives the fraction of TRUE’s. I.e. the fraction of speeds > 900

Scientific Computing (w2) Variables, Objects and Assignment > morley$Speed > 900 [1] FALSE FALSE FALSE TRUE... > mask 900) > print(morley$Speed[mask]) > mean(mask) > morley[mask, ] morley is a 100x3 array (100 rows, 3 columns). Here we use mask to select the matching rows only. Leaving the column index empty means it will use all columns

Scientific Computing (w2) A simple physics simulation

Scientific Computing (w2) Brownian motion & random walks Einstein (1905) developed physical theory of Brownian motion

Scientific Computing (w2) A 1 -dimensional random walk start at “time” x=0 position y=0

Scientific Computing (w2) A 1 -dimensional random walk move ahead to x=1 randomly jump +1 or -1 in y now at y=

Scientific Computing (w2) A 1 -dimensional random walk move ahead to x=2 randomly jump +1 or -1 in y now at y=0

Scientific Computing (w2) A 1 -dimensional random walk move ahead to x=3 randomly jump +1 or -1 in y now at y=-1

Scientific Computing (w2) A 1 -dimensional random walk what happens to y as we keep advancing x…? move ahead to x=4 randomly jump +1 or -1 in y now at y=-2

Scientific Computing (w2)

Writing you first script

Scientific Computing (w2) Help files, history, memory manager here graphics – Plots appear here The console – Type new commands here Editor - Write scripts here

Scientific Computing (w2) R Script Files Edit a script file and save (“ mysource.R ”) –to begin a new script: File  New file  R Script –to save the script: File  Save / Save As (in working directory) –to open/edit an existing script: File  Open Source the script file (run the script) > source(“mysource.R”) –Or click on Source button in editor window

Scientific Computing (w2) We are going to write a short script Click in the “editor” window (top left of RStudio) Start typing the commands on the next slide NOTE: Anything starting with a # symbol is a comment – the computer ignores it Comments are helpful to the reader/writer Remember to Save the script periodically (e.g. Save As…“random_walk.R”)

Scientific Computing (w2) # generate n.step steps n.step <- 100 jump <- 1 x <- 0:n.step # compute the y steps dy <- jump * sample(c(-1, 1), size=n.step, replace=TRUE) plot(dy) # compute the cumulative y position y <- c(0, cumsum(dy)) # plot the walk plot(x, y, type="s") a command may run over more than one line when you have finished typing, save and source (run) the script.

Scientific Computing (w2) A (short) random walk

Scientific Computing (w2) How does the script work?

Scientific Computing (w2) Randomly choose a jump of +1 or -1 # generate n.step steps n.step <- 100 jump <- 1 x <- 0:n.step # compute the y steps dy <- jump * sample(c(-1, 1), size=n.step, replace=TRUE) plot(dy) # compute the cumulative y position y <- c(0, cumsum(dy)) # plot the walk plot(x, y, type="s") Try this at the console to see how sample(…) works > sample( c(-1, 1), size=10, replace=TRUE) then try it again (use the up arrow key)

Scientific Computing (w2) # generate n.step steps n.step <- 100 jump <- 1 x <- 0:n.step # compute the y steps dy <- jump * sample(c(-1, 1), size=n.step, replace=TRUE) plot(dy) # compute the cumulative y position y <- c(0, cumsum(dy)) # plot the walk plot(x, y, type="s") Add up all the jumps - a cumulative sum Try this at the console to see how cumsum(…) works > x <- 1:10 > sum(x) > cumsum(x)

Scientific Computing (w2) # generate n.step steps n.step <- 100 jump <- 1 x <- 0:n.step # compute the y steps dy <- jump * sample(c(-1, 1), size=n.step, replace=TRUE) plot(dy) # compute the cumulative y position y <- c(0, cumsum(dy)) # plot the walk plot(x, y, type="s”) now change number of steps to and Source again

Scientific Computing (w2) A (longer) random walk run (Source) again, and again, …

Scientific Computing (w2) # plot a line at y=0 abline(h=0, lty=2) # plot the start and end points points(n.step, y[1], pch=16, cex=1.5) points(n.step, y[n.step+1], pch=16, cex=1.5) # join with a line the start and end points lines(c(n.step, n.step), c(0, y[n.step+1])) # compute the distance travelled r <- y[n.step+1] - y[1] # print on the plot label <- paste("distance=", signif(r, 3)) text(max(x), max(y), labels=label, pos=2) Now that it works, we are going to add some more lines to the bottom of our script. Click in the “editor” window (top left) Start typing the following commands at the end your existing script

Scientific Computing (w2) # plot a line at y=0 abline(h=0, lty=2) # plot the start and end points points(n.step, y[1], pch=16, cex=1.5) points(n.step, y[n.step+1], pch=16, cex=1.5) # join with a line the start and end points lines(c(n.step, n.step), c(0, y[n.step+1])) # compute the distance travelled r <- y[n.step+1] - y[1] # print on the plot label <- paste("distance=", signif(r, 3)) text(max(x), max(y), labels=label, pos=2)

Scientific Computing (w2) A (longer) random walk

Scientific Computing (w2) Brownian motion & random walks Now let’s try in 2 dimensions Pick a random direction to move in, call it theta Select this from a uniform distribution from 0 to 2  radians (equal probabilities) Step a distance (jump= 1 ) in direction theta Resolve into components of the motion in x and in y

Scientific Computing (w2) # generate n.step random directions (angles) n.step <- 100 theta <- runif(n.step, 0, 2*pi) jump <- 1 # compute the x and y step sizes dx <- jump * cos(theta) dy <- jump * sin(theta) # compute the cumulative x and y positions x <- c(0, cumsum(dx)) y <- c(0, cumsum(dy)) # plot the walk plot(x, y, type="l", bty="n", col="red") Begin a new script file  New file  R Script Remember to save it periodically

Scientific Computing (w2) # generate n.step random directions (angles) n.step <- 100 theta <- runif(n.step, 0, 2*pi) jump <- 1 # compute the x and y step sizes dx <- jump * cos(theta) dy <- jump * sin(theta) # compute the cumulative x and y positions x <- c(0, cumsum(dx)) y <- c(0, cumsum(dy)) # plot the walk plot(x, y, type="l", bty="n", col="red")

Scientific Computing (w2)

# plot the start and end points points(x[1], y[1], pch=16, cex=1.5) points(x[n.step+1], y[n.step+1], pch=16, cex=1.5) # join the start and end points lines(x[c(1, n.step+1)], y[c(1, n.step+1)], lwd=3) # compute the distance from start to end r <- sqrt(x[n.step+1]^2 + y[n.step+1]^2) # print on the plot label <- paste("distance=", signif(r, 3)) text(max(x), max(y), labels=label, pos=2) Add more lines to the new script

Scientific Computing (w2) # plot the start and end points points(x[1], y[1], pch=16, cex=1.5) points(x[n.step+1], y[n.step+1], pch=16, cex=1.5) # join the start and end points lines(x[c(1, n.step+1)], y[c(1, n.step+1)], lwd=3) # compute the distance from start to end r <- sqrt(x[n.step+1]^2 + y[n.step+1]^2) # print on the plot label <- paste("distance=", signif(r, 3)) text(max(x), max(y), labels=label, pos=2)

Scientific Computing (w2)

Interlude: loops > 1:10 > for (i in 1:10) { print(i) } > data.array <- array(0, dim=100) > for (i in 2:length(data.array)) { data.array[i] <- data.array[i-1]+1 print(i) } > data.array try this at the console. what happens between the curly brackets is ‘looped’ you can use many lines inside a loop

Scientific Computing (w2) Now that your script works, we are going to make some changes to it. There is no need to replace the entire script. The new script reuses some the lines from our last script. Keep these lines, add to and edit the rest. Recycle code! Save this new one with a different file name. Remember: Anything starting with a # symbol is a comment – the computer ignores it

Scientific Computing (w2) n.step <- 100 n.walks < jump <- 1 x <- array(0, dim=n.walks) y <- array(0, dim=n.walks) for (i in 1:n.walks) { theta <- runif(n.step, 0, 2*pi) dx <- jump * cos(theta) dy <- jump * sin(theta) x[i] <- sum(dx) y[i] <- sum(dy) } # compute the radial distances r <- sqrt(x^2 + y^2) # plot the end point of each walk in (x,y) coordinates plot(x, y) this is a loop - for each of i = 1,2,3,…,n.walks do whatever is {inside} prepare two arrays to store the outputs Pythagoras’ theorem

Scientific Computing (w2)

# plot histogram of x's hist(x, breaks=20, col="blue", border="white", prob=TRUE) # compare to the Normal curve x.norm <- seq(-50, 50, by=0.2) y.norm <- dnorm(x.norm, mean=0, sd=sqrt(n.step)*2/pi) lines(x.norm, y.norm, lwd=4) Still want more…? add this to your 2d script

Scientific Computing (w2) What have we learnt? some different kinds of object and data in R how to select subsets of arrays, use logical operators how to compute mean, variance, std. deviation, std. error how to make and plot a histogram how to start, test, edit, load and save a simple script Now you know how to do this, try using these to improve your data analysis and presentation in lab work. perform repetitive/iterative tasks in maths/physics explore (map out) new mathematical functions

Scientific Computing (w2)