from scipy.optimize import curve_fit
from numpy import linspace

from numpy import tanh
from scipy.constants import e, k


import pandas as pd


# Global variables

new_U = linspace(-25, 25, 1000)


# Function for approximation


def function_IU(U, I_n, T_e):
    return I_n * tanh(e*U/2/k/T_e)

# Find the best fit params of In and Te


def find_FitParams(data_I, data_U):
    popt, pcov = curve_fit(function_IU, data_U, data_I, p0=[0, 50000])
    return popt, pcov

# Returns pandas.DataFrame with approximated Current and Voltage values


def getApproxValues(data):
    data = data.sort_values(by=['U'])
    popt, pcov = find_FitParams(data['I'], data['U'])
    df = pd.DataFrame()
    df['U'] = new_U
    df['I'] = function_IU(df['U'], *popt)
    return df
