Python 高效地收集大量数据

Python 高效地收集大量数据,python,physics,astronomy,Python,Physics,Astronomy,我有一个程序,可以创建一个太阳系,集成到相邻行星之间发生近距离相遇(或者直到10e+9年),然后将两个数据点写入一个文件。当行星离得太近时,“尝试”和“例外”会起到旗帜的作用。此过程重复16000次。这一切都是通过导入模块完成的,该模块是一个软件包,集成了重力影响下粒子的运动 for i in range(0,16000): def P_dist(p1, p2): x = sim.particles[p1].x - sim.particles[p2].x

我有一个程序,可以创建一个太阳系,集成到相邻行星之间发生近距离相遇(或者直到10e+9年),然后将两个数据点写入一个文件。当行星离得太近时,“尝试”和“例外”会起到旗帜的作用。此过程重复16000次。这一切都是通过导入模块完成的,该模块是一个软件包,集成了重力影响下粒子的运动

for i in range(0,16000):
    def P_dist(p1, p2):
        x = sim.particles[p1].x - sim.particles[p2].x
        y = sim.particles[p1].y - sim.particles[p2].y
        z = sim.particles[p1].z - sim.particles[p2].z
        dist = np.sqrt(x**2 + y**2 + z**2)
        return dist

    init_periods = [sim.particles[1].P,sim.particles[2].P,sim.particles[3].P,sim.particles[4].P,sim.particles[5].P]

    try:
        sim.integrate(10e+9*2*np.pi)
    except rebound.Encounter as error:
        print(error)
        print(sim.t)

    for j in range(len(init_periods)-1):
        distance = P_dist(j, j+1)
        print(j,":",j+1, '=', distance)
        if distance <= .01: #returns the period ratio of the two planets that had the close enecounter and the inner orbital period between the two
            p_r = init_periods[j+1]/init_periods[j]
            with open('good.txt', 'a') as data: #opens a file writing the x & y values for the graph
                data.write(str(math.log10(sim.t/init_periods[j])))
                data.write('\n')
                data.write(str(p_r))
                data.write('\n')

问题不在于你每次发现一次亲密的邂逅都会写作。就是说,对于每一次遭遇,你打开文件,写一条输出记录,然后关闭文件。所有的打开和附加都很慢。请尝试这样做:打开文件一次,每个记录只写一次

# Near the top of the program
data = open('good.txt', 'a')
...
    if distance <= .01: #returns the period ratio of the two planets that had the close enecounter and the inner orbital period between the two
        # Write one output record
        p_r = init_periods[j+1]/init_periods[j]
        data.write(str(math.log10(sim.t/init_periods[j])) + '\n' +
                   str(p_r) + '\n')
...
data.close()
程序顶部附近的
#
数据=打开('good.txt','a')
...

如果距离很远,还有一个问题。我决定把我的样本量减少到4570个近距离接触。由于亲密接触并不是每次迭代都会发生,所以我想出了一种方法来保持程序运行,直到遇到4570次亲密接触。这是一个陈述,而不是一个问题。也许漏了一两个字?在我最近的一篇博文编辑中,我上传了一段与你类似的代码。这是获取我所需数据量的有效方法吗?啊。。。这些评论应该是关于问题的,而不是这个答案。你的想法是正确的,但逻辑是错误的。while循环是无限的:
count
当你进入循环时是1,它永远不会改变。您只有一个循环,但有两种退出方式:
j>=len(periods)
count>4570
。将这两个条件都编码到循环头中,或者使用第二个条件从循环中
中断
# Near the top of the program
data = open('good.txt', 'a')
...
    if distance <= .01: #returns the period ratio of the two planets that had the close enecounter and the inner orbital period between the two
        # Write one output record
        p_r = init_periods[j+1]/init_periods[j]
        data.write(str(math.log10(sim.t/init_periods[j])) + '\n' +
                   str(p_r) + '\n')
...
data.close()