��Y � @ su d d l m Z d d l m Z d d l m Z d d d d � Z d d l m Z d d l Td d d d d
� Z
d S)� )�print_function)�sqrt)�odrNc C s� d d � } t | � d } | d k r}| d k rI t t | � � } n d | d } t | � } | | } t | � } t | | � }
t | | � } t | | � } | | | |
| | | | }
|
| | | | | | | } t | | | | | � } t | | | | | � } | d k rPt |
| | | d � } n t |
| | | | d � } | | } n� | d | d | d | d } | d | d | } t j | � } t j d | d | d
| d | � } t j | | | | g � } | j � } | j \ }
} | j
\ } } | j } | d k rb| t | � } | t | � } | d k r{t d � n
t d
� t d | � t d | � |
| | | | | f S)a8
Performs a linear fit to data.
Parameters
----------
xdata : An array of length N.
ydata : An array of length N.
sigmay : None or an array of length N.
sigmax : None or an array of length N.
If one is provided, it is the standard deviation of ydata. Analytical linear regression used.
If both are provided, they are the standard deviations of ydata and xdata, respectively. ODR is used.
Returns
-------
a, b : Optimal parameter of linear fit (y = a*x + b)
sa, sb : Uncertainties of the parameters
c S s | \ } } | | | S)N� )�p�x�a�br r �&/home/user/LinearRegression/fitting.py�lin_func# s zlinear_fit.<locals>.lin_func� Ng �?� r r �y�sx�syzPno uncertainties provided, use uncertainties of slope and intercept with cautionzresults of linear_fit:z reduced chi squared = z degrees of freedom = �����r )
�len�ones�sumr r �Model�RealData�ODR�run�beta�sd_beta�res_var�print)�xdata�ydata�sigmay�sigmaxr �dof�w�sw�wxZswxZswyZswxyZswx2r r �sa�sb�chi2�rchi2�a0�b0�model�data�od�outr r r
�
linear_fit sL
""
"$
r/ )� curve_fit)�*c s� t | � t | � } | d k r� t � | | | | � \ } } | d k rl t � | | � | d � } n! t � | | � | | d � } | | }
t t | � � } x� t d t | � � D] } t | | | f � | | <q� Wn� � f d d � }
t j |
� } t j d | d | d | d | � } t j | | | � } | j
� } | j } | j } | j
}
|
d
k r�| t |
� } | t |
� } | d k r�t d � n
t d � t d
| � t d |
� | | |
| f S)z�
Pass all arguments to curve_fit, which uses non-linear least squares
to fit a function, f, to data. Calculate the uncertaities in the
fit parameters from the covariance matrix.
Nr r c s
� | | � S)Nr )r r )�fr r
�f_fixed� s zgeneral_fit.<locals>.f_fixedr r r r g �?zFresults of general_fit: no uncertainties provided, so use with cautionzresults of general_fit:z degrees of freedom = z reduced chi squared = )r r0 r �zeros�aranger r r r r r r r r r )r2 r r �p0r r r! ZpoptZpcovr'