"""Define tools for extracting phase information from time series"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/api/08_phasetools.ipynb.

# %% auto 0
__all__ = ['cosinor', 'cosinor_phase', 'cosinor_goals']

# %% ../nbs/api/08_phasetools.ipynb 4
import numpy as np 
import matplotlib.pyplot as plt

# %% ../nbs/api/08_phasetools.ipynb 8
def cosinor(t: np.array, # time vector
                  y: np.array, # signal vector
                  tau: float # period of cosinor analysis 
                  ) -> float: # phase estimate
    "Estimate the phase of a signal using cosinor analysis."
    omega = 2*np.pi/tau 
    sin_transform = np.sin(omega*t)
    cos_transform = np.cos(omega*t)
    a1 = np.dot(y, sin_transform) / np.dot(sin_transform, sin_transform)
    a2 = np.dot(y, cos_transform) / np.dot(cos_transform, cos_transform)
    return np.array([a1, a2])

# %% ../nbs/api/08_phasetools.ipynb 9
def cosinor_phase(a: np.array) -> float: 
    z = a[1]+ complex(0,1)*a[0]
    return np.angle(z)

# %% ../nbs/api/08_phasetools.ipynb 12
def cosinor_goals(t, y, tau: float):
    omega = 2*np.pi/tau 
    A = np.stack((np.ones(len(t)), np.sin(omega*t), np.cos(omega*t)), axis=1)
    
    Q, _ = np.linalg.qr(A)
    x1 = Q[:,1]
    x2 = Q[:,2] 
    
    z = complex(0,1)*np.dot(x1,y) /np.dot(x1,np.sin(omega*t)) + np.dot(x2,y)/np.dot(x2,np.cos(omega*t))
    return np.array([z.imag, z.real])
