关键词 > EN.500.113 Python代写

EN.500.113 Gateway Computing: Python

发布时间:2021-04-22

EN.500.113 Gateway Computing: Python

Project E


Due: 4/18/21


Introduction

With the advent of COVID-19 pandemic, there has been a tremendous interest in designing models that can predict or illustrates infectious disease transmission, recovery, and death. One the models that has been used in literature is referred to as susceptible-infected-recovered (SIR) model or its variant susceptible–infected–recovered–dead (SIRD) model. As the name suggests, in this model, population is divided into fractions:

1. Susceptible people who are capable of becoming sick from an infection when exposed to the infected people.

2. Infected people who are sick and can transmit the disease to susceptible people. In this project, we assume that people get infected only once.

3. Recovered people who were once infected, but now are free of disease and cannot transmit the disease.

4. Dead people who have died as a complication of disease.

        In this project, you will be using a simplified version of SIRD model for an illustrative purpose only. In this simplified model, we assume a close environment (containing box) where subjects are not entering or leaving the environment. Subjects are represented by circles and move and bounce each other or the wall of the environment according to the unit mass elastic collision law. At each time point in our simulation, subjects belong to one of the four categories listed above. At an initial time point, all subjects are either susceptible or infected. The number of infected people is determined by a probability number pinfected. So if the pinfected = 0.2, then at an initial time point, 20% of population is selected randomly to be infected. Infected subjects can either fully recover after a particular time period (recovery time) or die with a probability of pdeath. Recovered subjects are considered immune and will not be infected again. Susceptible, infected, and recovered people are allowed to move around and collide with each other or the walls of the container. Dead subjects will remain in place. Once an infected subject collides with a susceptible subject, that subject will be infected with a probability of pinfectionP rob.

        To implement this simulation you will need to complete two Python classes, Agents and visualize, using two separate Python files.


1 Agents class (50 points)

You have been given a template script AgentClass.py that contains constructor and template methods for class Agents. This class is used to instantiate an object that handles dynamics of subjects/agents (positions, velocities, collision, labels, ...) during the course of simulation. It contains the following attributes and methods:


1.1 constructor

In the class constructor which is provided, the following object attributes/- variables are defined and initialized:

• num : An integer scalar, defining the he number of subjects in the simulation (default = 100)

• speed: A float scalar defining the maximum speed of movement along x, and y coordinates for each subject/agent (default = 0.08)

• radius: A float scalar defining the radius of circles representing each subject/agent (default = 0.008)

• recoveryTime: A scalar defining the infection recovery time in days (default = 14).

• infProb: pinfectionP rob, a float number which is the probability of an infected subject transmit the infection to a susceptible subject at each encounter/collision (default = 0.99).

• dt: simulation time increment in days (Ex. 0.5)

• pInfected: pinfected, a float number which is the probability of subjects being infected at an initial time in the simulation (default = 0.02).

• pDeath: pdeath, a float number which is the probability of an infected subject dies at the end of recovery time (default = 0.2).

• Time: A scalar that is the simulation time tracker (default = 0).

• susc: percent of susceptible people initialized to 100 (scalar float).

• infec: percent of infected people initialized to 0 (scalar flloat).

• recov: percent of recovered people initialize to 0 (scalar float).

• dead: percent of dead people initialize to 0 (scalar float).

• timeArray: An empty Python list to keep track of simulation time.

• suscArray: An empty Python list to keep track of susceptible subjects’ number over time.

• infArray: An empty Python list to keep track of infected subjects’ number over time.

• recoArray: An empty Python list to keep track of recovered subjects’ number over time.

• deadArray: An empty Python list to keep track of dead subject number over time.

• labels: A numpy, one dimensional array of size of subjects and type integer initialized to all zeros. During simulation, each subject can take one of the following labels: (S=0,I=1,R=2,D=3).

• diseaseTime: A numpy one dimensional array of size of subjects initialized to all zeros to keep track of disease time for each subject.


1.2 setX

This provided class method sets the object’s attribute x which is the x-coordinate of the center of moving circles to a number between [0 1) using numpy uniform random number generator. The shape of this variable is (the number of subjects, ). Values are rounded to 3 decimal points.


1.3 setY

This provided class method sets the object’s attribute y which is the y-coordinate of the center of moving circles to a number between [0 1) using numpy uniform random number generator. The shape of this variable is (the number of subjects, ). Values are rounded to 3 decimal points.


1.4 setVx

This provided class method sets the object’s attribute vx which is the x-coordinate of the velocity of moving circles to a number between speed ∗ [−0.5, 0.5) using numpy uniform random number generator. The shape of this variable is (the number of subjects, ). Values are rounded to 3 decimal points.


1.5 setVy

This provided class method sets the object’s attribute vy which is the y-coordinate of the velocity of moving circles to a number between speed ∗ [−0.5, 0.5) using numpy uniform random number generator. The shape of this variable is (the number of subjects, ). Values are rounded to 3 decimal points.


1.6 updateX

This provided class method updates the object’s attribute according to xnew = xold + (vx ∗ dt).


1.7 updateY

This provided class method updates the object’s attribute according to ynew = yold + (vy ∗ dt).


1.8 updateTime

This provided class method updates the scalar object’s attribute Time ac-cording to dt, simulation time increment.


1.9 boxCollision (10 points)

Accepts four floats: xLow,xHigh,yLow,yHigh, which defines the x-coordinate thresholds for hitting the left and right walls and y-coordinate thresholds for hitting the bottom and top walls of the simulation containing box, respec-tively. In this code, you check if circles hitting the containing box walls using these thresholds and recalculate their positions and velocities. An Object’s attribute velocities (vx, vy) are set to the negative of original velocities. An object’s attribute positions x, y are set to the xLow, xHigh, yLow, yHigh if they are outside these boundaries. For example if the x value of an agent is less than or equal to xLow, then x will be set to xLow while the vx value will be set to -vx. Note that your code should be able to handle class object attributes x, y which have a shape of (the number of subjects/agents,).


1.10 updateCollisionVelocity (12 points)

This method, as input, accepts four numpy arrays with the shape of (2,) named X1: circle one xy-center positions, X2: circle two xy-center position, u1: circle one vx and vy velocities before collision ,u2: circle two vx and vy velocities before collision and returns V1: cir-cle one vx and vy velocities after collision , V2: circle two vx and vy velocities after collision using the following equations:

        Here < a, b > represents the dot products of vectors a and b, and ||a||2 is the norm squared of a vector a, which is the same as < a, a >. If any element in V1 and V2 arrays is greater than speed ∗ 0.5, it should be reassigned to speed ∗ 0.5. In case, calculations result in zero value denominator, assign V1 = −u and V2 = −u2. Round the updated velocities to 3 decimal points.

        For example for the speed of 0.03 and the following inputs: np.array([0.547, 0.88]), np.array([0.474, 0.691 ]), np.array([ 0.022, -0.01 ]), np.array([-0.035, 0.02 ]), you should get [0.015 -0.003] and [-0.038 0.013] as output.


1.11 removeCircles (13 points)

This class method checks if circles are overlapping based on the center-to-center distance of all pairs of circles. If center-to-center distance of two circles is less than or equal to 2∗radius, it will delete coordinates of one of the circles from the object’s x and y attributes. As an example, assume that we have 6 circles indexed from 0 to 5. Indexing is based on their order in the object’s x and y attributes. We calculate the center-to-center distance between circle 0 to all other circles (circle 0 to circle 1, circle 0 to circle 2, circle 0 to circle 3, and ...). Then we calculate center-to-center distance between circle 1 to all other circles (circle 1 to circle 0, circle 1 to circle 2, circle 1 to circle 3, and ...). We repeat this process for all circles. It turns out that the following circles are too close to each other (overlapping):

circle    0    to    1
circle    1    to    0
circle    1    to    2
circle    2    to    1
circle    2    to    3
circle    3    to    2
circle    4    to    5
circle    5    to    4

        For each pair, we select the circle with lower index. In this case, we remove circles 0 (from 0-1 pair), 1 (from 1-2 pair), 2 (from 2-3 pair), and 4 (from 4-5 pair) by deleting the corresponding object’s x and y attributes.


1.12 circleCollision (15 points)

This class method handles the behavior of colliding circles by calculating their position, velocity, and label according to their group membership (susceptible, infected, recovered, or death). The criterion for agents/subjects collision which are represented as circles is described in section 1.11. 

        Use the approach that was described in section 1.11 to identify overlapping circles and perform the following tasks:

• Once you selected the colliding circles (circles 0, 1, 2, and 4 in the example of section 1.11 which are colliding with circles 1, 2, 3, 5), instead of deleting them, move the center position (attributes x and y) of the first circle (circle with lower index) to 2.01*radius unit distance away from the center of its paired circle along the center-to-center direction. For example if two circles have the following center coordinates at a collision time [0.524, 0.373] and [0.532, 0.373], then their coordinate will change to [0.516, 0.373] and [0.532, 0.373]. In case, two circles fully overlap (have the same center coordinates), move the center of the first circle by 2.01*radius unit distance away from the center its paired circle along a random unit length direction. Make sure to update agents center coordinate in x and y attributes (rounded to 3 decimal points), accordingly.

Note that, in case circles have small radius and high velocity, you will observe partial circle overlaps or jumps which is acceptable in one time instance of simulation. The approach described above typically separate circles in the next movement. For a pair of colliding circles, make sure to only modify the location of a circle that is not a member of dead population.

• If one of the colliding agents/subjects/circles belongs to the susceptible group and the other to the infected, then the susceptible agent will be infected (change label to 1) with the probability of infProb.

• Calculate and update vx and vy attributes of colliding circles by calling updateCollisionVelocity(). If one of the colliding circles is a member of dead population, update the vx and vy attributes of the other circle to the negative of its original value.


1.13 checkRecovered

This provided class method checks if infected agents have been sick for the duration of greater than or equal to the recoveryTime, after which agents either die with the probability of pDeath or recover. An agent’s label is modified from 1 to 3, if an agent/subject dies and to 2, if an agent/subject recovers. The velocity attributes (vx, vy) of agents who die are set to zero.


1.14 makeStatic

This provided class method accepts one argument (labelCode) as an integer and makes the velocity attributes (vx, vy) of agents whose labels are equal to labelCode to zero.


1.15 getGroupPercents

This provided class method calculates the percent of susceptible (susc), infected (infec), recovered (recov), and dead (dead) people at each instance of simulation, rounded to one decimal point. For example, if at a particular time in the simulation, we have 100 subjects, out of which 70 are susceptible, 15 are infected, 10 are recovered, and 5 are dead then, we will have 70.0% of agents are susceptible, 15.0% are infected, 10.0% are recovered, and 5.0% are dead.


1.16 updateAgentsNumbers

This provided class method appends numpy object variables timeArray, suscArray, infArray, recoArray, deadArray after each iteration of simulation. For example at initial time point, timeArray = [], at the next time increment dt, timeArray = [dt], followed by timeArray = [dt, 2*dt, ...].


1.17 simulate

This provided class method executes the simulation. Inputs to this class method are simSteps and vis which are the number of steps in the simulation (an integer) and an object of class visualize, respectively. Other inputs are xLow,xHigh,yLow,yHigh, which defines the x-coordinate thresholds for hitting the left and right walls and y-coordinate thresholds for hitting the bottom and top walls (all floats), respectively. At each simulation itera tion in this method, circles position, velocity, and label will be updated and displayed.


1.18 getNumberOfCircles

This provided class method returns the number of circles.


2 Visualize class (35 points)

You have been given a template script simVis.py that contains constructor and template methods for class visualize. This class allows you to draw and update circles and filled areas trajectory at the each instance of simulation (see Figure 1). With this class you can generate two side-by-side sub-figures. The first sub-figure (left panel) follows the trajectory of circles and their labels during the simulation, and the second sub-figure (right panel) follows the percentage of each subgroup (SIRD) at each iteration of simulation. This class has the following two class attributes:

colorDict = { 0: ’ green ’ , 1 : ’ red ’ , 2 : ’ gray ’ , 3 : ’ black ’ }

faceColorDict = { 0: ( 0 , 1 , 0 , . 3 ) , 1 : ( 1 , 0 , 0 , . 3 ) , \

2 : ( 0 . 5 , 0 . 5 , 0 . 5 , . 3 ) , 3 : ( 0 , 0 , 0 , . 8 ) }

        Here key values representing group labels (0: S, 1: I, 2: R, 3: D).

        It contains the following attributes and methods:

