naif 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
naif/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """ naif: numerical analysis and integer combinations of frequencies"""
2
+ from .spec import find_peak_freqs
3
+ from ._base_funcs import chi_p, mn_phi_om, abs_fft_spectrum
4
+ from . import _base_funcs
naif/_base_funcs.py ADDED
@@ -0,0 +1,155 @@
1
+ import numpy as np
2
+ import math
3
+ from scipy import integrate
4
+
5
+ twopi = 2.*np.pi
6
+
7
+ #--------------------
8
+ def chi_p(t, p=1):
9
+ """ Window function \chi_p(t)
10
+
11
+ Parameters
12
+ ----------
13
+ t: float array (size N)
14
+ Time symmetric, from -T/2 to T/2
15
+ p: int, optional
16
+ p parameter
17
+
18
+ Returns
19
+ -------
20
+ float array
21
+ Window function chi_p
22
+ """
23
+
24
+ T = t[-1] - t[0] # total integration time
25
+ fact_p = math.factorial(p)
26
+ fact_2p = math.factorial(2*p)
27
+ return (2.**p*fact_p**2/fact_2p)*(1. + np.cos(twopi*t/T))**p
28
+ # -----------------------
29
+ def abs_fft_spectrum(f):
30
+ """Return abs(fft(f)/N) with full FFT ordering and length N.
31
+
32
+ If f is real, use rfft internally and reconstruct the full-length
33
+ spectrum with the same ordering as np.fft.fft.
34
+ This should be faster than using fft.
35
+
36
+ If f is complex, use the usual complex FFT.
37
+ """
38
+
39
+ N = len(f)
40
+
41
+ if np.isrealobj(f):
42
+ spec_pos = np.abs(np.fft.rfft(f) / N)
43
+ spec = np.zeros(N, dtype=float)
44
+ n_pos = len(spec_pos)
45
+
46
+ # Positive frequencies: 0, +df, ..., +Nyquist if N even
47
+ spec[:n_pos] = spec_pos
48
+
49
+ # Negative frequencies reconstructed by Hermitian symmetry
50
+ if N % 2 == 0:
51
+ # even N: rfft includes both zero and Nyquist;
52
+ # neither should be duplicated
53
+ spec[n_pos:] = spec_pos[1:-1][::-1]
54
+ else:
55
+ # odd N: no exact Nyquist term
56
+ spec[n_pos:] = spec_pos[1:][::-1]
57
+ return spec
58
+ else:
59
+ return np.abs(np.fft.fft(f) / N)
60
+ #-------------------------
61
+ # Scalar product with Window function:
62
+ #def inner_prod(t, u1_chi, u2):
63
+ def inner_prod(t, u1_chi, u2, axis=-1):
64
+ """ Inner product <u_1, u_2>
65
+
66
+ Parameters
67
+ ----------
68
+ t: float array (size N)
69
+ Time symmetric, from -T/2 to T/2
70
+ u1_chi: complex array
71
+ u_1 * chi_p(t) - 1st arg. of inner prod. times window
72
+ u_2: complex array
73
+ Second argument of inner product
74
+ axis : int, optional
75
+ Axis along which to integrate. Default is -1 (just to vectorize the call, making it faster)
76
+
77
+ Returns
78
+ -------
79
+ complex
80
+ Innter product <u_1, u_2>
81
+ """
82
+
83
+ T = t[-1] - t[0]
84
+ integrand = u1_chi*np.conj(u2)
85
+ return (1./T)*integrate.simpson(integrand, x=t, axis=axis)
86
+ # -----------------------
87
+ def mn_phi_om(om, f_chi, t):
88
+ """ Calculates -\|(phi(omega)\| = -\|<f(t), exp(i om t)>\|
89
+
90
+ The continuous projection of the time series onto the frequency space.
91
+ It calcuates the minimum (instead of the maximum)
92
+ because Brent's looks for minima
93
+
94
+ Parameters
95
+ ----------
96
+ om: float
97
+ Frequency omega (continuous)
98
+ f_chi: complex array
99
+ f_k * chi_p(t) - the windowed time-series
100
+ t: float array
101
+ Time symmetric, from -T/2 to T/2
102
+
103
+ Returns
104
+ -------
105
+ float or ndarray
106
+ -\|phi(omega)\|. Scalar if `om` is scalar, otherwise array.
107
+ """
108
+
109
+ #return -np.abs(inner_prod(t, f_chi, np.exp(1j*om*t)))
110
+ om = np.asarray(om)
111
+ # If on is scalar, same as old version:
112
+ if om.ndim == 0:
113
+ return -np.abs(inner_prod(t, f_chi, np.exp(1j * om * t)))
114
+
115
+ # Vectorized behavior: one row per trial frequency
116
+ exp_om_t = np.exp(1j * om[:, None] * t[None, :])
117
+
118
+ return -np.abs(inner_prod(t, f_chi[None, :], exp_om_t, axis=1))
119
+ # -----------------------
120
+ def gs(t, u, e, chi):
121
+ """ Gram-Schimidt orthonomal basis
122
+
123
+ For each peak identified at om, build vector
124
+ u = exp(i* om * t),
125
+ and obtain e_k's normal to all previous ones
126
+ (by Gram-Schimidt orthonomalization).
127
+
128
+ Parameters
129
+ ----------
130
+ t: float array
131
+ Time symmetric, from -T/2 to T/2
132
+ u: complex array
133
+ u_k = exp(i om_k t) - non-orthonormal vectors
134
+ e: complex, array
135
+ e_k: set of orthonormal vectors already calc.
136
+ (it has only elements up to k)
137
+ chi: float array
138
+ chi_p(t) - the window function
139
+
140
+ Returns
141
+ -------
142
+ complex array
143
+ Orthonormal vectors
144
+ """
145
+
146
+ k = len(e)
147
+ u_chi = u*chi
148
+ # projection of u_k onto e_j:
149
+ proj_ue_kj = np.zeros((k,1), dtype=np.complex128)
150
+ for j in range(k):
151
+ proj_ue_kj[j] = inner_prod(t, u_chi, e[j])
152
+
153
+ tmp_e = u - np.sum(proj_ue_kj*e, axis=0)
154
+ tmp_e_chi = tmp_e*chi
155
+ return tmp_e/np.sqrt(inner_prod(t, tmp_e_chi, tmp_e))
naif/spec.py ADDED
@@ -0,0 +1,184 @@
1
+ import numpy as np
2
+ from scipy.optimize import minimize_scalar as minimize
3
+ from ._base_funcs import inner_prod, gs, chi_p, mn_phi_om, abs_fft_spectrum
4
+
5
+ twopi = 2.*np.pi
6
+
7
+ #--------------------
8
+ def find_peak_freqs(f_k, t, n_freqs=1, p=1, spec=False,
9
+ brent_tol=1e-10, eps_spec=1e-7, n_scan_peak=100, verbose=True):
10
+ """Finds frequencies of peaks in the power spectrum,
11
+ from highest to lowest amplitudes
12
+
13
+ Parameters
14
+ ----------
15
+ f_k: float array (size N)
16
+ Time-series associated with a coordinate;
17
+ e.g.: f = r, or f = r + ivr
18
+ t: float array (size N)
19
+ Time-steps for the time-series
20
+ n_freqs: int, optional
21
+ Maximum number of frequencies to extract. 1 if only the leading frequency
22
+ p: int, optional
23
+ The p parameter of the Window function chi_p; p=0 for no windowing; p=1 for the Hanning window
24
+ spec: boolean, optional
25
+ Output the spectra before extraction of each frequency?
26
+ brent_tol: float, optional
27
+ Tolearance error for Brent's minimum finder method
28
+ eps_spec: float, optional
29
+ Minimum amplitude for keeping extracting freqss. If below that, it ends before extracting all freqs.
30
+ n_scan_peak: int, optional
31
+ Number of points where phi(omega) is evaluated. In case Brent's method fails (rarely used).
32
+
33
+ Returns
34
+ -------
35
+ om_k: float array or number
36
+ Extracted frequencies, in descending order of amplitude
37
+ a_k: complex array or number
38
+ Amplitudes associated to the frequencies om_k
39
+ spec_k: (optional, depending on spec) complex array;
40
+ Format (n_freqs, N) or size N. Full (windowed) spectrum before extraction of kth freq.
41
+ """
42
+
43
+ N = len(f_k)
44
+
45
+ tc = 0.5*(t[0] + t[-1]) # center of the time base-line
46
+ t_sym = t - tc # time symmetric around tc
47
+ T = t[-1] - t[0]
48
+ fourpi_T = 2.*twopi/T
49
+ chi = chi_p(t_sym, p=p) # window function
50
+
51
+ # normal vectors from Gram-Schimidt orthonomalization:
52
+ e = np.zeros((n_freqs, N), dtype=np.complex128)
53
+ om_k = np.zeros(n_freqs)
54
+ a_k = np.zeros(n_freqs, dtype=np.complex128)
55
+
56
+ # spec_k = np.zeros((n_freqs, N))
57
+ if spec:
58
+ spec_k = np.zeros((n_freqs, N))
59
+ else:
60
+ spec_k = None
61
+
62
+ # frequencies where DFT is evaluated:
63
+ om = twopi*np.fft.fftfreq(N, T/N)
64
+ # windowed time-series:
65
+ f_k_chi = f_k*chi
66
+
67
+ # Extracting "fake" line at om = 0 (sum of amplitudes):
68
+ # Because of the windowing, this line has a finite width,
69
+ # and needs to be extracted like the others:
70
+ # e_0 = np.exp(1j*om[0]*t_sym)
71
+ # because om[0] = 0:
72
+ e_0 = np.ones_like(t_sym)
73
+ # complex amplitude of om = 0:
74
+ a_0 = inner_prod(t_sym, f_k_chi, e_0)
75
+ # Extract peak from time-series:
76
+ f_k = f_k - a_0*e_0
77
+
78
+ # Start real extraction
79
+ for k in range(n_freqs):
80
+ f_k_chi = f_k*chi
81
+ # original NAFF starts without windowing:
82
+ # FT_k = np.fft.fft(f_k)/N
83
+ # but windowing from the start identifies freqs.
84
+ # in the right order, and the 1st is the leading one:
85
+
86
+ # spec_k[k] = np.abs(np.fft.fft(f_k_chi)/N)
87
+ spec_now = abs_fft_spectrum(f_k_chi)
88
+ #spec_now = np.abs(np.fft.fft(f_k_chi) / N)
89
+ if spec:
90
+ spec_k[k] = spec_now
91
+
92
+ # identify raw (discrete) max. and a range around it:
93
+ #om_max = om[np.argmax(spec_k[k])]
94
+ om_max = om[np.argmax(spec_now)]
95
+ om_inf = om_max - fourpi_T
96
+ om_sup = om_max + fourpi_T
97
+
98
+ # mn_phi(omega) = - |<f(t), e^(i*omega*t)>|
99
+ # values used as brackets in Brent's method:
100
+ mn_phi_om_max = mn_phi_om(om_max, f_k_chi, t_sym)
101
+ mn_phi_om_inf = mn_phi_om(om_inf, f_k_chi, t_sym)
102
+ mn_phi_om_sup = mn_phi_om(om_sup, f_k_chi, t_sym)
103
+
104
+ # Normally, phi(omega) has a maximum
105
+ # (and -phi a minimum) near om_max,
106
+ # and both -phi(om_inf) and
107
+ # -phi(om_sup) > -phi(omega_max):
108
+ if ((mn_phi_om_inf > mn_phi_om_max) &
109
+ (mn_phi_om_sup > mn_phi_om_max)):
110
+ best_peak = minimize(mn_phi_om, args=(f_k_chi, t_sym),
111
+ bracket=(om_inf, om_max, om_sup),
112
+ tol=brent_tol, method='brent')
113
+ # the frequency at the peak:
114
+ om_k[k] = best_peak.x
115
+ else:
116
+ # when it's crowded with peaks
117
+ # (or the interval is not large enough)
118
+ # and the minimum is not well bracketed,
119
+ # we scan mn_phi_om looking for the local minimum
120
+ if verbose:
121
+ print ('Frequency ',k+1,
122
+ ' - Peak not found in first shot. Refining...')
123
+ try:
124
+ scan_om = np.linspace(om_inf, om_sup, n_scan_peak)
125
+ # Vectorizing mn_phi_om (faster), but we can use with scalar too:
126
+
127
+ # scan_phi = np.zeros(len(scan_om))
128
+ # for i in range(n_scan_peak):
129
+ # scan_phi[i] = mn_phi_om(scan_om[i], f_k_chi, t_sym)
130
+ scan_phi = mn_phi_om(scan_om, f_k_chi, t_sym)
131
+ # identify among where derivative changes sign,
132
+ # the one with minimum value:
133
+ d1 = np.diff(scan_phi)
134
+ d1sign = np.sign(d1)
135
+ signchange = ((np.roll(d1sign, 1)[1:] - d1sign[1:]) != 0).astype(int)
136
+ idx = np.where(signchange ==1)[0]
137
+ idx_min = idx[np.argmin(scan_phi[idx])]
138
+ om_k[k] = scan_om[idx_min]
139
+ except:
140
+ print ('Frequency ',k+1,
141
+ 'Unable to find peak frequency')
142
+ break
143
+
144
+ #un-normalized vector:
145
+ u = np.exp(1j*om_k[k]*t_sym)
146
+
147
+ if (k==0):
148
+ # The first one is necessarily normalized:
149
+ e[k] = u
150
+ else:
151
+ # Gram-Schimidt ortonormalization to get e from u:
152
+ e[k] = gs(t_sym, u, e[:k], chi)
153
+
154
+ # complex amplitude at om_k:
155
+ a_k[k] = inner_prod(t_sym, f_k_chi, e[k])
156
+ # remove spectral line from time-series:
157
+ f_k = f_k - a_k[k]*e[k]
158
+ if (np.abs(a_k[k]) < eps_spec):
159
+ break
160
+ # deliver frequencies in descending order of amplitude:
161
+ idx_sort = np.argsort(-np.abs(a_k))
162
+ a_k = a_k[idx_sort]
163
+ om_k = om_k[idx_sort]
164
+ if (spec==True):
165
+ spec_k = spec_k[idx_sort]
166
+ if (n_freqs==1):
167
+ out_spec = spec_k[0]
168
+ else:
169
+ out_spec = spec_k[:k+1]
170
+
171
+ if (n_freqs==1):
172
+ out_om = om_k[0]
173
+ out_a = a_k[0]
174
+ else:
175
+ # :k+1 is in case less than n_freqs are extracted:
176
+ out_om = om_k[:k+1]
177
+ out_a = a_k[:k+1]
178
+
179
+ if (spec==False):
180
+ return out_om, out_a
181
+ else:
182
+ return out_om, out_a, out_spec
183
+ #-------------------------------------------------
184
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Leandro Beraldo e Silva
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,26 @@
1
+ Metadata-Version: 2.1
2
+ Name: naif
3
+ Version: 0.1.3
4
+ Summary: Numerical Analysis and Integer combinations of Frequencies
5
+ Author: Leandro Beraldo e Silva
6
+ Author-email: lberaldoesilva@gmail.com
7
+ License: MIT
8
+ Requires-Python: >=3
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: numpy
12
+ Requires-Dist: scipy>=1.6.0
13
+
14
+ $\texttt{naif}$ is a pure-python package for numerical analysis of
15
+ frequencies for orbits. It is based on the NAFF algorithm originally
16
+ proposed by Laskar (1990, 1993), and further developed by Valluri &
17
+ Merritt (1998). It is specially based on, and improves on, the Fortran
18
+ code developed by Valluri & Merritt (1998). Besides extracting the
19
+ frequencies with largest amplitudes in the spectrum, the package also
20
+ has tools to print the spectra before extraction of each frequency and
21
+ to "debug" the frequency identification around a specific peak.
22
+
23
+ A summary of the algorithm and some discussion on frequency analyses
24
+ can be found in [Beraldo e Silva et al
25
+ 2023](https://ui.adsabs.harvard.edu/abs/2023arXiv230304828B/abstract). Please,
26
+ cite this paper if you use $\texttt{naif}$.
@@ -0,0 +1,8 @@
1
+ naif/__init__.py,sha256=kIDkME02R8YzWdOWl2LH2SAGkYt58fjQF7UC8x2Lp5w,192
2
+ naif/_base_funcs.py,sha256=_kgMfr35Htx-9qBHmtPjC9SrupxwzjzC8adS_dor0pM,4323
3
+ naif/spec.py,sha256=qWndlvwKzUUaSla-YuaCB1I_yLmDuKt_JcKGgTqifCk,6816
4
+ naif-0.1.3.dist-info/LICENSE,sha256=wrhHSrpy6fUy70N6SR_MvMVSd3WhnJovauqXkRaeWMg,1080
5
+ naif-0.1.3.dist-info/METADATA,sha256=pTRU2JsSSc3s3rnQUn1Orf9cdTBY8M4ohpQYJDRZPDQ,1112
6
+ naif-0.1.3.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
7
+ naif-0.1.3.dist-info/top_level.txt,sha256=vFV1GYBrrwoMiTFxQyUa9KIEwMAap8eIPXjtB5Odxvs,5
8
+ naif-0.1.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.6.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ naif