Introduction

Estimation of the instantaneous phase and amplitude is essential for electrical and mechanical engineering, synchronization studies of oscillatory systems of different nature, time series analysis of physiological data, and, in particular, for neuroscience1,2,3,4. A special application is developing efficient sensing algorithms for adaptive deep brain stimulation, a recent advancement of a widely used treatment option for Parkinson’s disease and other neurological disorders5. One of the directions in this development is to adjust stimulation parameters according to a peripheral or neurophysiological signal’s phase and amplitude computed on the fly6,7,8,9,10,11,12. The popular approach to phase and amplitude estimation is to exploit the analytic signal approach based on the Hilbert Transform (HT) or, equivalently, the wavelet transform with a complex wavelet1,13,14,15. However, this widely-used tool is non-causal and therefore not appropriate for real-time analysis, whereas causal estimation of phase and amplitude is often crucial for closed-loop control of complex systems. Despite several attempts to adapt the HT for a causal measurement16,17, the reliable and fast estimation of phase and amplitude of real-world signals remains challenging.

In this study, we do not rely on the Hilbert Transform. Instead, we follow another development line and extend our previous approach18,19 for real-time estimation based on the oscillation theory and nonlinear dynamics. The main idea is as follows. Suppose we have an oscillator, e.g., an electronic circuit, which amplitude and phase we can monitor. Next, suppose we feed our measurement to this oscillator. We choose the oscillator so that there is a one-to-one correspondence between the oscillator’s phase and amplitude (what we can monitor) and the measured signal (what we want to determine). If this correspondence is achieved, we recompute the monitored state of the oscillator into desired quantities. Thus, the oscillator acts as a measuring device. Indeed, we will not exploit a physical oscillator but use a simple computer program that simulates the oscillator’s dynamics. In our approach, we rely on two well-known physical effects: linear resonance and synchronization. We present and compare three techniques that provide a fast estimation of phases and amplitudes, using only the past of the time series. We test the algorithms on model data and apply them to neural time series. Namely, demonstrating our approach’s efficiency, we causally estimate the phase and amplitude of the accelerometer tremor measurements and Parkinsonian patients’ beta-band brain activity and compare the results with non-causal HT-based analysis.

Results

Hilbert transform versus causal estimation

