python simple virus programming code, how to use python to make a spoof virus

This article will talk about simple virus programming codes in python and how to use python to make spoof viruses. I hope it will be helpful to you. Don’t forget to bookmark this site.

Virus spreading simulation program can also use python.

Overview

The thing is like this. @ele Lab, the UP master of Station B, wrote a simple epidemic spread simulation program to tell everyone the importance of staying at home. I believe everyone has watched the video, and the UP master also released the source code python example Basic 100 cases .

Because it was developed in Java, I didn't pay much attention at first. Later, I saw someone analyzing the code and found that I could understand it, and then I thought about how to implement it in Python.

A brief analysis of Java version programs

A person is an (x, y) coordinate point, and each person has a state.

public class Person extends Point {

private int state = State.NORMAL;

}

In each round of iteration, each person is traversed, and each person takes certain actions based on his or her own status, including:

move

status change

influence the others

The specific changes in these actions depend on the various coefficients defined.

After one iteration is completed, these points are printed, and different states correspond to different colors.

The Java drawing class Graphics is used directly in the drawing part.

Python version ideas

What should we do if we want to implement it in Python?

If the Java version is completely copied, each iteration needs to traverse everyone and calculate the distance to others, which is N^2 calculations. If there are 1,000 people, it will need to be cycled 1 million times. The performance of this Python is definitely poor.

However, Python has numpy, which can quickly operate on arrays. Combined with matplotlib, graphics can be drawn.

import numpy as np

import matplotlib.pyplot as plt

How to simulate a crowd

In order to reduce the number of functions passing parameters to each other and the use of global variables, we 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()

The coordinate data of everyone 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()

The status value and timer are also arrays, and a specified number of people are randomly selected to be infected each time:

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 a one-to-one correspondence can be formed.

Talents whose status changes record the time:

def random_people_state(self, num, state=1):

"""Randomly select people to set status

"""

assert self.count > num

# TODO: In extreme cases, an infinite loop may occur

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

# Record the time when the status changes

self._timer[i] = self._round

Through the status value, you can filter out the crowds, and each crowd is a slice view of people. The functions of numpy here are quite powerful and can be implemented with only very concise syntax:

@property

def healthy(self):

return self._people[self._status == 0]

@property

def infected(self):

return self._people[self._status == 1]

According to the established idea, we first define the actions to be performed in each iteration:

def update(self):

"""Update every iteration"""

self.change_state()

self.affect()

self.move()

self._round += 1

self.report()

The order is slightly different from that of the initial analysis, but it is not very important. You can also change their order.

How to change status

This step is to update the status array self._status and the timer array self._timer:

def change_state(self):

dt = self._round - self._timer

# The clock must be updated first and then the status

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 to be changed through slicing, and then update them all.

The specific implementation here is very simple, without introducing too many variables:

The status of infected persons within a certain period is set to confirmed. I simply assume here that the confirmed person is admitted to the hospital, so the opportunity to continue to infect others is lost (see below). If you want to make it more complicated, you can introduce states such as hospital bed, cure, and death.

how to influence others

Influencing others is the performance bottleneck of the entire program because the distance between each person needs to be calculated.

The simplification continues here, and only infected people are processed:

def infect_possible(self, x=0., safe_distance=3.0):

"""Infect nearby healthy people according to probability

The value of x refers to the normal distribution probability table. When x=0, the infection probability is 50%.

"""

for inf in self.infected:

dm = (self._people - inf) ** 2

d = dm.sum(axis=1) ** 0.5

sorted_index = d.argsort()

for i in sorted_index:

if d[i] >= safe_distance:

break # Out of range, don’t worry about it

if self._status[i] > 0:

continue

if np.random.normal() > x:

continue

self._status[i] = 1

# Record the time when the status changes

self._timer[i] = self._round

As you can see, the distance is still calculated through numpy matrix operations. However, each infected person needs to be calculated separately, so if there are many infected people, python's processing efficiency is impressive.

How to move

_people is a coordinate matrix, just generate the moving distance matrix dt and then add it. We can set a movable range width to control the moving distance within a certain range.

def move(self, width=1, x=.0):

movement = self.random_movement(width=width)

# Limit the movement of people in specific states

switch = self.random_switch(x=x)

movement[switch == 0] = 0

self._people = self._people + movement

Here we also need to add an option to control movement intention, which still uses normal distribution probability. Considering that this scenario may be reused, this method was specially extracted and an array containing only 0 1 was generated to act as a switch.

def random_switch(self, x=0.):

"""Randomly generate switch, 0 - off, 1 - on

The approximate value range of x is -1.99 - 1.99;

Corresponds to the probability of normal distribution. When the value is 0, the corresponding probability 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 results

After having all the data and changes, the next most important thing is to display the results graphically. Just use matplotlib's scatter plot directly:

def report(self):

plt.cla()

# plt.grid(False)

p1 = plt.scatter(self.healthy[:, 0], self.healthy[:, 1], s=1)

p2 = plt.scatter(self.infected[:, 0], self.infected[:, 1], s=1, c='pink')

p3 = plt.scatter(self.confirmed[:, 0], self.confirmed[:, 1], s=1, c='red')

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)

actual effect

start up.

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 for personal practice, some parameters are not fully extracted at present. If necessary, you can only change the source code directly.

postscript

From the results of multiple experiments, intuitive conclusions can be drawn by adjusting factors such as personnel mobility willingness and mobility distance.

This is my first time using numpy and matplotlib. I am learning and selling now. Please correct me if I use them improperly. The probability parameter settings have basically no scientific basis and are only for reference by Python enthusiasts.

In general, it should be feasible to use numpy to simulate virus infection. However, the influencing factors still need to be carefully designed. Performance is also an issue that needs to be considered.

Summarize

The above is a novel coronavirus epidemic spread simulation program written in Python introduced by the editor. I hope it will be helpful to you. Thank you very much for your support of the Script House website!

Guess you like

Origin blog.csdn.net/chatgpt002/article/details/132866800