繁体   English   中英

Numpy arrays 错误地具有相同的值?

[英]Numpy arrays incorrectly have identical values?

我有一个小程序,我正在玩创建与疾病传播相关的进化算法。 我遇到了一个问题,让我有点疯狂地试图找出问题所在。

我有两个 numpy arrays,“感染”,这是一个数组,其中每个元素都是该个人是否已暴露的二进制表示和“current_infections”,这只是持续感染,应该按天递增。

例如:

感染 = [0,0,0,1,1]
current_infections = [0,0,0,15,0]

这将代表 5 个人,其中 3 个人患有该病 15 天,而 4 个人患有该病的时间足够长,以至于他们已经康复并且目前不再患有该病。


infections = []
current_infections = []
responsible_infections = []
spread_rate = 0.1
contagious_period = 20
initial_node_infections = 2
current_network = #this is an array of adjacency matrices for nodes in a network


#initial infections.
def initialize_infections():
  global infections, current_infections, responsible_infections
  responsible_infections = np.zeros(current_network.shape[0])
  infections = np.zeros(current_network.shape[0])
  for each in rd.sample(range(len(current_network)), k=initial_node_infections):
    infections[each] = 1
  current_infections = infections[:]

# runs a day in simulation. 
# returns 1 if there are still ongoing infections at the end of day, 0 if not
def progress_day():
  global current_infections
  print(np.sum(current_infections), np.sum(infections))  #should not be equivalent, yet they are
  for i in range(len(current_infections)):
    if current_infections[i] >= 1 and current_infections[i]<contagious_period:
      current_infections[i]+=1
    elif current_infections[i]>=contagious_period:
      #patient recovered
      current_infections[i] = 0
  for i in range(contacts_per_day):
    for j in range(len(current_infections)):
      if current_infections[j] >= 1:
        spread_infection(current_network[j], j)

  if not np.sum(current_infections):
    return 0
  else:
    return 1




#given infected node it calculates spread of disease to adjacent nodes.
def spread_infection(person, rp):
  global infections, current_infections, responsible_infections
  for x in range(len(person)):
    if person[x] == 1 and infections[x] == 0 and rd.random()<=spread_rate:
      current_infections[x] = 1
      infections[x] = 1
      responsible_infections[rp]+=1 #infections a given person is responsible for.


def main():
  global current_infections, infections
  initialize_infections()
  day = 0
  while day<100:
    if not progress_day():
      break
    day+=1

main()

出于某种原因,对 current_infections 中的元素所做的更改也在感染中对该元素进行了更改,因此它们都在递增。 我是否对 numpy 做错了什么,以至于它们在某种程度上是同一个数组?

current_infections = infections[:]使 current_infections 成为感染元素的视图。 使用current_infections = infections.copy()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM