I generate some time-series out of a theoretical power spectral density.
Basically, my function in time-space is given by X(t) = SUM_n sqrt(a_n) + cos(w_n t + phi_n)
, where a_n
is the value of the PSD
at a given w_n
and phi
is some random phase. To get a realistic timeseries, i have to sum up 2^25
modes, and my t
of course is sized 2^25
as well.
If i do that with python, this will take some weeks...
Is there any way to speed this up? Like some vector calculation?
t_full = np.linspace(0,1e-2,2**12, endpoint = False)
signal = np.zeros_like(t_full)
for i in range(w.shape[0]):
signal += dataCOS[i] * np.cos(2*np.pi* t_full * w[i] + random.uniform(0,2*np.pi))
where dataCOS is sqrt a_n, w = w and random.uniform represents the random phase shift phi
You can use the outer
functions to calculate the angles and then sum along one axis to obtain your signal in a vectorized way:
import numpy as np
t_full = np.linspace(0, 1e-2, 2**12, endpoint=False)
thetas = np.multiply.outer((2*np.pi*t_full), w)
thetas += 2*pi*np.random.random(thetas.shape)
signal = np.cos(thetas)
signal *= dataCOS
signal = signal.sum(-1)
This is faster because when you use a Python for
loop the interpreter will loop at a slower speed compared to a C
loop. In this case, using numpy outer operations allow you to compute the multiplications and sums at the C
loop speed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.