Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Percolation assingment #3

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
target
*.DS_Store
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ see it online: [Algorithms I](https://www.coursera.org/learn/algorithms-part1/ho
## TOC

1. [quick find](quickfind/README.md)
2. [percolation](percolation/README.md)
1 change: 1 addition & 0 deletions percolation/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/RUST_BACKTRACE=full
5 changes: 5 additions & 0 deletions percolation/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions percolation/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "percolation"
version = "0.0.0"
authors = ["Dmitry N. Medvedev <[email protected]>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

[profile.release]
panic = 'abort'

[profile.dev]
panic = 'abort'
33 changes: 33 additions & 0 deletions percolation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Percolation

> Write a program to estimate the value of the percolation threshold via Monte Carlo simulation.

source article: [Percolation](https://coursera.cs.princeton.edu/algs4/assignments/percolation/specification.php)

**Percolation**. Given a composite systems comprised of randomly distributed insulating and metallic materials: what fraction of the materials need to be metallic so that the composite system is an electrical conductor? Given a porous landscape with water on the surface (or oil below), under what conditions will the water be able to drain through to the bottom (or the oil to gush through to the surface)? Scientists have defined an abstract process known as percolation to model such situations.

**The model**. We model a percolation system using an *n-by-n* grid of sites. Each site is either open or blocked. A full site is an open site that can be connected to an open site in the top row via a chain of neighboring (left, right, up, down) open sites. We say the system percolates if there is a full site in the bottom row. In other words, a system percolates if we fill all open sites connected to the top row and that process fills some open site on the bottom row. (For the insulating/metallic materials example, the open sites correspond to metallic materials, so that a system that percolates has a metallic path from top to bottom, with full sites conducting. For the porous substance example, the open sites correspond to empty space through which water might flow, so that a system that percolates lets water fill open sites, flowing from top to bottom.)

![percolates](README/percolates-yes.png) ![percolates](README/percolates-no.png)

**The problem**. In a famous scientific problem, researchers are interested in the following question: if sites are independently set to be open with probability *p* (and therefore blocked with probability *1 − p*), what is the probability that the system percolates? When *p* equals *0*, the system does not percolate; when *p* equals *1*, the system percolates. The plots below show the site vacancy probability *p* versus the percolation probability for 20-by-20 random grid (left) and 100-by-100 random grid (right).

When *n* is sufficiently large, there is a threshold value *p** such that when *p* < *p** a random *n*-by-*n* grid almost never percolates, and when *p* > *p**, a random *n*-by-*n* grid almost always percolates. No mathematical solution for determining the percolation threshold *p** has yet been derived. Your task is to write a computer program to estimate *p**.

*Performance requirements*. The constructor should take time proportional to n2; all methods should take constant time plus a constant number of calls to the union–find methods `union()`, `find()`, `connected()`, and `count()`.

**Monte Carlo simulation**. To estimate the percolation threshold, consider the following computational experiment:

1. Initialize all sites to be blocked.
2. Repeat the following until the system percolates:
- Choose a site uniformly at random among all blocked sites.
- Open the site.
3. The fraction of sites that are opened when the system percolates provides an estimate of the percolation threshold.

**For example**, if sites are opened in a 20-by-20 lattice according to the snapshots below, then our estimate of the percolation threshold is 204/400 = 0.51 because the system percolates when the 204th site is opened.

![50 open sites](README/percolation-50.png) ![100 open sites](README/percolation-100.png) ![150 open sites](README/percolation-150.png) ![204 open sites](README/percolation-204.png)

By repeating this computation experiment *T* times and averaging the results, we obtain a more accurate estimate of the percolation threshold. Let *xt* be the fraction of open sites in computational experiment *t*. The sample mean *x*
provides an estimate of the percolation threshold; the sample standard deviation *s*; measures the sharpness of the threshold.

Binary file added percolation/README/percolates-no.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added percolation/README/percolates-yes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added percolation/README/percolation-100.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added percolation/README/percolation-150.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added percolation/README/percolation-204.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added percolation/README/percolation-50.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions percolation/src/errors/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod size_is_too_big_error;
pub mod size_is_too_small_error;
21 changes: 21 additions & 0 deletions percolation/src/errors/size_is_too_big_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use std::error::Error;
use std::fmt;

#[derive(Debug, Clone)]
pub struct SizeIsTooBigError;

impl fmt::Display for SizeIsTooBigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "size is too big")
}
}

impl Error for SizeIsTooBigError {
fn cause(&self) -> Option<&(dyn std::error::Error)> {
None
}

fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}
21 changes: 21 additions & 0 deletions percolation/src/errors/size_is_too_small_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use std::error::Error;
use std::fmt::{Display, Formatter, Result};

#[derive(Debug)]
pub struct SizeIsTooSmallError;

impl Display for SizeIsTooSmallError {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "size is too small")
}
}

impl Error for SizeIsTooSmallError {
fn cause(&self) -> Option<&(dyn std::error::Error)> {
None
}

fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}
35 changes: 35 additions & 0 deletions percolation/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
pub mod errors;

use errors::size_is_too_big_error::SizeIsTooBigError;
use errors::size_is_too_small_error::SizeIsTooSmallError;

#[derive(Debug)]
pub struct Percolation {
sites: Vec<Option<usize>>,
}

const MINIMUM_SIZE_THAT_MAKES_SENSE: usize = 2;

impl Percolation {
pub fn new(size: usize) -> Result<Percolation, Box<dyn std::error::Error>> {
let number_of_items: usize = size.pow(2);

if size < MINIMUM_SIZE_THAT_MAKES_SENSE {
return Err(Box::new(SizeIsTooSmallError));
}

if number_of_items > usize::MAX {
return Err(Box::new(SizeIsTooBigError));
}

let mut result = Percolation {
sites: Vec::with_capacity(number_of_items),
};

for _ in 0..size {
result.sites.push(Option::None::<usize>);
}

Result::Ok(result)
}
}
17 changes: 17 additions & 0 deletions percolation/tests/lib_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#[cfg(test)]
mod percolation_tests {
use percolation::*;

#[test]
fn constructor_test() {
let mut _p = Percolation::new(0);

match _p {
Ok(_) => assert!(false, "this should throw SizeIsTooSmallError"),
Err(error) => assert_eq!(
error == percolation::errors::size_is_too_small_error::SizeIsTooSmallError,
true
),
}
}
}