当某个条件为m时,如何停止时间或打印时间

2022-12-01 04:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

这段代码是对森林火灾的模拟,我想让模拟在所有树木“烧焦”时停止,或者运行到最后,但打印燃烧所有树木所需的时间。我甚至不知道如何开始,所以我会很感激你的帮助!我在编码方面没有太多经验,最好使用最简单的方法,因为目前我必须手动查看所有树何时烧焦,很容易错过正确的时间

import pylab as plt
import matplotlib as mpl
import scipy as sp
import random as rd
import copy as cp
import time as tm

cdict = {
  'red'  :  ( (0.0, 1.0, 1.0),
              (0.3, 0.0, 0.0),
              (0.6, 255./256, 255./256),
              (1.0, 0.0, 0.0)),

  'green':  ( (0.0, 1.0, 1.0),
              (0.3, 1.0, 1.0),
              (0.6, 160./256, 160./256),
              (1.0, 0.0, 0.0)),

  'blue' :  ( (0.0, 1.0, 1.0),
              (0.3, 0.0, 0.0),
              (0.6, 0.0, 0.0),
              (1.0, 0.0, 0.0))
        }
cm = mpl.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

empty, tree, fire, charred = range(4)

plt.ion()

fig1 = plt.figure(num=1)

fig1.clear()
plt.show()
fig1.canvas.draw()
fig1.canvas.flush_events()

def count_states(matrix_):

counts = [0,0,0,0]
w,h = sp.shape(matrix_)
for y in range(h):
    for x in range(w):
        state = matrix_[x,y]
        counts[int(state)] = counts[int(state)] + 1

return list(counts)

def visualise(figure,matrix,time):

plt.cla()

plt.pcolor(matrix.T, vmin=0, vmax=3, cmap=cm)

plt.axis('square')

plt.title('time = ' + str(time))

figure.canvas.draw()
figure.canvas.flush_events()
maxTime = 50
width = 20
height = 20
ptree = 1
initial_delay = 2
time_between_frames = 0.2
matrix = sp.zeros([width, height])

initial_forest = cp.copy(matrix)
for x in range(width):
for y in range(height):

    random = rd.random()

    if random < ptree:
        matrix[x,y] = tree
matrix[:0] = empty


newmatrix = cp.copy(matrix)

visualise(fig1,matrix,'initial')

plt.savefig(name + '_initial.png')


matrix[rd.randint(0,width-1), rd.randint(0,height-1)] = fire

tm.sleep(initial_delay)

for time in range(maxTime):

    visualise(fig1,matrix,time)


for y in range(height):

    for x in range(width):

        state = matrix[x,y]

        if state == fire:
            state = charred


        if state == tree:

            for dx in [-1,0,1]:

                for dy in [-1,0,1]:

                    if matrix[(x+dx)%width, (y+dy)%height] == fire:

                        state = fire
        newmatrix[x,y] = state
matrix, newmatrix = newmatrix, matrix
tm.sleep(time_between_frames)
visualise(fig1,matrix,maxTime)
plt.savefig(name + '_final.png')

Tags: inimportfortimeasrangepltrandomwidthmatrixfireinitialstateheightfig1