import numpy as np
import pyfits
import matplotlib.pyplot as plt
import skimage
from skimage.feature import blob_dog, blob_doh, blob_log, canny
from skimage.color import rgb2gray
from skimage.feature import corner_harris, corner_subpix, corner_peaks
from skimage.segmentation import slic
from skimage.filters import sobel
from scipy.signal import convolve2d

from scipy.ndimage import gaussian_filter
from skimage import measure
from scipy.optimize import curve_fit
import matplotlib.ticker as mtick
from scipy.signal import savgol_filter

import scipy
from scipy import signal
from scipy.signal import argrelextrema


import cv2

## this function will get the values along each circle. We start by defining a range of angles, computing the 
#coordinates and then finding the values at the nearest pixel position.
def get_line(star,theta,radius,x_c,y_c):
    #theta = np.linspace(0,2*np.pi,N_theta)  
    x = x_c + radius*np.cos(theta)
    y = y_c + radius*np.sin(theta)
    x = np.round(x)
    y = np.round(y)
    x = x.astype(int)
    y = y.astype(int)
    I = star[y,x]
    
    return I,x,y

## a function to compute the frequecy for a certain radius
def get_radius(freq):
    N_p = 36
    r = N_p/(2*np.pi*freq)
    return r

## a function to compute the radius for a certain frequency
def get_freq(radius):
    N_p = 36
    freq = N_p/(2*np.pi*radius)
    return freq

def sinusoidal(theta,a,b,c):
    N_p = 36
    y = a + b*np.sin(N_p*theta) + c*np.cos(N_p*theta) 
    return y

def fit_sinusoid(I,theta,p0):
    popt, pcov = curve_fit(sinusoidal,theta,I,p0)
    a = popt[0]
    b = popt[1]
    c = popt[2]
    modulation = np.sqrt(b**2 + c**2)/a
    return modulation, popt

def Gaussian(x,a,x0,sigma):
  y = a*(1/(np.sqrt(2*np.pi)*sigma))*np.exp(-(x-x0)**2/(2*sigma**2))
  #y = np.exp(-2*(np.pi**2)*((x-x0)**2)*sigma**2)
  return y
