import logging
import numpy as np

logger = logging.getLogger('median.webserver')


def estimate_coef(x, y):
    # number of observations/points
    n = np.size(x)

    # mean of x and y vector
    m_x = np.mean(x)
    m_y = np.mean(y)

    # calculating cross-deviation and deviation about x
    SS_xy = np.sum(y * x) - n * m_y * m_x
    SS_xx = np.sum(x * x) - n * m_x * m_x

    # calculating regression coefficients
    a = (SS_xy / SS_xx) if SS_xx != 0 else None
    b = m_y - a * m_x if a is not None else None

    return a, b


def lineary_regression(coeff, x, y):
    estimed_value = []
    for point in x:
        estimed_value.append(coeff[0] * point + coeff[1])

    real_mean = np.mean(x)

    square = 1 - np.sum(pow(y - estimed_value, 2)) / np.sum(pow(y - real_mean, 2))

    return square