A common practice in extracting the amplitude and the phase of an input signal s(t) is based on application of the Hilbert transform. The HT analysis provides proper estimates for the instantaneous phase of s(t) for narrow-band one-component signals with slowly varying amplitude and frequency. We emphasize that, though formally one can compute the HT for an arbitrary signal s(t), not in all cases the extraction of the amplitude and the phase will lead to reasonable results. We also stress that HT is a non-causal operation: to extract features at time instant \(t'\), one has to know both the signals’ past \(t<t'\) and future \(t>t'\). For a further detailed discussion of the HT’s properties and practical implementation, see Methods.

The main goal of this paper is not to extend HT approach to complex signals (see20,21 for examples of such an extension), but to provide and explore causal alternatives to the HT approach. In what follows, we use the HT-based amplitude \(a_H\) and the HT-based phase \(\varphi _H\) as a “gold standard” for testing our algorithms. Strictly speaking, this is reasonable for narrow-band signals only. Definition and determination of the proper phase and amplitude for a complex signal represent a challenging problem that we do not address here. Instead, we use an operational approach: a proper amplitude should correctly represent an envelope of the signal; a proper phase should gain \(2\pi \) at each oscillatory cycle. Below, we present three techniques for causal computations and compare the computed amplitudes and phases with non-causally obtained \(a_H,\varphi _H\).

Causal estimation techniques

Phase locking approach

The first technique exploits the ideas from the synchronization theory. It is well-known that a force s(t) acting on a limit-cycle oscillator can entrain (lock) it. It means that the oscillator’s frequency becomes equal to that of the force, and their phases differ by a constant. Thus, the phase of the locked limit-cycle oscillator will correspond to the phase of the signal. For our purposes, it is helpful to use the simplest oscillator model, the so-called phase oscillator. To ensure the phase-locking to the force, we have to adjust the oscillator’s frequency to the signal’s frequency. We assume that we do not know the latter a priori, but can only roughly estimate it. We propose a simple approach that starts with this estimate and automatically tunes the “device’s” frequency to ensure the locking and thus provides the instantaneous phase \(\varphi _L(t)\). The amplitude is not determined with this approach. One can treat the suggested scheme as a software implementation of a phase-locked loop22. Technically, the algorithm reduces to solving differential equation incorporating measured data given at discrete time points; for details of the technique and its implementation, see Methods.

Nonresonant linear filter

The second technique relies on the resonance effect. Our measuring “device” consists now of two linear damped oscillators. The oscillators’ frequency is much larger than the frequency of the signal, i.e., the system is far from resonance. We choose the damping parameters to ensure that (i) phase of the first linear oscillator equals that of the input and that (ii) amplitude of the second one and the input relate by a known constant multiplicator. The technique yields both phase \(\varphi _N(t)\) and amplitude \(a_N(t)\), where the index N stands for “non-resonant”.

Resonant linear filter

Our third approach adopts the technique used for model studies in our previous publications18,19. The corresponding “device” consists of a linear oscillator in resonance with the measured signal and of an integrating unit. It also provides both the phase and the amplitude that we denote as \(\varphi _R\) and \(a_R\), respectively. The method exploits the known relation between the resonant oscillator’s phase and amplitude and those of the input. Additionally, the resonant oscillator acts as a bandpass filter for experimental data.

Technically, both latest techniques require the numerical solution of linear differential equations with the input signal s(t). We present a detailed description of the techniques and the developed numerical schemes in the Methods section. Like the phase-locking algorithm, both techniques include an automated frequency-tuning algorithm to adjust the systems to the a priori unknown signal’s frequency.

Testing the algorithms

Artificial data

First, we test our approach on artificial data. All algorithms work well with simple narrow-band signals like slowly modulated sine waves. So, we do not show these results and proceed with a more complicated case. The signal is

$$\begin{aligned} s(t)=\left[ 1+0.95\cos (\Omega _1 t)\right] \cdot \left[ \cos (\psi (t))+ 0.2\cos (2\psi (t)+\pi /6)+0.1\cos (3\psi (t)+\pi /3)\right] \;, \end{aligned}$$
(1)

where

$$\begin{aligned} \psi (t)=t+5\sin (\Omega _2 t)\;, \end{aligned}$$

its waveform has three harmonics. The signal is amplitude- and phase-modulated, see Fig. 1a; it is sampled with \(\Delta =0.01\) to yield \(s(\Delta k)=s_k\). The frequencies are \(\Omega _1=\sqrt{2}/30\), \(\Omega _2=\sqrt{5}/60\). Another test signal is \(\bar{s}_k=s_k+\xi _k\), where \(\xi _k\) are Gaussian random numbers with zero mean and standard deviation 0.05, see Fig. 2a.

Figure 1
figure 1

(a) The test signal s according to Eq. (1) and its Hilbert amplitude \(a_H\) (red); one can see that \(a_H\) does not represent a good envelope for s. On the contrary, the Hilbert-based phase estimation yields good results, and therefore we take it for the ground truth. Panels (b, c, d) show the difference between the Hilbert phase \(\varphi _H\) and causally estimated phases (\(\varphi _L\), \(\varphi _N\), and \(\varphi _R\) are obtained by means of the locking-based technique, non-resonant and resonant oscillator, respectively). These panels demonstrate that the output of the developed causal algorithms is very close to the HT-phase. Notice that in (c) we show \((\varphi _H-\varphi _N)\mod 2\pi \): within the first 20 time units the phase difference decreases to \(-14\pi \) until it saturates and oscillates around \((\varphi _H-\varphi _N)\mod 2\pi =0\).

Figure 2
figure 2

(a) Short epoch of noisy data \({\bar{s}}\) (blue) and causally obtained amplitudes \(a_N\) (red) and \(a_R\) (magenta); the latter provides the most smooth envelope (cf. \(a_H\) in Fig. 1a). When the signal’s amplitude is very small, the noise dominates and phase determination becomes complicated. The HT approach fails here (blue line in (b,c)), while both locked and resonant oscillator “devices” provide reasonable results. The performance of the non-resonant technique is poor: when the amplitude nearly vanishes, the phase estimated by this technique (not shown) is not better than the Hilbert phase.

For testing all three algorithms, we set the initial frequency of the device to be \(10\%\) higher than the actual value; in this way, we imitate the imprecision of the initial frequency estimation. The other parameters are given in the Methods.

Phase-locked oscillator

Figure 1b shows that after a short transient, the phase determined by the “device” becomes close to the Hilbert phase. The difference is due to the presence of the harmonics (for a mono-component amplitude-modulated signal, the phase difference is very small, its standard deviation is 0.03). The locking-based measurement’s advantage becomes evident in the noisy data, as expected for a phase-locked loop approach: here, the real-time estimation provides a reasonable phase even at low amplitudes, where the noise dominates, see Fig. 2a,b.

Non-resonant linear oscillator (filter)

This approach works well in noise-free case (Fig. 1c). Initially, the difference with \(\varphi _H\) grows rapidly due to decaying high-frequency oscillation with the natural frequency \(\omega \) of the system. (We remind that frequency \(\omega \) of the non-resonant oscillator is much larger than the input’s frequency.) Nevertheless, after the transient, the performance is comparable or even better than that of two other techniques. In the presence of noise the performance is poor because noisy perturbations excite high-frequency oscillation with the frequency \(\omega \). The amplitude estimation is slightly worse than that via HT, see Fig. 2a. Thus, for processing without a filter, this technique is not optimal.

Resonant linear oscillator (filter)

This technique also demonstrates efficient phase estimation, see Fig. 1d for the noise-free data and Fig. 2c for the noisy case. Actually, the results for the latter are hardly distinguishable from those in Fig. 2b, though the frequency adaptation of the resonant oscillator is faster. The technique also provides the instantaneous amplitude, see Fig. 2a. Notice that the Hilbert amplitude \(a_H\) for the multi-component signal \({\bar{s}}\) is not the perfect envelope. The real-time amplitude \(a_R\) is not perfect either, but is much more smooth than \(a_H\).

Estimation without an additional filter: tremor data

The tremor time series (Fig. 3a) is relatively simple: it resembles the test signal from the previous section. The tremor data is amplitude modulated, and its power spectrum also contains several harmonics (Fig. 3b). However, the real-world signals are naturally more complicated than the simple test data series Eq. (1). Analyzing them, one frequently faces additional difficulties. For the tremor signal under consideration these features are: a drift of the baseline; presence of epochs when the amplitude vanishes; and outliers. To cope with the baseline fluctuation, we exploit the following causal detrending algorithm. For each new measurement point, we remove the mean value computed over several previous cycles. For the sake of computational speed, we update this value several times per period. We denote the detrended signal by \({\tilde{s}}_k\) (Fig. 3c).

Figure 3
figure 3

The raw tremor data (a) and its power spectral density S(f), computed by the Burg algorithm (b). Panels (c,d) show some epochs of \({\tilde{s}}_k\) (the original signal with the constant component and baseline fluctuation removed on the fly), the Hilbert amplitude \(a_H\) (red) and the causal amplitude \(a_R\) (magenta). The latter provides a smooth envelope and does not reflect the outliers (d). Panels (e,f) demonstrate the Hilbert phase \(\varphi _H\) (blue) and causal phases \(\varphi _L\) (red) and \(\varphi _R\) (magenta). For epochs with vanishing amplitude, causal phases do not exhibit noisy jumps as the Hilbert phase. The causal phases are stable with respect to outliers (f).

Figure 3c compares the Hilbert amplitude \(a_H\) with the causally computed \(a_R\). Like in the case of test data, the causally computed amplitude \(a_R\) is a better estimation of the envelope than \(a_H\) is. Moreover, computation of \(a_R\) is stable with respect to outliers (Fig. 3d). Next, in Fig. 3e,f we show the Hilbert phase \(\varphi _H\) along with two causally-obtained phases \(\varphi _L\) and \(\varphi _R\). We see that for large-amplitude oscillation, all the phases practically coincide. When the amplitude almost vanishes, the “device” of the locking-based method falls out of synchrony and makes one cycle less. On the contrary, the resonant-oscillator phase \(\varphi _R\) and the Hilbert phase reveal the same number of cycles. We emphasize, that both causal techniques are not sensitive to the outliers in the original data, while the Hilbert approach is (see Fig. 3f). Finally, we mention that the non-resonant oscillator technique works poorly for the unfiltered tremor data. Only if we use the bandpass filter \(4.5\pm 2\) Hz, then this technique works perfectly.

Wide-band signal: beta-band brain activity

Elevated beta-band activity has been established as a marker for rigidity and bradykinesia in patients with Parkinson’s Disease23. As such, it has been employed in several studies of adaptive deep brain stimulation aiming for automatic adjustment of stimulation parameters in response to beta-band amplitude7,9. The analysis of the beta-band brain activity requires a bandpass filter preprocessing. We use a simple FIR filter with bandwidth \(17\pm 4\) Hz (281-point filter was generated by the Matlab fir1 function). A causal filtration introduces a delay, but this is a necessary price to be paid. Our tests with this signal demonstrate that the non-resonant-oscillator technique outperforms the other two that fail because of the substantial variation of the signal’s amplitude. Noteworthy, due to the bandpass, the approach works without the baseline correction and the frequency adaptation. Hence, the algorithm implementation requires only a few lines of code. The results are illustrated by Fig. 4.

Figure 4
figure 4

Beta-band brain activity data. (a) Power spectral density S(f) of the raw (blue) and filtered (red) series. (b) Bandpass filtered series (arbitrary units). (c) A short epoch of the filtered series (yellow) and two their envelopes computed via the Hilbert Transform (blue) and by means of the non-resonant oscillator (red). The envelopes practically overlap, as is also illustrated by panel (d). Panel (e) demonstrates the difference between the Hilbert phase \(\varphi _H\) and the real-time phase \(\varphi _N\) along with the amplitude. One can see that the phase difference is negligible when the amplitude is finite, and is not small only when the amplitude is at the level of noise (so that the phase is not well-defined). It means that for these amplitude values, neither HT nor causal algorithms provide a reliable phase determination. (Here \({\tilde{a}}_N\) is the amplitude rescaled for better visibility.) The probability distribution of the phase difference in panel (f) confirms practical coincidence of \(\varphi _H\) and \(\varphi _N\).

Computation time

An obvious requirement for a real-time estimation algorithm is its computational efficiency. Since our algorithms do not exploit the Hilbert Transform, they are extremely speedy. We illustrate here the performance of the Matlab code used to generate Fig. 1 and presented in Supplementary Material. The time to process a new measurement point on a desktop iMac computer with the 3.8 GHz Quad-Core Intel Core i5 processor is:

  • for the locking-based measurement (phase only): \(6.4\cdot 10^{-7}\) s;

  • for the non-resonant-oscillator algorithm (phase and amplitude): \(6.7\cdot 10^{-7}\) s;

  • for the resonant-oscillator algorithm (phase and amplitude): \(3.7\cdot 10^{-7}\) s.

One can further improve the efficiency by compiling the algorithms in C++.

Comparison to other techniques

There exist two approaches to causal estimation. The idea of the first approach is to complement the running-window non-causal computation of the HT by a predictor16,24,25. This approach works well for signals with a slow frequency variation, i.e., in cases where the frequency practically does not change within the running window. This property allows for the prediction of the phase value on the time scale of the window. The recent publication17 exploits a conceptually similar idea: an additional filter in the frequency domain reduces the boundary effects of the finite-length HT and, therefore, helps to predict the phase at the end of the finite-length window. However, there are two weak points in this approach. First, it is sensitive to modulation. Since even the non-causal HT does not provide a proper estimation for the signal \({\bar{s}}\), illustrated in Figs. 1 and 2, it is not surprising that prediction based on a finite-window HT fails as well. In Supplementary Material, Fig. 4, we illustrate this issue using the technique of Ref.17. Second, the HT-based methods require a time-consuming computation of the direct and inverse Fourier transforms in a running window. So, the algorithm by Schreglmann et al.17 is about thirty times more computationally demanding than an oscillator-based approach.

A different approach has been recently suggested by Wodeyar et al.26. Assuming that the signal represents a linearly filtered stationary stochastic process and using some portion of the data, they construct a linear state-space model27. When constructed, this model determines the phase and its error bars for new measurements (but not the amplitude). Wodeyar et al.26 demonstrate with several tests that their technique outperforms other methods, but they admit that the model construction is computationally demanding. We performed two tests with this algorithm, for details, see Supplementary Material. The method by Wodeyar et al. performs poorly for the test signal \({\bar{s}}\). For the brain activity data shown in Fig. 4, the precision of their algorithm is slightly worse then that of our non-resonant oscillator approach, but the algorithm26 is very slow. For example, it takes about one minute to construct a model and then use it to process a one-minute long segment of data. Our algorithm on the same computer runs about 0.03 sec.

Estimation error

We briefly discuss the complicated problem of an uncertainty quantification. To the best of our knowledge, there are no established techniques for error bars computation for a phase of a signal with unknown statistical properties, even for the non-causal Hilbert-based approach. (See28 for the analysis of the effects of noise and artifacts on the HT phase estimation.) In a recent attempt to tackle this problem, Wodeyar et al.26 computed confidence intervals for a signal representing linearly filtered Gaussian noise. Since our techniques are designed to analyze general rhythms and do not rely on any assumptions about their origin, we suggest two operational approaches to quantify the estimation precision. In both cases, we exploit some time interval to train the algorithms, cf.26. (1) As is demonstrated in Fig. 4e, for vanishing amplitude, the phase estimation error is of the order of \(\pi \) for any techniques because the phase is not defined for zero amplitude. On the contrary, if the amplitude is not small, then \(\varphi _N\approx \varphi _H\). Thus, the computed phase \(\varphi _N(t_k)\) is unreliable if \(a_N(t_k)<a_{thr}\) and reliable otherwise; for the threshold we use \(a_{thr}=\text {max}(a_N)/20\), where \(\text {max}(a_N)\) is the maximal value over the training interval. This observation suggests the following algorithm: We use the training interval to compute the standard deviation, \(\sigma \), for the circular difference \(\varphi _H-\varphi _N\) as a function of \(a_N\). In doing this, we consider the Hilbert phase as the ground truth. Completing the training, we proceed with the causal measurement: obtaining new values \(\varphi _N\) and \(a_N\), we compute the error bars as \(\varphi _N\pm 3\sigma (a_N)\). For the considered example, we find \(\sigma (a_N)\approx 6\cdot 10^{-4}\cdot a_N^{-0.94}\), for \(a_N>a_{thr}\). For details and plots, see Supplementary Material. (2) The results in Fig. 4e (supported by the dependence \(\sigma (a_N)\) shown in Fig. 2 in Supplementary Material) suggest a simplified algorithm: we discard the phase estimates for \(a_N<a_{thr}\), while for \(a_N>a_{thr}\) we take \(\varphi _N\) as a reliable measurement, since its deviation from the Hilbert phase is negligible. (The same consideration applies to quantifying the uncertainty of \(\varphi _R\).)

Figure  4d suggests a similar approach to uncertainty in the amplitude measurement: the width of the stripe in this representation provides a measure for deviation of \(a_N\) from \(a_H\). Computing \(a_N\), \(a_H\) over the training interval, we use this measure to obtain the error bars for the causal measurement.

Discussion

To summarize, in this paper, we considered the problem of causal instantaneous amplitude and frequency estimation. Contrary to attempts to adjust the inherently non-causal analytic signal approach, we used oscillation theory ideas. We presented and tested three algorithms. The first one exploits the phase-locking property of nonlinear limit-cycle oscillators, while the other two rely on linear resonance. Technically, we encountered solving differential equations incorporating experimental data; we suggested efficient numerical schemes to solve them. Below, we discuss the advantages and disadvantages of all three techniques. Since these techniques aim at real-time applications, we pay special attention to their computational efficiency. Although we illustrated our approach with tremor and brain activity data, it is of general interest to the nonlinear dynamics and control science community. One can exploit the method to analyze and control complex nonlinear systems of various origins, e.g., electrochemical oscillators29, nanomechanical systems30, and power grids31, to name just a few.

The locking-based technique is similar to the phase-locked loop approach and provides the phase only. It works well for relatively narrow-band signals like the tremor data and does not require an additional bandpass filter. It can easily incorporate the frequency adaptation that makes the algorithm able to cope with the signal’s frequency’s slow variation. The technique does not work well with the signals like beta-band activity, where both the frequency and the amplitude vary relatively fast; this results in frequent loss of synchrony. The algorithm is computationally efficient: the only demanding operations for a new phase value are several computations of the sine function.

As an advantage of the resonant oscillator technique, we mention that it provides both the phase and the amplitude. It is stable to high-frequency noise because the resonant oscillator acts as a weak bandpass filter. However, it requires baseline correction because the integrator unit enhances the low-frequency perturbations. The implementation described in the Methods section is very efficient, provided the oscillator’s frequency does not change. Adaptation of the frequency to that of the signal requires recomputation of algorithm’s coefficients what slightly reduces the efficiency.

If extraction of the rhythm of our interest requires a bandpass filter, the non-resonant oscillator approach is the best choice. Using the beta-band brain activity as an illustrative example, we demonstrated that this causal algorithm provides phase and amplitude very close to non-causally computed Hilbert Transform-based values. An essential advantage of the algorithm is its efficiency: computation of the new phase and amplitude values requires only several arithmetic operations and two function calculations. This property makes the algorithm especially appropriate for the real-time processing of high-frequency signals.

We emphasize that all three techniques are much faster than approaches based on the HT, because the latter require the computation of the direct and inverse Fourier transform in a running window plus additional filtration to compensate for the boundary effects and non-causal nature of the HT. Taken together, the techniques suggested here may provide useful means for real-time detection of phase and amplitude in the context of adaptive deep brain stimulation. For example, estimation of instantaneous amplitude has been implemented by interpolating beta-filtered and squared LFP data32. However, this approach is not able to recover the signal’s phase simultaneously. Additionally tracking phase may augment therapeutic benefit, though, by delivering stimulation pulses at specific points within the oscillatory cycle. This has been shown to effectively disrupt pathological oscillations10,11,12,17. So far, to our knowledge, adaptive stimulation algorithms integrating both the phase and amplitude of a signal have not been established yet.

Finally, we mention that our techniques do not cause any additional delay. The processing delay is only due to a causal filter if the latter is required, e.g., for brain activity data. To minimize the delay, one has to exploit specially designed filters33.

Methods

In the description of time-series analysis algorithms the input is an oscillatory signal s(t), sampled with interval \(\Delta \). Thus, available is a sequence \(s(t_k)=s(k\Delta )=s_k\).

The non-causal Hilbert-Transform based approach

In this approach one constructs the corresponding complex-valued analytic signal \(Z(t)=s(t)+\text {i}{\hat{s}}(t)\), where \({\hat{s}}(t)=\pi ^{-1}\text {P.V.}\int _{-\infty }^\infty \frac{s(\tau )}{t-\tau }\text {d}\tau \) is the HT of s(t). Obviously, the HT is a non-causal operation; HT of a finite-length time series yields spurious values for the boundaries. The absolute value and argument of Z(t) provide the instantaneous Hilbert amplitude \(a_H(t)\) and phase \(\varphi _H(t)\), respectively. For a narrow-band one-component signals like \(s(t)=A(t)\cos [\omega (t)t]\), where A(t), \(\omega (t)\) are slow functions of time, the analytic signal approach provides \(a_H\approx A\) and \(\varphi _H\approx \int \omega (t) \mathrm {d}t\). For a discussion of the HT’s practical implementation and technical hints we refer, e.g., to1,4,34. In a practical implementation either a discrete evaluation of the integral is performed, or a discrete Fourier transform is used.

Causal estimation of phase and amplitude

In these methods, we obtain the value of the instantaneous phase \(\varphi (t_k)=\varphi _k\) and amplitude \(a(t_k)=a_k\) by using only the current and the previous values of the signal, i.e., \(s_k,\; s_{k-1},\; \ldots \).

Measuring “device”: phase-locked oscillator

The synchronization theory says that an oscillatory force s(t) acting on a limit-cycle oscillator can entrain it, if the frequency of the force is close to the natural frequency of the limit-cycle oscillator. It means that the oscillator’s frequency becomes equal to that of the force, and their phases fulfill the locking condition \(\varphi -\theta \approx \text{ const }\), where \(\theta \) and \(\varphi \) are the oscillator’s and the signal’s phases. For our purposes, it is appropriate to use the so-called phase oscillator. Its forced dynamics is described by

$$\begin{aligned} \dot{\theta } =\omega -\varepsilon \sin \theta \cdot s(t)\;, \end{aligned}$$
(2)

where \(\varepsilon \) is a parameter that determines the coupling strength. Consider first a harmonic force, \(s=a\cos (\nu t)\). If \(\omega =\nu \), then in the locked state \(\varphi \approx \theta \). However, \(\nu \) is not known a priori, but we assume that we can roughly estimate it. Let this initial guess be \(\nu _0\). Thus, we set initially \(\omega =\nu _0\) and start our computation with this value. To adapt the phase oscillator to the signal, we estimate the frequency of the forced oscillator \(\nu _e\) on the fly. (The index e stands for “estimated”). To this end, for the time instant t, we take previously computed unwrapped phases \(\theta \) for the time interval \([t-T_e,t]\), where \(T_e\sim 2\pi /\nu _0\) (approximately one or two cycles). Assuming that within this time interval \(\theta (t')=\theta (t-T_e)+\nu _e(t'-t+T_e)\), we compute the frequency \(\nu _{e}\) via the linear fit. Next, we update the oscillator’s autonomous frequency as

$$\begin{aligned} \omega \quad \longrightarrow \quad \omega +K(\nu _e-\omega )\;, \end{aligned}$$
(3)

where K is a constant update factor. Adapting the frequency in this way, we ensure a transition from the unlocked to locked dynamics. Performing frequency estimation several times per cycle, we successfully estimate the phase of signals with slowly drifting frequency. We expect that this algorithm also works if the force’s amplitude a slightly varies with time (so that the oscillator still remains locked).

One can treat the suggested scheme as a software implementation of a phase-locked loop22, cf. also35. Practically, we have to solve the differential Eq. (2) numerically, whereas its right-hand side is known only in discrete time points \(t_k\). The easiest way is to exploit Euler’s technique with the integration step \(\Delta \) to advance from the known value \(\theta _k\) at \(t_k\) to the new phase \(\theta _{k+1}\) at \(t_{k+1}=t_k+\Delta \), given a new measurement \(s_{k+1}\). This technique may work properly if \(\Delta \) is sufficiently small; otherwise, the numerical solution becomes unstable. (We recall that \(\Delta \) is the fixed sampling interval that cannot be made arbitrarily small). Therefore, to advance the solution of Eq. (2) from \(\varphi _k\) to \(\varphi _{k+1}\) given new measurement \(s_{k+1}\), we use the parabolic approximation of s(t) on the interval \([t_k,t_{k+1}]\) and then exploit the standard Runge-Kutta algorithm. (Notice that the Runge-Kutta step can be much smaller than \(\Delta \).) The coefficients of the parabolic fit are computed from \(s_{k-1},s_{k},s_{k+1}\). Starting with some initial condition, e.g., \(\theta _0=0\), we achieve, after a short transient (see examples in Fig. 1), the synchronous state where \(\varphi _k\approx \theta _k\). Notice that the phase oscillator can be complimented by a low-pass filter:

$$\begin{aligned} \dot{\varphi }=\omega +\varepsilon w\;, \qquad \tau \dot{w} +w=-s(t)\sin \theta \;, \qquad \end{aligned}$$

then the scheme becomes the simplest traditional phase-locked loop4,22; for \(\tau \rightarrow 0\) it reduces to Eq. (2). This extension may be useful for the data with strong high-frequency noise but it does not show any advantages for the tremor data we use.

Measuring “device”: non-resonant linear oscillator

Our second measuring “device” is linear damped oscillator:

$$\begin{aligned} \ddot{x}+\alpha \dot{x} +\omega ^2 x= s(t)\;, \end{aligned}$$
(4)

where \(\omega \) and \(\alpha \) are the frequency and the damping parameter of the oscillator, respectively. Suppose first that s(t) is harmonic, \(s(t)=a\cos (\nu t)=a\cos (\varphi (t))\). The well-known stationary solution of linear Eq. (4) is \(x=b\cos (\nu t+\beta )\), where \(b=\frac{a}{\sqrt{(\omega ^2-\nu ^2)^2+(\alpha \nu )^2}}\) and \(\beta =\arctan \left[ \frac{-\alpha \nu }{\omega ^2-\nu ^2}\right] \). Thus, the forced system (4) oscillates with the force’s frequency \(\nu \) and the amplitude b. The dependencies of the amplitude ratio b/a and of the phase shift \(\beta \) on the forcing frequency \(\nu \) reflect the well-known resonance effect. Knowing the oscillator’s state \(x(t)=b\cos (\nu t+\beta )\), \(\dot{x}(t)=-b\nu \sin (\nu t+\beta )\) we find the amplitude and phase of the external force:

$$\begin{aligned} a(t)=\sqrt{x(t)^2+[\dot{x}(t)/\nu ]^2}\sqrt{(\omega ^2-\nu ^2)^2+(\alpha \nu )^2}\;, \qquad \varphi (t)=\arctan \left[ \frac{-\dot{x}(t)}{\nu x(t)}\right] -\beta \;. \end{aligned}$$
(5)

Thus, if our “device” yields x(t) and \(\dot{x}(t)\), then we easily compute a(t) and \(\varphi (t)\), provided the frequency \(\nu \) of the force is known. However, it is not known but can only be roughly estimated. Moreover, generally, it varies with time. Before we discuss how to cope with this fact, we mention how we practically obtain x(t) and \(\dot{x}(t)\). Here, we make use of the linearity of Eq. (4) and develop and exploit an efficient numerical scheme, presented below. With this scheme, starting with some initial conditions, e.g., \(x_0=\dot{x}_0=0\), we obtain, after a short transient, the forced solution of Eq. (4) and compute \(a(t_k)\) and \(\varphi (t_k)\) from Eqs. (5).

Now, we discuss how to choose the parameters of the measuring oscillator. Recall that to compute \(a,\varphi \), we need the value of the signal frequency \(\nu \). First, let us consider the amplitude measurement. Inspecting Fig. 5, we see that if we take a large value of \(\alpha \) (strongly damped oscillator) and \(\nu \ll \omega \) then the ratio b/a is practically independent on \(\nu \). Thus, to compute the second square root in Eq. (5) we need only a very rough estimate of \(\nu \). For the phase estimation, the damping parameter shall be different. Indeed, as follows from Fig. 5b, now we have to choose \(\alpha \) to be small, then the phase shift \(\beta \approx 0\) in a wide range of \(\nu \) and the phase of the external force equals the phase of the oscillator. A reasonable choice is to take the oscillator’s frequency \(\omega \) about five times larger than \(\nu \).

Figure 5
figure 5

Resonance curves for amplitude (left) and phase shift (right) for the linear oscillator with frequency \(\omega =5\). Blue and red curves correspond to the weakly (\(\alpha =0.2\)) and strongly (\(\alpha =6\)) damped oscillator, used for the phase and amplitude measurement, respectively (these parameters were used to process the artificial data). The domains where \(b/a\approx \text {const}\) (for the red curve) and \(\beta \approx 0\) (for the blue curve) are marked by red and blue arrows, respectively. These are intervals of signal frequency \(\nu \) where the algorithm’s performance is good. We see that \(\omega \approx 5\nu \) is a reasonable choice.

Thus, we neglect \(\beta \) in the expression for \(\varphi \) and compute \(\sqrt{(\omega ^2-\nu ^2)^2+(\alpha \nu )^2}\) in the expression for a only once, using an initial guess \(\nu _0\) for frequency. However, the terms \(\sqrt{x(t)^2+[\dot{x}(t)/\nu ]^2}\) and \(\arctan \left( \frac{-\dot{x}(t)}{\nu x(t)}\right) \) essentially depend on \(\nu \). Imprecise estimation of \(\nu \) and/or its variation with time results in spurious oscillations of the estimated amplitude and phase. To remove these oscillations and to make the results less dependent on the initial frequency estimation, we improve this estimation by computing the signal frequency in real-time as discussed in the precious section. We start with an initial guess \(\nu _0\) and begin the computation of a(t), \(\varphi (t)\). After a transient time of the order of several cycles, we begin with the frequency estimation to obtain \(\nu _e\). (The estimation is performed in exactly same way as for the phase-locked oscillator.) We use \(\nu _{e}\) instead of \(\nu _0\) and, in this way, significantly improve the real-time computation of the amplitude and frequency. Performing frequency estimation several times per cycle, we track the slowly drifting signal frequency. (Notice that for the bandpass filtered signal used in the last example, the algorithms works well without any frequency correction. Here we set \(\nu\) equal to the center of the bandpass.)

In summary, for the amplitude measurement, we need a strongly damped oscillator, while for the phase estimation, we need an oscillator with small damping. If we need both measurements simultaneously, then the solution is to exploit two “devices” concurrently. Though Eq. (5) are derived for the harmonic force, we expect that they approximately hold for signals with a slow variation of the amplitude and frequency. The presented numerical tests confirm this expectation.

Measuring “device”: resonant linear oscillator

Here we adopt the technique used for model studies in our previous publications18,19. The device consists of a linear oscillator in resonance with the measured signal and an integrating unit:

$$\begin{aligned}&\ddot{x}+\alpha \dot{x} +\omega ^2 x = s(t)\;, \end{aligned}$$
(6)
$$\begin{aligned}&\mu \dot{z} + z = \dot{x} \;. \end{aligned}$$
(7)

The role of the harmonic oscillator Eq. (6) is twofold. First, it acts as a bandpass filter and the damping factor \(\alpha \) determines the width \(\delta f\approx \alpha /2\pi \) of the bandpass. Second, the harmonic oscillator yields signal \(\dot{x}\) which phase is close to that of the input x(t), provided the frequency \(\omega \) is close to the mean frequency of s(t). (This condition also ensures that the band-pass is centered at the frequency of the signal.) Next, for \(\mu \gg 1\) Eq. (7) acts as the integrating unit. Its output is shifted by \(\pi /2\) with respect to \(\dot{x}\). It is useful to rescale \(\dot{x}\), z so that their amplitudes are close to that of s(t). For this, we compute \(u=\alpha \dot{x}\) and \(w=\alpha \omega _0\mu z\) and obtain the instantaneous phase and amplitude of s(t) as \(\varphi (t)=\arctan (w/u)\), \(a(t)=\sqrt{u^2 + w^2}\).

Solving the linear oscillator equation for discrete input signal

Here we present the numerical scheme for solving Eq. (4), adopted to the situation where the input signal is available at a finite sampling rate. Using the substitution \(y=xe^{\gamma t}\), where \(\gamma =\alpha /2\), one obtains

$$\begin{aligned} \ddot{y} +\eta ^2 y=s(t)e^{\gamma t}=S(t)\;, \quad \text {with } \eta ^2=\omega ^2-\gamma ^2\;. \end{aligned}$$

Another standard substitution

$$\begin{aligned} y=0.5(Ae^{\mathrm {i}\eta t}+A^*e^{-\mathrm {i}\eta t})\;, \qquad \dot{y} =0.5\mathrm {i}\omega (Ae^{\mathrm {i}\eta t}-A^*e^{-\mathrm {i}\eta t})\;, \end{aligned}$$
(8)

where \(A^*\) denotes complex conjugate of A, yields \(\dot{A}=-\mathrm {i}\eta ^{-1}S(t)e^{-\mathrm {i}\eta t}\). Integrating we obtain

$$\begin{aligned} A_{k+1}=A_k-\mathrm {i}\eta ^{-1}e^{-\mathrm {i}\eta t_k}\int _0^\Delta S(t_k+\tau )e^{-\mathrm {i}\eta \tau }\mathrm {d}\tau =A_k-\mathrm {i}\eta ^{-1} e^{-\mathrm {i}\eta t_k}I\;. \end{aligned}$$

Next, locally interpolating the measured signal s(t) by a parabola going through the points \(s_{k-1},s_k,s_{k+1}\) we compute the integral \(I=\int _0^\Delta S(t_k+\tau )e^{-\mathrm {i}\eta \tau }\mathrm {d}\tau \). As a result, we obtain the following practical scheme for integration of Eq. (4). First, we pre-compute the coefficients \(C_{1,2,3}\):

$$\begin{aligned} C_1=\mathrm {i}\eta ^{-1}e^{-\gamma \Delta }(I_2\Delta -I_3)/2\Delta ^2\;,\quad C_2=\mathrm {i}\eta ^{-1}(I_3/\Delta ^2-I_1)\;,\quad C_3=-\mathrm {i}\eta ^{-1}e^{\gamma \Delta } (I_2\Delta +I_3)/2\Delta ^2\;, \end{aligned}$$

where

$$\begin{aligned} I_1=i\eta ^{-1}(e^{-\mathrm {i}\eta \Delta }-1)\;,\quad I_2=\eta ^{-2}[e^{-\mathrm {i}\eta \Delta }(1+\mathrm {i}\Delta \eta )-1]\;, \quad I_3=\eta ^{-3}[e^{-\mathrm {i}\eta \Delta }(\Delta \eta (2+i\Delta \eta )-2\mathrm {i})+2\mathrm {i}]\;. \end{aligned}$$

Next, for given \(x_k,\dot{x}_k\) and the new measurement \(s_{k+1}\) we compute \(x_{k+1},\dot{x}_{k+1}\) in three steps:

  1. 1.

    Compute \( A_{k} = x_{k} - {\text{i}}(\dot{x}_{k} + \gamma x_{k} )/\eta \).

  2. 2.

    Compute \(A_{k+1}=A_k+C_1s_{k-1}+C_2s_k+C_3s_{k+1}\).

  3. 3.

    Compute \( x_{k+1}=\text{ Re }(A_{k+1}e^{\mathrm {i}\eta \Delta })e^{-\gamma \Delta }\;, \qquad \dot{x}_{k+1}=\left[ 0.5\mathrm {i}\eta (A_{k+1}e^{\mathrm {i}\eta \Delta }-A^*_{k+1}e^{-\mathrm {i}\eta \Delta })-\gamma \text{ Re }(A_{k+1}e^{\mathrm {i}\eta \Delta })\right] e^{-\gamma \Delta }\;.\)

We emphasize that all coefficients can be pre-computed, so that the integration step requires only a few summations and multiplications.

The extension of the approach to solving Eqs. (6,7) of the resonant oscillator is straightforward. The equation (6) of the linear oscillator is solved as just described. Then the known points \(\dot{x}_{k-1},\dot{x}_k, \dot{x}_{k+1}\) provide the local parabolic approximation of the function \(\dot{x}\) in Eq. (7). The solution of this linear equation is readily obtained by variation of the constant and reads:

$$\begin{aligned} z_{k+1}=(z_k-a+b\mu -2c\mu ^2)e^{-\Delta /\mu }+ a-b\mu +2c\mu ^2+b\Delta -2c\mu \Delta +c\Delta ^2 \;, \end{aligned}$$

with \(a=\dot{x}_k\), \(b=(\dot{x}_{k+1}-\dot{x}_{k-1})/2\Delta \), \(c=(\dot{x}_{k-1}-2\dot{x}_k+\dot{x}_{k+1})/2\Delta ^2\).

To summarize the presentation of numerical techniques, we emphasize that if the sampling rate is very high, the differential equations in all presented algorithms can be fast and easily solved by the midpoint or predictor-corrector technique36. However, the stability of these simple methods is not guaranteed.

Choosing parameters

Locking-based oscillator

The main parameter is the forcing coefficient \(\varepsilon \) (Eq. 2). The larger \(\varepsilon \) the faster the system synchronizes. On the other hand, the forcing term \(\varepsilon \sin \theta \cdot s(t)\) shall be small enough to ensure the monotonicity of the phase \(\theta \). So, if \(s(t)=a\cos \varphi \) then (Eq. 2) reads \(\dot{\theta }=\omega +\frac{\varepsilon a}{2}\sin (\varphi -\theta )- \frac{\varepsilon a}{2} \sin (\varphi +\theta )\); in the locked state \(\varphi \approx \theta \) the first sine term vanishes and \(\dot{\theta }>0\) if \(\varepsilon a < 2\omega \). In the artificial data example we checked that he values \(0.4\le \varepsilon \le 0.8\) provide good result. In this example, the amplitude goes up to \(\approx 2\) and the frequency is about 1, so that the above condition is satisfied. The parameter of the frequency adaptation shall be \(K\le 1\); the values between 0.5 and 1 work well. The data in Fig. 1 correspond to \(\varepsilon =0.8\), \(K=1\). For the tremor data \(\omega \approx 2\pi \cdot 4.5\), \(\varepsilon =30\), and \(K=0.5\). In both cases we updated the frequency \(\omega \) 20 times per period using the preceding phases \(\theta \) in the interval that is about one cycle long.

Non-resonant oscillator

To process the artificial signal we exploited \(\alpha _a=6\) (amplitude measurement), \(\alpha _p=0.2\) (phase measurement). For the LFP example, the parameters were \(\alpha _a=80\), \(\alpha _p=10\). In both cases we took \(\omega =5\nu \), where \(\nu =1\) and \(\nu =2\pi \cdot 17\), respectively. Practically, we have to choose \(\alpha _p\) so that \(|\tan \beta |\approx |\beta |\ll 1\). For the common choice \(\omega =5\nu \) it reduces to the condition \(|\beta |=\alpha _p/24\nu \ll 1\). (Notice that the smaller \(\alpha \) the longer the transient.) Similarly, we have to choose \(\alpha _a\) so that the derivative of the resonance curve \(\left. \frac{d}{d\nu }(a/b)\right| _{\nu =\omega /5}= \left. \frac{2(\omega ^2-\nu ^2)\nu -\alpha _a^2\nu }{[(\omega ^2-\nu ^2)^2+\alpha _a^2\nu ^2]^{3/2}}\right| _{\nu =\omega /5}\approx 0\) what yields \(\alpha _a\approx 7\nu \). For a bandpass filtered signal, the algorithm is not very sensitive to \(\alpha _a\). So, for \(\alpha _a\approx 0.75\nu \) in the LFP example, variation of the resonance curve within the bandpass is less than 4%.

Resonant oscillator

Here we always take \(\alpha =0.3\omega \) what corresponds to bandpass width about \(30\%\) of the central frequency \(\omega \). The requirement for the parameter \(\mu \) is \(\mu \gg 1\); in all computations we choose \(\mu =500\).

Patients and recordings

All patient data analyzed here were obtained from a study approved by the local ethics committee at Charité Universitätsmedizin Berlin (study number EA2/129/17) and followed the Declaration of Helsinki. All patients provided written informed consent. Tremor data was acquired from a patient with essential tremor using a 3D accelerometer (TMSi, Oldenzaal, The Netherlands) attached to the right index finger. The signal was sampled at 2048 Hz sampling rate using a Porti amplifier (TMSi). The patient stretched their arms out in front of their chest holding a bottle in order to provoke postural tremor. Only data from one axis was analyzed. LFP data was recorded from a patient with Parkinson’s Disease on medication, 2 days after surgery for deep brain stimulation with electrode cables being externalized. LFPs were acquired from the left subthalamic nucleus via a 4-contact electrode (Model 3389, Medtronic, Minneapolis, USA) using a D360 amplifier (Digitimer Ltd., Welwyn Garden City, UK) and were digitized at 1 kHz sampling rate with a 1401 analog-to-digital converter (CED Ltd., Cambridge, UK). A bipolar referencing scheme was adopted, with the signal shown here originating from contacts one to two. During the recording session, the patient was comfortably seated and was asked to rest quietly.