PHYS Tutorial 7: Random Walks & Monte Carlo Integration

Similar documents
ROSE-HULMAN INSTITUTE OF TECHNOLOGY Department of Mechanical Engineering. Mini-project 3 Tennis ball launcher

Calculation of Trail Usage from Counter Data

ORF 201 Computer Methods in Problem Solving. Final Project: Dynamic Programming Optimal Sailing Strategies

CAM Final Report John Scheele Advisor: Paul Ohmann I. Introduction

Taking Your Class for a Walk, Randomly

Epidemics and zombies

Lab 4: Root Locus Based Control Design

UNIVERSITY OF WATERLOO

Software Reliability 1

Opleiding Informatica

A Hare-Lynx Simulation Model

Assignment #3 Breakout! Due: 12pm on Wednesday, February 6th This assignment should be done individually (not in pairs)

Assignment #3 Breakout!

1.2 Example 1: A simple hydraulic system

Iteration: while, for, do while, Reading Input with Sentinels and User-defined Functions

ESTIMATION OF THE DESIGN WIND SPEED BASED ON

APPENDIX A COMPUTATIONALLY GENERATED RANDOM DIGITS 748 APPENDIX C CHI-SQUARE RIGHT-HAND TAIL PROBABILITIES 754

Assignment 3: Breakout!

Deer Population Student Guide

Based on a handout by Eric Roberts

Design of Experiments Example: A Two-Way Split-Plot Experiment

When zombies attack! The maths of infection rates

2 When Some or All Labels are Missing: The EM Algorithm

Excel Solver Case: Beach Town Lifeguard Scheduling

Chapter 11 Waves. Waves transport energy without transporting matter. The intensity is the average power per unit area. It is measured in W/m 2.

Laser Tag Pro: Battle Rifle

Understanding safety life cycles

Three-Dimensional Ray-Cast Pong

5.1 Introduction. Learning Objectives

CHEMICAL ENGINEERING LABORATORY CHEG 239W. Control of a Steam-Heated Mixing Tank with a Pneumatic Process Controller

Verification and Validation Pathfinder Release 0730 x64

2600T Series Pressure Transmitters Plugged Impulse Line Detection Diagnostic. Pressure Measurement Engineered solutions for all applications

Chapter 14 Coal Boiler Flue Gas Scrubber II

Application of the probabilistic-fuzzy method of assessing the risk of a ship manoeuvre in a restricted area

ECO 199 GAMES OF STRATEGY Spring Term 2004 Precept Materials for Week 3 February 16, 17

Queue analysis for the toll station of the Öresund fixed link. Pontus Matstoms *

The risk assessment of ships manoeuvring on the waterways based on generalised simulation data

MIL-STD-883G METHOD

4. Please Do Break the Crystal

Section 1: Multiple Choice Explained EXAMPLE

intended velocity ( u k arm movements

Lab # 03: Visualization of Shock Waves by using Schlieren Technique

CFD AND EXPERIMENTAL STUDY OF AERODYNAMIC DEGRADATION OF ICED AIRFOILS

Background Summary Kaibab Plateau: Source: Kormondy, E. J. (1996). Concepts of Ecology. Englewood Cliffs, NJ: Prentice-Hall. p.96.

Verification and Validation Pathfinder

Lecture 1: Knot Theory

Black Box testing Exercises. Lecturer: Giuseppe Santucci

Chapter 12 Practice Test

Workshop 1: Bubbly Flow in a Rectangular Bubble Column. Multiphase Flow Modeling In ANSYS CFX Release ANSYS, Inc. WS1-1 Release 14.

Safety Critical Systems

Zombies and Differential Equations

Legendre et al Appendices and Supplements, p. 1

Steam-Boiler Control Specification Problem

Appendix 12 Consequences

1 SE/P-02. Experimental and Analytical Studies on Thermal-Hydraulic Performance of a Vacuum Vessel Pressure Suppression System in ITER

E. Agu, M. Kasperski Ruhr-University Bochum Department of Civil and Environmental Engineering Sciences

New generation of Electronic Card Systems: The 4-D Card

Rewriting the Zombie Apocalypse The Day the Zombies Came

Saturated-Unsaturated Consolidation

Prior Knowledge: Students should have an understanding that plants and animals compete for resources such as food, space, water, air and shelter.

Determining Occurrence in FMEA Using Hazard Function

RESEARCH OPPURTINITIES ON AIRCRAFT EMERGENCY EVACUATION. Presented by: Dr. Minesh POUDEL

Ammonia Synthesis with Aspen Plus V8.0

A Research on the Airflow Efficiency Analysis according to the Variation of the Geometry Tolerance of the Sirocco Fan Cut-off for Air Purifier

A SEMI-PRESSURE-DRIVEN APPROACH TO RELIABILITY ASSESSMENT OF WATER DISTRIBUTION NETWORKS

ARTIFICIAL NEURAL NETWORK BASED DESIGN FOR DUAL LATERAL WELL APPLICATIONS

Advanced LOPA Topics

The benefits of the extended diagnostics feature. Compact, well-proven, and flexible

Numerical Simulations of a Train of Air Bubbles Rising Through Stagnant Water

Science Skills Station

Agilent Dimension Software for ELSD User Manual

Fast Floating Point Compression on the Cell BE Processor

CVEN Computer Applications in Engineering and Construction. Programming Assignment #4 Analysis of Wave Data Using Root-Finding Methods

Section 1: Multiple Choice

Wave Motion. interference destructive interferecne constructive interference in phase. out of phase standing wave antinodes resonant frequencies

FUBA RULEBOOK VERSION

RULES AND REGULATIONS OF FIXED ODDS BETTING GAMES

EVOLVING HEXAPOD GAITS USING A CYCLIC GENETIC ALGORITHM

Policy Gradient RL to learn fast walk

Title: 4-Way-Stop Wait-Time Prediction Group members (1): David Held

The system design must obey these constraints. The system is to have the minimum cost (capital plus operating) while meeting the constraints.

INTRODUCTION Page 2 SETTINGS

Global Journal of Engineering Science and Research Management

CS Problem Solving and Object-Oriented Programming Lab 2 - Methods, Variables and Functions in Alice Due: September 23/24

Introduction to Pattern Recognition

Safety Manual. Process pressure transmitter IPT-1* 4 20 ma/hart. Process pressure transmitter IPT-1*

Infrared Thermal Imaging, Inc.

INSTRUMENT INSTRUMENTAL ERROR (of full scale) INSTRUMENTAL RESOLUTION. Tutorial simulation. Tutorial simulation

Black Sea Bass Encounter

Chapter 20. Planning Accelerated Life Tests. William Q. Meeker and Luis A. Escobar Iowa State University and Louisiana State University

Energy capture performance

Carrying Capacity Activity. 5 th Grade PSI. Teacher s Notes Procedure: Simulation 1 Regular herds

ISOLATION OF NON-HYDROSTATIC REGIONS WITHIN A BASIN

Amendments to the International Convention on Maritime Search and Rescue of 27 April 1979

Guided Study Program in System Dynamics System Dynamics in Education Project System Dynamics Group MIT Sloan School of Management 1

Using MATLAB with CANoe

Ranger Walking Initiation Stephanie Schneider 5/15/2012 Final Report for Cornell Ranger Research

Digital Level Control One and Two Loops Proportional and Integral Control Single-Loop and Cascade Control

PURE SUBSTANCE. Nitrogen and gaseous air are pure substances.

CS 351 Design of Large Programs Zombie House

Transcription:

PHYS 410 - Tutorial 7: Random Walks & Monte Carlo Integration The goal of this tutorial is to model a random walk in two dimensions and observe a phase transition as parameters are varied. Additionally, some Monte Carlo integration exercises are included at the end for practice. 1. Zombie Apocalypse Rumour has it that mad scientists from UBC have been working on a dangerous virus that turns anyone it infects into a zombie. Alarmed, the City of Vancouver has contacted you because of your expertise in producing fast and reliable simulations. Their request is simple: they want you to model the potential consequences of a zombie invasion and to find ways to mitigate the damages it would cause to the population. The setup The simplest model of a zombie invasion is that of a two-dimensional random walk. For the sake of the argument, we will assume that both zombies and terrified humans walk randomly on a Cartesian lattice, and that the infection is transmitted when walkers find themselves on the same site as a zombie. We will also assume that the virus is so potent that zombies eventually die of organ failure, and thus stop infecting humans. An effective simulation therefore needs to keep track of the health status of all walkers on the lattice at each time step, updating it as necessary. In order to assess the consequences of a pandemic outbreak, many parameters have to be taken into account. Among those are the density of the population, the survival time of a zombie, the probability of transmitting the disease, and the fraction of people immune to the virus, to name only a few. Definitions Luckily for you, the officials at City Hall already have an incomplete version of a zombie invasion code. In it, they define the following parameters: a grid size N, such that the lattice possesses N N sites; a density variable that specifies the fraction of sites occupied by people; a time T which measures the number of iterations (hours) it takes for a zombie to die; a number of walker M, expressed in terms of N and density. 1

The advantage of vectorization Intuitively, it would make sense to code the zombie invasion with a series of embedded for and if loops that cover the realm of all possibilities for the walkers: do we take a step in x? in y? does the infection get transmitted? and so forth. However, coding that way is extremely inefficient. The City of Vancouver is in a state of emergency and time is a limited resource, so you need to find a way to get results quickly. Since MATLAB excels at manipulating matrices and vectors, the best solution is to minimize the quantity of loops, which act on individual elements, in favour of operations that act on arrays all at once. This technique is called vectorization. 1 Note: In a vectorized random walk, all walkers take random steps simultaneously. A subtle problem caused by this is that neighbours can never find themselves on the same site after a random step, which implies that zombies can never infect adjacent walkers. An easy fix is to infect the walkers who are on the same site as a zombie as well as those who step on a site where a zombie used to be at the previous iteration. Question 1: Initialization To initialize the random walk, the first step is to randomly assign positions to all M walkers. To keep track of the location of every walker, we can define two vectors x and y with the statement randi(n, M, 1), which creates a column vector whose M elements take random integer values between 1 and N. Thus, walker j has position {x(j), y(j)} on the lattice. The second step is to turn a random walker into a zombie. After this step, we need to be able to distinguish between healthy, infected, and dead walkers. To do so, let us initialize a vector, which we will call infect and whose elements take either the value 0 (healthy), 1 (zombie), or 2 (dead). Therefore, we would like infect to be 0 everywhere except at the position of the infected walker, where it takes the value 1. Remember that zombies can only wander around for T hours before dying, which means that we also have to keep track of the time that passes after every infection. An easy way to do so is through a vector hours initialized to the value T for everyone, but which decreases every iteration for all zombies. When an element hours(j) reaches 0, we will need to update infect(j) from 1 to 2 (where 2 means death; the walker stops moving altogether). Additionally, we will initialize three counters to keep track of casualties and time: ndeaths = 0, nzombies = 1, and iter = 1. 1 On my 2012 MacBook Pro, a simulation at high population density constructed of loops takes more than 200 seconds to run, compared to 1 second on the vectorized version of the same code. 2

Question 2: Random walk The random walk will take place in a while loop that keeps on running as long as the conditions nzombies > 0 and iter < Nitermax are met. To walk randomly, we need random directions. Convince yourself that the statement >> d e l t a x = 2 floor (2 rand) 1 ; where rand is a number randomly chosen in the open interval (0, 1), defines a variable deltax which exclusively takes the values -1 or 1. As mentioned earlier, the walkers in a vectorized random walk all take steps simultaneously. Look at the Random Walk part of the incomplete code, and add a section for the random walk in the y direction. Be sure to understand how to use array-wide statements like deltax(infect == 2) = 0, or what type of variable walkx and walky are, as knowing this is the key to eschew the use of loops. Notice how some problems might arise in xnew if walkers take steps outside of the N N lattice. Implement periodic boundary conditions in both the x and y directions to prevent walkers from leaving the simulation. Question 3: Infection and death counts There are a few tasks your code needs to do before each random step: If a walker is infected, subtract 1 from its hours counter; Update the status of all zombies who die on this iteration; Update the counters nzombies and ndeaths. Do not use if loops! Use logical operations instead, as in Question 2. For instance, the number of dead walkers is simply ndeaths = sum(infect == 2) in vectorized notation. Question 4: Contamination The contamination step occurs on two separate occasions: a healthy walker and a zombie land on the same site; a walker steps on a site that a zombie just left. We need to compare the x and y coordinates of the healthy walkers to those of the infected ones and, if there are matches, proceed with contamination. The statement C = ismember(a, B) compares the arrays A and B and outputs a logical array C taking the value 1 for all elements of A also found in B, and 0 for the unique ones. 3

Therefore, all that you need to do is to define a variable called I coord which contains the x and y coordinates (old and new) of the infected zombies. Also, make sure to understand why H coord has been initialized the way it has. Question 5: Additional modifications Make sure that your code works properly. When it does, add these two features to make it more realistic: There is a possibility that some people are naturally immune to the virus. Assume that a fraction pimmune of the population (chosen at random) cannot be contaminated, and modify the initialization part of your code to take this into account. Hint: in the case of immunization, inf ect should take an additional value. Some viruses are more contagious than others. Add a probability of transmission that determines whether contamination occurs or not. The variable infection status should be modified accordingly. Hint: The health status of walkers corresponds to the binary true/infected (1) and false/healthy (0). Therefore, a simple way to implement contagion is to make infection status a logical array obtained from a logical comparison to a transmission probability. If k walkers have been in contact with zombies after some iteration, then infection status should be a logical vector of length k where each element determines whether one of these walker randomly becomes a zombie or not. Question 6: Critical phenomena Now that you have a working model of a zombie invasion, you can answer some questions that the mayor Gregor Robertson has for you: Given a density of 0.5 and a transmission probability of 0.8, what is the minimum value of pimmune needed so that most people stay alive? What if the density is 0.25? Given a density of 0.5 and assuming that 30% of the population is immune against the virus, how contagious does the virus need to be in order to become pandemic? How would these results change if the zombies died after 12 hours (instead of 24)? You should observe critical phenomena as you play with various parameters. Indeed, there seems to be a phase transition between the two population states mostly alive and mostly dead. (1) Given the random nature of your simulation, you should run your code many times with the same parameters and average your results. How would you estimate the error associated with your predictions? 4

2. Monte Carlo Integration Question 1: Estimating π using Monte Carlo Explain why the following lines calculate π: >> k = 1 e7 ; >> p i e s t = 4 sum(sum(rand(k,2).ˆ2,2) <=1)/ k ; Question 2: Hyperspheres Monte Carlo integration shines the most in higher dimensional applications. Use the logic of Question 1 to calculate the volume inside S d, the d-sphere, defined by for d = 2, i.e. for a ball in R 3 ; for d = 5. d+1 x 2 i = 1, (2) i=1 Question 3: Importance sampling Compute the integral I = by using Monte Carlo integration with Uniform sampling; 1 0 ( x 1/3 + x ) dx (3) 10 Importance sampling with the sampling function w(x) = 2 3 x 1/3. The actual answer is 1.55. Plot the error for k going from 10 2 to 10 6 on a loglog plot; what do you observe? Question 4: Importance sampling (again) Repeat the above exercice with the integral I = 1 0 e x dx (4) with the sampling function w(x) = 1 + x, since e x 1 + x on the interval (0, 1). 5