Sunteți pe pagina 1din 29

492 STUDY REPORT

Engin Deniz Alpman

June 2, 2017

Instructor: Mehmet Burcin UNLU

1
1 Elements of programming
In this part of the book, I learn and do practice about loop and arrays in java.Also I improve my
knowledge about conditionals. At the end of the chapter there was a case-study called Random Web
Surfer. This model is used for investigating the users movement across the internet. To investigate
the model, I learned about Markov chains and matrices. Markov chain can be used in lots of field.
For example it helps us to compute the probability of being in specific state after certain steps
when initial state is known, or probability of being specific state as an array when initial state is
not known.Elements in the output array will give us the different probability depending on the
starting state. Also Markov chain can be used to make simulations and that is exactly what I
did. I have made simulation about a board game called Chutes and ladders.I create simplified
version of the game not because implementation is hard,infact implementation is the same, but it
is repetitive. So I create 3x3 version of the game which is originally 10x10.The simulation that I
created computes the relative probability of winning when a player starts as a first player and as a
second player. The code I write for it in java language can be seen at below.
import java.lang.*;
import java.util.*;

public class Random {

static int prob1=0;


static int prob2=0;

public static void main(String[] Args){

float[][] transition = new float[][]{


{ 0, 1/3f, 1/3f, 1/3f, 0, 0, 0, 0},
{ 0, 0, 1/3f, 2/3f, 0, 0, 0, 0},
{ 0, 0, 0, 2/3f, 0, 0, 1/3f, 0},
{ 0, 1/3f, 0, 0, 1/3f, 0, 1/3f, 0},
{ 0, 0, 0, 0, 1/3f, 1/3f, 1/3f, 0},
{ 0, 0, 0, 0, 0, 0, 1/3f, 2/3f},
{ 0, 0, 0, 0, 0, 0, 0, 1f},
{ 0, 0, 0, 0, 0, 0, 0, 1f}
};

int N = 8;

for(int k=0;k<50;k++){
int state1 = 0;
int state2=0;
int steps = 0;
int counter=0;

1
while (state1!=7 && state2!=7) {
// System.out.println(state);
steps++;
counter+=1;
double r1 = Math.random();
double r2 = Math.random();
double sum1 = 0.0;
double sum2=0.0;

if(counter==1){
for (int j = 0; j < N; j++) {
sum1 += transition[state1][j];

if (r1 <= sum1) {


state1 = j;

break;

}
}
}

else{

for (int j = 0; j < N; j++) {


sum1 += transition[state1][j];

if (r1 <= sum1) {


state1 = j;

break;

}
}

for (int j = 0; j < N; j++) {


sum2 += transition[state2][j];

if (r2 <= sum2) {


state2 = j;

break;

}
}
}

// System.out.println("The number of steps = " + steps);

2
if(state1==7){

System.out.println("The winner is first player!");


prob1++;

else{

System.out.println("The winner is second player!");


prob2++;

System.out.println("The probability of first one winning is: "+


(double)prob1/50*100);
}
}

Which give me the result:

The probability of first one winning is: 68.0

So we can say that first player has an advantage over the second player.

3
2 Functions
In this part of the book, I learned about static methods and recursion. Static methods and variables
can be used for creating more stable model and self-containing models like singletons. Also recursion
is useful for approaching problem with divide and conquer method. In recursion, problem is divided
into similar subproblems and then combination of those problem gives us the desired result. At the
end of the chapter, as was in the first chapter, there was a case study called Percolation. There
is an union find algorithm in the book for implementation of percolation algorithm. But rather
than copying the code, I decided to learn union find algorithm. After that I implement percolation
using my union find algorithm. Percolation is a mathematically unsolved problem but we can easily
compute it with computers. It can be used in numerous field like the damage evaluation of forest
fire, disease spread,electrical resistance in a mixture of two media,oil spread etc. I put the union
find algorithms and percolations code below.

#union find

import java.util.*;

public class Uf {

private int[] _parent;


private int[] _rank;

public int find(int i) {

int p = _parent[i];
if (i == p) {
return i;
}
return _parent[i]=find(p);

public void union(int i, int j) {

int root1 = find(i);


int root2 = find(j);

if (root2 == root1) return;

if (_rank[root1] > _rank[root2]) {


_parent[root2] = root1;
} else if (_rank[root2] > _rank[root1]) {
_parent[root1] = root2;
} else {
_parent[root2] = root1;
_rank[root1]++;
}
}

4
public Uf(int max) {

_parent = new int[max];


_rank = new int[max];

for (int i = 0; i < max; i++) {


_parent[i] = i;
}
}

public String toString() {


return "<UnionFind\np " + Arrays.toString(_parent) + "\nr " +
Arrays.toString(_rank) + "\n>";
}

5
#Percolation

import java.lang.*;

public class Persolate2 {

public static boolean[][] flow(boolean[][] isOpen) {


int n = isOpen.length;
boolean[][] isFull = new boolean[n][n];
for (int j = 0; j < n; j++)
isFull[0][j] = isOpen[0][j];

for (int i = 1; i < n; i++) {


for (int j = 0; j < n; j++) {
boolean filled = false;
for (int k = j; (k < n) && isOpen[i][k]; k++)
filled = filled || isFull[i-1][k];
for ( ; (j < n) && isOpen[i][j]; j++)
if (filled) isFull[i][j] = true;
}
}
return isFull;
}

public static boolean percolates(boolean[][] isOpen) {


boolean[][] isFull = flow(isOpen);
int n = isFull.length;
for (int j = 0; j < n; j++)
if (isFull[n-1][j]) return true;
return false;
}

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++)

if(Math.random()<=p){
a[i][j] = true;
}
else{

a[i][j] = false;
}
return a;
}
}

6
3 Object-Oriented-Programming
In this part of the book, I learned how to create and use classes. This is the core part of the object
oriented programming. By using classes we can divide problem to simpler subproblems that are
different from one another and solve them using different classes.This gives us very powerful tool
for solving problems. Because instead of solving one huge problem, now we can solve it by step by
step. In the case study of chapter 3, I studied object under gravitational force. To do that I used
different classes. For example body and a ball have different classes. Body gives us the object that
is affected by gravitational field, and the ball gives us the visual geometric image of the object we
are investigating. Using classes, we can assign different attributes to different objects while there
share similar attributes.
#Ball

public class Ball {

private double rx, ry; // position


private double vx, vy; // velocity
private final double radius; // radius

public Ball() {
rx = 0.0;
ry = 0.0;
vx = StdRandom.uniform(-0.015, 0.015);
vy = StdRandom.uniform(-0.015, 0.015);
radius = StdRandom.uniform(0.025, 0.075);
}

private void bounceOffVerticalWall() {


vx = -vx;
}

private void bounceOffHorizontalWall() {


vy = -vy;
}

public void move() {


if (Math.abs(rx + vx) + radius > 1.0) bounceOffVerticalWall();
if (Math.abs(ry + vy) + radius > 1.0) bounceOffHorizontalWall();
rx = rx + vx;
ry = ry + vy;
}

public void draw() {


StdDraw.filledCircle(rx, ry, radius);
}

7
public static void main(String[] args) {

Ball b1 = new Ball();


Ball b2 = new Ball();

StdDraw.setXscale(-1.0, +1.0);
StdDraw.setYscale(-1.0, +1.0);
StdDraw.enableDoubleBuffering();

while (true) {
StdDraw.clear(StdDraw.GRAY);
StdDraw.setPenColor(StdDraw.BLACK);
b1.move();
b2.move();
b1.draw();
b2.draw();
StdDraw.show();
StdDraw.pause(20);
}
}
}

8
#Body

public class Body {

private Vector r;
private Vector v;
private final double mass;

public Body(Vector r, Vector v, double mass) {


this.r = r;
this.v = v;
this.mass = mass;
}

public void move(Vector f, double dt) {


Vector a = f.scale(1/mass);
v = v.plus(a.scale(dt));
r = r.plus(v.scale(dt));
}

public Vector forceFrom(Body b) {


Body a = this;
double G =6.67e-11;
Vector delta = b.r.minus(a.r);
double dist = delta.magnitude();
double magnitude = (G * a.mass * b.mass) / (dist * dist);
return delta.direction().scale(magnitude);
}

public void draw() {


StdDraw.setPenRadius(0.025);
StdDraw.point(r.cartesian(0), r.cartesian(1));
}

public void draw(double penRadius) {


StdDraw.setPenRadius(penRadius);
StdDraw.point(r.cartesian(0), r.cartesian(1));
}

9
4 Data Structures
In the fourth part of the book, I learned about data types like Stack and Queues ; Symbol tables.
Learning data types is an importing step in learning programming because each problem has its
own properties and using correct data structure to approach problem is crucial in both efficiency
and implementation. In the case study of this chapter, I used what I learned about data structure
from this chapter to implement small world algorithm. I used those knowledge to make connections
between data points. That was not wanted but I want to implement doubly linked list,stack and
binary tree algorithms because I think it is crucial to know those algorithms and how they work.
#Node
public class Node{
String data;
int count=1;
Node left;
Node right;

public Node(String data){


this.data = data;
left = null;
right = null;
}
}

#binary tree that hold String

public class BinaryString {


public Node root;
public BinaryString(){
this.root = null;
}
public void insert(String id){
Node newNode = new Node(id);
if(root==null){
root = newNode;
return;
}
Node current = root;
Node parent = null;
while(true){
parent = current;
if(id.compareToIgnoreCase(current.data)<0){
current = current.left;
if(current==null){
parent.left = newNode;
return;
}
}
else if(id.compareToIgnoreCase(current.data)>0)
{
current = current.right;

10
if(current==null){
parent.right = newNode;
return;
}
}

else{

current.count++;
return;
}
}
}
public void display(Node root){
if(root!=null){
display(root.left);
System.out.println(" " + root.data+":"+ root.count);
display(root.right);
}}}

#Doubly linked lists Node


public class Node{
int data;
Node next;
Node previous;
public Node(int data){
this.data = data;
next = null;
previous = null;
}
}

#Doubly linked list


public class DoublyLinkedList {

int size =0;


Node head = null;
Node tail = null;

public Node addAtStart(int data){


System.out.println("Adding " + data + " to the start");
Node n = new Node(data);
if(size==0){
head = n;
tail = n;
}else{
n.next = head;
head.previous = n;
head = n;
}
size++;
return n;

11
}

public Node addAtEnd(int data){


System.out.println("Adding " + data + " to the End");
Node n = new Node(data);
if(size==0){
head = n;
tail = n;
}else{
tail.next = n;
n.previous = tail;
tail =n;
}
size++;
return n;
}

public void insertAtPos(int val , int pos)


{
System.out.println("Adding "+ val+" at position "+ pos);

Node insert= new Node(val);


if (pos == 1)
{
addAtStart(val);
return;
}
Node control = head;
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node temp = control.next;
control.next=insert;
insert.previous=control;
insert.next=temp;
temp.previous=insert;
}
control = control.next;
}
size++ ;
}

public void deleteFromStart(){


if(size==0){
System.out.println("\nList is Empty");
}else{
System.out.println("\ndeleting " + head.data + " from start");
head = head.next;
size--;
}
}

12
public void deleteFromEnd(){
if(size==0){
System.out.println("\nList is Empty");
}else if(size==1){
deleteFromStart();
}else{
//store the 2nd last node
int x = tail.data;
Node prevTail = tail.previous;

//detach the last node


tail = prevTail;
tail.next=null;
System.out.println("\ndeleting " + x + " from end");
size--;
}
}

public void deleteAtPos(int pos)


{
if (pos == 1)
{
if (size == 1)
{
head = null;
tail = null;
size = 0;
return;
}
head = head.next;
head.previous=null;
size--;
return ;
}
if (pos == size)
{
tail = tail.previous;
tail.previous=null;
size-- ;
}
Node del_node = head.next;
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node p = del_node.previous;
Node n = del_node.next;

p.next=n;
n.previous=p;
size-- ;
return;
}
del_node = del_node.next;

13
}
}

public int elementAt(int index){


if(index>size){
return -1;
}
Node n = head;
while(index-1!=0){
n=n.next;
index--;
}
return n.data;
}

//get Size
public int getSize(){
return size;
}

public void print(){


Node temp = head;
System.out.print("Doubly Linked List: ");
while(temp!=null){
System.out.print(" " + temp.data);
temp = temp.next;
}
System.out.println();

public void print_reverse(){


Node temp = tail;
System.out.print("Doubly Linked List in reverse: ");
while(temp!=null){
System.out.print(" " + temp.data);
temp = temp.previous;
}
System.out.println();

public static void main(String[] args) {


DoublyLinkedList test = new DoublyLinkedList();
test.addAtStart(3);
test.print();
test.addAtEnd(1);
test.print();

14
test.insertAtPos(2,2);

test.print();
test.deleteFromStart();
test.print();
System.out.println("Element at index 3: "+test.elementAt(3));
test.addAtStart(5);
test.print();
test.deleteFromEnd();

test.print();
System.out.println("Size of the Linked List: " + test.getSize());
test.print_reverse();
}
}

#Stack
public class Stack {

private int maxSize;


private char[] char_array;
private int top;

public Stack(int s) {
maxSize = s;
char_array = new char[maxSize];
top = -1;
}
public void push(char j) {
char_array[++top] = j;
}
public char pop() {
return char_array[top--];
}
public char peek() {
return char_array[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public static void main(String[] args) {
Stack theStack = new Stack(10);
theStack.push(n);
theStack.push(a);
theStack.push(b);
theStack.push(e);
theStack.push(r);

15
while (!theStack.isEmpty()) {
char value = theStack.pop();
System.out.print(value);
System.out.print(" ");
}
System.out.println("");
}

#Graph
public class Graph {

private ST<String, SET<String>> st;

private int E;

public Graph() {
st = new ST<String, SET<String>>();
}

public Graph(String filename, String delimiter) {


st = new ST<String, SET<String>>();
In in = new In(filename);
while (in.hasNextLine()) {
String line = in.readLine();
String[] names = line.split(delimiter);
for (int i = 1; i < names.length; i++) {
addEdge(names[0], names[i]);
}
}
}

public int V() {


return st.size();
}

public int E() {


return E;
}

private void validateVertex(String v) {


if (!hasVertex(v)) throw new IllegalArgumentException(v + " is not a vertex");
}

16
public void addEdge(String v, String w) {
if (!hasVertex(v)) addVertex(v);
if (!hasVertex(w)) addVertex(w);
if (!hasEdge(v, w)) E++;
st.get(v).add(w);
st.get(w).add(v);
}

public void addVertex(String v) {


if (!hasVertex(v)) st.put(v, new SET<String>());
}

public Iterable<String> vertices() {


return st.keys();
}

public Iterable<String> adjacentTo(String v) {


validateVertex(v);
return st.get(v);
}

public boolean hasVertex(String v) {


return st.contains(v);
}

public boolean hasEdge(String v, String w) {


validateVertex(v);
validateVertex(w);
return st.get(v).contains(w);
}

public String toString() {


StringBuilder s = new StringBuilder();
for (String v : st) {
s.append(v + ": ");
for (String w : st.get(v)) {
s.append(w + " ");
}
s.append(\n);
}
return s.toString();
}

public int degree(String v){


if(st.contains(v)){return st.get(v).size();}
else{return 0;}

17
}

public static void main(String[] args) {

Graph graph = new Graph();


while (!StdIn.isEmpty()) {
String v = StdIn.readString();
String w = StdIn.readString();
graph.addEdge(v, w);
}

StdOut.println(graph);

for (String v : graph.vertices()) {


StdOut.print(v + ": ");
for (String w : graph.adjacentTo(v)) {
StdOut.print(w + " ");
}
StdOut.println();
}

5 Disease Spread Modelling


5.1 SIR Model without births and deaths:
It is easiest to consider a closed population without births, deaths and migration.We are trying
to investigate the model in which a large population into which a low level of infectious agent is
introduced and where the resulting epidemic occurs sufficiently quickly that demographic processes
are not influential.Thus we get the following SIR equations:
dS
dt = SI

dI
dt = SI I

dR
dt = I

18
So we can model this by implementing this equations on python like this:
import scipy.integrate as spi
import numpy as np
import pylab as pl

beta=1.4247
gamma=0.14286
TS=1.0
ND=70.0
S0=1-1e-6
I0=1e-6
INPUT = (S0, I0, 0.0)

def eq(INP,t):

Y=np.zeros((3))
V = INP
Y[0] = - beta * V[0] * V[1]
Y[1] = beta * V[0] * V[1] - gamma * V[1]
Y[2] = gamma * V[1]
return Y

t_start = 0.0; t_end = ND; t_inc = TS


t_range = np.arange(t_start, t_end+t_inc, t_inc)
RES = spi.odeint(eq,INPUT,t_range)

pl.plot(RES[:,0], -g, label=Susceptibles)


pl.plot(RES[:,2], -k, label=Recovereds)
pl.plot(RES[:,1], -r, label=Infectious)
pl.xlabel(Time(weeks))
pl.ylabel(Fraction of population in each class)
pl.legend(loc=0)
pl.show()

19
Figure 1: SIR model without births and deaths

5.2 The SIR Model With Demography:


If we are interested in exploring the longer-term persistence and endemic dynamics of an infectious
disease, then clearly demographic processes will be important
the influx of new susceptibles through births is very important in this model.The simplest and
most common way of introducing demography into the SIR model is to assume there is a natural
host lifespan, 1/ years. Then, the rate at which individuals suffer natural mortality is given by
.This factor is independent of the disease.Thus we get the generalized SIR model:
dS
dt = SI S

dI
dt = SI I I

dR
dt = I R

20
So we can model this by implementing this equations on python like this:
import scipy.integrate as spi
import numpy as np
import pylab as pl

mu=1/(70*365.0)
beta=520/365.0
gamma=1/7.0
TS=1.0
ND=60*365
S0=0.1
I0=1e-4
R0=1-S0-I0
INPUT = (S0, I0, R0)

def eq(INP,t):

Y=np.zeros((3))
V = INP
Y[0] = mu - beta * V[0] * V[1] - mu * V[0]
Y[1] = beta * V[0] * V[1] - gamma * V[1] - mu * V[1]
Y[2] = gamma * V[1] - mu * V[2]
return Y

t_start = 0.0; t_end = ND; t_inc = TS


t_range = np.arange(t_start, t_end+t_inc, t_inc)
RES = spi.odeint(eq,INPUT,t_range)

pl.subplot(311)
pl.plot(RES[:,0], -g, label=Susceptibles)
pl.title(SIR)
pl.xlabel(Time)
pl.ylabel(Susceptibles)
pl.subplot(312)
pl.plot(RES[:,1], -r, label=Infectious)
pl.xlabel(Time)
pl.ylabel(Infectious)
pl.subplot(313)
pl.plot(RES[:,2], -k, label=Recovereds)
pl.xlabel(Time)
pl.ylabel(Recovereds)
pl.show()

21
Figure 2: General SIR model

5.3 SIS model:


The SIR model captures the dynamics of infections that either kill or confer lifelong immunity
once recovered. However, numerous infectious diseases confer no long-lasting immunity. For these
diseases, a individuals can be infected multiple times throughout their lives, with no apparent
immunity. Here, we concentrate briefly on this class of models, called SIS because recovery from
infection is followed by an instant return to the susceptible pool.

We can write equations like this:


dS
dt = I SIS

dI
dt = SI I

22
So we can model this by implementing this equations on python like this:
import scipy.integrate as spi
import numpy as np
import pylab as pl

beta=1.4247
gamma=0.14286
I0=1e-6
ND=70
TS=1.0
INPUT = (1.0-I0, I0)

def eq(INP,t):

Y=np.zeros((2))
V = INP
Y[0] = - beta * V[0] * V[1] + gamma * V[1]
Y[1] = beta * V[0] * V[1] - gamma * V[1]
return Y

t_start = 0.0; t_end = ND; t_inc = TS


t_range = np.arange(t_start, t_end+t_inc, t_inc)
RES = spi.odeint(eq,INPUT,t_range)

pl.subplot(211)
pl.plot(RES[:,0], -g, label=Susceptibles)
pl.title(SIS model)
pl.xlabel(Time)
pl.ylabel(Susceptibles)
pl.subplot(212)
pl.plot(RES[:,1], -r, label=Infectious)
pl.xlabel(Time)
pl.ylabel(Infectious)
pl.show()

23
Figure 3: SIS model

5.4 SEIR model:


The process of transmission often occurs due to an initial vaccination with a very small number of
pathogen units.During this stage, pathogen abundance is too low for active transmission to other
susceptible hosts, and yet the pathogen is present. Hence, the host cannot be categorized as sus-
ceptible, infectious, or recovered; we need to introduce a new category for these individuals who are
infected but not yet infectious. These individuals are referred to as Exposed and are represented
by the variable E in SEIR models.

We can write equations like this:


dS
dt = (I + )S

dE
dt = SI ( + )E

dI
dt = E ( + )I

dR
dt = I E

24
So we can model this by implementing this equations on python like this:
import scipy.integrate as spi
import numpy as np
import pylab as pl

mu=1/(70*365.0)
beta=520/365.0
sigma=1/14.0
gamma=1/7.0
ND=60*365.0
TS=1.0
S0=0.1
E0=1e-4
I0=1e-4
INPUT = (S0, E0, I0)

def eq(INP,t):

Y=np.zeros((3))
V = INP
Y[0] = mu - beta * V[0] * V[2] - mu * V[0]
Y[1] = beta * V[0] * V[2] - sigma * V[1] - mu * V[1]
Y[2] = sigma * V[1] - gamma * V[2] - mu * V[2]
return Y

t_start = 0.0; t_end = ND; t_inc = TS


t_range = np.arange(t_start, t_end+t_inc, t_inc)
RES = spi.odeint(eq,INPUT,t_range)

Rec=1. - (RES[:,0]+RES[:,1]+RES[:,2])

pl.subplot(311)
pl.plot(RES[:,0], -g, label=Susceptibles)
pl.title(SEIR Model)
pl.xlabel(Time)
pl.ylabel(Susceptibles)
pl.subplot(312)
pl.plot(RES[:,1], -m, label=Exposed)
pl.plot(RES[:,2], -r, label=Infectious)
pl.legend(loc=0)
pl.xlabel(Time)
pl.ylabel(Infected)
pl.subplot(313)
pl.plot(Rec, -k, label=Recovereds)
pl.xlabel(Time)
pl.ylabel(Recovereds)
pl.show()

25
Figure 4: SEIR model

5.5 SIR Model with Carrier:


Infected individuals may become chronic carriers, transmitting infection at a low rate for many
years. The greater biological complexity of these systems can be readily incorporated into our
current modeling framework, although accurate parameterization becomes more complex.

We can write equations like this:


dS
dt = (I + BC)S S

dI
dt = (I + BC)S I I

dC
dt = q C C

dR
dt = (1 q)I + C R

26
So we can model this by implementing this equations on python like this:
import scipy.integrate as spi
import numpy as np
import pylab as pl

beta=0.2
epsilon=0.1
gamma=0.01
Gamma=0.001
mu=1/(50*365.0)
q=0.4
S0=0.1
I0=1e-4
C0=1e-3
ND=60*365
TS=1.0
INPUT = (S0, I0, C0)

def eq(INP,t):

Y=np.zeros((3))
V = INP
Y[0] = mu - beta * V[0] * (V[1] + epsilon * V[2]) - mu * V[0]
Y[1] = beta * V[0] * (V[1] + epsilon * V[2]) - gamma * V[1] - mu * V[1]
Y[2] = q * gamma * V[1] - Gamma * V[2] - mu * V[2]
return Y

t_start = 0.0; t_end = ND; t_inc = TS


t_range = np.arange(t_start, t_end+t_inc, t_inc)
RES = spi.odeint(eq,INPUT,t_range)

Rec=1. - (RES[:,0]+RES[:,1]+RES[:,2])

pl.subplot(311)
pl.plot(RES[:,0], -g, label=Susceptibles)
pl.title(SIR model with carrier)
pl.xlabel(Time)
pl.ylabel(Susceptibles)
pl.subplot(312)
pl.plot(RES[:,1], -r, label=Infectious)
pl.xlabel(Time)
pl.ylabel(Infected)
pl.subplot(313)
pl.plot(RES[:,1], -m, label=Carriers)
pl.xlabel(Time)
pl.ylabel(Carriers)
pl.show()

27
Figure 5: SIR model with Carrier

References

[1] Matt J. Keeling and Pejman Rohani


Modeling Infectious Diseases an humans and animals
Princeton University Press

28

S-ar putea să vă placă și