【发布时间】:2010-09-28 17:19:23
【问题描述】:
这里是新手程序员。我正在编写一个程序来分析点(单元格)的相对空间位置。程序从数组中获取边界和单元格类型,其中 x 坐标位于第 1 列,y 坐标位于第 2 列,单元格类型位于第 3 列。然后它检查每个单元格的单元格类型和与边界的适当距离。如果它通过,它会计算它与数组中每个其他单元格的距离,如果距离在指定的分析范围内,它会将其添加到该距离处的输出数组中。
我的单元格标记程序在 wxpython 中,所以我希望也可以在 python 中开发这个程序,并最终将它粘贴到 GUI 中。不幸的是,现在 python 在我的机器上运行核心循环需要大约 20 秒,而 MATLAB 可以每秒执行大约 15 个循环。由于我计划对约 30 个案例乘以几种探索性分析类型进行 1000 个循环(具有随机比较条件),这不是一个微不足道的差异。
我尝试运行分析器,数组调用的时间是 1/4,其余几乎都是未指定的循环时间。
这是主循环的python代码:
for basecell in range (0, cellnumber-1):
if firstcelltype == np.array((cellrecord[basecell,2])):
xloc=np.array((cellrecord[basecell,0]))
yloc=np.array((cellrecord[basecell,1]))
xedgedist=(xbound-xloc)
yedgedist=(ybound-yloc)
if xloc>excludedist and xedgedist>excludedist and yloc>excludedist and yedgedist>excludedist:
for comparecell in range (0, cellnumber-1):
if secondcelltype==np.array((cellrecord[comparecell,2])):
xcomploc=np.array((cellrecord[comparecell,0]))
ycomploc=np.array((cellrecord[comparecell,1]))
dist=math.sqrt((xcomploc-xloc)**2+(ycomploc-yloc)**2)
dist=round(dist)
if dist>=1 and dist<=analysisdist:
arraytarget=round(dist*analysisdist/intervalnumber)
addone=np.array((spatialraw[arraytarget-1]))
addone=addone+1
targetcell=arraytarget-1
np.put(spatialraw,[targetcell,targetcell],addone)
这是主循环的matlab代码:
for basecell = 1:cellnumber;
if firstcelltype==cellrecord(basecell,3);
xloc=cellrecord(basecell,1);
yloc=cellrecord(basecell,2);
xedgedist=(xbound-xloc);
yedgedist=(ybound-yloc);
if (xloc>excludedist) && (yloc>excludedist) && (xedgedist>excludedist) && (yedgedist>excludedist);
for comparecell = 1:cellnumber;
if secondcelltype==cellrecord(comparecell,3);
xcomploc=cellrecord(comparecell,1);
ycomploc=cellrecord(comparecell,2);
dist=sqrt((xcomploc-xloc)^2+(ycomploc-yloc)^2);
if (dist>=1) && (dist<=100.4999);
arraytarget=round(dist*analysisdist/intervalnumber);
spatialsum(1,arraytarget)=spatialsum(1,arraytarget)+1;
end
end
end
end
end
end
谢谢!
【问题讨论】:
-
试试
xrange而不是range。 -
这给了我大约 25% 的改进,谢谢。
-
你确定你的两个例程给出了相同的结果(即它们都正确地执行了计算)吗?
-
是的,我正在检查 spatialsum/spatialraw(只是注意到我的命名方式不同。)它们都添加正确。
-
BUG:使用range(cellnumber),python排除了上限。