2.4 A Case Study: Percolation Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008.

Slides:



Advertisements
Similar presentations
Chapter 14 Recursion Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,, E. Reingold.
Advertisements

EXAMPLES (Arrays). Example Many engineering and scientific applications represent data as a 2-dimensional grid of values; say brightness of pixels in.
Introduction to Computer Science Robert Sedgewick and Kevin Wayne Recursive Factorial Demo pubic class Factorial {
2.3 Recursion do automated demo of towers of hanoi before class
1 Convert this problem into our standard form: Minimize 3 x x 2 – 6 x 3 subject to 1 x x 2 – 3 x 3 ≥ x x 2 – 6 x 3 ≤ 5 7 x 1.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CS 267: Automated Verification Lecture 10: Nested Depth First Search, Counter- Example Generation Revisited, Bit-State Hashing, On-The-Fly Model Checking.
1 Depth First Search dfs(0, 0) open site blocked site reachable from top via open sites.
Graphs Graphs are the most general data structures we will study in this course. A graph is a more general version of connected nodes than the tree. Both.
Data Structure and Algorithms (BCS 1223) GRAPH. Introduction of Graph A graph G consists of two things: 1.A set V of elements called nodes(or points or.
Algorithm and data structure. Overview Programming and problem solving, with applications Algorithm: method for solving a problem Data structure: method.
COS 126 – Atomic Theory of Matter. Goal of the Assignment Calculate Avogadro’s number Using Einstein’s equations Using fluorescent imaging Input data.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Classes, methods, and conditional statements We’re past the basics. These are the roots.
Unit 171 Algorithms and Problem Solving - II Algorithm Efficiency Primality Testing Improved Primality Testing Sieve of Eratosthenes Primality Testing.
Computer Science - I Course Introduction Computer Science Department Boston College Hao Jiang.
Computer Science 112 Fundamentals of Programming II Graph Algorithms.
Introduction Algorithms and Conventions The design and analysis of algorithms is the core subject matter of Computer Science. Given a problem, we want.
CSE 131 Computer Science 1 Module 1: (basics of Java)
1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008.
Slides from Kevin Wayne on Union- Find and Percolotion.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
Problem of the Day  Why are manhole covers round?
Review Recursion Call Stack. Two-dimensional Arrays Visualized as a grid int[][] grays = {{0, 20, 40}, {60, 80, 100}, {120, 140, 160}, {180, 200, 220}};
Recursion When to use it and when not to use it. Basics of Recursion Recursion uses a method Recursion uses a method Within that method a call is made.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)
Algorithms, 4 th Edition∙Robert Sedgewick and Kevin Wayne∙Copyright © 2002–2010∙ March 16, :10:29 PM ‣ dynamic connectivity ‣ quick find ‣ quick.
Multidimensional Arrays. 2 Two Dimensional Arrays Two dimensional arrays. n Table of grades for each student on various exams. n Table of data for each.
Lec 20 More Arrays--Algorithms. Agenda Array algorithms (section 7.5 in the book) – An algorithm is a well-defined specification for solving a problem.
CompSci 100E 3.1 Random Walks “A drunk man wil l find his way home, but a drunk bird may get lost forever”  – Shizuo Kakutani Suppose you proceed randomly.
2.1 Functions Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · 9/10/08 9/10/08.
COS 126 – Atomic Theory of Matter. Goal of the Assignment Calculate Avogadro’s number Using Einstein’s equations Using fluorescent imaging Input data.
Recap of Functions. Functions in Java f x y z f (x, y, z) Input Output Algorithm Allows you to clearly separate the tasks in a program. Enables reuse.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Java Basics Hussein Suleman March 2007 UCT Department of Computer Science Computer Science 1015F.
2.2 Libraries and Clients Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · December.
Austin Howard & Chris Wohlgamuth April 28, 2009 This presentation is available at
COS 126 – Atomic Theory of Matter. Goal of the Assignment Calculate Avogadro’s number Using Einstein’s equations Using fluorescent imaging Input data.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
CS-I MidTerm Review Hao Jiang Computer Science Department Boston College.
1.2 Built-in Types of Data Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · December.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
Where’s the title? You gotta search for it!. PotW Solution String s = new Scanner(System.in).next(); int[] prev = new int[s.length() * 2 + 2]; Arrays.fill(prev,
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
7. Graph Traversal Describe and compare depth-first and breadth-first graph searching, and look at the creation of spanning trees Contest Algorithms: 7.
CompSci 100E 4.1 Google’s PageRank web site xxx web site yyyy web site a b c d e f g web site pdq pdq.. web site yyyy web site a b c d e f g web site xxx.
NETWORK FLOWS Shruti Aggrawal Preeti Palkar. Requirements 1.Implement the Ford-Fulkerson algorithm for computing network flow in bipartite graphs. 2.For.
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 7: Graphs Data Structures.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
1 A Case Study: Percolation Percolation. Pour liquid on top of some porous material. Will liquid reach the bottom? Applications. [ chemistry, materials.
1 A Case Study: Percolation Percolation. Pour liquid on top of some porous material. Will liquid reach the bottom? Applications. [ chemistry, materials.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Recursion.
Compsci 201, Union-Find Algorithms
Java Software Structures: John Lewis & Joseph Chase
Chapter 12 Recursion (methods calling themselves)
Multidimensional Arrays
2.3 Recursion do automated demo of towers of hanoi before class
Exam 2 Review 1.
Multidimensional Arrays
COS 126 – Atomic Theory of Matter
COS 126 – Atomic Theory of Matter
Data Structures & Algorithms Union-Find Example
Data types, assignment statements, and math functions allow you to compute You write a sequence of statements that tell the computer what needs to be done.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
1.5 Input and Output Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 2/14/11.
Introduction to Computer Science I.
Loops and Iteration CS 21a: Introduction to Computing I
2.3 Recursion Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 · 2/17/11.
2.4 A Case Study: Percolation
Presentation transcript:

2.4 A Case Study: Percolation Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · June 8, :06 tt

2.4 A Case Study: Percolation

3 A Case Study: Percolation Percolation. Pour liquid on top of some porous material. Will liquid reach the bottom? Applications. [ chemistry, materials science, … ] n Chromatography. n Spread of forest fires. n Natural gas through semi-porous rock. n Flow of electricity through network of resistors. n Permeation of gas in coal mine through a gas mask filter. n …

4 A Case Study: Percolation Percolation. Pour liquid on top of some porous material. Will liquid reach the bottom? Abstract model. N -by- N grid of sites. n Each site is either blocked or open. open site blocked site

5 A Case Study: Percolation Percolation. Pour liquid on top of some porous material. Will liquid reach the bottom? Abstract model. N -by- N grid of sites. n Each site is either blocked or open. n An open site is full if it is connected to the top via open sites. open site blocked site percolates (full site connected to top) full site does not percolate (no full site on bottom row)

6 A Scientific Question Random percolation. Given an N-by-N system where each site is vacant with probability p, what is the probability that system percolates? Remark. Famous open question in statistical physics. Recourse. Take a computational approach: Monte Carlo simulation. no known mathematical solution p = 0.3 (does not percolate) p = 0.4 (does not percolate) p = 0.5 (does not percolate) p = 0.6 (percolates) p = 0.7 (percolates)

7 Data Representation Data representation. Use one N -by- N boolean matrix to store which sites are open; use another to compute which sites are full. Standard array I/O library. Library to support reading and printing 1- and 2-dimensional arrays open[][] shorthand: 0 for blocked, 1 for open blocked site open site

8 Data Representation Data representation. Use one N -by- N boolean matrix to store which sites are open; use another to compute which sites are full. Standard array I/O library. Library to support reading and printing 1- and 2-dimensional arrays full[][] shorthand: 0 for not full, 1 for full full site

9 Standard Array IO Library (Program 2.2.2) public class StdArrayIO {... // read M-by-N boolean matrix from standard input public static boolean[][] readBoolean2D() { int M = StdIn.readInt(); int N = StdIn.readInt(); boolean[][] a = new boolean[M][N]; for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) if (StdIn.readInt() != 0) a[i][j] = true; return a; } // print boolean matrix to standard output public static void print(boolean[][] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { if (a[i][j]) StdOut.print("1 "); else StdOut.print("0 "); } StdOut.println(); }

10 Scaffolding Approach. Write the easy code first. Fill in details later. public class Percolation { // return boolean matrix representing full sites public static boolean[][] flow(boolean[][] open) // does the system percolate? public static boolean percolates(boolean[][] open) { int N = open.length; boolean[][] full = flow(open); for (int j = 0; j < N; j++) if (full[N-1][j]) return true; return false; } // test client public static void main(String[] args) { boolean[][] open = StdArrayIO.readBoolean2D(); StdArrayIO.print(flow(open)); StdOut.println(percolates(open)); } system percolates if any full site in bottom row

Vertical Percolation

12 Vertical Percolation Next step. Start by solving an easier version of the problem. Vertical percolation. Is there a path of open sites from the top to the bottom that goes straight down?

13 Vertical Percolation Q. How to determine if site (i, j) is full? A. It's full if (i, j) is open and (i-1, j) is full. Algorithm. Scan rows from top to bottom. row i-1 row i

14 Vertical Percolation Q. How to determine if site (i, j) is full? A. It's full if (i, j) is open and (i-1, j) is full. Algorithm. Scan rows from top to bottom. public static boolean[][] flow(boolean[][] open) { int N = open.length; boolean[][] full = new boolean[N][N]; for (int j = 0; j < N; j++) full[0][j] = open[0][j]; for (int i = 1; i < N; i++) for (int j = 0; j < N; j++) full[i][j] = open[i][j] && full[i-1][j]; return full; } find full sites initialize

15 % java VerticalPercolation < testT.txt true % java VerticalPercolation < testF.txt false Vertical Percolation: Testing Testing. Use standard input and output to test small inputs. % more testT.txt % more testF.txt

16 Vertical Percolation: Testing Testing. Add helper methods to generate random inputs and visualize using standard draw. public class Percolation {... // return a random N-by-N matrix; each cell true with prob p public static boolean[][] random(int N, double p) { boolean[][] a = new boolean[N][N]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) a[i][j] = StdRandom.bernoulli(p); return a; } // plot matrix to standard drawing public static void show(boolean[][] a, boolean foreground) }

17 Data Visualization Visualization. Use standard drawing to visualize larger inputs. public class Visualize { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double p = Double.parseDouble(args[1]); boolean[][] open = Percolation.random(N, p); boolean[][] full = Percolation.flow(open); StdDraw.setPenColor(StdDraw.BLACK); Percolation.show(open, false); StdDraw.setPenColor(StdDraw.CYAN); Percolation.show(full, true); }

18 Vertical Percolation: Probability Estimate Analysis. Given N and p, run simulation T times and report average. public class Estimate { public static double eval(int N, double p, int T) { int cnt = 0; for (int t = 0; t < T; t++) { boolean[][] open = Percolation.random(N, p); if (VerticalPercolation.percolates(open)) cnt++; } return (double) cnt / M; } public static void main(String[] args) { int N = Integer.parseInt(args[0]); double p = Double.parseDouble(args[1]); int T = Integer.parseInt(args[2]); StdOut.println(eval(N, p, T)); } test client

19 Vertical Percolation: Probability Estimate Analysis. Given N and p, run simulation T times and report average. Running time. Proportional to T N 2. Memory consumption. Proportional to N 2. % java Estimate % java Estimate % java Estimate % java Estimate a lot of computation! agrees with theory 1 – (1 – p N ) N takes about 1 minute takes about 4 minutes

General Percolation

21 General Percolation: Recursive Solution Percolation. Given an N -by- N system, is there any path of open sites from the top to the bottom. Depth first search. To visit all sites reachable from i-j: n If i-j already marked as reachable, return. n If i-j not open, return. n Mark i-j as reachable. n Visit the 4 neighbors of i-j recursively. Percolation solution. n Run DFS from each site on top row. n Check if any site in bottom row is marked as reachable. not just straight down

22 Depth First Search: Java Implementation public static boolean[][] flow(boolean[][] open) { int N = open.length; boolean[][] full = new boolean[N][N]; for (int j = 0; j < N; j++) if (open[0][j]) flow(open, full, 0, j); return full; } public static void flow(boolean[][] open, boolean[][] full, int i, int j) { int N = full.length; if (i = N || j = N) return; if (!open[i][j]) return; if ( full[i][j]) return; full[i][j] = true; // mark flow(open, full, i+1, j); // down flow(open, full, i, j+1); // right flow(open, full, i, j-1); // left flow(open, full, i-1, j); // up }

23 General Percolation: Probability Estimate Analysis. Given N and p, run simulation T times and report average. Running time. Still proportional to T N 2. Memory consumption. Still proportional to N 2. % java Estimate % java Estimate % java Estimate % java Estimate

Adaptive Plot

25 In Silico Experiment Plot results. Plot the probability that an N -by- N system percolates as a function of the site vacancy probability p. Design decisions. How many values of p ? For which values of p ? How many experiments for each value of p ? too few points too many points judicious choice of points

26 Adaptive Plot Adaptive plot. To plot f(x) in the interval [x 0, x 1 ] : n Stop if interval is sufficiently small. Divide interval in half and compute f(x m ). Stop if f(x m ) is close to ½ ( f(x 0 ) + f(x 1 ) ). Recursively plot f(x) in the interval [x 0, x m ]. Plot the point (x m, f(x m )). Recursively plot f(x) in the interval [x m, x 1 ]. Net effect. Short program that judiciously chooses values of p to produce a "good" looking curve without excessive computation.

27 Percolation Plot: Java Implementation public class PercolationPlot { public static void curve(int N, double x0, double y0, public static void curve(int N, double x1, double y1) { double gap = 0.05; double error = 0.005; int T = 10000; double xm = (x0 + x1) / 2; double ym = (y0 + y1) / 2; double fxm = Estimate.eval(N, xm, T); if (x1 - x0 < gap && Math.abs(ym - fxm) < error) { StdDraw.line(x0, y0, x1, y1); return; } curve(N, x0, y0, xm, fxm); StdDraw.filledCircle(xm, fxm,.005); curve(N, xm, fxm, x1, y1); } public static void main(String[] args) { int N = Integer.parseInt(args[0]); curve(N, 0.0, 0.0, 1.0, 1.0); }

28 Adaptive Plot Plot results. Plot the probability that an N -by- N system percolates as a function of the site vacancy probability p. Phase transition. If p 0.593, system almost always percolates.

29 Dependency Call Graph

30 Lessons Expect bugs. Run code on small test cases. Keep modules small. Enables testing and debugging. Incremental development. Run and debug each module as you write it. Solve an easier problem. Provides a first step. Consider a recursive solution. An indispensable tool. Build reusable libraries. StdArrayIO, StdRandom, StdIn, StdDraw …