1

这是一个由我的教授分发并由学生修改的群体遗传学项目。

基本上,它应该使用给定的样本、种群和突变率 (u) 模拟预期的突变数量 20 次。然而,一个关键部分是总分支长度 (L),它是各种较小分支长度 (branch_length) 的总和。但是,当我将 L 定义如下时,它会不断返回错误:

  L += branch_length  
NameError: name 'L' is not defined

我不确定出了什么问题,因为 tree_depth 的定义方式相同并且可以完美地工作。

这是完整的代码:

from random import expovariate
from pgen import poidev
K = 77       # sample size (number of gene copies)
twoN = 5000  # population size
u = .001

tree_depth = 0.0 # age of last common ancestor in generations

# Each pass through loop deals with one coalescent interval.

for A in range(20):
    while K > 1:
        h = K*(K-1)/(2.0*twoN) # hazard of a coalescent event
        t = expovariate(h)       # time until next coalescent event
        tree_depth += t
        branch_length = t*K
        K -= 1
        L += branch_length
    S = poidev(u*L)
    print "Simulation:", A+1, "Total Mutations:", S
print "Total tree depth (L):", L, "generations"

我只是错过了一些非常非常明显的东西吗?提前致谢。

4

2 回答 2

4

L += x将 x 添加到现有的 L,但您尚未初始化 L。大概,您希望L = 0位于文件顶部的某个位置。

于 2011-10-07T22:03:06.247 回答
1

你需要L = 0在做之前定义L += x

一般来说,在修改之前需要定义变量。对于赋值,没有问题,因为 python 会为你推断类型。

一些例子:

>>> a += 0 #Invalid
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = 5 #Valid
>>> a += 0 #Now it's valid, because a is defined.
>>> 
>>> my_list.append(5) #Invalid
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'my_list' is not defined
>>> my_list = [] 
>>> my_list.append(5) #Now valid
>>> my_list
[5]
>>>
>>> my_list2 = [1, 2, 3, 4] #Valid, because it's an assignment.
于 2011-10-07T22:22:41.040 回答