In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to use Python to realize novel coronavirus epidemic transmission simulation program". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Analysis of Java version Program
A person is a (x, y) coordinate point, and each person has a state.
Public class Person extends Point {private int state = State.NORMAL;}
In each iteration, each person is traversed, and each person makes certain actions according to his or her own state, including:
Changes in mobile status affect others
The specific changes in these actions depend on the various coefficients defined.
A round of iterations is completed, printing these points, and different states correspond to different colors.
The Java drawing class Graphics that is directly used in the drawing part.
Python version of ideas
What should we do if we want to implement it in Python?
If the Java version is fully copied, each iteration needs to traverse everyone and calculate the distance from others, which is N ^ 2 calculations. If it's 1000 people, it needs to be recycled a million times. The performance of this Python must be urgent.
However, Python has numpy, which can quickly manipulate arrays. Combined with matplotlib, you can draw graphics.
Import numpy as npimport matplotlib.pyplot as plt
How to simulate the crowd
To reduce the number of functions passing parameters to each other and using global variables, let's also define a class:
Class People (object): def _ init__ (self, count=1000, first_infected_count=3): self.count = count self.first_infected_count = first_infected_count self.init ()
Everyone's coordinate data is an array of N rows and 2 columns, accompanied by a certain state:
Def init (self): self._people = np.random.normal (0,100, (self.count, 2) self.reset ()
Status values and timers are also arrays, and each time a specified number of people are randomly selected for infection:
Def reset (self): self._round = 0 self._status = np.array ([0] * self.count) self._timer = np.array ([0] * self.count) self.random_people_state (self.first_infected_count, 1)
The key point here is that the size of the auxiliary array is consistent with the number of people, so that an one-to-one correspondence can be formed.
People with a change in status record the time by the way:
Def random_people_state (self, num, state=1): "randomly selected person setting status"assert self.count > num # TODO: in extreme cases there will be an infinite loop n = 0 while n"
< num: i = np.random.randint(0, self.count) if self._status[i] == state: continue else: self.set_state(i, state) n += 1 def set_state(self, i, state): self._status[i] = state # 记录状态改变的时间 self._timer[i] = self._round 通过状态值,就可以过滤出人群,每个人群都是 people 的切片视图。这里 numpy 的功能相当强大,只需要非常简洁的语法即可实现: @property def healthy(self): return self._people[self._status == 0] @property def infected(self): return self._people[self._status == 1] 按照既定的思路,我们先来定义每轮迭代要做的动作: def update(self): """每一次迭代更新""" self.change_state() self.affect() self.move() self._round += 1 self.report() 顺序和开始分析的略有差异,其实并不是十分重要,调换它们的顺序也是可以的。 如何改变状态 这一步就是更新状态数组 self._status 和 计时器数组 self._timer: def change_state(self): dt = self._round - self._timer # 必须先更新时钟再更新状态 d = np.random.randint(3, 5) self._timer[(self._status == 1) & ((dt == d) | (dt >14))] = self._round self._status [(self._status = = 1) & (dt = = d) | (dt > 14)] + = 1
Still filter out the targets you want to change through slices, and then update them all.
The specific implementation here is very simple, without introducing too many variables:
In a certain cycle of infection (infected), the status is set to confirmed (confirmed). I simply assume here that the diagnosed person will be admitted to the hospital, so I lose the opportunity to continue to infect others (see below). If you want to make it more complicated, you can introduce hospital beds, cure, death and other states.
How to influence others
Affecting others is the performance bottleneck of the entire program, because the distance between each person needs to be calculated.
Simplification continues to be made here, dealing only with infected people:
Def infect_possible (self, x = 0, safe_distance=3.0): "" the value of healthy people who are close to the probability of infection refers to the normal distribution probability table. "" for inf in self.infected: dm = (self._people-inf) * * 2d = dm.sum (axis=1) * * 0.5 sorted_index = d.argsort () for i in sorted_index: if d [I] > = safe_distance: break # is out of range Forget if self._ status [I] > 0: continue if np.random.normal () > x: continue self._ status [I] = 1 # record the time of state change self._ timer [I] = self._round
As you can see, the distance is still calculated through the matrix operation of numpy. However, each infected person needs to be calculated separately, so if there are more infected people, the processing efficiency of python is touching.
How to move
_ people is a coordinate matrix, just generate the moving distance matrix dt, and then it can be added. We can set a movable range width to control the moving distance within a certain range.
Def move (self, width=1, xroom.0): movement = self.random_movement (width=width) # define the movement of people in a specific state switch = self.random_switch (xampx) movement [switch = = 0] = 0 self._people = self._people + movement
We also need to add an option to control the movement intention, which still takes advantage of the normal distribution probability. Considering that this scenario is likely to be reused, this method is specifically extracted to generate an array containing only 0 1 to act as a switch.
Def random_switch (self, x switch 0.): "" randomly generate switches, 0-off, 1-on x roughly range from-1.99 to 1.99; the probability corresponding to normal distribution is 50%: param x: control switch ratio: return: "" normal = np.random.normal (0,1, self.count) switch = np.where (normal < x, 1, 0) return switch
Output result
With all the data and changes, the next most important thing is to graphically display the results. Just use matplotlib's scatter plot directly:
Def report (self): plt.cla () # plt.grid (False) p1 = plt.scatter (self.healthy [:, 0], self.healthy [:, 1], splash1) p2 = plt.scatter (self.infected [:, 0], self.infected [:, 1], plt.scatter (self.confirmed [:, 0], self.confirmed [:, 1]) plt.legend ([p1, p2, p3], [healthy', 'infected'') 'confirmed'], loc='upper right', scatterpoints=1) t = "Round:% s, Healthy:% s, Infected:% s, Confirmed:% s"%\ (self._round, len (self.healthy), len (self.infected), len (self.confirmed)) plt.text (- 200,400, t, ha='left', wrap=True)
The actual effect is activated.
If _ _ name__ ='_ main__': np.random.seed (0) plt.figure (figsize= (16,16), dpi=100) plt.ion () p = People (5000, 3) for i in range (100): p.update () p.report () plt.pause (.1) plt.pause (3)
Because this small demo is mainly used by individuals to practice hands, some parameters have not been completely extracted at present. If you need it, you can only change the source code directly.
This is the end of the content of "how to use Python to achieve novel coronavirus epidemic transmission simulation program". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.