问题描述
我正在使用AstroPy SkyCoord进行具有数百万个数据的赤道坐标到银河坐标的转换,这非常慢.任何人都有加速它的想法,否则将需要花费永远的时间来运行整个数据集.代码如下:
I am using AstroPy SkyCoord to do conversion from equatorial coordinates to galactic coordinates with millions data, it is extremely slow. Anyone has idea to speed it up, otherwise it takes forever to run the whole dataset. The code is below:
from astropy import units as u
from astropy.coordinates import SkyCoord
import numpy as np
ra1 = np.loadtxt('data.txt',usecols=(0,))
dec1 = np.loadtxt('data.txt',usecols=(1,))
size = len(ra1)
for i in range(size):
ra = ra1[i]
dec = dec1[i]
c = SkyCoord(ra*u.degree, dec*u.degree)
cc = c.galactic
b = cc.b.degree
l = cc.l.degree
推荐答案
不要那样做.像numpy一样,以向量为单位进行思考.astropy中的大多数例程都应按矢量进行使用.
Don't do that. Think vector-wise, just like numpy. Most routines in astropy are meant to be used vector-wise.
因此:
from astropy import units as u
from astropy.coordinates import SkyCoord
import numpy as np
c = SkyCoord(np.array(ra1)*u.degree, np.array(dec1)*u.degree)
cc = c.galactic
b = cc.b.degree
l = cc.l.degree
,不要在上面循环播放.
and don't loop over it.
c
, cc
, b
和 l
都将是数组(尽管有些是 SkyCoord
数组),其长度与 ra1
和 dec1
相同.
c
, cc
, b
and l
will all be arrays (albeit some are SkyCoord
arrays), with the same length as ra1
and dec1
.
对于您的计算机上的180,000,这需要不到一秒钟的时间来运行.
For a 180,000 on your machine, this should take less than a second to run.
当数据(列表)增长到超过10,000或100,000个元素时,几乎没有必要在Python中运行for循环.使用numpy(或此处为astropy),或者如果没有其他选择,请寻找Cython或什至用C编写代码.(或使用PyPi,但这会损失很多库兼容性.)
Hardly ever should you have to run a for-loop in Python when your data (list) grows to more than 10,000 or 100,000 elements. Use numpy (or astropy here), or if there is no other option, seek out Cython or even code it in C. (Or use PyPi, but that loses a lot of library compatibilities.)
在遍历(大)列表/数组时,Python的速度并不快,而且从来都不是.
Python is not fast when looping over (large) lists/arrays, and it was never meant to be.
这篇关于AstroPy SkyCoord非常慢,该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!