在python中自动计算旋转周期

2024-05-16 04:23:43 发布

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

我是编程初学者,我使用python。我有一个计算恒星自转周期的代码,但是每次我都要更改恒星ID,这需要我付出努力和时间来完成。 我能自动更改星号吗?你知道吗

from lightkurve import search_lightcurvefile
lcf = search_lightcurvefile('201691589').download()  ## star Id = 201691589
lc = lcf.PDCSAP_FLUX.remove_nans()
pg = lc.to_periodogram()
Prot= pg.frequency_at_max_power**-1
print Prot

我将所有要使用的“stars\u ID”保存在一个txt文件中(starID.txt文件)有10000行,我想自动计算旋转周期(Prot),这样代码就可以从txt文件中一个接一个地获取星ID并进行计算,然后将星ID和Prot保存在csv文件中(两列:'星ID','Prot')。你能帮我做吗。你知道吗


Tags: 文件代码fromtxtidsearch编程时间
2条回答

这应该让你接近,但我没有一堆明星身份证,也不是在我的领域。你知道吗

要点:

  1. 使用^{}模块读写文件。你知道吗
  2. 当您有需要多次调用的代码时(对于逻辑分组,通常甚至只调用一次),您需要考虑将其打包成function

你还有其他的研究方向。如果我不尝试使事情比基本循环更简洁一点,那么代码将相当长,我尽量不使它太简洁。希望你能继续跟进。你知道吗

from lightkurve import search_lightcurvefile

import csv

# You need to read the file and get the star IDs. I'm taking a guess here that
# the file has a single column of IDs
with open('starID.txt') as infile:
    reader = csv.reader(infile)
    # Below is where my guess matters. A "list comprehension" assuming a single 
    # column so I just take the first value of each row.
    star_ids = [item[0] for item in reader] 


def data_reader(star_id):
    """
    Function to read periodogram for a star_id

    Returns [star_id, periodogram]
    """

    lcf = search_lightcurvefile('201691589').download()
    lc = lcf.PDCSAP_FLUX.remove_nans()
    pg = lc.to_periodogram()
    Prot= pg.frequency_at_max_power**-1

    return [star_id, Prot]


# Now start calling the function on your list of star IDs and storing the result
results = [] 
for id_number in star_ids:
    individual_result = data_reader(id_number) # Call function
    results.append(individual_result) # Add function response to the result collection


# Now write the data out
with open('star_results.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)
    writer.writerows(results)

你说的是“初学者”,所以这是一个几乎是第一次写程序的人的答案。你知道吗

在Python中,每次更改star id的直接方法是编写一个函数并使用不同的star id多次调用它。将您拥有的代码转换为一个函数而完全不改变其行为可能如下所示:

from lightkurve import search_lightcurvefile

def prot_for_star(star_id):
  lcf = search_lightcurvefile(star_id).download()
  pg = lcf.PDCSAP_FLUX.remove_nans().to_periodogram()
  return pg.frequency_at_max_power**-1

# Now use map to call the function for each star id in the list
star_ids = ['201691589', '201692382']
prots = map(prot_for_star, star_ids)
print(list(prots))

但这可能是低效的代码。我不知道这个lightkurve包到底做了什么,所以有其他方法可以节省时间。如果需要对每个lcf对象执行多个操作,则可能需要对函数进行不同的结构。或者,如果创建一个周期图是CPU密集型的,并且最终多次生成相同的周期图,那么有很多方法可以节省时间。你知道吗

但这是使用抽象避免重复同一行代码的基本思想。你知道吗

将原始恒星id与其自转周期结合起来可以这样实现。这是一点函数式编程的魔力。你知道吗

# interleave the star ids with their periods of rotation
for pair in zip(star_ids, prots):
  # separate the id and prot with a comma for csv format
  print(','.join(pair))

Python脚本的输出可以存储在csv文件中。你知道吗

相关问题 更多 >