将列表中的一个值与列表中的所有值进行比较

时间:2017-11-07 01:14:02

标签: python-3.x astronomy

我试图将数据库中每颗恒星的Ra(坐标)值与同一列表中其他恒星的所有其他Ra进行比较,并且仅在1度范围内拉出恒星。我上传了数据,并进行了转换。我的麻烦实际上是将所有值与所有其他值进行比较。 我在循环中使用布尔值。

for i,r in enumerate(lyrae):
    q=r['ra']-lyrae['ra']
    m=(q<1) & (q>0)
    c=q[m]
    print(r,c)
    for i,r in enumerate(lyrae):
        v=r['dec']-lyrae['dec']
        n=(v<1) & (v>0)
        b=v[n]
        print(i,b)

似乎不起作用。也需要永远加载。

1 个答案:

答案 0 :(得分:0)

看看这是否符合您的意思?使用高效的内置/ numpy / scipy函数可以节省大量的计算时间。例如,m=(q<1) & (q>0)可以替换为abs(q) < 1(同样,当您要查找1度范围内的所有对象时,m=(q<1) & (q>0)应为m=(q<1) & (q>-1))。

要在球面极坐标中正确找到物体,需要找到大圆距离,否则,计算将在极点附近和循环边界处失效(即(0.1,10.2)和(359.9,10.1))

如果你想在两个巨大的目录之间交叉匹配(例如,两者都是10 ^ 9行),由于代码效率低下,这不是可行的方法。但是,鉴于您的一个目录只有~700行,高效搜索功能的开发时间可能比搜索本身长得多。

import numpy as np

# Set arbitrary size for a reference catalogue and a RR Lyrae cataloge
cat_size = 1000000
lyrae_size = 1000

# Draw sample randomly in a cartesian plane for the catalogue
# (1) RA, (2) Dec and (3) unique ID
ra_cat = np.random.random(cat_size) * 360.
dec_cat = np.random.random(cat_size) * 180. - 90.
id_cat = np.arange(cat_size)

# Draw sample randomly in a cartesian plane for the RR Lyrae catalogue
ra_lyrae = np.random.random(lyrae_size) * 360.
dec_lyrae = np.random.random(lyrae_size) * 180. - 90.
id_lyrae = np.arange(lyrae_size)

def great_circle_distance(ra1, dec1, ra_list, dec_list):
    '''
    Finding the great circle distance between given points and the list of
    points given in equatorial coordinates. Note: this from cosine rule, which
    is not the most accurate way to find the great circle distance.
    Input:
    ra1, dec1 - the reference point in degrees
    ra_list, dec_list - is the list of object positions in degrees
    Output:
    list of distances between the reference point and the list of objects
    in units of degrees.
    '''
    ra1 = np.radians(ra1)
    dec1 = np.radians(dec1)
    ra2 = np.radians(ra_list)
    dec2 = np.radians(dec_list)
    # Great circle distance in radians
    dist = (np.arccos(np.sin(dec1) * np.sin(dec2) +
                      np.cos(dec1) * np.cos(dec2) * np.cos(ra1 - ra2)))
    return np.degrees(dist)

# Loop through the RR Lyrae catalogue
for i, position in enumerate(zip(ra_lyrae, dec_lyrae)):
    # Get the (RA, Dec) from zipped position
    ra, dec = position
    # Consider only objects within a 2x2 degree box
    mask_candidate = (np.abs(ra_cat - ra) < 1.) | (np.abs(dec_cat - dec) < 1.)
    # Get the distance between the RR Lyrae star to the objects in the box
    distance = great_circle_distance(
        ra, dec, ra_cat[mask_candidate], dec_cat[mask_candidate]
        )
    # Select all objects within 1 degree radius
    mask_final = (distance < 1.)
    # Get the unique ID of the catalogue objects
    id_cat_matched = id_cat[mask_candidate][mask_final]
    # print/save/further analysis with the list of matched objects
    print 'lyrae id: ' + str(i+1) + ' matched with catalogue id: ' + str(id_cat_matched)