Figure 1: An example of 80 days SIRD, 2D simulation. Left panel: green circles: susceptible subjects, gray: recovered subjects. Right panel: green area: percent of susceptible subjects over time, red area: percent of infected subjects over time, gray area: percent of recovered subjects over time. Note that, in this particular simulation, we don’t have any dead subjects.


2.1 constructor

In this provided class constructor, the following object attributes/variables are defined and initialized:

• figWidth: The width of figure (default = 10)

• figHeight: The height of figure (default = 5)

• Ax1xmin: The x-coordinate of left wall in left panel in Figure 1, initialized to zero.

• Ax1xmax: The x-coordinate of right wall in left panel in Figure 1, initialized to one.

• Ax1ymin: The y-coordinate of bottom wall in left panel in Figure 1, initialized to zero.

• Ax1ymax: The y-coordinate of top wall in left panel in Figure 1, initialized to one.

• pauseTime: Pause time after each update in your figure allowing the simulation to run as a movie (default = 0.001).

        In constructor, a subplot with one row and two columns and figure size provided above will be initialized. The returned values of subplot are assigned to f, ax1, and ax2 which are additional object attributes for class visualize. ax1 attribute allows you to control and modify left panel sub- figure and ax2 attribute allows you to control and modify right panel sub-figure.


2.2 circle (13 points)

This class method uses four input arguments x, y, radius,colorCode to draw a circle with a center coordinates of x, y, and radius value of radius using Circle method from matplotlib.patches. Assign edge color and face color according to the agent’s group label by using class attributes colorDict and faceColorDict, respectively. Add the circle to ax1 by using matplotlib add artist method.


2.3 drawCircles (14 points)

This class method accepts an input which is an object of class Agents and call circle method to draw circles for all subjects in the simulation in the left panel figure. Use time.sleep to pause for a random time between 0.001*[0 1) after adding each circle.


2.4 getXminMax

This provided class method gets the minimum and maximum x-coordinates of ax1 and assign it to Ax1xmin and Ax1xmax attributes, respectively.


2.5 getYminMax

This provided class method gets the minimum and maximum y-coordinates of ax1 and assign it to Ax1ymin and Ax1ymax attributes, respectively.


2.6 setAx1Limits

This provided class method sets the ax1 x-limits and y-limits to Ax1xmin and Ax1xmax and Ax1ymin and Ax1ymax, respectively.


2.7 setAx1Title (8 points)

This class method accepts an input which is an object of class Agents to setup the left panel figure’s title exactly as illustrated in Figure 1.


2.8 drawAxis2

This provided class method accepts two input arguments: i and class object Agents to plot the pattern observed in right panel in Figure 1 at each iteration of simulation represented by input variable i.


2.9 plotPause

This provided class method pauses the plot by the amount defined in the object attribute pauseTime.


2.10 axis1Clear

This provided class method clears the ax1 plot.


3 Application (15 points)

3.1 Initial simulation (5 points)

Run the simulation for 80 days with a simulation time increment of 0.5 day. Initialize the number of agents/subjects to 600 and the speed to 0.07 unit. Save the final figure after the completion of the simulation.


3.2 Mobility (5 points)

To see the effect of mobility on the spread of disease , modify the speed to 0.01. Keep other parameters the same as section 3.1. Save the final figure after the completion of the simulation.


3.3 Personal protection (5 points)

Assume that hand-washing and the use of face mask reduce the infPro to 0.5. Run the simulation with updated infPro. Keep other parameters the same as section 3.1. Save the final figure after the completion of the simulation.

Include all figures along with your write up regarding the interpretation of results in a pdf file named projectE App.pdf.


4 Grading

• This project should be implemented and completed individually. No code sharing is accepted and violations are subject to penalty.

• Make sure that codes that are completed by you in AgentClass.py, simVis.py and runSimulation.py are well-commented for full credit. This means that they should contain comments explaining what the code does. Avoid commenting every line in your code. Line-by-line commentary makes the code look almost unreadable. Break down your code into subsections and write a brief comment describing the task.

• We will deduct points if Python’s global keyword is used.

• Make sure your code is well organized. Points may be deducted for poor coding style.

• Upload AgentClass.py, simVis.py, runSimulation.py, and projectE App.pdf to GradeScope by 11:59pm on 4/18/21.